{"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\"bytes\"\n\t\"exec\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"go\/token\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc usage() {\n\tfmt.Fprint(os.Stderr, \"usage: goinstall importpath...\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tgoinstall -a\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nconst logfile = \"goinstall.log\"\n\nvar (\n\tfset          = token.NewFileSet()\n\targv0         = os.Args[0]\n\terrors        = false\n\tparents       = make(map[string]string)\n\tvisit         = make(map[string]status)\n\tinstalledPkgs = make(map[string]map[string]bool)\n\tschemeRe      = regexp.MustCompile(`^[a-z]+:\/\/`)\n\n\tallpkg            = flag.Bool(\"a\", false, \"install all previously installed packages\")\n\treportToDashboard = flag.Bool(\"dashboard\", true, \"report public packages at \"+dashboardURL)\n\tupdate            = flag.Bool(\"u\", false, \"update already-downloaded packages\")\n\tdoInstall         = flag.Bool(\"install\", true, \"build and install\")\n\tclean             = flag.Bool(\"clean\", false, \"clean the package directory before installing\")\n\tnuke              = flag.Bool(\"nuke\", false, \"clean the package directory and target before installing\")\n\tuseMake           = flag.Bool(\"make\", true, \"use make to build and install\")\n\tverbose           = flag.Bool(\"v\", false, \"verbose\")\n)\n\ntype status int \/\/ status for visited map\nconst (\n\tunvisited status = iota\n\tvisiting\n\tdone\n)\n\nfunc logf(format string, args ...interface{}) {\n\tformat = \"%s: \" + format\n\targs = append([]interface{}{argv0}, args...)\n\tfmt.Fprintf(os.Stderr, format, args...)\n}\n\nfunc printf(format string, args ...interface{}) {\n\tif *verbose {\n\t\tlogf(format, args...)\n\t}\n}\n\nfunc errorf(format string, args ...interface{}) {\n\terrors = true\n\tlogf(format, args...)\n}\n\nfunc main() {\n\tflag.Usage = usage\n\tflag.Parse()\n\tif runtime.GOROOT() == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"%s: no $GOROOT\\n\", argv0)\n\t\tos.Exit(1)\n\t}\n\treadPackageList()\n\n\t\/\/ special case - \"unsafe\" is already installed\n\tvisit[\"unsafe\"] = done\n\n\targs := flag.Args()\n\tif *allpkg {\n\t\tif len(args) != 0 {\n\t\t\tusage() \/\/ -a and package list both provided\n\t\t}\n\t\t\/\/ install all packages that were ever installed\n\t\tn := 0\n\t\tfor _, pkgs := range installedPkgs {\n\t\t\tfor pkg := range pkgs {\n\t\t\t\targs = append(args, pkg)\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t\tif n == 0 {\n\t\t\tlogf(\"no installed packages\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\tusage()\n\t}\n\tfor _, path := range args {\n\t\tif s := schemeRe.FindString(path); s != \"\" {\n\t\t\terrorf(\"%q used in import path, try %q\\n\", s, path[len(s):])\n\t\t\tcontinue\n\t\t}\n\n\t\tinstall(path, \"\")\n\t}\n\tif errors {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ printDeps prints the dependency path that leads to pkg.\nfunc printDeps(pkg string) {\n\tif pkg == \"\" {\n\t\treturn\n\t}\n\tif visit[pkg] != done {\n\t\tprintDeps(parents[pkg])\n\t}\n\tfmt.Fprintf(os.Stderr, \"\\t%s ->\\n\", pkg)\n}\n\n\/\/ readPackageList reads the list of installed packages from the\n\/\/ goinstall.log files in GOROOT and the GOPATHs and initalizes\n\/\/ the installedPkgs variable.\nfunc readPackageList() {\n\tfor _, t := range build.Path {\n\t\tinstalledPkgs[t.Path] = make(map[string]bool)\n\t\tname := filepath.Join(t.Path, logfile)\n\t\tpkglistdata, err := ioutil.ReadFile(name)\n\t\tif err != nil {\n\t\t\tprintf(\"%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tpkglist := strings.Fields(string(pkglistdata))\n\t\tfor _, pkg := range pkglist {\n\t\t\tinstalledPkgs[t.Path][pkg] = true\n\t\t}\n\t}\n}\n\n\/\/ logPackage logs the named package as installed in the goinstall.log file\n\/\/ in the given tree if the package is not already in that file.\nfunc logPackage(pkg string, tree *build.Tree) (logged bool) {\n\tif installedPkgs[tree.Path][pkg] {\n\t\treturn false\n\t}\n\tname := filepath.Join(tree.Path, logfile)\n\tfout, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlogf(\"%s\\n\", err)\n\t\treturn false\n\t}\n\tfmt.Fprintf(fout, \"%s\\n\", pkg)\n\tfout.Close()\n\treturn true\n}\n\n\/\/ install installs the package named by path, which is needed by parent.\nfunc install(pkg, parent string) {\n\t\/\/ Make sure we're not already trying to install pkg.\n\tswitch visit[pkg] {\n\tcase done:\n\t\treturn\n\tcase visiting:\n\t\tfmt.Fprintf(os.Stderr, \"%s: package dependency cycle\\n\", argv0)\n\t\tprintDeps(parent)\n\t\tfmt.Fprintf(os.Stderr, \"\\t%s\\n\", pkg)\n\t\tos.Exit(2)\n\t}\n\tparents[pkg] = parent\n\tvisit[pkg] = visiting\n\tdefer func() {\n\t\tvisit[pkg] = done\n\t}()\n\n\t\/\/ Check whether package is local or remote.\n\t\/\/ If remote, download or update it.\n\ttree, pkg, err := build.FindTree(pkg)\n\t\/\/ Don't build the standard library.\n\tif err == nil && tree.Goroot && isStandardPath(pkg) {\n\t\tif parent == \"\" {\n\t\t\terrorf(\"%s: can not goinstall the standard library\\n\", pkg)\n\t\t} else {\n\t\t\tprintf(\"%s: skipping standard library\\n\", pkg)\n\t\t}\n\t\treturn\n\t}\n\t\/\/ Download remote packages if not found or forced with -u flag.\n\tremote, public := isRemote(pkg), false\n\tif remote && (err == build.ErrNotFound || (err == nil && *update)) {\n\t\tprintf(\"%s: download\\n\", pkg)\n\t\tpublic, err = download(pkg, tree.SrcDir())\n\t}\n\tif err != nil {\n\t\terrorf(\"%s: %v\\n\", pkg, err)\n\t\treturn\n\t}\n\tdir := filepath.Join(tree.SrcDir(), pkg)\n\n\t\/\/ Install prerequisites.\n\tdirInfo, err := build.ScanDir(dir, parent == \"\")\n\tif err != nil {\n\t\terrorf(\"%s: %v\\n\", pkg, err)\n\t\treturn\n\t}\n\tif len(dirInfo.GoFiles)+len(dirInfo.CgoFiles) == 0 {\n\t\terrorf(\"%s: package has no files\\n\", pkg)\n\t\treturn\n\t}\n\tfor _, p := range dirInfo.Imports {\n\t\tif p != \"C\" {\n\t\t\tinstall(p, pkg)\n\t\t}\n\t}\n\tif errors {\n\t\treturn\n\t}\n\n\t\/\/ Install this package.\n\tif *useMake {\n\t\terr := domake(dir, pkg, tree, dirInfo.IsCommand())\n\t\tif err != nil {\n\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tscript, err := build.Build(tree, pkg, dirInfo)\n\t\tif err != nil {\n\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\treturn\n\t\t}\n\t\tif *nuke {\n\t\t\tprintf(\"%s: nuke\\n\", pkg)\n\t\t\tscript.Nuke()\n\t\t} else if *clean {\n\t\t\tprintf(\"%s: clean\\n\", pkg)\n\t\t\tscript.Clean()\n\t\t}\n\t\tif *doInstall {\n\t\t\tif script.Stale() {\n\t\t\t\tprintf(\"%s: install\\n\", pkg)\n\t\t\t\tif err := script.Run(); err != nil {\n\t\t\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprintf(\"%s: up-to-date\\n\", pkg)\n\t\t\t}\n\t\t}\n\t}\n\n\tif remote {\n\t\t\/\/ mark package as installed in goinstall.log\n\t\tlogged := logPackage(pkg, tree)\n\n\t\t\/\/ report installation to the dashboard if this is the first\n\t\t\/\/ install from a public repository.\n\t\tif logged && public {\n\t\t\tmaybeReportToDashboard(pkg)\n\t\t}\n\t}\n}\n\n\/\/ Is this a standard package path?  strings container\/vector etc.\n\/\/ Assume that if the first element has a dot, it's a domain name\n\/\/ and is not the standard package path.\nfunc isStandardPath(s string) bool {\n\tdot := strings.Index(s, \".\")\n\tslash := strings.Index(s, \"\/\")\n\treturn dot < 0 || 0 < slash && slash < dot\n}\n\n\/\/ run runs the command cmd in directory dir with standard input stdin.\n\/\/ If the command fails, run prints the command and output on standard error\n\/\/ in addition to returning a non-nil os.Error.\nfunc run(dir string, stdin []byte, cmd ...string) os.Error {\n\treturn genRun(dir, stdin, cmd, false)\n}\n\n\/\/ quietRun is like run but prints nothing on failure unless -v is used.\nfunc quietRun(dir string, stdin []byte, cmd ...string) os.Error {\n\treturn genRun(dir, stdin, cmd, true)\n}\n\n\/\/ genRun implements run and quietRun.\nfunc genRun(dir string, stdin []byte, arg []string, quiet bool) os.Error {\n\tcmd := exec.Command(arg[0], arg[1:]...)\n\tcmd.Stdin = bytes.NewBuffer(stdin)\n\tcmd.Dir = dir\n\tprintf(\"%s: %s %s\\n\", dir, cmd.Path, strings.Join(arg[1:], \" \"))\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif !quiet || *verbose {\n\t\t\tif dir != \"\" {\n\t\t\t\tdir = \"cd \" + dir + \"; \"\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stderr, \"%s: === %s%s\\n\", cmd.Path, dir, strings.Join(cmd.Args, \" \"))\n\t\t\tos.Stderr.Write(out)\n\t\t\tfmt.Fprintf(os.Stderr, \"--- %s\\n\", err)\n\t\t}\n\t\treturn os.NewError(\"running \" + arg[0] + \": \" + err.String())\n\t}\n\treturn nil\n}\n<commit_msg>goinstall: report all newly-installed public packages<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\"bytes\"\n\t\"exec\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"go\/token\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc usage() {\n\tfmt.Fprint(os.Stderr, \"usage: goinstall importpath...\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tgoinstall -a\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nconst logfile = \"goinstall.log\"\n\nvar (\n\tfset          = token.NewFileSet()\n\targv0         = os.Args[0]\n\terrors        = false\n\tparents       = make(map[string]string)\n\tvisit         = make(map[string]status)\n\tinstalledPkgs = make(map[string]map[string]bool)\n\tschemeRe      = regexp.MustCompile(`^[a-z]+:\/\/`)\n\n\tallpkg            = flag.Bool(\"a\", false, \"install all previously installed packages\")\n\treportToDashboard = flag.Bool(\"dashboard\", true, \"report public packages at \"+dashboardURL)\n\tupdate            = flag.Bool(\"u\", false, \"update already-downloaded packages\")\n\tdoInstall         = flag.Bool(\"install\", true, \"build and install\")\n\tclean             = flag.Bool(\"clean\", false, \"clean the package directory before installing\")\n\tnuke              = flag.Bool(\"nuke\", false, \"clean the package directory and target before installing\")\n\tuseMake           = flag.Bool(\"make\", true, \"use make to build and install\")\n\tverbose           = flag.Bool(\"v\", false, \"verbose\")\n)\n\ntype status int \/\/ status for visited map\nconst (\n\tunvisited status = iota\n\tvisiting\n\tdone\n)\n\nfunc logf(format string, args ...interface{}) {\n\tformat = \"%s: \" + format\n\targs = append([]interface{}{argv0}, args...)\n\tfmt.Fprintf(os.Stderr, format, args...)\n}\n\nfunc printf(format string, args ...interface{}) {\n\tif *verbose {\n\t\tlogf(format, args...)\n\t}\n}\n\nfunc errorf(format string, args ...interface{}) {\n\terrors = true\n\tlogf(format, args...)\n}\n\nfunc main() {\n\tflag.Usage = usage\n\tflag.Parse()\n\tif runtime.GOROOT() == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"%s: no $GOROOT\\n\", argv0)\n\t\tos.Exit(1)\n\t}\n\treadPackageList()\n\n\t\/\/ special case - \"unsafe\" is already installed\n\tvisit[\"unsafe\"] = done\n\n\targs := flag.Args()\n\tif *allpkg {\n\t\tif len(args) != 0 {\n\t\t\tusage() \/\/ -a and package list both provided\n\t\t}\n\t\t\/\/ install all packages that were ever installed\n\t\tn := 0\n\t\tfor _, pkgs := range installedPkgs {\n\t\t\tfor pkg := range pkgs {\n\t\t\t\targs = append(args, pkg)\n\t\t\t\tn++\n\t\t\t}\n\t\t}\n\t\tif n == 0 {\n\t\t\tlogf(\"no installed packages\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\tif len(args) == 0 {\n\t\tusage()\n\t}\n\tfor _, path := range args {\n\t\tif s := schemeRe.FindString(path); s != \"\" {\n\t\t\terrorf(\"%q used in import path, try %q\\n\", s, path[len(s):])\n\t\t\tcontinue\n\t\t}\n\n\t\tinstall(path, \"\")\n\t}\n\tif errors {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ printDeps prints the dependency path that leads to pkg.\nfunc printDeps(pkg string) {\n\tif pkg == \"\" {\n\t\treturn\n\t}\n\tif visit[pkg] != done {\n\t\tprintDeps(parents[pkg])\n\t}\n\tfmt.Fprintf(os.Stderr, \"\\t%s ->\\n\", pkg)\n}\n\n\/\/ readPackageList reads the list of installed packages from the\n\/\/ goinstall.log files in GOROOT and the GOPATHs and initalizes\n\/\/ the installedPkgs variable.\nfunc readPackageList() {\n\tfor _, t := range build.Path {\n\t\tinstalledPkgs[t.Path] = make(map[string]bool)\n\t\tname := filepath.Join(t.Path, logfile)\n\t\tpkglistdata, err := ioutil.ReadFile(name)\n\t\tif err != nil {\n\t\t\tprintf(\"%s\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tpkglist := strings.Fields(string(pkglistdata))\n\t\tfor _, pkg := range pkglist {\n\t\t\tinstalledPkgs[t.Path][pkg] = true\n\t\t}\n\t}\n}\n\n\/\/ logPackage logs the named package as installed in the goinstall.log file\n\/\/ in the given tree if the package is not already in that file.\nfunc logPackage(pkg string, tree *build.Tree) (logged bool) {\n\tif installedPkgs[tree.Path][pkg] {\n\t\treturn false\n\t}\n\tname := filepath.Join(tree.Path, logfile)\n\tfout, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlogf(\"%s\\n\", err)\n\t\treturn false\n\t}\n\tfmt.Fprintf(fout, \"%s\\n\", pkg)\n\tfout.Close()\n\treturn true\n}\n\n\/\/ install installs the package named by path, which is needed by parent.\nfunc install(pkg, parent string) {\n\t\/\/ Make sure we're not already trying to install pkg.\n\tswitch visit[pkg] {\n\tcase done:\n\t\treturn\n\tcase visiting:\n\t\tfmt.Fprintf(os.Stderr, \"%s: package dependency cycle\\n\", argv0)\n\t\tprintDeps(parent)\n\t\tfmt.Fprintf(os.Stderr, \"\\t%s\\n\", pkg)\n\t\tos.Exit(2)\n\t}\n\tparents[pkg] = parent\n\tvisit[pkg] = visiting\n\tdefer func() {\n\t\tvisit[pkg] = done\n\t}()\n\n\t\/\/ Check whether package is local or remote.\n\t\/\/ If remote, download or update it.\n\ttree, pkg, err := build.FindTree(pkg)\n\t\/\/ Don't build the standard library.\n\tif err == nil && tree.Goroot && isStandardPath(pkg) {\n\t\tif parent == \"\" {\n\t\t\terrorf(\"%s: can not goinstall the standard library\\n\", pkg)\n\t\t} else {\n\t\t\tprintf(\"%s: skipping standard library\\n\", pkg)\n\t\t}\n\t\treturn\n\t}\n\t\/\/ Download remote packages if not found or forced with -u flag.\n\tremote, public := isRemote(pkg), false\n\tif remote {\n\t\tif err == build.ErrNotFound || (err == nil && *update) {\n\t\t\t\/\/ Download remote package.\n\t\t\tprintf(\"%s: download\\n\", pkg)\n\t\t\tpublic, err = download(pkg, tree.SrcDir())\n\t\t} else {\n\t\t\t\/\/ Test if this is a public repository\n\t\t\t\/\/ (for reporting to dashboard).\n\t\t\tm, _ := findPublicRepo(pkg)\n\t\t\tpublic = m != nil\n\t\t}\n\t}\n\tif err != nil {\n\t\terrorf(\"%s: %v\\n\", pkg, err)\n\t\treturn\n\t}\n\tdir := filepath.Join(tree.SrcDir(), pkg)\n\n\t\/\/ Install prerequisites.\n\tdirInfo, err := build.ScanDir(dir, parent == \"\")\n\tif err != nil {\n\t\terrorf(\"%s: %v\\n\", pkg, err)\n\t\treturn\n\t}\n\tif len(dirInfo.GoFiles)+len(dirInfo.CgoFiles) == 0 {\n\t\terrorf(\"%s: package has no files\\n\", pkg)\n\t\treturn\n\t}\n\tfor _, p := range dirInfo.Imports {\n\t\tif p != \"C\" {\n\t\t\tinstall(p, pkg)\n\t\t}\n\t}\n\tif errors {\n\t\treturn\n\t}\n\n\t\/\/ Install this package.\n\tif *useMake {\n\t\terr := domake(dir, pkg, tree, dirInfo.IsCommand())\n\t\tif err != nil {\n\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tscript, err := build.Build(tree, pkg, dirInfo)\n\t\tif err != nil {\n\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\treturn\n\t\t}\n\t\tif *nuke {\n\t\t\tprintf(\"%s: nuke\\n\", pkg)\n\t\t\tscript.Nuke()\n\t\t} else if *clean {\n\t\t\tprintf(\"%s: clean\\n\", pkg)\n\t\t\tscript.Clean()\n\t\t}\n\t\tif *doInstall {\n\t\t\tif script.Stale() {\n\t\t\t\tprintf(\"%s: install\\n\", pkg)\n\t\t\t\tif err := script.Run(); err != nil {\n\t\t\t\t\terrorf(\"%s: install: %v\\n\", pkg, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprintf(\"%s: up-to-date\\n\", pkg)\n\t\t\t}\n\t\t}\n\t}\n\n\tif remote {\n\t\t\/\/ mark package as installed in goinstall.log\n\t\tlogged := logPackage(pkg, tree)\n\n\t\t\/\/ report installation to the dashboard if this is the first\n\t\t\/\/ install from a public repository.\n\t\tif logged && public {\n\t\t\tmaybeReportToDashboard(pkg)\n\t\t}\n\t}\n}\n\n\/\/ Is this a standard package path?  strings container\/vector etc.\n\/\/ Assume that if the first element has a dot, it's a domain name\n\/\/ and is not the standard package path.\nfunc isStandardPath(s string) bool {\n\tdot := strings.Index(s, \".\")\n\tslash := strings.Index(s, \"\/\")\n\treturn dot < 0 || 0 < slash && slash < dot\n}\n\n\/\/ run runs the command cmd in directory dir with standard input stdin.\n\/\/ If the command fails, run prints the command and output on standard error\n\/\/ in addition to returning a non-nil os.Error.\nfunc run(dir string, stdin []byte, cmd ...string) os.Error {\n\treturn genRun(dir, stdin, cmd, false)\n}\n\n\/\/ quietRun is like run but prints nothing on failure unless -v is used.\nfunc quietRun(dir string, stdin []byte, cmd ...string) os.Error {\n\treturn genRun(dir, stdin, cmd, true)\n}\n\n\/\/ genRun implements run and quietRun.\nfunc genRun(dir string, stdin []byte, arg []string, quiet bool) os.Error {\n\tcmd := exec.Command(arg[0], arg[1:]...)\n\tcmd.Stdin = bytes.NewBuffer(stdin)\n\tcmd.Dir = dir\n\tprintf(\"%s: %s %s\\n\", dir, cmd.Path, strings.Join(arg[1:], \" \"))\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif !quiet || *verbose {\n\t\t\tif dir != \"\" {\n\t\t\t\tdir = \"cd \" + dir + \"; \"\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stderr, \"%s: === %s%s\\n\", cmd.Path, dir, strings.Join(cmd.Args, \" \"))\n\t\t\tos.Stderr.Write(out)\n\t\t\tfmt.Fprintf(os.Stderr, \"--- %s\\n\", err)\n\t\t}\n\t\treturn os.NewError(\"running \" + arg[0] + \": \" + err.String())\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package serf\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/hashicorp\/memberlist\"\n)\n\ntype MergeDelegate interface {\n\tNotifyMerge([]*Member) error\n}\n\ntype mergeDelegate struct {\n\tserf *Serf\n}\n\nfunc (m *mergeDelegate) NotifyMerge(nodes []*memberlist.Node) error {\n\tmembers := make([]*Member, len(nodes))\n\tfor idx, n := range nodes {\n\t\tvar err error\n\t\tmembers[idx], err = m.nodeToMember(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn m.serf.config.Merge.NotifyMerge(members)\n}\n\nfunc (m *mergeDelegate) NotifyAlive(peer *memberlist.Node) error {\n\tmember, err := m.nodeToMember(peer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.serf.config.Merge.NotifyMerge([]*Member{member})\n}\n\nfunc (m *mergeDelegate) nodeToMember(n *memberlist.Node) (*Member, error) {\n\tstatus := StatusNone\n\tif n.State == memberlist.StateLeft {\n\t\tstatus = StatusLeft\n\t}\n\tif err := m.validiateMemberInfo(n); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Member{\n\t\tName:        n.Name,\n\t\tAddr:        net.IP(n.Addr),\n\t\tPort:        n.Port,\n\t\tTags:        m.serf.decodeTags(n.Meta),\n\t\tStatus:      status,\n\t\tProtocolMin: n.PMin,\n\t\tProtocolMax: n.PMax,\n\t\tProtocolCur: n.PCur,\n\t\tDelegateMin: n.DMin,\n\t\tDelegateMax: n.DMax,\n\t\tDelegateCur: n.DCur,\n\t}, nil\n}\n\n\/\/ validateMemberInfo checks that the data we are sending is valid\nfunc (m *mergeDelegate) validiateMemberInfo(n *memberlist.Node) error {\n\tif err := m.serf.ValidateNodeNames(); err != nil {\n\t\treturn err\n\t}\n\n\thost, port, err := net.SplitHostPort(string(n.Addr))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip == nil || (ip.To4() == nil && ip.To16() == nil) {\n\t\treturn fmt.Errorf(\"%v is not a valid IPv4 or IPv6 address\\n\", ip)\n\t}\n\n\tp, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif p < 0 || p > 65535 {\n\t\treturn fmt.Errorf(\"invalid port %v , port must be a valid number from 0-65535\", p)\n\t}\n\n\tif len(n.Meta) > memberlist.MetaMaxSize {\n\t\treturn fmt.Errorf(\"Encoded length of tags exceeds limit of %d bytes\",\n\t\t\tmemberlist.MetaMaxSize)\n\t}\n\treturn nil\n}\n<commit_msg>Fix typo: s\/validiate\/validate\/<commit_after>package serf\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/hashicorp\/memberlist\"\n)\n\ntype MergeDelegate interface {\n\tNotifyMerge([]*Member) error\n}\n\ntype mergeDelegate struct {\n\tserf *Serf\n}\n\nfunc (m *mergeDelegate) NotifyMerge(nodes []*memberlist.Node) error {\n\tmembers := make([]*Member, len(nodes))\n\tfor idx, n := range nodes {\n\t\tvar err error\n\t\tmembers[idx], err = m.nodeToMember(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn m.serf.config.Merge.NotifyMerge(members)\n}\n\nfunc (m *mergeDelegate) NotifyAlive(peer *memberlist.Node) error {\n\tmember, err := m.nodeToMember(peer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.serf.config.Merge.NotifyMerge([]*Member{member})\n}\n\nfunc (m *mergeDelegate) nodeToMember(n *memberlist.Node) (*Member, error) {\n\tstatus := StatusNone\n\tif n.State == memberlist.StateLeft {\n\t\tstatus = StatusLeft\n\t}\n\tif err := m.validateMemberInfo(n); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Member{\n\t\tName:        n.Name,\n\t\tAddr:        net.IP(n.Addr),\n\t\tPort:        n.Port,\n\t\tTags:        m.serf.decodeTags(n.Meta),\n\t\tStatus:      status,\n\t\tProtocolMin: n.PMin,\n\t\tProtocolMax: n.PMax,\n\t\tProtocolCur: n.PCur,\n\t\tDelegateMin: n.DMin,\n\t\tDelegateMax: n.DMax,\n\t\tDelegateCur: n.DCur,\n\t}, nil\n}\n\n\/\/ validateMemberInfo checks that the data we are sending is valid\nfunc (m *mergeDelegate) validateMemberInfo(n *memberlist.Node) error {\n\tif err := m.serf.ValidateNodeNames(); err != nil {\n\t\treturn err\n\t}\n\n\thost, port, err := net.SplitHostPort(string(n.Addr))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip == nil || (ip.To4() == nil && ip.To16() == nil) {\n\t\treturn fmt.Errorf(\"%v is not a valid IPv4 or IPv6 address\\n\", ip)\n\t}\n\n\tp, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif p < 0 || p > 65535 {\n\t\treturn fmt.Errorf(\"invalid port %v , port must be a valid number from 0-65535\", p)\n\t}\n\n\tif len(n.Meta) > memberlist.MetaMaxSize {\n\t\treturn fmt.Errorf(\"Encoded length of tags exceeds limit of %d bytes\",\n\t\t\tmemberlist.MetaMaxSize)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/cumulodev\/goutils\/pool\"\n\t\"github.com\/cumulodev\/nimbusec\"\n)\n\nfunc main() {\n\turl := flag.String(\"url\", nimbusec.DefaultAPI, \"API Url\")\n\tkey := flag.String(\"key\", \"abc\", \"API key for authentication\")\n\tsecret := flag.String(\"secret\", \"abc\", \"API secret for authentication\")\n\tfile := flag.String(\"file\", \"import.csv\", \"path to import file\")\n\tdelete := flag.Bool(\"delete\", false, \"delete domains from nimbusec if not provided in the CSV\")\n\tupdate := flag.Bool(\"update\", false, \"updates domain info; false to just insert new domains\")\n\tworkers := flag.Int(\"workers\", 1, \"number of paralell workers (please do not use too many workers)\")\n\tflag.Parse()\n\n\t\/\/ creates a new nimbusec API instance\n\tapi, err := nimbusec.NewAPI(*url, *key, *secret)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ open csv input file and parse it\n\tfh, err := os.Open(*file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer fh.Close()\n\treader := csv.NewReader(fh)\n\treader.FieldsPerRecord = -1 \/\/ see the Reader struct information below\n\trows, err := reader.ReadAll()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpool := pool.New(*workers)\n\tpool.Start()\n\n\t\/\/ keep track of domain names (required for delete step later)\n\tref := make(map[string]struct{})\n\n\tfor _, row := range rows {\n\t\tname := row[0]\n\t\tscheme := row[2]\n\t\tbundle := row[3]\n\n\t\turl := scheme + \":\/\/\" + name\n\t\tif len(row) > 4 {\n\t\t\turl = url + row[4]\n\t\t}\n\n\t\t\/\/ construct domain\n\t\tdomain := &nimbusec.Domain{\n\t\t\tName:      name,\n\t\t\tBundle:    bundle,\n\t\t\tScheme:    scheme,\n\t\t\tDeepScan:  url,\n\t\t\tFastScans: []string{url},\n\t\t}\n\n\t\t\/\/ upsert domain\n\t\tref[name] = struct{}{}\n\t\tpool.Add(upsertJob{\n\t\t\tapi:    api,\n\t\t\tdomain: domain,\n\t\t\tupdate: *update,\n\t\t})\n\t}\n\n\tpool.Wait()\n\n\t\/\/ sync\n\t\/\/ delete domains not listed in new set\n\tif *delete {\n\t\t\/\/ read all domains from api\n\t\tdomains, err := api.FindDomains(nimbusec.EmptyFilter)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ cross reference domains in nimbusec with csv file and delete all\n\t\t\/\/ domains not present in csv file\n\t\tfor _, domain := range domains {\n\t\t\tif _, ok := ref[domain.Name]; !ok {\n\t\t\t\tpool.Add(deleteJob{\n\t\t\t\t\tapi:    api,\n\t\t\t\t\tdomain: &domain,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tpool.Wait()\n\t}\n}\n\ntype upsertJob struct {\n\tapi    *nimbusec.API\n\tdomain *nimbusec.Domain\n\tupdate bool\n}\n\nfunc (this upsertJob) Work() {\n\tfmt.Printf(\"upsert domain: %+v\\n\", this.domain)\n\tif this.update {\n\t\tif _, err := this.api.CreateOrUpdateDomain(this.domain); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tif _, err := this.api.CreateOrGetDomain(this.domain); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc (this upsertJob) Save() {}\n\ntype deleteJob struct {\n\tapi    *nimbusec.API\n\tdomain *nimbusec.Domain\n}\n\nfunc (this deleteJob) Work() {\n\tfmt.Printf(\"delete domain: %s\\n\", this.domain.Name)\n\tthis.api.DeleteDomain(this.domain, true)\n}\n\nfunc (this deleteJob) Save() {}\n<commit_msg>fixed typo<commit_after>package main\n\nimport (\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/cumulodev\/goutils\/pool\"\n\t\"github.com\/cumulodev\/nimbusec\"\n)\n\nfunc main() {\n\turl := flag.String(\"url\", nimbusec.DefaultAPI, \"API Url\")\n\tkey := flag.String(\"key\", \"abc\", \"API key for authentication\")\n\tsecret := flag.String(\"secret\", \"abc\", \"API secret for authentication\")\n\tfile := flag.String(\"file\", \"import.csv\", \"path to import file\")\n\tdelete := flag.Bool(\"delete\", false, \"delete domains from nimbusec if not provided in the CSV\")\n\tupdate := flag.Bool(\"update\", false, \"updates domain info; false to just insert new domains\")\n\tworkers := flag.Int(\"workers\", 1, \"number of parallel workers (please do not use too many workers)\")\n\tflag.Parse()\n\n\t\/\/ creates a new nimbusec API instance\n\tapi, err := nimbusec.NewAPI(*url, *key, *secret)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ open csv input file and parse it\n\tfh, err := os.Open(*file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer fh.Close()\n\treader := csv.NewReader(fh)\n\treader.FieldsPerRecord = -1 \/\/ see the Reader struct information below\n\trows, err := reader.ReadAll()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpool := pool.New(*workers)\n\tpool.Start()\n\n\t\/\/ keep track of domain names (required for delete step later)\n\tref := make(map[string]struct{})\n\n\tfor _, row := range rows {\n\t\tname := row[0]\n\t\tscheme := row[2]\n\t\tbundle := row[3]\n\n\t\turl := scheme + \":\/\/\" + name\n\t\t\/\/\t\tif len(row) > 4 {\n\t\t\/\/\t\t\tdeeplink := row[4]\n\t\t\/\/\t\t\tif deeplink == \"\" {\n\t\t\/\/\t\t\t\t\/\/ do nothing\n\t\t\/\/\t\t\t} else if strings.HasPrefix(deeplink, \"\/\") {\n\t\t\/\/\t\t\t\turl = url + deeplink\n\t\t\/\/\t\t\t} else {\n\t\t\/\/\t\t\t\turl = deeplink\n\t\t\/\/\t\t\t}\n\t\t\/\/\t\t}\n\n\t\t\/\/ construct domain\n\t\tdomain := &nimbusec.Domain{\n\t\t\tName:      name,\n\t\t\tBundle:    bundle,\n\t\t\tScheme:    scheme,\n\t\t\tDeepScan:  url,\n\t\t\tFastScans: []string{url},\n\t\t}\n\n\t\t\/\/ upsert domain\n\t\tref[name] = struct{}{}\n\t\tpool.Add(upsertJob{\n\t\t\tapi:    api,\n\t\t\tdomain: domain,\n\t\t\tupdate: *update,\n\t\t})\n\t}\n\n\tpool.Wait()\n\n\t\/\/ sync\n\t\/\/ delete domains not listed in new set\n\tif *delete {\n\t\t\/\/ read all domains from api\n\t\tdomains, err := api.FindDomains(nimbusec.EmptyFilter)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ cross reference domains in nimbusec with csv file and delete all\n\t\t\/\/ domains not present in csv file\n\t\tfor _, domain := range domains {\n\t\t\tif _, ok := ref[domain.Name]; !ok {\n\t\t\t\tpool.Add(deleteJob{\n\t\t\t\t\tapi:    api,\n\t\t\t\t\tdomain: &domain,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tpool.Wait()\n\t}\n}\n\ntype upsertJob struct {\n\tapi    *nimbusec.API\n\tdomain *nimbusec.Domain\n\tupdate bool\n}\n\nfunc (this upsertJob) Work() {\n\tfmt.Printf(\"upsert domain: %+v\\n\", this.domain)\n\tif this.update {\n\t\tif _, err := this.api.CreateOrUpdateDomain(this.domain); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tif _, err := this.api.CreateOrGetDomain(this.domain); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc (this upsertJob) Save() {}\n\ntype deleteJob struct {\n\tapi    *nimbusec.API\n\tdomain *nimbusec.Domain\n}\n\nfunc (this deleteJob) Work() {\n\tfmt.Printf(\"delete domain: %s\\n\", this.domain.Name)\n\tthis.api.DeleteDomain(this.domain, true)\n}\n\nfunc (this deleteJob) Save() {}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ dupes finds duplicate files in the given root directory\n\/\/\n\/\/ TODO concurrent checksum\/compare? library for other programs?\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ bytesize ints represent a size as in \"bytes of memory\"\ntype bytesize uint64\n\n\/\/ String formats the underlying integer with suitable units\n\/\/ (KB, MB, .., YB) to keep the number itself small-ish.\nfunc (bs bytesize) String() string {\n\tunits := []string{\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"}\n\tvalue := float64(bs)\n\tunit := 0\n\tfor value > 1024.0 && unit < len(units)-1 {\n\t\tvalue \/= 1024.0\n\t\tunit++\n\t}\n\treturn fmt.Sprintf(\"%.2f %s\", value, units[unit])\n}\n\n\/\/ countin ints represent a count\ntype countin uint64\n\n\/\/ String formats the underlying integer with commas as \"thousands separators\"\n\/\/ to make it easier to read.\nfunc (ci countin) String() string {\n\tstr := fmt.Sprintf(\"%d\", ci)\n\tchunks := splitFromBack(str, 3)\n\tstr = strings.Join(chunks, \",\")\n\treturn str\n}\n\n\/\/ split string s into chunks of at most n characters from the back.\nfunc splitFromBack(s string, n int) []string {\n\tvar chunks []string\n\n\tfullChunks := len(s) \/ n\n\trestChunk := len(s) % n\n\n\tif restChunk > 0 {\n\t\tchunks = append(chunks, s[0:restChunk])\n\t}\n\n\tvar i = restChunk\n\tfor fullChunks > 0 {\n\t\tchunks = append(chunks, s[i:i+n])\n\t\ti += n\n\t\tfullChunks--\n\t}\n\treturn chunks\n}\n\nvar paranoid = flag.Bool(\"p\", false, \"paranoid byte-by-byte comparison\")\nvar goroutines = flag.Int(\"j\", runtime.NumCPU(), \"number of goroutines\")\n\n\/\/ hashes maps from digests to paths\nvar hashes = make(map[string]string)\n\n\/\/ sizes maps from sizes to paths\nvar sizes = make(map[int64]string)\n\n\/\/ files counts the number of files examined\nvar files countin\n\n\/\/ dupes counts the number of duplicate files\nvar dupes countin\n\n\/\/ wasted counts the space (in bytes) occupied by duplicates\nvar wasted bytesize\n\n\/\/ identical does a byte-by-byte comparison of the files with the\n\/\/ given paths\nfunc identical(pa, pb string) (bool, error) {\n\tbufferSize := os.Getpagesize()\n\n\ta, err := os.Open(pa)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer a.Close()\n\tb, err := os.Open(pb)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer b.Close()\n\n\tba := make([]byte, bufferSize)\n\tbb := make([]byte, bufferSize)\n\n\tfor {\n\t\tla, erra := a.Read(ba)\n\t\tlb, errb := b.Read(bb)\n\n\t\tif erra != nil || errb != nil {\n\t\t\tif erra == io.EOF && errb == io.EOF {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif erra != nil {\n\t\t\t\treturn false, erra\n\t\t\t}\n\t\t\tif errb != nil {\n\t\t\t\treturn false, errb\n\t\t\t}\n\t\t}\n\n\t\tif la != lb { \/\/ TODO: short read always at end of file?\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif !bytes.Equal(ba, bb) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n}\n\n\/\/ checksum calculates a hash digest for the file with the given path\nfunc checksum(path string) (string, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\thasher := sha256.New()\n\tio.Copy(hasher, file)\n\tsum := fmt.Sprintf(\"%x\", hasher.Sum(nil))\n\n\treturn sum, nil\n}\n\n\/\/ check is called for each path we walk. It only examines regular, non-empty\n\/\/ files. It first rules out duplicates by file size; for files that remain\n\/\/ it calculates a checksum; if it has seen the same checksum before, it\n\/\/ signals a duplicate; otherwise it remembers the checksum and the path of\n\/\/ the original file before moving on; in paranoid mode it follows up with a\n\/\/ byte-by-byte file comparison.\nfunc check(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsize := info.Size()\n\n\tif !info.Mode().IsRegular() || size == 0 {\n\t\treturn nil\n\t}\n\n\tfiles++\n\n\tvar dupe string\n\tvar ok bool\n\tif dupe, ok = sizes[size]; !ok {\n\t\tsizes[size] = path\n\t\treturn nil\n\t}\n\n\t\/\/ backpatch new file into hashes\n\tsum, err := checksum(dupe)\n\tif err != nil {\n\t\treturn err\n\t}\n\thashes[sum] = dupe\n\n\tsum, err = checksum(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dupe, ok = hashes[sum]; !ok {\n\t\thashes[sum] = path\n\t\treturn nil\n\t}\n\n\tif *paranoid {\n\t\tsame, err := identical(path, dupe)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !same {\n\t\t\tfmt.Printf(\"cool: %s sha256-collides with %s!\\n\", path, dupe)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfmt.Printf(\"%s\\n%s\\n\\n\", path, dupe)\n\tdupes++\n\twasted += bytesize(size)\n\n\treturn nil\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tvar program = os.Args[0]\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [option...] directory...\\n\", program)\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tflag.Usage()\n\t}\n\n\tfor _, root := range flag.Args() {\n\t\tfilepath.Walk(root, check)\n\t}\n\n\tif len(sizes) > 0 || len(hashes) > 0 {\n\t\tfmt.Printf(\"%v files examined, %v duplicates found, %v wasted\\n\", files, dupes, wasted)\n\t}\n}\n<commit_msg>Move TODO to README, remove concurrency pieces.<commit_after>\/\/ dupes finds duplicate files in the given root directory\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ bytesize ints represent a size as in \"bytes of memory\"\ntype bytesize uint64\n\n\/\/ String formats the underlying integer with suitable units\n\/\/ (KB, MB, .., YB) to keep the number itself small-ish.\nfunc (bs bytesize) String() string {\n\tunits := []string{\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"}\n\tvalue := float64(bs)\n\tunit := 0\n\tfor value > 1024.0 && unit < len(units)-1 {\n\t\tvalue \/= 1024.0\n\t\tunit++\n\t}\n\treturn fmt.Sprintf(\"%.2f %s\", value, units[unit])\n}\n\n\/\/ countin ints represent a count\ntype countin uint64\n\n\/\/ String formats the underlying integer with commas as \"thousands separators\"\n\/\/ to make it easier to read.\nfunc (ci countin) String() string {\n\tstr := fmt.Sprintf(\"%d\", ci)\n\tchunks := splitFromBack(str, 3)\n\tstr = strings.Join(chunks, \",\")\n\treturn str\n}\n\n\/\/ split string s into chunks of at most n characters from the back.\nfunc splitFromBack(s string, n int) []string {\n\tvar chunks []string\n\n\tfullChunks := len(s) \/ n\n\trestChunk := len(s) % n\n\n\tif restChunk > 0 {\n\t\tchunks = append(chunks, s[0:restChunk])\n\t}\n\n\tvar i = restChunk\n\tfor fullChunks > 0 {\n\t\tchunks = append(chunks, s[i:i+n])\n\t\ti += n\n\t\tfullChunks--\n\t}\n\treturn chunks\n}\n\nvar paranoid = flag.Bool(\"p\", false, \"paranoid byte-by-byte comparison\")\n\n\/\/ hashes maps from digests to paths\nvar hashes = make(map[string]string)\n\n\/\/ sizes maps from sizes to paths\nvar sizes = make(map[int64]string)\n\n\/\/ files counts the number of files examined\nvar files countin\n\n\/\/ dupes counts the number of duplicate files\nvar dupes countin\n\n\/\/ wasted counts the space (in bytes) occupied by duplicates\nvar wasted bytesize\n\n\/\/ identical does a byte-by-byte comparison of the files with the\n\/\/ given paths\nfunc identical(pa, pb string) (bool, error) {\n\tbufferSize := os.Getpagesize()\n\n\ta, err := os.Open(pa)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer a.Close()\n\tb, err := os.Open(pb)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer b.Close()\n\n\tba := make([]byte, bufferSize)\n\tbb := make([]byte, bufferSize)\n\n\tfor {\n\t\tla, erra := a.Read(ba)\n\t\tlb, errb := b.Read(bb)\n\n\t\tif erra != nil || errb != nil {\n\t\t\tif erra == io.EOF && errb == io.EOF {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tif erra != nil {\n\t\t\t\treturn false, erra\n\t\t\t}\n\t\t\tif errb != nil {\n\t\t\t\treturn false, errb\n\t\t\t}\n\t\t}\n\n\t\tif la != lb { \/\/ TODO: short read always at end of file?\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif !bytes.Equal(ba, bb) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n}\n\n\/\/ checksum calculates a hash digest for the file with the given path\nfunc checksum(path string) (string, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\thasher := sha256.New()\n\tio.Copy(hasher, file)\n\tsum := fmt.Sprintf(\"%x\", hasher.Sum(nil))\n\n\treturn sum, nil\n}\n\n\/\/ check is called for each path we walk. It only examines regular, non-empty\n\/\/ files. It first rules out duplicates by file size; for files that remain\n\/\/ it calculates a checksum; if it has seen the same checksum before, it\n\/\/ signals a duplicate; otherwise it remembers the checksum and the path of\n\/\/ the original file before moving on; in paranoid mode it follows up with a\n\/\/ byte-by-byte file comparison.\nfunc check(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsize := info.Size()\n\n\tif !info.Mode().IsRegular() || size == 0 {\n\t\treturn nil\n\t}\n\n\tfiles++\n\n\tvar dupe string\n\tvar ok bool\n\tif dupe, ok = sizes[size]; !ok {\n\t\tsizes[size] = path\n\t\treturn nil\n\t}\n\n\t\/\/ backpatch new file into hashes\n\tsum, err := checksum(dupe)\n\tif err != nil {\n\t\treturn err\n\t}\n\thashes[sum] = dupe\n\n\tsum, err = checksum(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dupe, ok = hashes[sum]; !ok {\n\t\thashes[sum] = path\n\t\treturn nil\n\t}\n\n\tif *paranoid {\n\t\tsame, err := identical(path, dupe)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !same {\n\t\t\tfmt.Printf(\"cool: %s sha256-collides with %s!\\n\", path, dupe)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfmt.Printf(\"%s\\n%s\\n\\n\", path, dupe)\n\tdupes++\n\twasted += bytesize(size)\n\n\treturn nil\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tvar program = os.Args[0]\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [option...] directory...\\n\", program)\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tflag.Usage()\n\t}\n\n\tfor _, root := range flag.Args() {\n\t\tfilepath.Walk(root, check)\n\t}\n\n\tif len(sizes) > 0 || len(hashes) > 0 {\n\t\tfmt.Printf(\"%v files examined, %v duplicates found, %v wasted\\n\", files, dupes, wasted)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package stripe\n\nimport \"encoding\/json\"\n\n\/\/ ReversalParams is the set of parameters that can be used when reversing a transfer.\ntype ReversalParams struct {\n\tParams\n\tTransfer string\n\tAmount   uint64\n\tFee      bool\n}\n\n\/\/ ReversalListParams is the set of parameters that can be used when listing reversals.\ntype ReversalListParams struct {\n\tListParams\n\tTransfer string\n}\n\n\/\/ Reversal represents a transfer reversal.\ntype Reversal struct {\n\tID       string            `json:\"id\"`\n\tAmount   uint64            `json:\"amount\"`\n\tCreated  int64             `json:\"created\"`\n\tCurrency Currency          `json:\"currency\"`\n\tTransfer string            `json:\"transfer\"`\n\tMeta     map[string]string `json:\"metadata\"`\n}\n\n\/\/ ReversalList is a list of object for reversals.\ntype ReversalList struct {\n\tListMeta\n\tValues []*Reversal `json:\"data\"`\n}\n\n\/\/ UnmarshalJSON handles deserialization of a Reversal.\n\/\/ This custom unmarshaling is needed because the resulting\n\/\/ property may be an id or the full struct if it was expanded.\nfunc (r *Reversal) UnmarshalJSON(data []byte) error {\n\ttype reversal Reversal\n\tvar rr reversal\n\terr := json.Unmarshal(data, &rr)\n\tif err == nil {\n\t\t*r = Reversal(rr)\n\t} else {\n\t\t\/\/ the id is surrounded by \"\\\" characters, so strip them\n\t\tr.ID = string(data[1 : len(data)-1])\n\t}\n\n\treturn nil\n}\n<commit_msg>Add balance transaction to reversals<commit_after>package stripe\n\nimport \"encoding\/json\"\n\n\/\/ ReversalParams is the set of parameters that can be used when reversing a transfer.\ntype ReversalParams struct {\n\tParams\n\tTransfer string\n\tAmount   uint64\n\tFee      bool\n}\n\n\/\/ ReversalListParams is the set of parameters that can be used when listing reversals.\ntype ReversalListParams struct {\n\tListParams\n\tTransfer string\n}\n\n\/\/ Reversal represents a transfer reversal.\ntype Reversal struct {\n\tID       string            `json:\"id\"`\n\tAmount   uint64            `json:\"amount\"`\n\tCreated  int64             `json:\"created\"`\n\tCurrency Currency          `json:\"currency\"`\n\tTransfer string            `json:\"transfer\"`\n\tMeta     map[string]string `json:\"metadata\"`\n\tTx       *Transaction      `json:\"balance_transaction\"`\n}\n\n\/\/ ReversalList is a list of object for reversals.\ntype ReversalList struct {\n\tListMeta\n\tValues []*Reversal `json:\"data\"`\n}\n\n\/\/ UnmarshalJSON handles deserialization of a Reversal.\n\/\/ This custom unmarshaling is needed because the resulting\n\/\/ property may be an id or the full struct if it was expanded.\nfunc (r *Reversal) UnmarshalJSON(data []byte) error {\n\ttype reversal Reversal\n\tvar rr reversal\n\terr := json.Unmarshal(data, &rr)\n\tif err == nil {\n\t\t*r = Reversal(rr)\n\t} else {\n\t\t\/\/ the id is surrounded by \"\\\" characters, so strip them\n\t\tr.ID = string(data[1 : len(data)-1])\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package decoders\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/seadsystem\/Backend\/DB\/landingzone\/constants\"\n)\n\ntype SeadPacket struct {\n\tType      byte\n\tLocation  byte\n\tTimestamp float64\n\tPeriod    float64\n\tCount     int\n\tData      float64\n\tSerial    int\n}\n\nvar headerRegex *regexp.Regexp\nvar InvalidHeader = errors.New(\"Invalid header.\")\nvar InvalidPacket = errors.New(\"Invalid packet.\")\nvar InvalidTime = errors.New(\"Invalid time.\")\n\n\/\/ init sets up stuff we need with proper error handling. If it isn't complicated or doesn't need error handling, it can probably just be assigned directly.\nfunc init() {\n\tvar err error\n\theaderRegex, err = regexp.Compile(constants.HEADER_REGEX)\n\tif err != nil {\n\t\tlog.Panic(\"Regex compile error:\", err)\n\t}\n}\n\n\/\/ DecodeHeader verifies that the header is in the correct format and extracts the serial number\nfunc DecodeHeader(packet []byte) (serial int, err error) {\n\tserialStrings := headerRegex.FindSubmatch(packet)\n\n\tif serialStrings == nil || len(serialStrings) != 2 {\n\t\terr = InvalidHeader\n\t\treturn\n\t}\n\n\tlog.Printf(\"Header serial string: %s\\n\", string(serialStrings[1]))\n\n\tserial, err = strconv.Atoi(string(serialStrings[1]))\n\treturn\n}\n\n\/\/ DecodePacket extracts the data sent from sensor\nfunc DecodePacket(buffer []byte) (packet SeadPacket, err error) {\n\tfor i := 0; i < len(buffer); {\n\t\tdatatype := buffer[i]\n\t\ti++\n\n\t\t\/\/ Switch on the type of data sent in the packet\n\t\tswitch {\n\t\tcase datatype == 'T':\n\t\t\t\/\/ Type\n\t\t\tpacket.Type = buffer[i]\n\t\t\ti++\n\t\tcase datatype == 'l':\n\t\t\t\/\/ Location\n\t\t\tpacket.Location = buffer[i]\n\t\t\ti++\n\t\tcase datatype == 't':\n\t\t\t\/\/ Timestamp\n\t\t\tpacket.Timestamp, err = asciiTimeToDouble(buffer[i : i+14])\n\t\t\ti += 14\n\t\tcase datatype == 'P':\n\t\t\t\/\/ Period separator\n\t\t\tpacket.Period, err = asciiTimeToDouble(buffer[i : i+14])\n\t\t\ti += 14\n\t\tcase datatype == 'C':\n\t\t\t\/\/ Count\n\t\t\tpacket.Count, err = Binary2int(buffer[i : i+2])\n\t\t\ti += 2\n\t\tcase datatype == 'D':\n\t\t\t\/\/ Data\n\t\t\t\/\/ if count isn't set, return error\n\t\t\t\/\/ TODO finish parsing data\n\t\tcase datatype == 'S':\n\t\t\t\/\/ Serial\n\t\t\tpacket.Serial, err = strconv.Atoi(string(buffer[i : i+6]))\n\t\t\ti += 6\n\t\tcase datatype == 'X':\n\t\t\treturn\n\t\tdefault:\n\t\t\terr = InvalidPacket\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\terr = InvalidPacket\n\treturn\n}\n\nfunc doubleToAsciiTime(double_time float64) string {\n\t\/\/ TODO: Check if this logic is correct or if we need to use http:\/\/golang.org\/pkg\/math\/#Mod\n\tint_time := int(double_time)\n\tvar days = math.Floor(double_time \/ (60 * 60 * 24))\n\tvar hours = (int_time % (60 * 60 * 24)) \/ (60 * 60)\n\tvar minutes = (int_time % (60 * 60)) \/ 60\n\tvar seconds = (int_time % (60)) \/ 1\n\tvar milliseconds = (int_time * 1000) % 1000\n\tvar clock_time = (int_time * 12000) % 12\n\n\treturn fmt.Sprintf(\"%03d%02d%02d%02d%03d%02d\", days, hours, minutes, seconds, milliseconds, clock_time)\n}\n\nfunc asciiTimeToDouble(ascii_time []byte) (time float64, err error) {\n\t\/\/ Check time string format\n\tif len(ascii_time) != 16 {\n\t\terr = InvalidTime\n\t}\n\t_, err = strconv.Atoi(string(ascii_time))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Do the conversion now that we know it should work\n\tvar ptr int = 0\n\tdays, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 3\n\ttime += float64(60 * 60 * 24 * days)\n\thours, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(60 * 60 * hours)\n\tminutes, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(60 * minutes)\n\tseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(seconds)\n\tmilliseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 3\n\ttime += float64(milliseconds) \/ 1000.0\n\tclock, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(clock) \/ 12000.0\n\treturn\n}\n\n\/\/ Every checks if every byte in a slice meets some criteria\nfunc Every(data []byte, check func(byte) bool) bool {\n\tfor _, element := range data {\n\t\tif !check(element) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Binary2int converts a byte array containing binary data into an int\nfunc Binary2int(data []byte) (total int) {\n\tfor index, element := range data {\n\t\ttotal += int(element)<<(index * 8)\n\t}\n\treturn\n}\n<commit_msg>Fixed type error<commit_after>package decoders\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/seadsystem\/Backend\/DB\/landingzone\/constants\"\n)\n\ntype SeadPacket struct {\n\tType      byte\n\tLocation  byte\n\tTimestamp float64\n\tPeriod    float64\n\tCount     int\n\tData      float64\n\tSerial    int\n}\n\nvar headerRegex *regexp.Regexp\nvar InvalidHeader = errors.New(\"Invalid header.\")\nvar InvalidPacket = errors.New(\"Invalid packet.\")\nvar InvalidTime = errors.New(\"Invalid time.\")\n\n\/\/ init sets up stuff we need with proper error handling. If it isn't complicated or doesn't need error handling, it can probably just be assigned directly.\nfunc init() {\n\tvar err error\n\theaderRegex, err = regexp.Compile(constants.HEADER_REGEX)\n\tif err != nil {\n\t\tlog.Panic(\"Regex compile error:\", err)\n\t}\n}\n\n\/\/ DecodeHeader verifies that the header is in the correct format and extracts the serial number\nfunc DecodeHeader(packet []byte) (serial int, err error) {\n\tserialStrings := headerRegex.FindSubmatch(packet)\n\n\tif serialStrings == nil || len(serialStrings) != 2 {\n\t\terr = InvalidHeader\n\t\treturn\n\t}\n\n\tlog.Printf(\"Header serial string: %s\\n\", string(serialStrings[1]))\n\n\tserial, err = strconv.Atoi(string(serialStrings[1]))\n\treturn\n}\n\n\/\/ DecodePacket extracts the data sent from sensor\nfunc DecodePacket(buffer []byte) (packet SeadPacket, err error) {\n\tfor i := 0; i < len(buffer); {\n\t\tdatatype := buffer[i]\n\t\ti++\n\n\t\t\/\/ Switch on the type of data sent in the packet\n\t\tswitch {\n\t\tcase datatype == 'T':\n\t\t\t\/\/ Type\n\t\t\tpacket.Type = buffer[i]\n\t\t\ti++\n\t\tcase datatype == 'l':\n\t\t\t\/\/ Location\n\t\t\tpacket.Location = buffer[i]\n\t\t\ti++\n\t\tcase datatype == 't':\n\t\t\t\/\/ Timestamp\n\t\t\tpacket.Timestamp, err = asciiTimeToDouble(buffer[i : i+14])\n\t\t\ti += 14\n\t\tcase datatype == 'P':\n\t\t\t\/\/ Period separator\n\t\t\tpacket.Period, err = asciiTimeToDouble(buffer[i : i+14])\n\t\t\ti += 14\n\t\tcase datatype == 'C':\n\t\t\t\/\/ Count\n\t\t\tpacket.Count, err = Binary2int(buffer[i : i+2])\n\t\t\ti += 2\n\t\tcase datatype == 'D':\n\t\t\t\/\/ Data\n\t\t\t\/\/ if count isn't set, return error\n\t\t\t\/\/ TODO finish parsing data\n\t\tcase datatype == 'S':\n\t\t\t\/\/ Serial\n\t\t\tpacket.Serial, err = strconv.Atoi(string(buffer[i : i+6]))\n\t\t\ti += 6\n\t\tcase datatype == 'X':\n\t\t\treturn\n\t\tdefault:\n\t\t\terr = InvalidPacket\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\terr = InvalidPacket\n\treturn\n}\n\nfunc doubleToAsciiTime(double_time float64) string {\n\t\/\/ TODO: Check if this logic is correct or if we need to use http:\/\/golang.org\/pkg\/math\/#Mod\n\tint_time := int(double_time)\n\tvar days = math.Floor(double_time \/ (60 * 60 * 24))\n\tvar hours = (int_time % (60 * 60 * 24)) \/ (60 * 60)\n\tvar minutes = (int_time % (60 * 60)) \/ 60\n\tvar seconds = (int_time % (60)) \/ 1\n\tvar milliseconds = (int_time * 1000) % 1000\n\tvar clock_time = (int_time * 12000) % 12\n\n\treturn fmt.Sprintf(\"%03d%02d%02d%02d%03d%02d\", days, hours, minutes, seconds, milliseconds, clock_time)\n}\n\nfunc asciiTimeToDouble(ascii_time []byte) (time float64, err error) {\n\t\/\/ Check time string format\n\tif len(ascii_time) != 16 {\n\t\terr = InvalidTime\n\t}\n\t_, err = strconv.Atoi(string(ascii_time))\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Do the conversion now that we know it should work\n\tvar ptr int = 0\n\tdays, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 3\n\ttime += float64(60 * 60 * 24 * days)\n\thours, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(60 * 60 * hours)\n\tminutes, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(60 * minutes)\n\tseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(seconds)\n\tmilliseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 3\n\ttime += float64(milliseconds) \/ 1000.0\n\tclock, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))\n\tif err != nil {\n\t\treturn\n\t}\n\tptr += 2\n\ttime += float64(clock) \/ 12000.0\n\treturn\n}\n\n\/\/ Every checks if every byte in a slice meets some criteria\nfunc Every(data []byte, check func(byte) bool) bool {\n\tfor _, element := range data {\n\t\tif !check(element) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Binary2int converts a byte array containing binary data into an int\nfunc Binary2int(data []byte) (total int) {\n\tfor index, element := range data {\n\t\ttotal += int(element)<<uint(index * 8)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package notifications\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Notification struct {\n\tID        int       `json:\"id\"`\n\tData      Data      `json:\"notification\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tRead      bool      `json:\"read\"`\n}\n\ntype Data interface {\n\t\/\/ TODO maybe should be made 'real interface', which will allow\n\t\/\/ to use typed channels, type checking and semantic dispatching\n\t\/\/ instead of typecase:\n\n\t\/\/ Serialize() []byte\n\t\/\/ Describe() (string, string)\n}\n\ntype notificationWrapper struct {\n\tNotification Data `json:\"notification\"`\n}\n\ntype messageWrapper struct {\n\tMessage Data `json:\"message\"`\n}\n\ntype messageReadWrapper struct {\n\tMessageRead interface{} `json:\"messageRead\"`\n}\n\ntype messageTypingWrapper struct {\n\tMessageRead interface{} `json:\"messageTyping\"`\n}\n\ntype orderWrapper struct {\n\tOrderNotification `json:\"order\"`\n}\n\ntype paymentWrapper struct {\n\tPaymentNotification `json:\"payment\"`\n}\n\ntype orderConfirmationWrapper struct {\n\tOrderConfirmationNotification `json:\"orderConfirmation\"`\n}\n\ntype orderCancelWrapper struct {\n\tOrderCancelNotification `json:\"orderConfirmation\"`\n}\n\ntype refundWrapper struct {\n\tRefundNotification `json:\"refund\"`\n}\n\ntype fulfillmentWrapper struct {\n\tFulfillmentNotification `json:\"orderFulfillment\"`\n}\n\ntype completionWrapper struct {\n\tCompletionNotification `json:\"orderCompletion\"`\n}\n\ntype disputeOpenWrapper struct {\n\tDisputeOpenNotification `json:\"disputeOpen\"`\n}\n\ntype disputeUpdateWrapper struct {\n\tDisputeUpdateNotification `json:\"disputeUpdate\"`\n}\n\ntype disputeCloseWrapper struct {\n\tDisputeCloseNotification `json:\"disputeClose\"`\n}\n\ntype OrderNotification struct {\n\tTitle             string `json:\"title\"`\n\tBuyerGuid         string `json:\"buyerGuid\"`\n\tBuyerBlockchainId string `json:\"buyerBlockchainId\"`\n\tThumbnail         string `json:\"thumbnail\"`\n\tTimestamp         int    `json:\"timestamp\"`\n\tOrderId           string `json:\"orderId\"`\n}\n\ntype PaymentNotification struct {\n\tOrderId      string `json:\"orderId\"`\n\tFundingTotal uint64 `json:\"fundingTotal\"`\n}\n\ntype OrderConfirmationNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype OrderCancelNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype RefundNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype FulfillmentNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype CompletionNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeOpenNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeUpdateNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeCloseNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype FollowNotification struct {\n\tFollow string `json:\"follow\"`\n}\n\ntype UnfollowNotification struct {\n\tUnfollow string `json:\"unfollow\"`\n}\n\ntype StatusNotification struct {\n\tStatus string `json:\"status\"`\n}\n\ntype ChatMessage struct {\n\tMessageId string    `json:\"messageId\"`\n\tPeerId    string    `json:\"peerId\"`\n\tSubject   string    `json:\"subject\"`\n\tMessage   string    `json:\"message\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n\ntype ChatRead struct {\n\tMessageId string `json:\"messageId\"`\n\tPeerId    string `json:\"peerId\"`\n\tSubject   string `json:\"subject\"`\n}\n\ntype ChatTyping struct {\n\tPeerId  string `json:\"peerId\"`\n\tSubject string `json:\"subject\"`\n}\n\nfunc Serialize(i interface{}) []byte {\n\tvar n notificationWrapper\n\tswitch i.(type) {\n\tcase OrderNotification:\n\t\tn = notificationWrapper{\n\t\t\torderWrapper{\n\t\t\t\tOrderNotification: i.(OrderNotification),\n\t\t\t},\n\t\t}\n\tcase PaymentNotification:\n\t\tn = notificationWrapper{\n\t\t\tpaymentWrapper{\n\t\t\t\tPaymentNotification: i.(PaymentNotification),\n\t\t\t},\n\t\t}\n\tcase OrderConfirmationNotification:\n\t\tn = notificationWrapper{\n\t\t\torderConfirmationWrapper{\n\t\t\t\tOrderConfirmationNotification: i.(OrderConfirmationNotification),\n\t\t\t},\n\t\t}\n\tcase OrderCancelNotification:\n\t\tn = notificationWrapper{\n\t\t\torderCancelWrapper{\n\t\t\t\tOrderCancelNotification: i.(OrderCancelNotification),\n\t\t\t},\n\t\t}\n\tcase RefundNotification:\n\t\tn = notificationWrapper{\n\t\t\trefundWrapper{\n\t\t\t\tRefundNotification: i.(RefundNotification),\n\t\t\t},\n\t\t}\n\tcase FulfillmentNotification:\n\t\tn = notificationWrapper{\n\t\t\tfulfillmentWrapper{\n\t\t\t\tFulfillmentNotification: i.(FulfillmentNotification),\n\t\t\t},\n\t\t}\n\tcase CompletionNotification:\n\t\tn = notificationWrapper{\n\t\t\tcompletionWrapper{\n\t\t\t\tCompletionNotification: i.(CompletionNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeOpenNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeOpenWrapper{\n\t\t\t\tDisputeOpenNotification: i.(DisputeOpenNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeUpdateNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeUpdateWrapper{\n\t\t\t\tDisputeUpdateNotification: i.(DisputeUpdateNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeCloseNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeCloseWrapper{\n\t\t\t\tDisputeCloseNotification: i.(DisputeCloseNotification),\n\t\t\t},\n\t\t}\n\tcase FollowNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(FollowNotification),\n\t\t}\n\tcase UnfollowNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(UnfollowNotification),\n\t\t}\n\tcase StatusNotification:\n\t\ts := i.(StatusNotification)\n\t\tb, _ := json.Marshal(s)\n\t\treturn b\n\tcase ChatMessage:\n\t\tm := messageWrapper{\n\t\t\ti.(ChatMessage),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase ChatRead:\n\t\tm := messageReadWrapper{\n\t\t\ti.(ChatRead),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase ChatTyping:\n\t\tm := messageTypingWrapper{\n\t\t\ti.(ChatTyping),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase []byte:\n\t\treturn i.([]byte)\n\t}\n\n\tb, _ := json.MarshalIndent(n, \"\", \"    \")\n\treturn b\n}\n\nfunc Describe(i interface{}) (string, string) {\n\tvar head, body string\n\tswitch i.(type) {\n\tcase OrderNotification:\n\t\thead = \"Order received\"\n\n\t\tn := i.(OrderNotification)\n\t\tvar buyer string\n\t\tif n.BuyerBlockchainId != \"\" {\n\t\t\tbuyer = n.BuyerBlockchainId\n\t\t} else {\n\t\t\tbuyer = n.BuyerGuid\n\t\t}\n\t\tform := \"You received an order \\\"%s\\\".\\n\\nOrder ID: %s\\nBuyer: %s\\nThumbnail: %s\\nTimestamp: %d\"\n\t\tbody = fmt.Sprintf(form, n.Title, n.OrderId, buyer, n.Thumbnail, n.Timestamp)\n\n\tcase PaymentNotification:\n\t\thead = \"Payment received\"\n\n\t\tn := i.(PaymentNotification)\n\t\tform := \"Payment for order \\\"%s\\\" received (total %d).\"\n\t\tbody = fmt.Sprintf(form, n.OrderId, n.FundingTotal)\n\n\tcase OrderConfirmationNotification:\n\t\thead = \"Order confirmed\"\n\n\t\tn := i.(OrderConfirmationNotification)\n\t\tform := \"Order \\\"%s\\\" has been confirmed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase OrderCancelNotification:\n\t\thead = \"Order cancelled\"\n\n\t\tn := i.(OrderCancelNotification)\n\t\tform := \"Order \\\"%s\\\" has been cancelled.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase RefundNotification:\n\t\thead = \"Payment refunded\"\n\n\t\tn := i.(RefundNotification)\n\t\tform := \"Payment refund for order \\\"%s\\\" received.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase FulfillmentNotification:\n\t\thead = \"Order fulfilled\"\n\n\t\tn := i.(FulfillmentNotification)\n\t\tform := \"Order \\\"%s\\\" was marked as fulfilled.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase CompletionNotification:\n\t\thead = \"Order completed\"\n\n\t\tn := i.(CompletionNotification)\n\t\tform := \"Order \\\"%s\\\" was marked as completed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeOpenNotification:\n\t\thead = \"Dispute opened\"\n\n\t\tn := i.(DisputeOpenNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was opened.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeUpdateNotification:\n\t\thead = \"Dispute updated\"\n\n\t\tn := i.(DisputeUpdateNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was updated.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeCloseNotification:\n\t\thead = \"Dispute closed\"\n\n\t\tn := i.(DisputeCloseNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was closed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\t}\n\treturn head, body\n}\n<commit_msg>Create moderator add and remove notifications<commit_after>package notifications\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Notification struct {\n\tID        int       `json:\"id\"`\n\tData      Data      `json:\"notification\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tRead      bool      `json:\"read\"`\n}\n\ntype Data interface {\n\t\/\/ TODO maybe should be made 'real interface', which will allow\n\t\/\/ to use typed channels, type checking and semantic dispatching\n\t\/\/ instead of typecase:\n\n\t\/\/ Serialize() []byte\n\t\/\/ Describe() (string, string)\n}\n\ntype notificationWrapper struct {\n\tNotification Data `json:\"notification\"`\n}\n\ntype messageWrapper struct {\n\tMessage Data `json:\"message\"`\n}\n\ntype messageReadWrapper struct {\n\tMessageRead interface{} `json:\"messageRead\"`\n}\n\ntype messageTypingWrapper struct {\n\tMessageRead interface{} `json:\"messageTyping\"`\n}\n\ntype orderWrapper struct {\n\tOrderNotification `json:\"order\"`\n}\n\ntype paymentWrapper struct {\n\tPaymentNotification `json:\"payment\"`\n}\n\ntype orderConfirmationWrapper struct {\n\tOrderConfirmationNotification `json:\"orderConfirmation\"`\n}\n\ntype orderCancelWrapper struct {\n\tOrderCancelNotification `json:\"orderConfirmation\"`\n}\n\ntype refundWrapper struct {\n\tRefundNotification `json:\"refund\"`\n}\n\ntype fulfillmentWrapper struct {\n\tFulfillmentNotification `json:\"orderFulfillment\"`\n}\n\ntype completionWrapper struct {\n\tCompletionNotification `json:\"orderCompletion\"`\n}\n\ntype disputeOpenWrapper struct {\n\tDisputeOpenNotification `json:\"disputeOpen\"`\n}\n\ntype disputeUpdateWrapper struct {\n\tDisputeUpdateNotification `json:\"disputeUpdate\"`\n}\n\ntype disputeCloseWrapper struct {\n\tDisputeCloseNotification `json:\"disputeClose\"`\n}\n\ntype OrderNotification struct {\n\tTitle             string `json:\"title\"`\n\tBuyerGuid         string `json:\"buyerGuid\"`\n\tBuyerBlockchainId string `json:\"buyerBlockchainId\"`\n\tThumbnail         string `json:\"thumbnail\"`\n\tTimestamp         int    `json:\"timestamp\"`\n\tOrderId           string `json:\"orderId\"`\n}\n\ntype PaymentNotification struct {\n\tOrderId      string `json:\"orderId\"`\n\tFundingTotal uint64 `json:\"fundingTotal\"`\n}\n\ntype OrderConfirmationNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype OrderCancelNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype RefundNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype FulfillmentNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype CompletionNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeOpenNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeUpdateNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype DisputeCloseNotification struct {\n\tOrderId string `json:\"orderId\"`\n}\n\ntype FollowNotification struct {\n\tFollow string `json:\"follow\"`\n}\n\ntype UnfollowNotification struct {\n\tUnfollow string `json:\"unfollow\"`\n}\n\ntype ModeratorAddNotification struct {\n\tModeratorAdd string `json:\"moderatorAdd\"`\n}\n\ntype ModeratorRemoveNotification struct {\n\tModeratorRemove string `json:\"moderatorRemove\"`\n}\n\ntype StatusNotification struct {\n\tStatus string `json:\"status\"`\n}\n\ntype ChatMessage struct {\n\tMessageId string    `json:\"messageId\"`\n\tPeerId    string    `json:\"peerId\"`\n\tSubject   string    `json:\"subject\"`\n\tMessage   string    `json:\"message\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n}\n\ntype ChatRead struct {\n\tMessageId string `json:\"messageId\"`\n\tPeerId    string `json:\"peerId\"`\n\tSubject   string `json:\"subject\"`\n}\n\ntype ChatTyping struct {\n\tPeerId  string `json:\"peerId\"`\n\tSubject string `json:\"subject\"`\n}\n\nfunc Serialize(i interface{}) []byte {\n\tvar n notificationWrapper\n\tswitch i.(type) {\n\tcase OrderNotification:\n\t\tn = notificationWrapper{\n\t\t\torderWrapper{\n\t\t\t\tOrderNotification: i.(OrderNotification),\n\t\t\t},\n\t\t}\n\tcase PaymentNotification:\n\t\tn = notificationWrapper{\n\t\t\tpaymentWrapper{\n\t\t\t\tPaymentNotification: i.(PaymentNotification),\n\t\t\t},\n\t\t}\n\tcase OrderConfirmationNotification:\n\t\tn = notificationWrapper{\n\t\t\torderConfirmationWrapper{\n\t\t\t\tOrderConfirmationNotification: i.(OrderConfirmationNotification),\n\t\t\t},\n\t\t}\n\tcase OrderCancelNotification:\n\t\tn = notificationWrapper{\n\t\t\torderCancelWrapper{\n\t\t\t\tOrderCancelNotification: i.(OrderCancelNotification),\n\t\t\t},\n\t\t}\n\tcase RefundNotification:\n\t\tn = notificationWrapper{\n\t\t\trefundWrapper{\n\t\t\t\tRefundNotification: i.(RefundNotification),\n\t\t\t},\n\t\t}\n\tcase FulfillmentNotification:\n\t\tn = notificationWrapper{\n\t\t\tfulfillmentWrapper{\n\t\t\t\tFulfillmentNotification: i.(FulfillmentNotification),\n\t\t\t},\n\t\t}\n\tcase CompletionNotification:\n\t\tn = notificationWrapper{\n\t\t\tcompletionWrapper{\n\t\t\t\tCompletionNotification: i.(CompletionNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeOpenNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeOpenWrapper{\n\t\t\t\tDisputeOpenNotification: i.(DisputeOpenNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeUpdateNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeUpdateWrapper{\n\t\t\t\tDisputeUpdateNotification: i.(DisputeUpdateNotification),\n\t\t\t},\n\t\t}\n\tcase DisputeCloseNotification:\n\t\tn = notificationWrapper{\n\t\t\tdisputeCloseWrapper{\n\t\t\t\tDisputeCloseNotification: i.(DisputeCloseNotification),\n\t\t\t},\n\t\t}\n\tcase FollowNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(FollowNotification),\n\t\t}\n\tcase UnfollowNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(UnfollowNotification),\n\t\t}\n\tcase ModeratorAddNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(ModeratorAddNotification),\n\t\t}\n\tcase ModeratorRemoveNotification:\n\t\tn = notificationWrapper{\n\t\t\ti.(ModeratorRemoveNotification),\n\t\t}\n\tcase StatusNotification:\n\t\ts := i.(StatusNotification)\n\t\tb, _ := json.Marshal(s)\n\t\treturn b\n\tcase ChatMessage:\n\t\tm := messageWrapper{\n\t\t\ti.(ChatMessage),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase ChatRead:\n\t\tm := messageReadWrapper{\n\t\t\ti.(ChatRead),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase ChatTyping:\n\t\tm := messageTypingWrapper{\n\t\t\ti.(ChatTyping),\n\t\t}\n\t\tb, _ := json.MarshalIndent(m, \"\", \"    \")\n\t\treturn b\n\tcase []byte:\n\t\treturn i.([]byte)\n\t}\n\n\tb, _ := json.MarshalIndent(n, \"\", \"    \")\n\treturn b\n}\n\nfunc Describe(i interface{}) (string, string) {\n\tvar head, body string\n\tswitch i.(type) {\n\tcase OrderNotification:\n\t\thead = \"Order received\"\n\n\t\tn := i.(OrderNotification)\n\t\tvar buyer string\n\t\tif n.BuyerBlockchainId != \"\" {\n\t\t\tbuyer = n.BuyerBlockchainId\n\t\t} else {\n\t\t\tbuyer = n.BuyerGuid\n\t\t}\n\t\tform := \"You received an order \\\"%s\\\".\\n\\nOrder ID: %s\\nBuyer: %s\\nThumbnail: %s\\nTimestamp: %d\"\n\t\tbody = fmt.Sprintf(form, n.Title, n.OrderId, buyer, n.Thumbnail, n.Timestamp)\n\n\tcase PaymentNotification:\n\t\thead = \"Payment received\"\n\n\t\tn := i.(PaymentNotification)\n\t\tform := \"Payment for order \\\"%s\\\" received (total %d).\"\n\t\tbody = fmt.Sprintf(form, n.OrderId, n.FundingTotal)\n\n\tcase OrderConfirmationNotification:\n\t\thead = \"Order confirmed\"\n\n\t\tn := i.(OrderConfirmationNotification)\n\t\tform := \"Order \\\"%s\\\" has been confirmed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase OrderCancelNotification:\n\t\thead = \"Order cancelled\"\n\n\t\tn := i.(OrderCancelNotification)\n\t\tform := \"Order \\\"%s\\\" has been cancelled.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase RefundNotification:\n\t\thead = \"Payment refunded\"\n\n\t\tn := i.(RefundNotification)\n\t\tform := \"Payment refund for order \\\"%s\\\" received.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase FulfillmentNotification:\n\t\thead = \"Order fulfilled\"\n\n\t\tn := i.(FulfillmentNotification)\n\t\tform := \"Order \\\"%s\\\" was marked as fulfilled.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase CompletionNotification:\n\t\thead = \"Order completed\"\n\n\t\tn := i.(CompletionNotification)\n\t\tform := \"Order \\\"%s\\\" was marked as completed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeOpenNotification:\n\t\thead = \"Dispute opened\"\n\n\t\tn := i.(DisputeOpenNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was opened.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeUpdateNotification:\n\t\thead = \"Dispute updated\"\n\n\t\tn := i.(DisputeUpdateNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was updated.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\n\tcase DisputeCloseNotification:\n\t\thead = \"Dispute closed\"\n\n\t\tn := i.(DisputeCloseNotification)\n\t\tform := \"Dispute around order \\\"%s\\\" was closed.\"\n\t\tbody = fmt.Sprintf(form, n.OrderId)\n\t}\n\treturn head, body\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\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\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\/neptune\"\n)\n\nfunc resourceAwsNeptuneParameterGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsNeptuneParameterGroupCreate,\n\t\tRead:   resourceAwsNeptuneParameterGroupRead,\n\t\tUpdate: resourceAwsNeptuneParameterGroupUpdate,\n\t\tDelete: resourceAwsNeptuneParameterGroupDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\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\tForceNew: true,\n\t\t\t\tRequired: true,\n\t\t\t\tStateFunc: func(val interface{}) string {\n\t\t\t\t\treturn strings.ToLower(val.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"family\": &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\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDefault:  \"Managed by Terraform\",\n\t\t\t},\n\t\t\t\"parameter\": &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\"name\": &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},\n\t\t\t\t\t\t\"value\": &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},\n\t\t\t\t\t\t\"apply_method\": &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:  \"immediate\",\n\t\t\t\t\t\t\t\/\/ this parameter is not actually state, but a\n\t\t\t\t\t\t\t\/\/ meta-parameter describing how the RDS API call\n\t\t\t\t\t\t\t\/\/ to modify the parameter group should be made.\n\t\t\t\t\t\t\t\/\/ Future reads of the resource from AWS don't tell\n\t\t\t\t\t\t\t\/\/ us what we used for apply_method previously, so\n\t\t\t\t\t\t\t\/\/ by squashing state to an empty string we avoid\n\t\t\t\t\t\t\t\/\/ needing to do an update for every future run.\n\t\t\t\t\t\t\tStateFunc: func(interface{}) string { return \"\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSet: resourceAwsNeptuneParameterHash,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsNeptuneParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\tcreateOpts := neptune.CreateDBParameterGroupInput{\n\t\tDBParameterGroupName:   aws.String(d.Get(\"name\").(string)),\n\t\tDBParameterGroupFamily: aws.String(d.Get(\"family\").(string)),\n\t\tDescription:            aws.String(d.Get(\"description\").(string)),\n\t}\n\n\tlog.Printf(\"[DEBUG] Create Neptune Parameter Group: %#v\", createOpts)\n\tresp, err := conn.CreateDBParameterGroup(&createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Neptune Parameter Group: %s\", err)\n\t}\n\n\td.Partial(true)\n\td.SetPartial(\"name\")\n\td.SetPartial(\"family\")\n\td.SetPartial(\"description\")\n\td.Partial(false)\n\n\td.SetId(*resp.DBParameterGroup.DBParameterGroupName)\n\tlog.Printf(\"[INFO] Neptune Parameter Group ID: %s\", d.Id())\n\n\treturn resourceAwsNeptuneParameterGroupUpdate(d, meta)\n}\n\nfunc resourceAwsNeptuneParameterGroupRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\tdescribeOpts := neptune.DescribeDBParameterGroupsInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\n\tdescribeResp, err := conn.DescribeDBParameterGroups(&describeOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(describeResp.DBParameterGroups) != 1 ||\n\t\t*describeResp.DBParameterGroups[0].DBParameterGroupName != d.Id() {\n\t\treturn fmt.Errorf(\"Unable to find Parameter Group: %#v\", describeResp.DBParameterGroups)\n\t}\n\n\td.Set(\"name\", describeResp.DBParameterGroups[0].DBParameterGroupName)\n\td.Set(\"family\", describeResp.DBParameterGroups[0].DBParameterGroupFamily)\n\td.Set(\"description\", describeResp.DBParameterGroups[0].Description)\n\n\t\/\/ Only include user customized parameters as there's hundreds of system\/default ones\n\tdescribeParametersOpts := neptune.DescribeDBParametersInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\tSource:               aws.String(\"user\"),\n\t}\n\n\tdescribeParametersResp, err := conn.DescribeDBParameters(&describeParametersOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Set(\"parameter\", flattenNeptuneParameters(describeParametersResp.Parameters))\n\n\treturn nil\n}\n\nfunc resourceAwsNeptuneParameterGroupUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\td.Partial(true)\n\n\tif d.HasChange(\"parameter\") {\n\t\to, n := d.GetChange(\"parameter\")\n\t\tif o == nil {\n\t\t\to = new(schema.Set)\n\t\t}\n\t\tif n == nil {\n\t\t\tn = new(schema.Set)\n\t\t}\n\n\t\tos := o.(*schema.Set)\n\t\tns := n.(*schema.Set)\n\n\t\ttoRemove, err := expandNeptuneParameters(os.Difference(ns).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] Parameters to remove: %#v\", toRemove)\n\n\t\ttoAdd, err := expandNeptuneParameters(ns.Difference(os).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] Parameters to add: %#v\", toAdd)\n\n\t\t\/\/ We can only modify 20 parameters at a time, so walk them until\n\t\t\/\/ we've got them all.\n\t\tmaxParams := 20\n\n\t\tfor len(toRemove) > 0 {\n\t\t\tparamsToModify := make([]*neptune.Parameter, 0)\n\t\t\tif len(toRemove) <= maxParams {\n\t\t\t\tparamsToModify, toRemove = toRemove[:], nil\n\t\t\t} else {\n\t\t\t\tparamsToModify, toRemove = toRemove[:maxParams], toRemove[maxParams:]\n\t\t\t}\n\t\t\tresetOpts := neptune.ResetDBParameterGroupInput{\n\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\tParameters:           paramsToModify,\n\t\t\t}\n\n\t\t\tlog.Printf(\"[DEBUG] Reset Neptune Parameter Group: %s\", resetOpts)\n\t\t\terr := resource.Retry(30*time.Second, func() *resource.RetryError {\n\t\t\t\t_, err = conn.ResetDBParameterGroup(&resetOpts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif isAWSErr(err, \"InvalidDBParameterGroupState\", \" has pending changes\") {\n\t\t\t\t\t\treturn resource.RetryableError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn resource.NonRetryableError(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 fmt.Errorf(\"Error resetting Neptune Parameter Group: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tfor len(toAdd) > 0 {\n\t\t\tparamsToModify := make([]*neptune.Parameter, 0)\n\t\t\tif len(toAdd) <= maxParams {\n\t\t\t\tparamsToModify, toAdd = toAdd[:], nil\n\t\t\t} else {\n\t\t\t\tparamsToModify, toAdd = toAdd[:maxParams], toAdd[maxParams:]\n\t\t\t}\n\t\t\tmodifyOpts := neptune.ModifyDBParameterGroupInput{\n\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\tParameters:           paramsToModify,\n\t\t\t}\n\n\t\t\tlog.Printf(\"[DEBUG] Modify Neptune Parameter Group: %s\", modifyOpts)\n\t\t\t_, err = conn.ModifyDBParameterGroup(&modifyOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error modifying Neptune Parameter Group: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\td.SetPartial(\"parameter\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsNeptuneParameterGroupRead(d, meta)\n}\n\nfunc resourceAwsNeptuneParameterGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\treturn resource.Retry(3*time.Minute, func() *resource.RetryError {\n\t\tdeleteOpts := neptune.DeleteDBParameterGroupInput{\n\t\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\t}\n\t\t_, err := conn.DeleteDBParameterGroup(&deleteOpts)\n\t\tif err != nil {\n\t\t\tawsErr, ok := err.(awserr.Error)\n\t\t\tif ok && awsErr.Code() == \"DBParameterGroupNotFound\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif ok && awsErr.Code() == \"InvalidDBParameterGroupState\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc resourceAwsNeptuneParameterHash(v interface{}) int {\n\tvar buf bytes.Buffer\n\tm := v.(map[string]interface{})\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"name\"].(string)))\n\t\/\/ Store the value as a lower case string, to match how we store them in flattenParameters\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", strings.ToLower(m[\"value\"].(string))))\n\n\treturn hashcode.String(buf.String())\n}\n<commit_msg>cleaning up schema declarations<commit_after>package aws\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\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\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\/neptune\"\n)\n\nfunc resourceAwsNeptuneParameterGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsNeptuneParameterGroupCreate,\n\t\tRead:   resourceAwsNeptuneParameterGroupRead,\n\t\tUpdate: resourceAwsNeptuneParameterGroupUpdate,\n\t\tDelete: resourceAwsNeptuneParameterGroupDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tForceNew: true,\n\t\t\t\tRequired: true,\n\t\t\t\tStateFunc: func(val interface{}) string {\n\t\t\t\t\treturn strings.ToLower(val.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"family\": {\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\tForceNew: true,\n\t\t\t\tDefault:  \"Managed by Terraform\",\n\t\t\t},\n\t\t\t\"parameter\": {\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\"name\": {\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},\n\t\t\t\t\t\t\"value\": {\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},\n\t\t\t\t\t\t\"apply_method\": {\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:  \"immediate\",\n\t\t\t\t\t\t\t\/\/ this parameter is not actually state, but a\n\t\t\t\t\t\t\t\/\/ meta-parameter describing how the RDS API call\n\t\t\t\t\t\t\t\/\/ to modify the parameter group should be made.\n\t\t\t\t\t\t\t\/\/ Future reads of the resource from AWS don't tell\n\t\t\t\t\t\t\t\/\/ us what we used for apply_method previously, so\n\t\t\t\t\t\t\t\/\/ by squashing state to an empty string we avoid\n\t\t\t\t\t\t\t\/\/ needing to do an update for every future run.\n\t\t\t\t\t\t\tStateFunc: func(interface{}) string { return \"\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSet: resourceAwsNeptuneParameterHash,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsNeptuneParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\tcreateOpts := neptune.CreateDBParameterGroupInput{\n\t\tDBParameterGroupName:   aws.String(d.Get(\"name\").(string)),\n\t\tDBParameterGroupFamily: aws.String(d.Get(\"family\").(string)),\n\t\tDescription:            aws.String(d.Get(\"description\").(string)),\n\t}\n\n\tlog.Printf(\"[DEBUG] Create Neptune Parameter Group: %#v\", createOpts)\n\tresp, err := conn.CreateDBParameterGroup(&createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Neptune Parameter Group: %s\", err)\n\t}\n\n\td.Partial(true)\n\td.SetPartial(\"name\")\n\td.SetPartial(\"family\")\n\td.SetPartial(\"description\")\n\td.Partial(false)\n\n\td.SetId(*resp.DBParameterGroup.DBParameterGroupName)\n\tlog.Printf(\"[INFO] Neptune Parameter Group ID: %s\", d.Id())\n\n\treturn resourceAwsNeptuneParameterGroupUpdate(d, meta)\n}\n\nfunc resourceAwsNeptuneParameterGroupRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\tdescribeOpts := neptune.DescribeDBParameterGroupsInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\n\tdescribeResp, err := conn.DescribeDBParameterGroups(&describeOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(describeResp.DBParameterGroups) != 1 ||\n\t\t*describeResp.DBParameterGroups[0].DBParameterGroupName != d.Id() {\n\t\treturn fmt.Errorf(\"Unable to find Parameter Group: %#v\", describeResp.DBParameterGroups)\n\t}\n\n\td.Set(\"name\", describeResp.DBParameterGroups[0].DBParameterGroupName)\n\td.Set(\"family\", describeResp.DBParameterGroups[0].DBParameterGroupFamily)\n\td.Set(\"description\", describeResp.DBParameterGroups[0].Description)\n\n\t\/\/ Only include user customized parameters as there's hundreds of system\/default ones\n\tdescribeParametersOpts := neptune.DescribeDBParametersInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\tSource:               aws.String(\"user\"),\n\t}\n\n\tdescribeParametersResp, err := conn.DescribeDBParameters(&describeParametersOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.Set(\"parameter\", flattenNeptuneParameters(describeParametersResp.Parameters))\n\n\treturn nil\n}\n\nfunc resourceAwsNeptuneParameterGroupUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\td.Partial(true)\n\n\tif d.HasChange(\"parameter\") {\n\t\to, n := d.GetChange(\"parameter\")\n\t\tif o == nil {\n\t\t\to = new(schema.Set)\n\t\t}\n\t\tif n == nil {\n\t\t\tn = new(schema.Set)\n\t\t}\n\n\t\tos := o.(*schema.Set)\n\t\tns := n.(*schema.Set)\n\n\t\ttoRemove, err := expandNeptuneParameters(os.Difference(ns).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] Parameters to remove: %#v\", toRemove)\n\n\t\ttoAdd, err := expandNeptuneParameters(ns.Difference(os).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Printf(\"[DEBUG] Parameters to add: %#v\", toAdd)\n\n\t\t\/\/ We can only modify 20 parameters at a time, so walk them until\n\t\t\/\/ we've got them all.\n\t\tmaxParams := 20\n\n\t\tfor len(toRemove) > 0 {\n\t\t\tparamsToModify := make([]*neptune.Parameter, 0)\n\t\t\tif len(toRemove) <= maxParams {\n\t\t\t\tparamsToModify, toRemove = toRemove[:], nil\n\t\t\t} else {\n\t\t\t\tparamsToModify, toRemove = toRemove[:maxParams], toRemove[maxParams:]\n\t\t\t}\n\t\t\tresetOpts := neptune.ResetDBParameterGroupInput{\n\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\tParameters:           paramsToModify,\n\t\t\t}\n\n\t\t\tlog.Printf(\"[DEBUG] Reset Neptune Parameter Group: %s\", resetOpts)\n\t\t\terr := resource.Retry(30*time.Second, func() *resource.RetryError {\n\t\t\t\t_, err = conn.ResetDBParameterGroup(&resetOpts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif isAWSErr(err, \"InvalidDBParameterGroupState\", \" has pending changes\") {\n\t\t\t\t\t\treturn resource.RetryableError(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn resource.NonRetryableError(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 fmt.Errorf(\"Error resetting Neptune Parameter Group: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tfor len(toAdd) > 0 {\n\t\t\tparamsToModify := make([]*neptune.Parameter, 0)\n\t\t\tif len(toAdd) <= maxParams {\n\t\t\t\tparamsToModify, toAdd = toAdd[:], nil\n\t\t\t} else {\n\t\t\t\tparamsToModify, toAdd = toAdd[:maxParams], toAdd[maxParams:]\n\t\t\t}\n\t\t\tmodifyOpts := neptune.ModifyDBParameterGroupInput{\n\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\tParameters:           paramsToModify,\n\t\t\t}\n\n\t\t\tlog.Printf(\"[DEBUG] Modify Neptune Parameter Group: %s\", modifyOpts)\n\t\t\t_, err = conn.ModifyDBParameterGroup(&modifyOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error modifying Neptune Parameter Group: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\td.SetPartial(\"parameter\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsNeptuneParameterGroupRead(d, meta)\n}\n\nfunc resourceAwsNeptuneParameterGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).neptuneconn\n\n\treturn resource.Retry(3*time.Minute, func() *resource.RetryError {\n\t\tdeleteOpts := neptune.DeleteDBParameterGroupInput{\n\t\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\t}\n\t\t_, err := conn.DeleteDBParameterGroup(&deleteOpts)\n\t\tif err != nil {\n\t\t\tawsErr, ok := err.(awserr.Error)\n\t\t\tif ok && awsErr.Code() == \"DBParameterGroupNotFound\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif ok && awsErr.Code() == \"InvalidDBParameterGroupState\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc resourceAwsNeptuneParameterHash(v interface{}) int {\n\tvar buf bytes.Buffer\n\tm := v.(map[string]interface{})\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"name\"].(string)))\n\t\/\/ Store the value as a lower case string, to match how we store them in flattenParameters\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", strings.ToLower(m[\"value\"].(string))))\n\n\treturn hashcode.String(buf.String())\n}\n<|endoftext|>"}
{"text":"<commit_before>package message\n\nimport (\n\t\"..\/queue\"\n\t\"..\/util\"\n\t\"errors\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Channel struct {\n\tname                string\n\taddClientChan       chan util.ChanReq\n\tremoveClientChan    chan util.ChanReq\n\tbackend             queue.BackendQueue\n\tincomingMessageChan chan *Message\n\tmsgChan             chan *Message\n\tinFlightMessageChan chan *Message\n\tackMessageChan      chan util.ChanReq\n\trequeueMessageChan  chan util.ChanReq\n\tfinishMessageChan   chan util.ChanReq\n\texitChan            chan int\n\tinFlightMessages    map[string]*Message\n}\n\n\/\/ Channel constructor\nfunc NewChannel(channelName string, inMemSize int) *Channel {\n\tchannel := &Channel{name: channelName,\n\t\taddClientChan:       make(chan util.ChanReq),\n\t\tremoveClientChan:    make(chan util.ChanReq),\n\t\tbackend:             queue.NewDiskQueue(channelName),\n\t\tincomingMessageChan: make(chan *Message, 5),\n\t\tmsgChan:             make(chan *Message, inMemSize),\n\t\tinFlightMessageChan: make(chan *Message),\n\t\tackMessageChan:      make(chan util.ChanReq),\n\t\trequeueMessageChan:  make(chan util.ChanReq),\n\t\tfinishMessageChan:   make(chan util.ChanReq),\n\t\texitChan:            make(chan int),\n\t\tinFlightMessages:    make(map[string]*Message)}\n\tgo channel.Router()\n\treturn channel\n}\n\n\/\/ PutMessage writes to the appropriate incoming\n\/\/ message channel\nfunc (c *Channel) PutMessage(msg *Message) {\n\tc.incomingMessageChan <- msg\n}\n\nfunc (c *Channel) AckMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.ackMessageChan <- util.ChanReq{uuidStr, errChan}\n\treturn (<-errChan).(error)\n}\n\nfunc (c *Channel) FinishMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.finishMessageChan <- util.ChanReq{uuidStr, errChan}\n\treturn (<-errChan).(error)\n}\n\nfunc (c *Channel) RequeueMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.requeueMessageChan <- util.ChanReq{uuidStr, errChan}\n\treturn (<-errChan).(error)\n}\n\n\/\/ Router handles the muxing of Channel messages including\n\/\/ the addition of a Client to the Channel\nfunc (c *Channel) Router() {\n\thelperCloseChan := make(chan int)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-c.inFlightMessageChan:\n\t\t\t\tc.pushInFlightMessage(msg)\n\t\t\t\tgo func(msg *Message) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-time.After(60 * time.Second):\n\t\t\t\t\t\tlog.Printf(\"CHANNEL(%s): auto requeue of message(%s)\", c.name, util.UuidToStr(msg.Uuid()))\n\t\t\t\t\tcase <-msg.timerChan:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr := c.RequeueMessage(util.UuidToStr(msg.Uuid()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"ERROR: channel(%s) - %s\", c.name, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}(msg)\n\t\t\tcase requeueReq := <-c.requeueMessageChan:\n\t\t\t\tuuidStr := requeueReq.Variable.(string)\n\t\t\t\tmsg, err := c.popInFlightMessage(uuidStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: failed to requeue message(%s) - %s\", uuidStr, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tgo func(msg *Message) {\n\t\t\t\t\t\tc.PutMessage(msg)\n\t\t\t\t\t}(msg)\n\t\t\t\t}\n\t\t\t\trequeueReq.RetChan <- err\n\t\t\tcase finishReq := <-c.finishMessageChan:\n\t\t\t\tuuidStr := finishReq.Variable.(string)\n\t\t\t\t_, err := c.popInFlightMessage(uuidStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: failed to finish message(%s) - %s\", uuidStr, err.Error())\n\t\t\t\t}\n\t\t\t\tfinishReq.RetChan <- err\n\t\t\tcase ackReq := <-c.ackMessageChan:\n\t\t\t\t\/\/ uuidStr := ackReq.Variable.(string)\n\t\t\t\t\/\/ TODO: do something\n\t\t\t\tackReq.RetChan <- nil\n\t\t\tcase <-helperCloseChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.incomingMessageChan:\n\t\t\tselect {\n\t\t\tcase c.msgChan <- msg:\n\t\t\t\tlog.Printf(\"CHANNEL(%s): wrote to msgChan\", c.name)\n\t\t\tdefault:\n\t\t\t\terr := c.backend.Put(msg.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: t.backend.Put() - %s\", err.Error())\n\t\t\t\t\t\/\/ TODO: requeue?\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"CHANNEL(%s): wrote to backend\", c.name)\n\t\t\t}\n\t\tcase <-c.exitChan:\n\t\t\thelperCloseChan <- 1\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Channel) pushInFlightMessage(msg *Message) {\n\tuuidStr := util.UuidToStr(msg.Uuid())\n\tc.inFlightMessages[uuidStr] = msg\n}\n\nfunc (c *Channel) popInFlightMessage(uuidStr string) (*Message, error) {\n\tmsg, ok := c.inFlightMessages[uuidStr]\n\tif !ok {\n\t\treturn nil, errors.New(\"UUID not in flight\")\n\t}\n\tdelete(c.inFlightMessages, uuidStr)\n\tmsg.EndTimer()\n\treturn msg, nil\n}\n\n\/\/ GetMessage pulls a single message off the client channel\nfunc (c *Channel) GetMessage(block bool) *Message {\n\tvar msg *Message\n\n\tfor {\n\t\tif block {\n\t\t\tselect {\n\t\t\tcase msg = <-c.msgChan:\n\t\t\tcase <-c.backend.ReadReadyChan():\n\t\t\t\tbuf, err := c.backend.Get()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: c.backend.Get() - %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmsg = NewMessage(buf)\n\t\t\t}\n\t\t} else {\n\t\t\tselect {\n\t\t\tcase msg = <-c.msgChan:\n\t\t\tcase <-c.backend.ReadReadyChan():\n\t\t\t\tbuf, err := c.backend.Get()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: c.backend.Get() - %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmsg = NewMessage(buf)\n\t\t\tdefault:\n\t\t\t\tmsg = nil\n\t\t\t}\n\t\t}\n\n\t\tif msg != nil {\n\t\t\tc.inFlightMessageChan <- msg\n\t\t}\n\n\t\tbreak\n\t}\n\n\treturn msg\n}\n\nfunc (c *Channel) Close() error {\n\tvar err error\n\n\tlog.Printf(\"CHANNEL(%s): closing\", c.name)\n\n\tc.exitChan <- 1\n\n\terr = c.backend.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>throw away type assertion failures<commit_after>package message\n\nimport (\n\t\"..\/queue\"\n\t\"..\/util\"\n\t\"errors\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Channel struct {\n\tname                string\n\taddClientChan       chan util.ChanReq\n\tremoveClientChan    chan util.ChanReq\n\tbackend             queue.BackendQueue\n\tincomingMessageChan chan *Message\n\tmsgChan             chan *Message\n\tinFlightMessageChan chan *Message\n\tackMessageChan      chan util.ChanReq\n\trequeueMessageChan  chan util.ChanReq\n\tfinishMessageChan   chan util.ChanReq\n\texitChan            chan int\n\tinFlightMessages    map[string]*Message\n}\n\n\/\/ Channel constructor\nfunc NewChannel(channelName string, inMemSize int) *Channel {\n\tchannel := &Channel{name: channelName,\n\t\taddClientChan:       make(chan util.ChanReq),\n\t\tremoveClientChan:    make(chan util.ChanReq),\n\t\tbackend:             queue.NewDiskQueue(channelName),\n\t\tincomingMessageChan: make(chan *Message, 5),\n\t\tmsgChan:             make(chan *Message, inMemSize),\n\t\tinFlightMessageChan: make(chan *Message),\n\t\tackMessageChan:      make(chan util.ChanReq),\n\t\trequeueMessageChan:  make(chan util.ChanReq),\n\t\tfinishMessageChan:   make(chan util.ChanReq),\n\t\texitChan:            make(chan int),\n\t\tinFlightMessages:    make(map[string]*Message)}\n\tgo channel.Router()\n\treturn channel\n}\n\n\/\/ PutMessage writes to the appropriate incoming\n\/\/ message channel\nfunc (c *Channel) PutMessage(msg *Message) {\n\tc.incomingMessageChan <- msg\n}\n\nfunc (c *Channel) AckMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.ackMessageChan <- util.ChanReq{uuidStr, errChan}\n\terr, _ := (<-errChan).(error)\n\treturn err\n}\n\nfunc (c *Channel) FinishMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.finishMessageChan <- util.ChanReq{uuidStr, errChan}\n\terr, _ := (<-errChan).(error)\n\treturn err\n}\n\nfunc (c *Channel) RequeueMessage(uuidStr string) error {\n\terrChan := make(chan interface{})\n\tc.requeueMessageChan <- util.ChanReq{uuidStr, errChan}\n\terr, _ := (<-errChan).(error)\n\treturn err\n}\n\n\/\/ Router handles the muxing of Channel messages including\n\/\/ the addition of a Client to the Channel\nfunc (c *Channel) Router() {\n\thelperCloseChan := make(chan int)\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-c.inFlightMessageChan:\n\t\t\t\tc.pushInFlightMessage(msg)\n\t\t\t\tgo func(msg *Message) {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-time.After(60 * time.Second):\n\t\t\t\t\t\tlog.Printf(\"CHANNEL(%s): auto requeue of message(%s)\", c.name, util.UuidToStr(msg.Uuid()))\n\t\t\t\t\tcase <-msg.timerChan:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr := c.RequeueMessage(util.UuidToStr(msg.Uuid()))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"ERROR: channel(%s) - %s\", c.name, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}(msg)\n\t\t\tcase requeueReq := <-c.requeueMessageChan:\n\t\t\t\tuuidStr := requeueReq.Variable.(string)\n\t\t\t\tmsg, err := c.popInFlightMessage(uuidStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: failed to requeue message(%s) - %s\", uuidStr, err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tgo func(msg *Message) {\n\t\t\t\t\t\tc.PutMessage(msg)\n\t\t\t\t\t}(msg)\n\t\t\t\t}\n\t\t\t\trequeueReq.RetChan <- err\n\t\t\tcase finishReq := <-c.finishMessageChan:\n\t\t\t\tuuidStr := finishReq.Variable.(string)\n\t\t\t\t_, err := c.popInFlightMessage(uuidStr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: failed to finish message(%s) - %s\", uuidStr, err.Error())\n\t\t\t\t}\n\t\t\t\tfinishReq.RetChan <- err\n\t\t\tcase ackReq := <-c.ackMessageChan:\n\t\t\t\t\/\/ uuidStr := ackReq.Variable.(string)\n\t\t\t\t\/\/ TODO: acks are wierd in the sense that they're not technically necessary...\n\t\t\t\t\/\/ it's possible we don't need them at all...\n\t\t\t\tackReq.RetChan <- nil\n\t\t\tcase <-helperCloseChan:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.incomingMessageChan:\n\t\t\tselect {\n\t\t\tcase c.msgChan <- msg:\n\t\t\t\tlog.Printf(\"CHANNEL(%s): wrote to msgChan\", c.name)\n\t\t\tdefault:\n\t\t\t\terr := c.backend.Put(msg.Data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: t.backend.Put() - %s\", err.Error())\n\t\t\t\t\t\/\/ TODO: requeue?\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"CHANNEL(%s): wrote to backend\", c.name)\n\t\t\t}\n\t\tcase <-c.exitChan:\n\t\t\thelperCloseChan <- 1\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Channel) pushInFlightMessage(msg *Message) {\n\tuuidStr := util.UuidToStr(msg.Uuid())\n\tc.inFlightMessages[uuidStr] = msg\n}\n\nfunc (c *Channel) popInFlightMessage(uuidStr string) (*Message, error) {\n\tmsg, ok := c.inFlightMessages[uuidStr]\n\tif !ok {\n\t\treturn nil, errors.New(\"UUID not in flight\")\n\t}\n\tdelete(c.inFlightMessages, uuidStr)\n\tmsg.EndTimer()\n\treturn msg, nil\n}\n\n\/\/ GetMessage pulls a single message off the client channel\nfunc (c *Channel) GetMessage(block bool) *Message {\n\tvar msg *Message\n\n\tfor {\n\t\tif block {\n\t\t\tselect {\n\t\t\tcase msg = <-c.msgChan:\n\t\t\tcase <-c.backend.ReadReadyChan():\n\t\t\t\tbuf, err := c.backend.Get()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: c.backend.Get() - %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmsg = NewMessage(buf)\n\t\t\t}\n\t\t} else {\n\t\t\tselect {\n\t\t\tcase msg = <-c.msgChan:\n\t\t\tcase <-c.backend.ReadReadyChan():\n\t\t\t\tbuf, err := c.backend.Get()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"ERROR: c.backend.Get() - %s\", err.Error())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmsg = NewMessage(buf)\n\t\t\tdefault:\n\t\t\t\tmsg = nil\n\t\t\t}\n\t\t}\n\n\t\tif msg != nil {\n\t\t\tc.inFlightMessageChan <- msg\n\t\t}\n\n\t\tbreak\n\t}\n\n\treturn msg\n}\n\nfunc (c *Channel) Close() error {\n\tvar err error\n\n\tlog.Printf(\"CHANNEL(%s): closing\", c.name)\n\n\tc.exitChan <- 1\n\n\terr = c.backend.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package mailmessage\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net\/mail\"\n\t\/\/\"net\/textproto\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tCRLF               = \"\\r\\n\"\n\tMSG_MULTIPARTMIXED = iota\n\tMSG_MULTIPARTALTERNATIVE\n\tMSG_MESSAGE\n)\n\ntype Message struct {\n\tKind     int\n\tHeader   mail.Header\n\ttempbody io.Reader\n\tPath     string\n\tFile     *os.File\n\tChildren []*Message\n\tdecoded  bool\n}\n\nfunc (m *Message) Purge() {\n\tif m.File != nil {\n\t\tm.File.Close()\n\t\tm.File = nil\n\t}\n\tif len(m.Path) > 0 {\n\t\tos.Remove(m.Path)\n\t}\n\tif m.Children != nil {\n\t\tfor k := range m.Children {\n\t\t\tm.Children[k].Purge()\n\t\t}\n\t}\n}\n\nfunc (m *Message) HTML() string {\n\tvar rdr *os.File\n\tif m.Kind == MSG_MULTIPARTALTERNATIVE {\n\t\t\/\/ find html\n\t\tfor k := range m.Children {\n\t\t\tct := m.Children[k].Header.Get(\"Content-Type\")\n\t\t\tif strings.HasPrefix(ct, \"text\/html\") {\n\t\t\t\trdr = m.Children[k].File\n\t\t\t\tlog.Println(\"^^^ HTML HEADER:::\", m.Children[k].Header)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else if m.Kind == MSG_MESSAGE {\n\t\tct := m.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(ct, \"text\/html\") {\n\t\t\trdr = m.File\n\t\t}\n\t}\n\tif rdr == nil {\n\t\treturn \"\"\n\t}\n\tvar buffer bytes.Buffer\n\tio.Copy(&buffer, rdr)\n\trdr.Seek(0, 0)\n\treturn buffer.String()\n}\n\nfunc (m *Message) Plaintext() string {\n\tvar rdr io.Reader\n\tif m.Kind == MSG_MULTIPARTALTERNATIVE {\n\t\t\/\/ find text\n\t\tfor k := range m.Children {\n\t\t\tct := m.Children[k].Header.Get(\"Content-Type\")\n\t\t\tif strings.HasPrefix(ct, \"text\/plain\") {\n\t\t\t\trdr = m.Children[k].File\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else if m.Kind == MSG_MESSAGE {\n\t\tct := m.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(ct, \"text\/plain\") {\n\t\t\trdr = m.File\n\t\t}\n\t}\n\tif rdr == nil {\n\t\treturn \"\"\n\t}\n\tvar buffer bytes.Buffer\n\tio.Copy(&buffer, rdr)\n\treturn buffer.String()\n}\n\nfunc New(rdr *bufio.Reader) (*Message, error) {\n\n\tline, err := rdr.ReadString('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strings.HasPrefix(line, \"+OK\") {\n\t\tlog.Println(\"NEW MAIL\", line[4:])\n\t} else if strings.HasPrefix(line, \"-ERR\") {\n\t\treturn nil, errors.New(line[5:])\n\t} else {\n\t\treturn nil, errors.New(\"Unknown pop3 server response `\" + line + \"`\")\n\t}\n\t\/\/ save to a temporary file\n\tnowf := \"msg_\" + strconv.FormatInt(time.Now().Unix(), 10) + \".dat\"\n\tfil0, err := os.OpenFile(path.Join(os.TempDir(), nowf), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor {\n\t\tline, err = rdr.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif line == \".\"+CRLF {\n\t\t\tbreak\n\t\t}\n\t\t_, err = fil0.WriteString(line)\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROROROR\", err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfil0.Seek(0, 0)\n\tmainm, err := mail.ReadMessage(fil0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontentType := mainm.Header.Get(\"Content-Type\")\n\tif strings.HasPrefix(contentType, \"multipart\/mixed\") {\n\t\treturn multipartMessage(mainm, fil0)\n\t} else if strings.HasPrefix(contentType, \"multipart\/alternative\") {\n\t\treturn alternativeMessage(mainm, fil0)\n\t}\n\treturn basicMessage(mainm, fil0)\n}\n\nfunc basicMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\tmsg0 := &Message{}\n\tmsg0.Header = mainm.Header\n\tmsg0.File = f\n\tif f != nil {\n\t\tmsg0.Path = f.Name()\n\t}\n\tmsg0.Kind = MSG_MESSAGE\n\tmsg0.tempbody = mainm.Body\n\n\ttf2n, tf2, _ := tempFile()\n\tio.Copy(tf2, msg0.tempbody)\n\n\tif f != nil {\n\t\tfn := f.Name()\n\t\tf.Close()\n\t\tos.Remove(fn)\n\t}\n\ttf2.Seek(0, 0)\n\tmsg0.File = tf2\n\tmsg0.Path = tf2n\n\n\tcte := msg0.Header.Get(\"Content-Transfer-Encoding\")\n\tcte = strings.TrimSpace(cte)\n\tcte = strings.ToLower(cte)\n\n\tif cte == \"base64\" && !msg0.decoded {\n\t\tbio := bufio.NewReader(msg0.File)\n\t\ttf3n, tf3, _ := tempFile()\n\t\tfor {\n\t\t\tline, err := bio.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasSuffix(line, CRLF) {\n\t\t\t\ttf3.WriteString(line[:len(line)-2])\n\t\t\t} else {\n\t\t\t\ttf3.WriteString(line[:len(line)-1])\n\t\t\t}\n\t\t}\n\t\ttf3.Sync()\n\t\ttf3.Seek(0, 0)\n\n\t\ttrdr := base64.NewDecoder(base64.StdEncoding, tf3)\n\t\ttf2.Seek(0, 0)\n\t\ttf2.Truncate(0)\n\t\tlog.Println(io.Copy(tf2, trdr))\n\t\ttf2.Sync()\n\t\ttf2.Seek(0, 0)\n\t\ttf3.Close()\n\t\tos.Remove(tf3n)\n\t\tmsg0.decoded = true\n\t} else if cte == \"quoted-printable\" && !msg0.decoded {\n\t\tbio := newQuotedPrintableReader(msg0.File)\n\t\ttf3n, tf3, _ := tempFile()\n\t\tio.Copy(tf3, bio)\n\t\ttf3.Sync()\n\t\ttf3.Seek(0, 0)\n\t\ttf2.Seek(0, 0)\n\t\ttf2.Truncate(0)\n\t\tio.Copy(tf2, tf3)\n\t\ttf2.Sync()\n\t\ttf2.Seek(0, 0)\n\t\ttf3.Close()\n\t\tos.Remove(tf3n)\n\t\tmsg0.decoded = true\n\t}\n\n\treturn msg0, nil\n}\n\nfunc alternativeMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\ta, b := multipartMessage(mainm, f)\n\tif b != nil {\n\t\treturn nil, b\n\t}\n\ta.Kind = MSG_MULTIPARTALTERNATIVE\n\treturn a, b\n}\n\nfunc multipartMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\tct := mainm.Header.Get(\"Content-Type\")\n\tlog.Println(\"it's multipart mixed\", ct)\n\tboundary, err := getBoundary(ct)\n\tlog.Println(\"`\" + boundary + \"`\")\n\tif err != nil {\n\t\tlog.Println(\"BOUNDARY ERROR\", err)\n\t\treturn nil, err\n\t}\n\tboundary = strings.Trim(boundary, \"\\\"\")\n\trdr := bufio.NewReader(mainm.Body)\n\tfor {\n\t\t\/\/ read first boundary\n\t\tline, lerr := rdr.ReadString('\\n')\n\t\t\/\/log.Println(line)\n\t\tif lerr != nil {\n\t\t\t\/\/log.Println(\"FGHG ERROR\", lerr)\n\t\t\tif lerr.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\treturn nil, lerr\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(line, \"--\"+boundary) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tmsg0 := &Message{}\n\tmsg0.File = f\n\tif f != nil {\n\t\tmsg0.Path = f.Name()\n\t}\n\tmsg0.Kind = MSG_MULTIPARTMIXED\n\tmsg0.Header = mainm.Header\n\tmsg0.Children = make([]*Message, 0)\n\n\tbound1 := \"--\" + boundary\n\tbound2 := \"--\" + boundary + \"--\"\n\n\tcont0 := true\n\n\tfor cont0 {\n\t\t_, tf, err := tempFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor {\n\t\t\tline, err := rdr.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, bound2) {\n\t\t\t\tcont0 = false\n\t\t\t\tbreak\n\t\t\t} else if strings.HasPrefix(line, bound1) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttf.WriteString(line)\n\t\t}\n\t\ttf.Seek(0, 0)\n\t\tnmsg, err := mail.ReadMessage(tf)\n\t\tif err != nil {\n\t\t\tlog.Println(\"nmsg, err := mail.ReadMessage(tf)\", err)\n\t\t\tcontinue\n\t\t}\n\t\tvar mmmsg *Message\n\t\tcontentType := nmsg.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(contentType, \"multipart\/mixed\") {\n\t\t\tmmmsg, err = multipartMessage(nmsg, tf)\n\t\t} else if strings.HasPrefix(contentType, \"multipart\/alternative\") {\n\t\t\tmmmsg, err = alternativeMessage(nmsg, tf)\n\t\t} else {\n\t\t\tmmmsg, err = basicMessage(nmsg, tf)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(\"err johnson\", err)\n\t\t\tcontinue\n\t\t}\n\t\tmsg0.Children = append(msg0.Children, mmmsg)\n\t}\n\tf.Close()\n\tos.Remove(msg0.Path)\n\tmsg0.Path = \"\"\n\tmsg0.File = nil\n\treturn msg0, nil\n}\n\nfunc getBoundary(contentType string) (string, error) {\n\tstrs := strings.Split(contentType, \";\")\n\tfor _, v := range strs {\n\t\tv = strings.TrimSpace(v)\n\t\tif strings.HasPrefix(v, \"boundary=\") {\n\t\t\treturn v[9:], nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"Boundary not found!\")\n}\n\nvar (\n\ttfi = 1\n)\n\nfunc tempFile() (string, *os.File, error) {\n\ttfi++\n\tbs := make([]byte, 6)\n\trand.Read(bs)\n\tfn := hex.EncodeToString(bs) + \"_\" + strconv.FormatInt(time.Now().Unix(), 10) + \"_\" + strconv.Itoa(tfi) + \".dat\"\n\tp0 := path.Join(os.TempDir(), fn)\n\tfile, err := os.OpenFile(p0, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)\n\treturn p0, file, err\n}\n<commit_msg>treat multipart\/related as multipart\/mixed<commit_after>package mailmessage\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net\/mail\"\n\t\/\/\"net\/textproto\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tCRLF               = \"\\r\\n\"\n\tMSG_MULTIPARTMIXED = iota\n\tMSG_MULTIPARTALTERNATIVE\n\tMSG_MESSAGE\n)\n\ntype Message struct {\n\tKind     int\n\tHeader   mail.Header\n\ttempbody io.Reader\n\tPath     string\n\tFile     *os.File\n\tChildren []*Message\n\tdecoded  bool\n}\n\nfunc (m *Message) Purge() {\n\tif m.File != nil {\n\t\tm.File.Close()\n\t\tm.File = nil\n\t}\n\tif len(m.Path) > 0 {\n\t\tos.Remove(m.Path)\n\t}\n\tif m.Children != nil {\n\t\tfor k := range m.Children {\n\t\t\tm.Children[k].Purge()\n\t\t}\n\t}\n}\n\nfunc (m *Message) HTML() string {\n\tvar rdr *os.File\n\tif m.Kind == MSG_MULTIPARTALTERNATIVE {\n\t\t\/\/ find html\n\t\tfor k := range m.Children {\n\t\t\tct := m.Children[k].Header.Get(\"Content-Type\")\n\t\t\tif strings.HasPrefix(ct, \"text\/html\") {\n\t\t\t\trdr = m.Children[k].File\n\t\t\t\tlog.Println(\"^^^ HTML HEADER:::\", m.Children[k].Header)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else if m.Kind == MSG_MESSAGE {\n\t\tct := m.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(ct, \"text\/html\") {\n\t\t\trdr = m.File\n\t\t}\n\t}\n\tif rdr == nil {\n\t\treturn \"\"\n\t}\n\tvar buffer bytes.Buffer\n\tio.Copy(&buffer, rdr)\n\trdr.Seek(0, 0)\n\treturn buffer.String()\n}\n\nfunc (m *Message) Plaintext() string {\n\tvar rdr io.Reader\n\tif m.Kind == MSG_MULTIPARTALTERNATIVE {\n\t\t\/\/ find text\n\t\tfor k := range m.Children {\n\t\t\tct := m.Children[k].Header.Get(\"Content-Type\")\n\t\t\tif strings.HasPrefix(ct, \"text\/plain\") {\n\t\t\t\trdr = m.Children[k].File\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else if m.Kind == MSG_MESSAGE {\n\t\tct := m.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(ct, \"text\/plain\") {\n\t\t\trdr = m.File\n\t\t}\n\t}\n\tif rdr == nil {\n\t\treturn \"\"\n\t}\n\tvar buffer bytes.Buffer\n\tio.Copy(&buffer, rdr)\n\treturn buffer.String()\n}\n\nfunc New(rdr *bufio.Reader) (*Message, error) {\n\n\tline, err := rdr.ReadString('\\n')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strings.HasPrefix(line, \"+OK\") {\n\t\tlog.Println(\"NEW MAIL\", line[4:])\n\t} else if strings.HasPrefix(line, \"-ERR\") {\n\t\treturn nil, errors.New(line[5:])\n\t} else {\n\t\treturn nil, errors.New(\"Unknown pop3 server response `\" + line + \"`\")\n\t}\n\t\/\/ save to a temporary file\n\tnowf := \"msg_\" + strconv.FormatInt(time.Now().Unix(), 10) + \".dat\"\n\tfil0, err := os.OpenFile(path.Join(os.TempDir(), nowf), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor {\n\t\tline, err = rdr.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif line == \".\"+CRLF {\n\t\t\tbreak\n\t\t}\n\t\t_, err = fil0.WriteString(line)\n\t\tif err != nil {\n\t\t\tlog.Println(\"ERROROROR\", err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfil0.Seek(0, 0)\n\tmainm, err := mail.ReadMessage(fil0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontentType := mainm.Header.Get(\"Content-Type\")\n\tif strings.HasPrefix(contentType, \"multipart\/mixed\") || strings.HasPrefix(contentType, \"multipart\/related\") {\n\t\treturn multipartMessage(mainm, fil0)\n\t} else if strings.HasPrefix(contentType, \"multipart\/alternative\") {\n\t\treturn alternativeMessage(mainm, fil0)\n\t}\n\treturn basicMessage(mainm, fil0)\n}\n\nfunc basicMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\tmsg0 := &Message{}\n\tmsg0.Header = mainm.Header\n\tmsg0.File = f\n\tif f != nil {\n\t\tmsg0.Path = f.Name()\n\t}\n\tmsg0.Kind = MSG_MESSAGE\n\tmsg0.tempbody = mainm.Body\n\n\ttf2n, tf2, _ := tempFile()\n\tio.Copy(tf2, msg0.tempbody)\n\n\tif f != nil {\n\t\tfn := f.Name()\n\t\tf.Close()\n\t\tos.Remove(fn)\n\t}\n\ttf2.Seek(0, 0)\n\tmsg0.File = tf2\n\tmsg0.Path = tf2n\n\n\tcte := msg0.Header.Get(\"Content-Transfer-Encoding\")\n\tcte = strings.TrimSpace(cte)\n\tcte = strings.ToLower(cte)\n\n\tif cte == \"base64\" && !msg0.decoded {\n\t\tbio := bufio.NewReader(msg0.File)\n\t\ttf3n, tf3, _ := tempFile()\n\t\tfor {\n\t\t\tline, err := bio.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasSuffix(line, CRLF) {\n\t\t\t\ttf3.WriteString(line[:len(line)-2])\n\t\t\t} else {\n\t\t\t\ttf3.WriteString(line[:len(line)-1])\n\t\t\t}\n\t\t}\n\t\ttf3.Sync()\n\t\ttf3.Seek(0, 0)\n\n\t\ttrdr := base64.NewDecoder(base64.StdEncoding, tf3)\n\t\ttf2.Seek(0, 0)\n\t\ttf2.Truncate(0)\n\t\tlog.Println(io.Copy(tf2, trdr))\n\t\ttf2.Sync()\n\t\ttf2.Seek(0, 0)\n\t\ttf3.Close()\n\t\tos.Remove(tf3n)\n\t\tmsg0.decoded = true\n\t} else if cte == \"quoted-printable\" && !msg0.decoded {\n\t\tbio := newQuotedPrintableReader(msg0.File)\n\t\ttf3n, tf3, _ := tempFile()\n\t\tio.Copy(tf3, bio)\n\t\ttf3.Sync()\n\t\ttf3.Seek(0, 0)\n\t\ttf2.Seek(0, 0)\n\t\ttf2.Truncate(0)\n\t\tio.Copy(tf2, tf3)\n\t\ttf2.Sync()\n\t\ttf2.Seek(0, 0)\n\t\ttf3.Close()\n\t\tos.Remove(tf3n)\n\t\tmsg0.decoded = true\n\t}\n\n\treturn msg0, nil\n}\n\nfunc alternativeMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\ta, b := multipartMessage(mainm, f)\n\tif b != nil {\n\t\treturn nil, b\n\t}\n\ta.Kind = MSG_MULTIPARTALTERNATIVE\n\treturn a, b\n}\n\nfunc multipartMessage(mainm *mail.Message, f *os.File) (*Message, error) {\n\tct := mainm.Header.Get(\"Content-Type\")\n\tlog.Println(\"it's multipart mixed\", ct)\n\tboundary, err := getBoundary(ct)\n\tlog.Println(\"`\" + boundary + \"`\")\n\tif err != nil {\n\t\tlog.Println(\"BOUNDARY ERROR\", err)\n\t\treturn nil, err\n\t}\n\tboundary = strings.Trim(boundary, \"\\\"\")\n\trdr := bufio.NewReader(mainm.Body)\n\tfor {\n\t\t\/\/ read first boundary\n\t\tline, lerr := rdr.ReadString('\\n')\n\t\t\/\/log.Println(line)\n\t\tif lerr != nil {\n\t\t\t\/\/log.Println(\"FGHG ERROR\", lerr)\n\t\t\tif lerr.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\treturn nil, lerr\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(line, \"--\"+boundary) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tmsg0 := &Message{}\n\tmsg0.File = f\n\tif f != nil {\n\t\tmsg0.Path = f.Name()\n\t}\n\tmsg0.Kind = MSG_MULTIPARTMIXED\n\tmsg0.Header = mainm.Header\n\tmsg0.Children = make([]*Message, 0)\n\n\tbound1 := \"--\" + boundary\n\tbound2 := \"--\" + boundary + \"--\"\n\n\tcont0 := true\n\n\tfor cont0 {\n\t\t_, tf, err := tempFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor {\n\t\t\tline, err := rdr.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif strings.HasPrefix(line, bound2) {\n\t\t\t\tcont0 = false\n\t\t\t\tbreak\n\t\t\t} else if strings.HasPrefix(line, bound1) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttf.WriteString(line)\n\t\t}\n\t\ttf.Seek(0, 0)\n\t\tnmsg, err := mail.ReadMessage(tf)\n\t\tif err != nil {\n\t\t\tlog.Println(\"nmsg, err := mail.ReadMessage(tf)\", err)\n\t\t\tcontinue\n\t\t}\n\t\tvar mmmsg *Message\n\t\tcontentType := nmsg.Header.Get(\"Content-Type\")\n\t\tif strings.HasPrefix(contentType, \"multipart\/mixed\") || strings.HasPrefix(contentType, \"multipart\/related\") {\n\t\t\tmmmsg, err = multipartMessage(nmsg, tf)\n\t\t} else if strings.HasPrefix(contentType, \"multipart\/alternative\") {\n\t\t\tmmmsg, err = alternativeMessage(nmsg, tf)\n\t\t} else {\n\t\t\tmmmsg, err = basicMessage(nmsg, tf)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(\"err johnson\", err)\n\t\t\tcontinue\n\t\t}\n\t\tmsg0.Children = append(msg0.Children, mmmsg)\n\t}\n\tf.Close()\n\tos.Remove(msg0.Path)\n\tmsg0.Path = \"\"\n\tmsg0.File = nil\n\treturn msg0, nil\n}\n\nfunc getBoundary(contentType string) (string, error) {\n\tstrs := strings.Split(contentType, \";\")\n\tfor _, v := range strs {\n\t\tv = strings.TrimSpace(v)\n\t\tif strings.HasPrefix(v, \"boundary=\") {\n\t\t\treturn v[9:], nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"Boundary not found!\")\n}\n\nvar (\n\ttfi = 1\n)\n\nfunc tempFile() (string, *os.File, error) {\n\ttfi++\n\tbs := make([]byte, 6)\n\trand.Read(bs)\n\tfn := hex.EncodeToString(bs) + \"_\" + strconv.FormatInt(time.Now().Unix(), 10) + \"_\" + strconv.Itoa(tfi) + \".dat\"\n\tp0 := path.Join(os.TempDir(), fn)\n\tfile, err := os.OpenFile(p0, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)\n\treturn p0, file, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/smartystreets\/smartystreets-go-sdk\/us-autocomplete-api\"\n\t\"github.com\/smartystreets\/smartystreets-go-sdk\/wireup\"\n)\n\nfunc main() {\n\tlog.SetFlags(log.Ltime)\n\n\tclient := wireup.NewClientBuilder().\n\t\tWithSecretKeyCredential(os.Getenv(\"SMARTY_AUTH_ID\"), os.Getenv(\"SMARTY_AUTH_TOKEN\")).\n\t\tWithDebugHTTPOutput(). \/\/ uncomment this line to see detailed HTTP request\/response information.\n\t\tBuildUSAutocompleteAPIClient()\n\n\tlookup := &autocomplete.Lookup{Prefix: \"123 main\"}\n\n\tif err := client.SendLookup(lookup); err != nil {\n\t\tlog.Fatal(\"Error sending batch:\", err)\n\t}\n\n\tfmt.Println(\"Results for input:\")\n\tfmt.Println()\n\tfor s, suggestion := range lookup.Results {\n\t\tfmt.Println(\"  Suggestion:\", s)\n\t\tfmt.Println(\" \", suggestion.Text)\n\t\tfmt.Println(\" \", suggestion.StreetLine)\n\t\tfmt.Println(\" \", suggestion.City)\n\t\tfmt.Println(\" \", suggestion.State)\n\t\tfmt.Println()\n\t}\n}\n<commit_msg>Commented out diagnostic output.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/smartystreets\/smartystreets-go-sdk\/us-autocomplete-api\"\n\t\"github.com\/smartystreets\/smartystreets-go-sdk\/wireup\"\n)\n\nfunc main() {\n\tlog.SetFlags(log.Ltime)\n\n\tclient := wireup.NewClientBuilder().\n\t\tWithSecretKeyCredential(os.Getenv(\"SMARTY_AUTH_ID\"), os.Getenv(\"SMARTY_AUTH_TOKEN\")).\n\t\t\/\/WithDebugHTTPOutput(). \/\/ uncomment this line to see detailed HTTP request\/response information.\n\t\tBuildUSAutocompleteAPIClient()\n\n\tlookup := &autocomplete.Lookup{Prefix: \"123 main\"}\n\n\tif err := client.SendLookup(lookup); err != nil {\n\t\tlog.Fatal(\"Error sending batch:\", err)\n\t}\n\n\tfmt.Println(\"Results for input:\")\n\tfmt.Println()\n\tfor s, suggestion := range lookup.Results {\n\t\tfmt.Println(\"  Suggestion:\", s)\n\t\tfmt.Println(\" \", suggestion.Text)\n\t\tfmt.Println(\" \", suggestion.StreetLine)\n\t\tfmt.Println(\" \", suggestion.City)\n\t\tfmt.Println(\" \", suggestion.State)\n\t\tfmt.Println()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Package email is designed to provide an \"email interface for humans.\"\n\/\/Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.\npackage email\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"mime\"\n\t\"mime\/multipart\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"net\/textproto\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tMAX_LINE_LENGTH = 76 \/\/The maximum line length per RFC 2045\n)\n\n\/\/Email is the type used for email messages\ntype Email struct {\n\tFrom        string\n\tTo          []string\n\tBcc         []string\n\tCc          []string\n\tSubject     string\n\tText        string \/\/Plaintext message (optional)\n\tHtml        string \/\/Html message (optional)\n\tHeaders     textproto.MIMEHeader\n\tAttachments map[string]*Attachment\n\tReadReceipt []string\n}\n\n\/\/NewEmail creates an Email, and returns the pointer to it.\nfunc NewEmail() *Email {\n\treturn &Email{Attachments: make(map[string]*Attachment), Headers: textproto.MIMEHeader{}}\n}\n\n\/\/Attach is used to attach a file to the email.\n\/\/It attempts to open the file referenced by filename and, if successful, creates an Attachment.\n\/\/This Attachment is then appended to the slice of Email.Attachments.\n\/\/The function will then return the Attachment for reference, as well as nil for the error, if successful.\nfunc (e *Email) Attach(filename string) (a *Attachment, err error) {\n\t\/\/Check if the file exists, return any error\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\t\/\/Read the file, and set the appropriate headers\n\tbuffer, _ := ioutil.ReadFile(filename)\n\te.Attachments[filename] = &Attachment{\n\t\tFilename: filename,\n\t\tHeader:   textproto.MIMEHeader{},\n\t\tContent:  buffer}\n\tat := e.Attachments[filename]\n\t\/\/Get the Content-Type to be used in the MIMEHeader\n\tct := mime.TypeByExtension(filepath.Ext(filename))\n\tif ct != \"\" {\n\t\tat.Header.Set(\"Content-Type\", ct)\n\t} else {\n\t\t\/\/If the Content-Type is blank, set the Content-Type to \"application\/octet-stream\"\n\t\tat.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\t}\n\tat.Header.Set(\"Content-Disposition\", fmt.Sprintf(\"attachment;\\r\\n filename=\\\"%s\\\"\", filename))\n\tat.Header.Set(\"Content-Transfer-Encoding\", \"base64\")\n\treturn e.Attachments[filename], nil\n}\n\n\/\/Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.\nfunc (e *Email) Bytes() ([]byte, error) {\n\tbuff := &bytes.Buffer{}\n\tw := multipart.NewWriter(buff)\n\t\/\/Set the appropriate headers (overwriting any conflicts)\n\t\/\/Leave out Bcc (only included in envelope headers)\n\t\/\/TODO: Support wrapping on 76 characters (ref: MIME RFC)\n\te.Headers.Set(\"To\", strings.Join(e.To, \",\"))\n\tif e.Cc != nil {\n\t\te.Headers.Set(\"Cc\", strings.Join(e.Cc, \",\"))\n\t}\n\te.Headers.Set(\"From\", e.From)\n\te.Headers.Set(\"Subject\", e.Subject)\n\tif len(e.ReadReceipt) != 0 {\n\t\te.Headers.Set(\"Disposition-Notification-To\", strings.Join(e.ReadReceipt, \",\"))\n\t}\n\te.Headers.Set(\"MIME-Version\", \"1.0\")\n\te.Headers.Set(\"Content-Type\", fmt.Sprintf(\"multipart\/mixed;\\r\\n boundary=%s\\r\\n\", w.Boundary()))\n\n\t\/\/Write the envelope headers (including any custom headers)\n\tif err := headerToBytes(buff, e.Headers); err != nil {\n\t}\n\t\/\/Start the multipart\/mixed part\n\tfmt.Fprintf(buff, \"--%s\\r\\n\", w.Boundary())\n\theader := textproto.MIMEHeader{}\n\t\/\/Check to see if there is a Text or HTML field\n\tif e.Text != \"\" || e.Html != \"\" {\n\t\tsubWriter := multipart.NewWriter(buff)\n\t\t\/\/Create the multipart alternative part\n\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"multipart\/alternative;\\r\\n boundary=%s\\r\\n\", subWriter.Boundary()))\n\t\t\/\/Write the header\n\t\tif err := headerToBytes(buff, header); err != nil {\n\n\t\t}\n\t\t\/\/Create the body sections\n\t\tif e.Text != \"\" {\n\t\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"text\/plain; charset=UTF-8\"))\n\t\t\t\/*part, err := subWriter.CreatePart(header)\n\t\t\tif err != nil {\n\n\t\t\t}*\/\n\t\t\t\/\/ Write the text, splitting it into chunks of MAX_LINE_LENGTH\n\t\t\t\/\/splitStr := lineSplit(e.Text)\n\t\t}\n\t\tif e.Html != \"\" {\n\t\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"text\/html; charset=UTF-8\"))\n\t\t\theader.Set(\"Content-Transfer-Encoding\", \"quoted-printable\")\n\t\t\tsubWriter.CreatePart(header)\n\t\t\t\/\/ Write the text\n\t\t\tif err := quotePrintEncode(buff, e.Html); err != nil {\n\n\t\t\t}\n\t\t}\n\t\tsubWriter.Close()\n\t}\n\t\/\/Create attachment part, if necessary\n\tif e.Attachments != nil {\n\t\tfor _, a := range e.Attachments {\n\t\t\tap, err := w.CreatePart(a.Header)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t\/\/Write the base64Wrapped content to the part\n\t\t\tbase64Wrap(ap, a.Content)\n\t\t}\n\t}\n\tw.Close()\n\treturn buff.Bytes(), nil\n}\n\n\/\/Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail\n\/\/This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message\nfunc (e *Email) Send(addr string, a smtp.Auth) error {\n\t\/\/Check to make sure there is at least one recipient and one \"From\" address\n\tif e.From == \"\" || (len(e.To) == 0 && len(e.Cc) == 0 && len(e.Bcc) == 0) {\n\t\treturn errors.New(\"Must specify at least one From address and one To address\")\n\t}\n\t\/\/ Merge the To, Cc, and Bcc fields\n\tto := append(append(e.To, e.Cc...), e.Bcc...)\n\tfrom, err := mail.ParseAddress(e.From)\n\tif err != nil {\n\t\treturn err\n\t}\n\traw, err := e.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn smtp.SendMail(addr, a, from.Address, to, raw)\n}\n\n\/\/Attachment is a struct representing an email attachment.\n\/\/Based on the mime\/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question\ntype Attachment struct {\n\tFilename string\n\tHeader   textproto.MIMEHeader\n\tContent  []byte\n}\n\n\/\/lineSplit splits the given string into lines of 76 characters at the most\n\/*func lineSplit(s string) string {\n\tfor i, c := range s {\n\n\t}\n\treturn \"\"\n}*\/\n\n\/\/quotePrintEncode writes the quoted-printable text to the IO Writer\nfunc quotePrintEncode(w io.Writer, s string) error {\n\t\/\/ Basic rules (comments to be removed once this function is fully implemented)\n\t\/\/ * If character is printable, it can be represented AS IS\n\t\/\/ * Lines must have a max of 76 characters\n\t\/\/ * Lines must not end with whitespace\n\t\/\/\t\t- Rather, append a soft break (=) to the end of the line after the space for preservation\n\t\/\/ *\n\t_, err := fmt.Fprintf(w, \"%s\\r\\n\", s)\n\t\/\/Split into MAX_LINE_LENGTH chunks, with needed soft breaks\n\tfor i := 0; i < MAX_LINE_LENGTH; i++ {\n\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)\n\/\/The output is then written to the specified io.Writer\nfunc base64Wrap(w io.Writer, b []byte) {\n\tencoded := base64.StdEncoding.EncodeToString(b)\n\tfor i := 0; i < len(encoded); i += 76 {\n\t\t\/\/Do we need to print 76 characters, or the rest of the string?\n\t\tif len(encoded)-i < 76 {\n\t\t\tfmt.Fprintf(w, \"%s\\r\\n\", encoded[i:])\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"%s\\r\\n\", encoded[i:i+76])\n\t\t}\n\t}\n}\n\n\/\/headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer\nfunc headerToBytes(w io.Writer, t textproto.MIMEHeader) error {\n\tfor k, v := range t {\n\t\t\/\/Write the header key\n\t\t_, err := fmt.Fprintf(w, \"%s:\", k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/Write each value in the header\n\t\tfor _, c := range v {\n\t\t\t_, err := fmt.Fprintf(w, \" %s\\r\\n\", c)\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<commit_msg>Got line wrapping working in quotePrintEncode - just need to implement special char encoding.<commit_after>\/\/Package email is designed to provide an \"email interface for humans.\"\n\/\/Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.\npackage email\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"mime\"\n\t\"mime\/multipart\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"net\/textproto\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tMAX_LINE_LENGTH = 76 \/\/The maximum line length per RFC 2045\n)\n\n\/\/Email is the type used for email messages\ntype Email struct {\n\tFrom        string\n\tTo          []string\n\tBcc         []string\n\tCc          []string\n\tSubject     string\n\tText        string \/\/Plaintext message (optional)\n\tHtml        string \/\/Html message (optional)\n\tHeaders     textproto.MIMEHeader\n\tAttachments map[string]*Attachment\n\tReadReceipt []string\n}\n\n\/\/NewEmail creates an Email, and returns the pointer to it.\nfunc NewEmail() *Email {\n\treturn &Email{Attachments: make(map[string]*Attachment), Headers: textproto.MIMEHeader{}}\n}\n\n\/\/Attach is used to attach a file to the email.\n\/\/It attempts to open the file referenced by filename and, if successful, creates an Attachment.\n\/\/This Attachment is then appended to the slice of Email.Attachments.\n\/\/The function will then return the Attachment for reference, as well as nil for the error, if successful.\nfunc (e *Email) Attach(filename string) (a *Attachment, err error) {\n\t\/\/Check if the file exists, return any error\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\t\/\/Read the file, and set the appropriate headers\n\tbuffer, _ := ioutil.ReadFile(filename)\n\te.Attachments[filename] = &Attachment{\n\t\tFilename: filename,\n\t\tHeader:   textproto.MIMEHeader{},\n\t\tContent:  buffer}\n\tat := e.Attachments[filename]\n\t\/\/Get the Content-Type to be used in the MIMEHeader\n\tct := mime.TypeByExtension(filepath.Ext(filename))\n\tif ct != \"\" {\n\t\tat.Header.Set(\"Content-Type\", ct)\n\t} else {\n\t\t\/\/If the Content-Type is blank, set the Content-Type to \"application\/octet-stream\"\n\t\tat.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\t}\n\tat.Header.Set(\"Content-Disposition\", fmt.Sprintf(\"attachment;\\r\\n filename=\\\"%s\\\"\", filename))\n\tat.Header.Set(\"Content-Transfer-Encoding\", \"base64\")\n\treturn e.Attachments[filename], nil\n}\n\n\/\/Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.\nfunc (e *Email) Bytes() ([]byte, error) {\n\tbuff := &bytes.Buffer{}\n\tw := multipart.NewWriter(buff)\n\t\/\/Set the appropriate headers (overwriting any conflicts)\n\t\/\/Leave out Bcc (only included in envelope headers)\n\t\/\/TODO: Support wrapping on 76 characters (ref: MIME RFC)\n\te.Headers.Set(\"To\", strings.Join(e.To, \",\"))\n\tif e.Cc != nil {\n\t\te.Headers.Set(\"Cc\", strings.Join(e.Cc, \",\"))\n\t}\n\te.Headers.Set(\"From\", e.From)\n\te.Headers.Set(\"Subject\", e.Subject)\n\tif len(e.ReadReceipt) != 0 {\n\t\te.Headers.Set(\"Disposition-Notification-To\", strings.Join(e.ReadReceipt, \",\"))\n\t}\n\te.Headers.Set(\"MIME-Version\", \"1.0\")\n\te.Headers.Set(\"Content-Type\", fmt.Sprintf(\"multipart\/mixed;\\r\\n boundary=%s\\r\\n\", w.Boundary()))\n\n\t\/\/Write the envelope headers (including any custom headers)\n\tif err := headerToBytes(buff, e.Headers); err != nil {\n\t}\n\t\/\/Start the multipart\/mixed part\n\tfmt.Fprintf(buff, \"--%s\\r\\n\", w.Boundary())\n\theader := textproto.MIMEHeader{}\n\t\/\/Check to see if there is a Text or HTML field\n\tif e.Text != \"\" || e.Html != \"\" {\n\t\tsubWriter := multipart.NewWriter(buff)\n\t\t\/\/Create the multipart alternative part\n\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"multipart\/alternative;\\r\\n boundary=%s\\r\\n\", subWriter.Boundary()))\n\t\t\/\/Write the header\n\t\tif err := headerToBytes(buff, header); err != nil {\n\n\t\t}\n\t\t\/\/Create the body sections\n\t\tif e.Text != \"\" {\n\t\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"text\/plain; charset=UTF-8\"))\n\t\t\t\/*part, err := subWriter.CreatePart(header)\n\t\t\tif err != nil {\n\n\t\t\t}*\/\n\t\t\t\/\/ Write the text, splitting it into chunks of MAX_LINE_LENGTH\n\t\t\t\/\/splitStr := lineSplit(e.Text)\n\t\t}\n\t\tif e.Html != \"\" {\n\t\t\theader.Set(\"Content-Type\", fmt.Sprintf(\"text\/html; charset=UTF-8\"))\n\t\t\theader.Set(\"Content-Transfer-Encoding\", \"quoted-printable\")\n\t\t\tsubWriter.CreatePart(header)\n\t\t\t\/\/ Write the text\n\t\t\tif err := quotePrintEncode(buff, e.Html); err != nil {\n\n\t\t\t}\n\t\t}\n\t\tsubWriter.Close()\n\t}\n\t\/\/Create attachment part, if necessary\n\tif e.Attachments != nil {\n\t\tfor _, a := range e.Attachments {\n\t\t\tap, err := w.CreatePart(a.Header)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t\/\/Write the base64Wrapped content to the part\n\t\t\tbase64Wrap(ap, a.Content)\n\t\t}\n\t}\n\tw.Close()\n\treturn buff.Bytes(), nil\n}\n\n\/\/Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail\n\/\/This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message\nfunc (e *Email) Send(addr string, a smtp.Auth) error {\n\t\/\/Check to make sure there is at least one recipient and one \"From\" address\n\tif e.From == \"\" || (len(e.To) == 0 && len(e.Cc) == 0 && len(e.Bcc) == 0) {\n\t\treturn errors.New(\"Must specify at least one From address and one To address\")\n\t}\n\t\/\/ Merge the To, Cc, and Bcc fields\n\tto := append(append(e.To, e.Cc...), e.Bcc...)\n\tfrom, err := mail.ParseAddress(e.From)\n\tif err != nil {\n\t\treturn err\n\t}\n\traw, err := e.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn smtp.SendMail(addr, a, from.Address, to, raw)\n}\n\n\/\/Attachment is a struct representing an email attachment.\n\/\/Based on the mime\/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question\ntype Attachment struct {\n\tFilename string\n\tHeader   textproto.MIMEHeader\n\tContent  []byte\n}\n\n\/\/quotePrintEncode writes the quoted-printable text to the IO Writer\nfunc quotePrintEncode(w io.Writer, s string) error {\n\tmc := 0\n\tfor _, c := range s {\n\t\t\/\/Change these to a switch\n\t\t\/\/ If we've reached the line length limit\n\t\t\/\/ or we've found a special character whose encoding will surpass the limit\n\t\t\/\/append a soft break\n\t\tif mc == 75 || (!((c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\\n' || c == '\\t')) && mc >= 72) {\n\t\t\tif _, err := fmt.Fprintf(w, \"%s%s\", \"=\\r\\n\", string(c)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmc = 0\n\t\t\tcontinue\n\t\t}\n\t\t\/\/append the appropriate character\n\t\tif (c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\\n' || c == '\\t') {\n\t\t\t\/\/Printable character\n\t\t\tif _, err := fmt.Fprintf(w, \"%s\", string(c)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t\/\/ Reset the counter if we wrote a newline\n\t\t\tif c == '\\n' {\n\t\t\t\tmc = 0\n\t\t\t}\n\t\t\tmc++\n\t\t\tcontinue\n\t\t} else {\n\t\t\t\/\/non-printable.. encode it (TODO)\n\t\t\tif _, err := fmt.Fprintf(w, \"%s\", string(c)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmc++\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)\n\/\/The output is then written to the specified io.Writer\nfunc base64Wrap(w io.Writer, b []byte) {\n\tencoded := base64.StdEncoding.EncodeToString(b)\n\tfor i := 0; i < len(encoded); i += 76 {\n\t\t\/\/Do we need to print 76 characters, or the rest of the string?\n\t\tif len(encoded)-i < 76 {\n\t\t\tfmt.Fprintf(w, \"%s\\r\\n\", encoded[i:])\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"%s\\r\\n\", encoded[i:i+76])\n\t\t}\n\t}\n}\n\n\/\/headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer\nfunc headerToBytes(w io.Writer, t textproto.MIMEHeader) error {\n\tfor k, v := range t {\n\t\t\/\/Write the header key\n\t\t_, err := fmt.Fprintf(w, \"%s:\", k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/Write each value in the header\n\t\tfor _, c := range v {\n\t\t\t_, err := fmt.Fprintf(w, \" %s\\r\\n\", c)\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<|endoftext|>"}
{"text":"<commit_before>package mockdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\n\t\"github.com\/Nivl\/go-rest-tools\/storage\/db\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\nvar (\n\t\/\/ StringType represent a string argument\n\tStringType  = mock.AnythingOfType(\"string\")\n\tserverError = &pq.Error{\n\t\tCode:    \"08006\",\n\t\tMessage: \"error: connection failure\",\n\t\tDetail:  \"the connection to the database failed\",\n\t}\n)\n\nfunc newConflictError(fieldName string) *pq.Error {\n\treturn &pq.Error{\n\t\tCode:    db.ErrDup,\n\t\tMessage: \"error: duplicate field\",\n\t\tDetail:  fmt.Sprintf(\"Key (%s)=(Google) already exists.\", fieldName),\n\t}\n}\n\n\/\/ ExpectGet is a helper that expects a Get\nfunc (mdb *DB) ExpectGet(typ string, runnable func(args mock.Arguments)) *mock.Call {\n\tgetCall := mdb.On(\"Get\", mock.AnythingOfType(typ), StringType, StringType)\n\tgetCall.Return(nil)\n\tif runnable != nil {\n\t\tgetCall.Run(runnable)\n\t}\n\treturn getCall\n}\n\n\/\/ ExpectGetNotFound is a helper that expects a not found on a Get\nfunc (mdb *DB) ExpectGetNotFound(typ string) *mock.Call {\n\tgetCall := mdb.On(\"Get\", mock.AnythingOfType(typ), StringType, StringType)\n\tgetCall.Return(sql.ErrNoRows)\n\treturn getCall\n}\n\n\/\/ ExpectDeletion is a helper that expects a deletion\nfunc (mdb *DB) ExpectDeletion() *mock.Call {\n\treturn mdb.On(\"Exec\", StringType, StringType).Return(nil, nil)\n}\n\n\/\/ ExpectDeletionError is a helper that expects a deletion to fail\nfunc (mdb *DB) ExpectDeletionError() *mock.Call {\n\treturn mdb.On(\"Exec\", StringType, StringType).Return(nil, serverError)\n}\n\n\/\/ ExpectInsert is a helper that expects an insertion\nfunc (mdb *DB) ExpectInsert(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, nil)\n}\n\n\/\/ ExpectInsertError is a helper that expects an insert to fail\nfunc (mdb *DB) ExpectInsertError() *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, StringType).Return(nil, serverError)\n}\n\n\/\/ ExpectInsertConflict is a helper that expects a conflict on an insertion\nfunc (mdb *DB) ExpectInsertConflict(typ string, fieldName string) *mock.Call {\n\tconflictError := newConflictError(fieldName)\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)\n}\n\n\/\/ ExpectUpdate is a helper that expects an update\nfunc (mdb *DB) ExpectUpdate(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, nil)\n}\n\n\/\/ ExpectUpdateConflict is a helper that expects a conflict on an update\nfunc (mdb *DB) ExpectUpdateConflict(typ string, fieldName string) *mock.Call {\n\tconflictError := newConflictError(fieldName)\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)\n}\n\n\/\/ ExpectUpdateError is a helper that expects an update to fail\nfunc (mdb *DB) ExpectUpdateError() *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, StringType).Return(nil, serverError)\n}\n<commit_msg>fix(mockdb): fix type issue<commit_after>package mockdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\n\t\"github.com\/Nivl\/go-rest-tools\/storage\/db\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\nvar (\n\t\/\/ StringType represent a string argument\n\tStringType  = mock.AnythingOfType(\"string\")\n\tserverError = &pq.Error{\n\t\tCode:    \"08006\",\n\t\tMessage: \"error: connection failure\",\n\t\tDetail:  \"the connection to the database failed\",\n\t}\n)\n\nfunc newConflictError(fieldName string) *pq.Error {\n\treturn &pq.Error{\n\t\tCode:    db.ErrDup,\n\t\tMessage: \"error: duplicate field\",\n\t\tDetail:  fmt.Sprintf(\"Key (%s)=(Google) already exists.\", fieldName),\n\t}\n}\n\n\/\/ ExpectGet is a helper that expects a Get\nfunc (mdb *DB) ExpectGet(typ string, runnable func(args mock.Arguments)) *mock.Call {\n\tgetCall := mdb.On(\"Get\", mock.AnythingOfType(typ), StringType, StringType)\n\tgetCall.Return(nil)\n\tif runnable != nil {\n\t\tgetCall.Run(runnable)\n\t}\n\treturn getCall\n}\n\n\/\/ ExpectGetNotFound is a helper that expects a not found on a Get\nfunc (mdb *DB) ExpectGetNotFound(typ string) *mock.Call {\n\tgetCall := mdb.On(\"Get\", mock.AnythingOfType(typ), StringType, StringType)\n\tgetCall.Return(sql.ErrNoRows)\n\treturn getCall\n}\n\n\/\/ ExpectDeletion is a helper that expects a deletion\nfunc (mdb *DB) ExpectDeletion() *mock.Call {\n\treturn mdb.On(\"Exec\", StringType, StringType).Return(nil, nil)\n}\n\n\/\/ ExpectDeletionError is a helper that expects a deletion to fail\nfunc (mdb *DB) ExpectDeletionError() *mock.Call {\n\treturn mdb.On(\"Exec\", StringType, StringType).Return(nil, serverError)\n}\n\n\/\/ ExpectInsert is a helper that expects an insertion\nfunc (mdb *DB) ExpectInsert(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, nil)\n}\n\n\/\/ ExpectInsertError is a helper that expects an insert to fail\nfunc (mdb *DB) ExpectInsertError(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, serverError)\n}\n\n\/\/ ExpectInsertConflict is a helper that expects a conflict on an insertion\nfunc (mdb *DB) ExpectInsertConflict(typ string, fieldName string) *mock.Call {\n\tconflictError := newConflictError(fieldName)\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)\n}\n\n\/\/ ExpectUpdate is a helper that expects an update\nfunc (mdb *DB) ExpectUpdate(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, nil)\n}\n\n\/\/ ExpectUpdateConflict is a helper that expects a conflict on an update\nfunc (mdb *DB) ExpectUpdateConflict(typ string, fieldName string) *mock.Call {\n\tconflictError := newConflictError(fieldName)\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, conflictError)\n}\n\n\/\/ ExpectUpdateError is a helper that expects an update to fail\nfunc (mdb *DB) ExpectUpdateError(typ string) *mock.Call {\n\treturn mdb.On(\"NamedExec\", StringType, mock.AnythingOfType(typ)).Return(nil, serverError)\n}\n<|endoftext|>"}
{"text":"<commit_before>package backend_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"code.cloudfoundry.org\/garden\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\/backendfakes\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\/libcontainerd\/libcontainerdfakes\"\n\t\"github.com\/containerd\/containerd\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\ntype BackendSuite struct {\n\tsuite.Suite\n\t*require.Assertions\n\n\tbackend backend.Backend\n\tclient  *libcontainerdfakes.FakeClient\n\tnetwork *backendfakes.FakeNetwork\n\tuserns  *backendfakes.FakeUserNamespace\n\tkiller  *backendfakes.FakeKiller\n}\n\nfunc (s *BackendSuite) SetupTest() {\n\ts.client = new(libcontainerdfakes.FakeClient)\n\ts.killer = new(backendfakes.FakeKiller)\n\ts.network = new(backendfakes.FakeNetwork)\n\ts.userns = new(backendfakes.FakeUserNamespace)\n\n\tvar err error\n\ts.backend, err = backend.New(s.client,\n\t\tbackend.WithKiller(s.killer),\n\t\tbackend.WithNetwork(s.network),\n\t\tbackend.WithUserNamespace(s.userns),\n\t)\n\ts.NoError(err)\n}\n\nfunc (s *BackendSuite) TestNew() {\n\t_, err := backend.New(nil)\n\ts.EqualError(err, \"nil client\")\n}\n\nfunc (s *BackendSuite) TestPing() {\n\tfor _, tc := range []struct {\n\t\tdesc          string\n\t\tversionReturn error\n\t\tsucceeds      bool\n\t}{\n\t\t{\n\t\t\tdesc:          \"fail from containerd version service\",\n\t\t\tsucceeds:      true,\n\t\t\tversionReturn: nil,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"ok from containerd's version service\",\n\t\t\tsucceeds:      false,\n\t\t\tversionReturn: errors.New(\"error returning version\"),\n\t\t},\n\t} {\n\t\ts.T().Run(tc.desc, func(t *testing.T) {\n\t\t\ts.client.VersionReturns(tc.versionReturn)\n\n\t\t\terr := s.backend.Ping()\n\t\t\tif tc.succeeds {\n\t\t\t\ts.NoError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.EqualError(errors.Unwrap(err), \"error returning version\")\n\t\t})\n\t}\n}\n\nvar (\n\tinvalidGdnSpec      = garden.ContainerSpec{}\n\tminimumValidGdnSpec = garden.ContainerSpec{\n\t\tHandle: \"handle\", RootFSPath: \"raw:\/\/\/rootfs\",\n\t}\n)\n\nfunc (s *BackendSuite) TestCreateWithInvalidSpec() {\n\t_, err := s.backend.Create(invalidGdnSpec)\n\n\ts.Error(err)\n\ts.Equal(0, s.client.NewContainerCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateWithNewContainerFailure() {\n\ts.client.NewContainerReturns(nil, errors.New(\"err\"))\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.Error(err)\n\n\ts.Equal(1, s.client.NewContainerCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateContainerNewTaskFailure() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\texpectedErr := errors.New(\"task-err\")\n\tfakeContainer.NewTaskReturns(nil, expectedErr)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.EqualError(errors.Unwrap(err), expectedErr.Error())\n\n\ts.Equal(1, fakeContainer.NewTaskCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateContainerTaskStartFailure() {\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\tfakeContainer.NewTaskReturns(fakeTask, nil)\n\tfakeTask.StartReturns(errors.New(\"start-err\"))\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.Error(err)\n\n\ts.EqualError(errors.Unwrap(err), \"start-err\")\n}\n\nfunc (s *BackendSuite) TestCreateContainerSetsHandle() {\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\tfakeContainer.IDReturns(\"handle\")\n\tfakeContainer.NewTaskReturns(fakeTask, nil)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\tcont, err := s.backend.Create(minimumValidGdnSpec)\n\ts.NoError(err)\n\n\ts.Equal(\"handle\", cont.Handle())\n\n}\n\nfunc (s *BackendSuite) TestContainersWithContainerdFailure() {\n\ts.client.ContainersReturns(nil, errors.New(\"err\"))\n\n\t_, err := s.backend.Containers(nil)\n\ts.Error(err)\n\ts.Equal(1, s.client.ContainersCallCount())\n}\n\nfunc (s *BackendSuite) TestContainersWithInvalidPropertyFilters() {\n\tfor _, tc := range []struct {\n\t\tdesc   string\n\t\tfilter map[string]string\n\t}{\n\t\t{\n\t\t\tdesc: \"empty key\",\n\t\t\tfilter: map[string]string{\n\t\t\t\t\"\": \"bar\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty value\",\n\t\t\tfilter: map[string]string{\n\t\t\t\t\"foo\": \"\",\n\t\t\t},\n\t\t},\n\t} {\n\t\ts.T().Run(tc.desc, func(t *testing.T) {\n\t\t\t_, err := s.backend.Containers(tc.filter)\n\n\t\t\ts.Error(err)\n\t\t\ts.Equal(0, s.client.ContainersCallCount())\n\t\t})\n\t}\n}\n\nfunc (s *BackendSuite) TestContainersWithProperProperties() {\n\t_, _ = s.backend.Containers(map[string]string{\"foo\": \"bar\", \"caz\": \"zaz\"})\n\ts.Equal(1, s.client.ContainersCallCount())\n\n\t_, labelSet := s.client.ContainersArgsForCall(0)\n\ts.ElementsMatch([]string{\"labels.foo==bar\", \"labels.caz==zaz\"}, labelSet)\n}\n\nfunc (s *BackendSuite) TestContainersConversion() {\n\tfakeContainer1 := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer2 := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.ContainersReturns([]containerd.Container{\n\t\tfakeContainer1, fakeContainer2,\n\t}, nil)\n\n\tcontainers, err := s.backend.Containers(nil)\n\ts.NoError(err)\n\ts.Equal(1, s.client.ContainersCallCount())\n\ts.Len(containers, 2)\n}\n\nfunc (s *BackendSuite) TestLookupEmptyHandleError() {\n\t_, err := s.backend.Lookup(\"\")\n\ts.Equal(\"empty handle\", err.Error())\n}\n\nfunc (s *BackendSuite) TestLookupCallGetContainerWithHandle() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\n\t_, _ = s.backend.Lookup(\"handle\")\n\ts.Equal(1, s.client.GetContainerCallCount())\n\n\t_, handle := s.client.GetContainerArgsForCall(0)\n\ts.Equal(\"handle\", handle)\n}\n\nfunc (s *BackendSuite) TestLookupGetContainerError() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\n\ts.client.GetContainerReturns(nil, errors.New(\"containerd-err\"))\n\n\t_, err := s.backend.Lookup(\"handle\")\n\ts.Error(err)\n\ts.EqualError(errors.Unwrap(err), \"containerd-err\")\n}\n\nfunc (s *BackendSuite) TestLookupGetContainerFails() {\n\ts.client.GetContainerReturns(nil, errors.New(\"err\"))\n\t_, err := s.backend.Lookup(\"non-existent-handle\")\n\ts.Error(err)\n\ts.EqualError(errors.Unwrap(err), \"err\")\n}\n\nfunc (s *BackendSuite) TestLookupGetNoContainerReturned() {\n\ts.client.GetContainerReturns(nil, errors.New(\"not found\"))\n\tcontainer, err := s.backend.Lookup(\"non-existent-handle\")\n\ts.Error(err)\n\ts.Nil(container)\n}\n\nfunc (s *BackendSuite) TestLookupGetContainer() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tcontainer, err := s.backend.Lookup(\"handle\")\n\ts.NoError(err)\n\ts.NotNil(container)\n\ts.Equal(\"handle\", container.Handle())\n}\n\nfunc (s *BackendSuite) TestDestroyEmptyHandleError() {\n\terr := s.backend.Destroy(\"\")\n\ts.EqualError(err, \"empty handle\")\n}\n\nfunc (s *BackendSuite) TestDestroyGetContainerError() {\n\ts.client.GetContainerReturns(nil, errors.New(\"get-container-failed\"))\n\n\terr := s.backend.Destroy(\"some-handle\")\n\ts.EqualError(errors.Unwrap(err), \"get-container-failed\")\n}\n\n\/\/ func (s *BackendSuite) TestDestroyGracefullyStopErrors() {\n\/\/ \tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\/\/ \ts.client.GetContainerReturns(fakeContainer, nil)\n\/\/ \ts.containerStopper.GracefullyStopReturns(errors.New(\"gracefully-stop-failed\"))\n\n\/\/ \terr := s.backend.Destroy(\"some-handle\")\n\n\/\/ \ts.Equal(1, s.containerStopper.GracefullyStopCallCount())\n\/\/ \ts.EqualError(errors.Unwrap(err), \"gracefully-stop-failed\")\n\/\/ }\n\n\/\/ func (s *BackendSuite) TestDestroyContainerDeleteError() {\n\/\/ \tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\/\/ \tfakeContainer.DeleteReturns(errors.New(\"destroy-error\"))\n\n\/\/ \ts.client.GetContainerReturns(fakeContainer, nil)\n\n\/\/ \terr := s.backend.Destroy(\"some-handle\")\n\n\/\/ \ts.Equal(1, s.containerStopper.GracefullyStopCallCount())\n\/\/ \ts.Equal(1, fakeContainer.DeleteCallCount())\n\/\/ \ts.EqualError(errors.Unwrap(err), \"destroy-error\")\n\/\/ }\n\n\/\/ func (s *BackendSuite) TestDestroy() {\n\/\/ \tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\/\/ \ts.client.GetContainerReturns(fakeContainer, nil)\n\n\/\/ \terr := s.backend.Destroy(\"some-handle\")\n\/\/ \ts.NoError(err)\n\n\/\/ \ts.Equal(1, s.client.GetContainerCallCount())\n\/\/ \ts.Equal(1, s.containerStopper.GracefullyStopCallCount())\n\/\/ \ts.Equal(1, fakeContainer.DeleteCallCount())\n\/\/ }\n\nfunc (s *BackendSuite) TestStart() {\n\terr := s.backend.Start()\n\ts.NoError(err)\n\ts.Equal(1, s.client.InitCallCount())\n}\n\nfunc (s *BackendSuite) TestStartInitError() {\n\ts.client.InitReturns(errors.New(\"init failed\"))\n\terr := s.backend.Start()\n\ts.EqualError(errors.Unwrap(err), \"init failed\")\n}\n\nfunc (s *BackendSuite) TestStop() {\n\ts.backend.Stop()\n\ts.Equal(1, s.client.StopCallCount())\n}\n<commit_msg>containerd: backfill tests<commit_after>package backend_test\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"code.cloudfoundry.org\/garden\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\/backendfakes\"\n\t\"github.com\/concourse\/concourse\/worker\/backend\/libcontainerd\/libcontainerdfakes\"\n\t\"github.com\/containerd\/containerd\"\n\t\"github.com\/containerd\/containerd\/errdefs\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\ntype BackendSuite struct {\n\tsuite.Suite\n\t*require.Assertions\n\n\tbackend backend.Backend\n\tclient  *libcontainerdfakes.FakeClient\n\tnetwork *backendfakes.FakeNetwork\n\tuserns  *backendfakes.FakeUserNamespace\n\tkiller  *backendfakes.FakeKiller\n}\n\nfunc (s *BackendSuite) SetupTest() {\n\ts.client = new(libcontainerdfakes.FakeClient)\n\ts.killer = new(backendfakes.FakeKiller)\n\ts.network = new(backendfakes.FakeNetwork)\n\ts.userns = new(backendfakes.FakeUserNamespace)\n\n\tvar err error\n\ts.backend, err = backend.New(s.client,\n\t\tbackend.WithKiller(s.killer),\n\t\tbackend.WithNetwork(s.network),\n\t\tbackend.WithUserNamespace(s.userns),\n\t)\n\ts.NoError(err)\n}\n\nfunc (s *BackendSuite) TestNew() {\n\t_, err := backend.New(nil)\n\ts.EqualError(err, \"nil client\")\n}\n\nfunc (s *BackendSuite) TestPing() {\n\tfor _, tc := range []struct {\n\t\tdesc          string\n\t\tversionReturn error\n\t\tsucceeds      bool\n\t}{\n\t\t{\n\t\t\tdesc:          \"fail from containerd version service\",\n\t\t\tsucceeds:      true,\n\t\t\tversionReturn: nil,\n\t\t},\n\t\t{\n\t\t\tdesc:          \"ok from containerd's version service\",\n\t\t\tsucceeds:      false,\n\t\t\tversionReturn: errors.New(\"error returning version\"),\n\t\t},\n\t} {\n\t\ts.T().Run(tc.desc, func(t *testing.T) {\n\t\t\ts.client.VersionReturns(tc.versionReturn)\n\n\t\t\terr := s.backend.Ping()\n\t\t\tif tc.succeeds {\n\t\t\t\ts.NoError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.EqualError(errors.Unwrap(err), \"error returning version\")\n\t\t})\n\t}\n}\n\nvar (\n\tinvalidGdnSpec      = garden.ContainerSpec{}\n\tminimumValidGdnSpec = garden.ContainerSpec{\n\t\tHandle: \"handle\", RootFSPath: \"raw:\/\/\/rootfs\",\n\t}\n)\n\nfunc (s *BackendSuite) TestCreateWithInvalidSpec() {\n\t_, err := s.backend.Create(invalidGdnSpec)\n\n\ts.Error(err)\n\ts.Equal(0, s.client.NewContainerCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateWithNewContainerFailure() {\n\ts.client.NewContainerReturns(nil, errors.New(\"err\"))\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.Error(err)\n\n\ts.Equal(1, s.client.NewContainerCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateContainerNewTaskFailure() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\texpectedErr := errors.New(\"task-err\")\n\tfakeContainer.NewTaskReturns(nil, expectedErr)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.EqualError(errors.Unwrap(err), expectedErr.Error())\n\n\ts.Equal(1, fakeContainer.NewTaskCallCount())\n}\n\nfunc (s *BackendSuite) TestCreateContainerTaskStartFailure() {\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\tfakeContainer.NewTaskReturns(fakeTask, nil)\n\tfakeTask.StartReturns(errors.New(\"start-err\"))\n\n\t_, err := s.backend.Create(minimumValidGdnSpec)\n\ts.Error(err)\n\n\ts.EqualError(errors.Unwrap(err), \"start-err\")\n}\n\nfunc (s *BackendSuite) TestCreateContainerSetsHandle() {\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\tfakeContainer.IDReturns(\"handle\")\n\tfakeContainer.NewTaskReturns(fakeTask, nil)\n\n\ts.client.NewContainerReturns(fakeContainer, nil)\n\tcont, err := s.backend.Create(minimumValidGdnSpec)\n\ts.NoError(err)\n\n\ts.Equal(\"handle\", cont.Handle())\n\n}\n\nfunc (s *BackendSuite) TestContainersWithContainerdFailure() {\n\ts.client.ContainersReturns(nil, errors.New(\"err\"))\n\n\t_, err := s.backend.Containers(nil)\n\ts.Error(err)\n\ts.Equal(1, s.client.ContainersCallCount())\n}\n\nfunc (s *BackendSuite) TestContainersWithInvalidPropertyFilters() {\n\tfor _, tc := range []struct {\n\t\tdesc   string\n\t\tfilter map[string]string\n\t}{\n\t\t{\n\t\t\tdesc: \"empty key\",\n\t\t\tfilter: map[string]string{\n\t\t\t\t\"\": \"bar\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty value\",\n\t\t\tfilter: map[string]string{\n\t\t\t\t\"foo\": \"\",\n\t\t\t},\n\t\t},\n\t} {\n\t\ts.T().Run(tc.desc, func(t *testing.T) {\n\t\t\t_, err := s.backend.Containers(tc.filter)\n\n\t\t\ts.Error(err)\n\t\t\ts.Equal(0, s.client.ContainersCallCount())\n\t\t})\n\t}\n}\n\nfunc (s *BackendSuite) TestContainersWithProperProperties() {\n\t_, _ = s.backend.Containers(map[string]string{\"foo\": \"bar\", \"caz\": \"zaz\"})\n\ts.Equal(1, s.client.ContainersCallCount())\n\n\t_, labelSet := s.client.ContainersArgsForCall(0)\n\ts.ElementsMatch([]string{\"labels.foo==bar\", \"labels.caz==zaz\"}, labelSet)\n}\n\nfunc (s *BackendSuite) TestContainersConversion() {\n\tfakeContainer1 := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer2 := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.ContainersReturns([]containerd.Container{\n\t\tfakeContainer1, fakeContainer2,\n\t}, nil)\n\n\tcontainers, err := s.backend.Containers(nil)\n\ts.NoError(err)\n\ts.Equal(1, s.client.ContainersCallCount())\n\ts.Len(containers, 2)\n}\n\nfunc (s *BackendSuite) TestLookupEmptyHandleError() {\n\t_, err := s.backend.Lookup(\"\")\n\ts.Equal(\"empty handle\", err.Error())\n}\n\nfunc (s *BackendSuite) TestLookupCallGetContainerWithHandle() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\n\t_, _ = s.backend.Lookup(\"handle\")\n\ts.Equal(1, s.client.GetContainerCallCount())\n\n\t_, handle := s.client.GetContainerArgsForCall(0)\n\ts.Equal(\"handle\", handle)\n}\n\nfunc (s *BackendSuite) TestLookupGetContainerError() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\n\ts.client.GetContainerReturns(nil, errors.New(\"containerd-err\"))\n\n\t_, err := s.backend.Lookup(\"handle\")\n\ts.Error(err)\n\ts.EqualError(errors.Unwrap(err), \"containerd-err\")\n}\n\nfunc (s *BackendSuite) TestLookupGetContainerFails() {\n\ts.client.GetContainerReturns(nil, errors.New(\"err\"))\n\t_, err := s.backend.Lookup(\"non-existent-handle\")\n\ts.Error(err)\n\ts.EqualError(errors.Unwrap(err), \"err\")\n}\n\nfunc (s *BackendSuite) TestLookupGetNoContainerReturned() {\n\ts.client.GetContainerReturns(nil, errors.New(\"not found\"))\n\tcontainer, err := s.backend.Lookup(\"non-existent-handle\")\n\ts.Error(err)\n\ts.Nil(container)\n}\n\nfunc (s *BackendSuite) TestLookupGetContainer() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeContainer.IDReturns(\"handle\")\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tcontainer, err := s.backend.Lookup(\"handle\")\n\ts.NoError(err)\n\ts.NotNil(container)\n\ts.Equal(\"handle\", container.Handle())\n}\n\nfunc (s *BackendSuite) TestDestroyEmptyHandleError() {\n\terr := s.backend.Destroy(\"\")\n\ts.EqualError(err, \"empty handle\")\n}\n\nfunc (s *BackendSuite) TestDestroyGetContainerError() {\n\ts.client.GetContainerReturns(nil, errors.New(\"get-container-failed\"))\n\n\terr := s.backend.Destroy(\"some-handle\")\n\ts.EqualError(errors.Unwrap(err), \"get-container-failed\")\n}\n\nfunc (s *BackendSuite) TestDestroyGetTaskError() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\n\texpectedError := errors.New(\"get-task-failed\")\n\tfakeContainer.TaskReturns(nil, expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n}\n\nfunc (s *BackendSuite) TestDestroyGetTaskErrorNotFoundAndDeleteFails() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(nil, errdefs.ErrNotFound)\n\n\texpectedError := errors.New(\"delete-container-failed\")\n\tfakeContainer.DeleteReturns(expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n}\n\nfunc (s *BackendSuite) TestDestroyGetTaskErrorNotFoundAndDeleteSucceeds() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(nil, errdefs.ErrNotFound)\n\n\terr := s.backend.Destroy(\"some handle\")\n\n\ts.Equal(1, fakeContainer.DeleteCallCount())\n\ts.NoError(err)\n}\n\nfunc (s *BackendSuite) TestDestroyKillTaskFails() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(fakeTask, nil)\n\n\texpectedError := errors.New(\"kill-task-failed\")\n\ts.killer.KillReturns(expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n\t_, _, behaviour := s.killer.KillArgsForCall(0)\n\ts.Equal(backend.KillGracefully, behaviour)\n}\n\nfunc (s *BackendSuite) TestDestroyRemoveNetworkFails() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(fakeTask, nil)\n\n\texpectedError := errors.New(\"remove-network-failed\")\n\ts.network.RemoveReturns(expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n}\n\nfunc (s *BackendSuite) TestDestroyDeleteTaskFails() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(fakeTask, nil)\n\n\texpectedError := errors.New(\"delete-container-failed\")\n\tfakeTask.DeleteReturns(nil, expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n}\n\nfunc (s *BackendSuite) TestDestroyContainerDeleteFailsAndDeleteTaskSucceeds() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(fakeTask, nil)\n\n\texpectedError := errors.New(\"delete-container-failed\")\n\tfakeContainer.DeleteReturns(expectedError)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.True(errors.Is(err, expectedError))\n}\n\nfunc (s *BackendSuite) TestDestroySucceeds() {\n\tfakeContainer := new(libcontainerdfakes.FakeContainer)\n\tfakeTask := new(libcontainerdfakes.FakeTask)\n\ts.client.GetContainerReturns(fakeContainer, nil)\n\tfakeContainer.TaskReturns(fakeTask, nil)\n\n\terr := s.backend.Destroy(\"some handle\")\n\ts.NoError(err)\n}\n\nfunc (s *BackendSuite) TestStart() {\n\terr := s.backend.Start()\n\ts.NoError(err)\n\ts.Equal(1, s.client.InitCallCount())\n}\n\nfunc (s *BackendSuite) TestStartInitError() {\n\ts.client.InitReturns(errors.New(\"init failed\"))\n\terr := s.backend.Start()\n\ts.EqualError(errors.Unwrap(err), \"init failed\")\n}\n\nfunc (s *BackendSuite) TestStop() {\n\ts.backend.Stop()\n\ts.Equal(1, s.client.StopCallCount())\n}\n<|endoftext|>"}
{"text":"<commit_before>package workflow\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go-v2\/aws\"\n\taw \"github.com\/deanishe\/awgo\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/aliases\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/awsconfig\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/awsworkflow\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/parsers\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/searchers\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/searchers\/searchutil\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/util\"\n)\n\nfunc Run(wf *aw.Workflow, rawQuery string, transport http.RoundTripper, forceFetch, openAll bool, ymlPath string) {\n\tlog.Println(\"using workflow cacheDir: \" + wf.CacheDir())\n\tlog.Println(\"using workflow dataDir: \" + wf.DataDir())\n\n\tparser := parsers.NewParser(rawQuery)\n\tquery, awsServices := parser.Parse(ymlPath)\n\tdefer finalize(wf, query)\n\n\tlog.Printf(\"using query: %#v\", query)\n\n\tif query.RegionQuery != nil {\n\t\tfor _, region := range awsconfig.AllAWSRegions {\n\t\t\tautocomplete := strings.Replace(rawQuery, aliases.OverrideAwsRegion+*query.RegionQuery, aliases.OverrideAwsRegion+region.Name+\" \", 1)\n\t\t\twf.NewItem(region.Name).\n\t\t\t\tSubtitle(region.Description).\n\t\t\t\tIcon(aw.IconWeb).\n\t\t\t\tAutocomplete(autocomplete).\n\t\t\t\tUID(region.Name)\n\t\t}\n\t\tlog.Printf(\"filtering with region override %q\", *query.RegionQuery)\n\t\tres := wf.Filter(*query.RegionQuery)\n\t\tlog.Printf(\"%d results match %q\", len(res), *query.RegionQuery)\n\t\treturn\n\t}\n\n\tif query.ProfileQuery != nil {\n\t\tfor _, profile := range awsconfig.GetAwsProfiles() {\n\t\t\tautocomplete := strings.Replace(rawQuery, aliases.OverrideAwsProfile+*query.ProfileQuery, aliases.OverrideAwsProfile+profile.Name+\" \", 1)\n\t\t\titem := wf.NewItem(profile.Name).\n\t\t\t\tIcon(aw.IconAccount).\n\t\t\t\tAutocomplete(autocomplete).\n\t\t\t\tUID(profile.Name)\n\n\t\t\tif profile.Region != \"\" {\n\t\t\t\titem.Subtitle(fmt.Sprintf(\"🌎 %s\", profile.Region))\n\t\t\t} else {\n\t\t\t\titem.Subtitle(\"⚠️ This profile does not specify a region. Functionality will be limited\")\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"filtering with profile override %q\", *query.ProfileQuery)\n\t\tres := wf.Filter(*query.ProfileQuery)\n\t\tlog.Printf(\"%d results match %q\", len(res), *query.ProfileQuery)\n\t\treturn\n\t}\n\n\tcfg := awsworkflow.InitAWS(transport, query.ProfileOverride, query.GetRegionOverride())\n\tsearchArgs := searchutil.SearchArgs{\n\t\tCfg:        cfg,\n\t\tForceFetch: forceFetch,\n\t\tFullQuery:  rawQuery,\n\t\tProfile:    util.GetProfile(cfg),\n\t}\n\n\tif query.IsEmpty() {\n\t\thandleEmptyQuery(wf, searchArgs)\n\t\treturn\n\t}\n\n\tif query.HasOpenAll {\n\t\thandleOpenAll(wf, query.Service, awsServices, openAll, rawQuery, cfg)\n\t\treturn\n\t}\n\n\tif query.Service == nil || (!query.HasTrailingWhitespace && query.SubService == nil && !query.HasDefaultSearchAlias && query.RemainingQuery == \"\") {\n\t\tif query.Service == nil {\n\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t} else if query.Service.ShortName != \"\" {\n\t\t\tsearchArgs.Query = strings.ToLower(query.Service.ShortName)\n\t\t} else {\n\t\t\tsearchArgs.Query = query.Service.Id\n\t\t}\n\t\tlog.Printf(\"using searcher associated with services with query %q\", searchArgs.Query)\n\t\tSearchServices(wf, awsServices, searchArgs)\n\t} else {\n\t\tif !query.HasDefaultSearchAlias && (query.Service.SubServices == nil || len(query.Service.SubServices) <= 0) {\n\t\t\thandleUnimplemented(wf, query.Service, nil, fmt.Sprintf(\"%s doesn't have sub-services configured (yet)\", query.Service.Id), searchArgs)\n\t\t\treturn\n\t\t}\n\n\t\tsearchArgs.GetRegionFunc = query.Service.GetRegion\n\n\t\tif query.HasDefaultSearchAlias || query.SubService != nil && (query.HasTrailingWhitespace || query.RemainingQuery != \"\") {\n\t\t\tserviceId := query.Service.Id\n\t\t\tif query.SubService != nil {\n\t\t\t\tserviceId += \"_\" + query.SubService.Id\n\t\t\t}\n\t\t\tlog.Println(\"using searcher associated with \" + serviceId)\n\t\t\tsearcher := searchers.SearchersByServiceId[serviceId]\n\t\t\tif searcher != nil {\n\t\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t\t\terr := searcher.Search(wf, searchArgs)\n\t\t\t\tif err != nil {\n\t\t\t\t\twf.FatalError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandleUnimplemented(wf, query.Service, query.SubService, fmt.Sprintf(\"No searcher for `%s %s` (yet)\", query.Service.Id, query.SubService.Id), searchArgs)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"using searcher associated with sub-services\")\n\t\t\tif query.SubService != nil {\n\t\t\t\tsearchArgs.Query = query.SubService.Id\n\t\t\t} else {\n\t\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t\t}\n\t\t\tSearchSubServices(wf, *query.Service, searchArgs)\n\t\t}\n\t}\n\n\tif searchArgs.Query != \"\" {\n\t\tlog.Printf(\"filtering with query %q\", searchArgs.Query)\n\t\tres := wf.Filter(searchArgs.Query)\n\t\tlog.Printf(\"%d results match %q\", len(res), searchArgs.Query)\n\t}\n}\n\nfunc finalize(wf *aw.Workflow, query *parsers.Query) {\n\tif wf.IsEmpty() {\n\t\ttitle := \"\"\n\t\tsubtitle := \"\"\n\t\tif query.RegionQuery != nil {\n\t\t\ttitle = \"No matching regions found\"\n\t\t\tsubtitle = fmt.Sprintf(\"Try starting over with \\\"%s\\\" again to see the full list\", aliases.OverrideAwsRegion)\n\t\t} else if query.ProfileQuery != nil {\n\t\t\ttitle = \"No matching profiles found\"\n\t\t\tsubtitle = fmt.Sprintf(\"Try starting over with \\\"%s\\\" again to see the full list\", aliases.OverrideAwsProfile)\n\t\t} else {\n\t\t\ttitle = \"No matching services found\"\n\t\t\tsubtitle = \"Try another query (example: `aws ec2 instances`)\"\n\t\t}\n\t\twf.NewItem(title).\n\t\t\tSubtitle(subtitle).\n\t\t\tIcon(aw.IconNote)\n\t\thandleUpdateAvailable(wf)\n\t}\n\twf.SendFeedback()\n}\n\nfunc handleEmptyQuery(wf *aw.Workflow, searchArgs searchutil.SearchArgs) {\n\tlog.Println(\"no search type parsed\")\n\twf.NewItem(\"Search for an AWS Service ...\").\n\t\tSubtitle(\"e.g., cloudformation, ec2, s3 ...\")\n\n\tif searchArgs.Profile == \"\" {\n\t\tutil.NewURLItem(wf, \"No profile configured\").\n\t\t\tSubtitle(\"Select this option to open AWS docs on how to configure\").\n\t\t\tArg(\"https:\/\/aws.github.io\/aws-sdk-go-v2\/docs\/configuring-sdk\/#creating-the-config-file\").\n\t\t\tIcon(aw.IconWarning)\n\t} else {\n\t\twf.NewItem(\"Using profile \\\"\" + searchArgs.Profile + \"\\\"\").\n\t\t\tSubtitle(\"Use \\\"\" + aliases.OverrideAwsProfile + \"\\\" to override for the current query\").\n\t\t\tIcon(aw.IconAccount)\n\t}\n\n\tif searchArgs.Cfg.Region == \"\" {\n\t\tutil.NewURLItem(wf, \"No region configured for this profile\").\n\t\t\tSubtitle(\"Select this option to open AWS docs on how to configure\").\n\t\t\tArg(\"https:\/\/aws.github.io\/aws-sdk-go-v2\/docs\/configuring-sdk\/#creating-the-config-file\").\n\t\t\tIcon(aw.IconWarning)\n\t} else {\n\t\twf.NewItem(\"Using region \\\"\" + searchArgs.Cfg.Region + \"\\\"\").\n\t\t\tSubtitle(\"Use \\\"\" + aliases.OverrideAwsRegion + \"\\\" to override for the current query\").\n\t\t\tIcon(aw.IconWeb)\n\t}\n\n\tutil.NewURLItem(wf, \"Like this workflow? Consider donating! 😻\").\n\t\tSubtitle(\"Select this option to open this project's Patreon\").\n\t\tArg(\"https:\/\/www.patreon.com\/rkoval_alfred_aws_console_services_workflow\").\n\t\tIcon(aw.IconFavorite)\n\n\tif wf.UpdateCheckDue() {\n\t\tif err := wf.CheckForUpdate(); err != nil {\n\t\t\twf.FatalError(err)\n\t\t}\n\t}\n\thandleUpdateAvailable(wf)\n}\n\nfunc handleUnimplemented(wf *aw.Workflow, awsService, subService *awsworkflow.AwsService, header string, searchArgs searchutil.SearchArgs) {\n\tsearchArgs.IgnoreAutocompleteTerm = true\n\tif subService == nil {\n\t\tAddServiceToWorkflow(wf, *awsService, searchArgs)\n\t} else {\n\t\tAddSubServiceToWorkflow(wf, *awsService, *subService, searchArgs)\n\t}\n\tutil.NewURLItem(wf, header).\n\t\tSubtitle(\"Select this result to open the contributing guide to easily add them!\").\n\t\tArg(\"https:\/\/github.com\/rkoval\/alfred-aws-console-services-workflow\/blob\/master\/CONTRIBUTING.md\").\n\t\tIcon(aw.IconNote)\n\thandleUpdateAvailable(wf)\n}\n\nfunc handleUpdateAvailable(wf *aw.Workflow) {\n\tif wf.UpdateAvailable() {\n\t\tutil.NewURLItem(wf, fmt.Sprintf(\"Update available (current version: %s)\", wf.Version())).\n\t\t\tSubtitle(\"Select this result to navigate to download\").\n\t\t\tArg(\"https:\/\/github.com\/rkoval\/alfred-aws-console-services-workflow\/releases\").\n\t\t\tIcon(aw.IconInfo)\n\t}\n}\n\nfunc handleOpenAll(wf *aw.Workflow, awsService *awsworkflow.AwsService, allAwsServices []awsworkflow.AwsService, openAll bool, rawQuery string, cfg aws.Config) {\n\tif openAll {\n\t\tif awsService == nil {\n\t\t\tfor _, awsService := range allAwsServices {\n\t\t\t\topenServiceInBrowser(wf, awsService, awsService, cfg)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, subService := range awsService.SubServices {\n\t\t\t\topenServiceInBrowser(wf, subService, *awsService, cfg)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvar length int\n\t\tvar entityName string\n\t\tif awsService == nil {\n\t\t\tlength = len(allAwsServices)\n\t\t\tentityName = \"services\"\n\t\t} else {\n\t\t\tlength = len(awsService.SubServices)\n\t\t\tentityName = awsService.Id + \" sub-services\"\n\t\t}\n\n\t\ttitle := fmt.Sprintf(\"Open the %d %s in browser\", length, entityName)\n\t\tcmd := fmt.Sprintf(`%s -query=\"%s\" -open_all`, os.Args[0], rawQuery)\n\t\twf.NewItem(title).\n\t\t\tSubtitle(\"Fair warning: this may briefly overload your system\").\n\t\t\tIcon(aw.IconWarning).\n\t\t\tArg(cmd).\n\t\t\tVar(\"action\", \"run-script\").\n\t\t\tValid(true)\n\t}\n}\n\nfunc openServiceInBrowser(wf *aw.Workflow, awsService, awsServiceForRegion awsworkflow.AwsService, cfg aws.Config) {\n\tcmd := exec.Command(\"open\", util.ConstructAWSConsoleUrl(awsService.Url, awsServiceForRegion.GetRegion(cfg)))\n\tif err := wf.RunInBackground(\"open-service-in-browser-\"+awsService.Id, cmd); err != nil {\n\t\tpanic(err)\n\t}\n\ttime.Sleep(250 * time.Millisecond) \/\/ sleep so that tabs are more-or-less opened in the order by which this function is called\n}\n<commit_msg>added writing to json file all services opened via OPEN_ALL for automated validation<commit_after>package workflow\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go-v2\/aws\"\n\taw \"github.com\/deanishe\/awgo\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/aliases\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/awsconfig\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/awsworkflow\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/parsers\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/searchers\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/searchers\/searchutil\"\n\t\"github.com\/rkoval\/alfred-aws-console-services-workflow\/util\"\n)\n\nfunc Run(wf *aw.Workflow, rawQuery string, transport http.RoundTripper, forceFetch, openAll bool, ymlPath string) {\n\tlog.Println(\"using workflow cacheDir: \" + wf.CacheDir())\n\tlog.Println(\"using workflow dataDir: \" + wf.DataDir())\n\n\tparser := parsers.NewParser(rawQuery)\n\tquery, awsServices := parser.Parse(ymlPath)\n\tdefer finalize(wf, query)\n\n\tlog.Printf(\"using query: %#v\", query)\n\n\tif query.RegionQuery != nil {\n\t\tfor _, region := range awsconfig.AllAWSRegions {\n\t\t\tautocomplete := strings.Replace(rawQuery, aliases.OverrideAwsRegion+*query.RegionQuery, aliases.OverrideAwsRegion+region.Name+\" \", 1)\n\t\t\twf.NewItem(region.Name).\n\t\t\t\tSubtitle(region.Description).\n\t\t\t\tIcon(aw.IconWeb).\n\t\t\t\tAutocomplete(autocomplete).\n\t\t\t\tUID(region.Name)\n\t\t}\n\t\tlog.Printf(\"filtering with region override %q\", *query.RegionQuery)\n\t\tres := wf.Filter(*query.RegionQuery)\n\t\tlog.Printf(\"%d results match %q\", len(res), *query.RegionQuery)\n\t\treturn\n\t}\n\n\tif query.ProfileQuery != nil {\n\t\tfor _, profile := range awsconfig.GetAwsProfiles() {\n\t\t\tautocomplete := strings.Replace(rawQuery, aliases.OverrideAwsProfile+*query.ProfileQuery, aliases.OverrideAwsProfile+profile.Name+\" \", 1)\n\t\t\titem := wf.NewItem(profile.Name).\n\t\t\t\tIcon(aw.IconAccount).\n\t\t\t\tAutocomplete(autocomplete).\n\t\t\t\tUID(profile.Name)\n\n\t\t\tif profile.Region != \"\" {\n\t\t\t\titem.Subtitle(fmt.Sprintf(\"🌎 %s\", profile.Region))\n\t\t\t} else {\n\t\t\t\titem.Subtitle(\"⚠️ This profile does not specify a region. Functionality will be limited\")\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"filtering with profile override %q\", *query.ProfileQuery)\n\t\tres := wf.Filter(*query.ProfileQuery)\n\t\tlog.Printf(\"%d results match %q\", len(res), *query.ProfileQuery)\n\t\treturn\n\t}\n\n\tcfg := awsworkflow.InitAWS(transport, query.ProfileOverride, query.GetRegionOverride())\n\tsearchArgs := searchutil.SearchArgs{\n\t\tCfg:        cfg,\n\t\tForceFetch: forceFetch,\n\t\tFullQuery:  rawQuery,\n\t\tProfile:    util.GetProfile(cfg),\n\t}\n\n\tif query.IsEmpty() {\n\t\thandleEmptyQuery(wf, searchArgs)\n\t\treturn\n\t}\n\n\tif query.HasOpenAll {\n\t\thandleOpenAll(wf, query.Service, awsServices, openAll, rawQuery, cfg)\n\t\treturn\n\t}\n\n\tif query.Service == nil || (!query.HasTrailingWhitespace && query.SubService == nil && !query.HasDefaultSearchAlias && query.RemainingQuery == \"\") {\n\t\tif query.Service == nil {\n\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t} else if query.Service.ShortName != \"\" {\n\t\t\tsearchArgs.Query = strings.ToLower(query.Service.ShortName)\n\t\t} else {\n\t\t\tsearchArgs.Query = query.Service.Id\n\t\t}\n\t\tlog.Printf(\"using searcher associated with services with query %q\", searchArgs.Query)\n\t\tSearchServices(wf, awsServices, searchArgs)\n\t} else {\n\t\tif !query.HasDefaultSearchAlias && (query.Service.SubServices == nil || len(query.Service.SubServices) <= 0) {\n\t\t\thandleUnimplemented(wf, query.Service, nil, fmt.Sprintf(\"%s doesn't have sub-services configured (yet)\", query.Service.Id), searchArgs)\n\t\t\treturn\n\t\t}\n\n\t\tsearchArgs.GetRegionFunc = query.Service.GetRegion\n\n\t\tif query.HasDefaultSearchAlias || query.SubService != nil && (query.HasTrailingWhitespace || query.RemainingQuery != \"\") {\n\t\t\tserviceId := query.Service.Id\n\t\t\tif query.SubService != nil {\n\t\t\t\tserviceId += \"_\" + query.SubService.Id\n\t\t\t}\n\t\t\tlog.Println(\"using searcher associated with \" + serviceId)\n\t\t\tsearcher := searchers.SearchersByServiceId[serviceId]\n\t\t\tif searcher != nil {\n\t\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t\t\terr := searcher.Search(wf, searchArgs)\n\t\t\t\tif err != nil {\n\t\t\t\t\twf.FatalError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thandleUnimplemented(wf, query.Service, query.SubService, fmt.Sprintf(\"No searcher for `%s %s` (yet)\", query.Service.Id, query.SubService.Id), searchArgs)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Println(\"using searcher associated with sub-services\")\n\t\t\tif query.SubService != nil {\n\t\t\t\tsearchArgs.Query = query.SubService.Id\n\t\t\t} else {\n\t\t\t\tsearchArgs.Query = query.RemainingQuery\n\t\t\t}\n\t\t\tSearchSubServices(wf, *query.Service, searchArgs)\n\t\t}\n\t}\n\n\tif searchArgs.Query != \"\" {\n\t\tlog.Printf(\"filtering with query %q\", searchArgs.Query)\n\t\tres := wf.Filter(searchArgs.Query)\n\t\tlog.Printf(\"%d results match %q\", len(res), searchArgs.Query)\n\t}\n}\n\nfunc finalize(wf *aw.Workflow, query *parsers.Query) {\n\tif wf.IsEmpty() {\n\t\ttitle := \"\"\n\t\tsubtitle := \"\"\n\t\tif query.RegionQuery != nil {\n\t\t\ttitle = \"No matching regions found\"\n\t\t\tsubtitle = fmt.Sprintf(\"Try starting over with \\\"%s\\\" again to see the full list\", aliases.OverrideAwsRegion)\n\t\t} else if query.ProfileQuery != nil {\n\t\t\ttitle = \"No matching profiles found\"\n\t\t\tsubtitle = fmt.Sprintf(\"Try starting over with \\\"%s\\\" again to see the full list\", aliases.OverrideAwsProfile)\n\t\t} else {\n\t\t\ttitle = \"No matching services found\"\n\t\t\tsubtitle = \"Try another query (example: `aws ec2 instances`)\"\n\t\t}\n\t\twf.NewItem(title).\n\t\t\tSubtitle(subtitle).\n\t\t\tIcon(aw.IconNote)\n\t\thandleUpdateAvailable(wf)\n\t}\n\twf.SendFeedback()\n}\n\nfunc handleEmptyQuery(wf *aw.Workflow, searchArgs searchutil.SearchArgs) {\n\tlog.Println(\"no search type parsed\")\n\twf.NewItem(\"Search for an AWS Service ...\").\n\t\tSubtitle(\"e.g., cloudformation, ec2, s3 ...\")\n\n\tif searchArgs.Profile == \"\" {\n\t\tutil.NewURLItem(wf, \"No profile configured\").\n\t\t\tSubtitle(\"Select this option to open AWS docs on how to configure\").\n\t\t\tArg(\"https:\/\/aws.github.io\/aws-sdk-go-v2\/docs\/configuring-sdk\/#creating-the-config-file\").\n\t\t\tIcon(aw.IconWarning)\n\t} else {\n\t\twf.NewItem(\"Using profile \\\"\" + searchArgs.Profile + \"\\\"\").\n\t\t\tSubtitle(\"Use \\\"\" + aliases.OverrideAwsProfile + \"\\\" to override for the current query\").\n\t\t\tIcon(aw.IconAccount)\n\t}\n\n\tif searchArgs.Cfg.Region == \"\" {\n\t\tutil.NewURLItem(wf, \"No region configured for this profile\").\n\t\t\tSubtitle(\"Select this option to open AWS docs on how to configure\").\n\t\t\tArg(\"https:\/\/aws.github.io\/aws-sdk-go-v2\/docs\/configuring-sdk\/#creating-the-config-file\").\n\t\t\tIcon(aw.IconWarning)\n\t} else {\n\t\twf.NewItem(\"Using region \\\"\" + searchArgs.Cfg.Region + \"\\\"\").\n\t\t\tSubtitle(\"Use \\\"\" + aliases.OverrideAwsRegion + \"\\\" to override for the current query\").\n\t\t\tIcon(aw.IconWeb)\n\t}\n\n\tutil.NewURLItem(wf, \"Like this workflow? Consider donating! 😻\").\n\t\tSubtitle(\"Select this option to open this project's Patreon\").\n\t\tArg(\"https:\/\/www.patreon.com\/rkoval_alfred_aws_console_services_workflow\").\n\t\tIcon(aw.IconFavorite)\n\n\tif wf.UpdateCheckDue() {\n\t\tif err := wf.CheckForUpdate(); err != nil {\n\t\t\twf.FatalError(err)\n\t\t}\n\t}\n\thandleUpdateAvailable(wf)\n}\n\nfunc handleUnimplemented(wf *aw.Workflow, awsService, subService *awsworkflow.AwsService, header string, searchArgs searchutil.SearchArgs) {\n\tsearchArgs.IgnoreAutocompleteTerm = true\n\tif subService == nil {\n\t\tAddServiceToWorkflow(wf, *awsService, searchArgs)\n\t} else {\n\t\tAddSubServiceToWorkflow(wf, *awsService, *subService, searchArgs)\n\t}\n\tutil.NewURLItem(wf, header).\n\t\tSubtitle(\"Select this result to open the contributing guide to easily add them!\").\n\t\tArg(\"https:\/\/github.com\/rkoval\/alfred-aws-console-services-workflow\/blob\/master\/CONTRIBUTING.md\").\n\t\tIcon(aw.IconNote)\n\thandleUpdateAvailable(wf)\n}\n\nfunc handleUpdateAvailable(wf *aw.Workflow) {\n\tif wf.UpdateAvailable() {\n\t\tutil.NewURLItem(wf, fmt.Sprintf(\"Update available (current version: %s)\", wf.Version())).\n\t\t\tSubtitle(\"Select this result to navigate to download\").\n\t\t\tArg(\"https:\/\/github.com\/rkoval\/alfred-aws-console-services-workflow\/releases\").\n\t\t\tIcon(aw.IconInfo)\n\t}\n}\n\nfunc handleOpenAll(wf *aw.Workflow, awsService *awsworkflow.AwsService, allAwsServices []awsworkflow.AwsService, openAll bool, rawQuery string, cfg aws.Config) {\n\tif openAll {\n\t\tvar urls []string\n\t\tif awsService == nil {\n\t\t\tfor _, awsService := range allAwsServices {\n\t\t\t\turls = append(urls, openServiceInBrowser(wf, awsService, awsService, cfg))\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, subService := range awsService.SubServices {\n\t\t\t\turls = append(urls, openServiceInBrowser(wf, subService, *awsService, cfg))\n\t\t\t}\n\t\t}\n\t\t\/\/ write these to disk so that we can use this file to run automated validation against the pages as they redirect (or error) in AWS\n\t\tlastOpenedUrlsPath := wf.CacheDir() + \"\/last-opened-urls.json\"\n\t\turlBytes, err := json.Marshal(urls)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = ioutil.WriteFile(lastOpenedUrlsPath, urlBytes, 0600)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t} else {\n\t\tvar length int\n\t\tvar entityName string\n\t\tif awsService == nil {\n\t\t\tlength = len(allAwsServices)\n\t\t\tentityName = \"services\"\n\t\t} else {\n\t\t\tlength = len(awsService.SubServices)\n\t\t\tentityName = awsService.Id + \" sub-services\"\n\t\t}\n\n\t\ttitle := fmt.Sprintf(\"Open the %d %s in browser\", length, entityName)\n\t\tcmd := fmt.Sprintf(`%s -query=\"%s\" -open_all`, os.Args[0], rawQuery)\n\t\twf.NewItem(title).\n\t\t\tSubtitle(\"Fair warning: this may briefly overload your system\").\n\t\t\tIcon(aw.IconWarning).\n\t\t\tArg(cmd).\n\t\t\tVar(\"action\", \"run-script\").\n\t\t\tValid(true)\n\t}\n}\n\nfunc openServiceInBrowser(wf *aw.Workflow, awsService, awsServiceForRegion awsworkflow.AwsService, cfg aws.Config) string {\n\turl := util.ConstructAWSConsoleUrl(awsService.Url, awsServiceForRegion.GetRegion(cfg))\n\tlog.Printf(\"opening url: %s ...\", url)\n\tcmd := exec.Command(\"open\", url)\n\tif err := wf.RunInBackground(\"open-service-in-browser-\"+awsService.Id, cmd); err != nil {\n\t\tpanic(err)\n\t}\n\ttime.Sleep(250 * time.Millisecond) \/\/ sleep so that tabs are more-or-less opened in the order by which this function is called\n\treturn url\n}\n<|endoftext|>"}
{"text":"<commit_before>package mavlink\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Connection struct {\n\twrappedConn        io.ReadWriter\n\tchannel            chan *Packet\n\tcloseTime          chan time.Time\n\tcloseError         chan error\n\tclosed             bool\n\tlocalComponentSeq  [256]uint8\n\tremoteComponentSeq [256]uint8\n\tsystemID           uint8\n}\n\nfunc NewConnection(wrappedConn io.ReadWriter, systemID uint8) *Connection {\n\tconn := &Connection{\n\t\twrappedConn: wrappedConn,\n\t\tchannel:     make(chan *Packet, 64),\n\t\tcloseTime:   make(chan time.Time, 1),\n\t\tcloseError:  make(chan error),\n\t\tsystemID:    systemID,\n\t}\n\tgo conn.sendLoop()\n\tgo conn.receiveLoop()\n\treturn conn\n}\n\nfunc (conn *Connection) receiveLoop() {\n\tfor !conn.closed {\n\n\t\tpacket, err := Receive(conn.wrappedConn)\n\t\tif err != nil {\n\t\t\tif LogAllErrors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\tconn.close() \/\/ make sure everything is in closed state\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tconn.channel <- &Packet{Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcomponent := packet.Header.ComponentID\n\t\tloss := int(packet.Header.PacketSequence) - int(conn.remoteComponentSeq[component]) - 1\n\t\tif loss < 0 {\n\t\t\tloss = 255 - loss\n\t\t}\n\t\tif loss > 0 {\n\t\t\terr := ErrPacketLoss(loss)\n\t\t\tif LogAllErrors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tconn.channel <- &Packet{Err: err}\n\t\t}\n\n\t\tconn.channel <- packet\n\t}\n}\n\nfunc (conn *Connection) sendLoop() {\n\tfor !conn.closed {\n\t\tselect {\n\t\tcase packet := <-conn.channel:\n\t\t\tconn.localComponentSeq[packet.Header.ComponentID]++\n\t\t\tpacket.Header.PacketSequence = conn.localComponentSeq[packet.Header.ComponentID]\n\n\t\t\t_, packet.Err = packet.WriteTo(conn.wrappedConn)\n\t\t\tif packet.Err != nil {\n\t\t\t\tif LogAllErrors {\n\t\t\t\t\tlog.Println(packet.Err)\n\t\t\t\t}\n\t\t\t\tif packet.OnErr != nil {\n\t\t\t\t\tpacket.OnErr(packet)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n}\n\nfunc (conn *Connection) Send(componentID uint8, message Message, onErr func(*Packet)) {\n\tif conn.closed {\n\t\treturn\n\t}\n\n\tpacket := NewPacket(conn.systemID, componentID, 0, message)\n\tpacket.OnErr = onErr\n\n\tconn.channel <- packet\n}\n\nfunc (conn *Connection) Receive() *Packet {\n\tif conn.closed {\n\t\treturn nil\n\t}\n\n\treturn <-conn.channel\n}\n\nfunc (conn *Connection) close() (err error) {\n\tdefer func() { conn.closed = true }()\n\n\tif closer, ok := conn.wrappedConn.(io.Closer); ok {\n\t\terr = closer.Close()\n\t\tif err != nil && LogAllErrors {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (conn *Connection) Close(timeout time.Time) error {\n\treturn conn.close()\n\t\/\/ conn.closeTime <- timeout\n\t\/\/ return <-conn.closeError\n}\n<commit_msg>Close with timeout for write buffer<commit_after>package mavlink\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"time\"\n)\n\ntype Connection struct {\n\twrappedConn        io.ReadWriter\n\tchannel            chan *Packet\n\tcloseTimeout       time.Time\n\tsendLoopFinished   chan struct{}\n\tclosed             bool\n\tlocalComponentSeq  [256]uint8\n\tremoteComponentSeq [256]uint8\n\tsystemID           uint8\n}\n\nfunc NewConnection(wrappedConn io.ReadWriter, systemID uint8) *Connection {\n\tconn := &Connection{\n\t\twrappedConn:      wrappedConn,\n\t\tchannel:          make(chan *Packet, 64),\n\t\tsendLoopFinished: make(chan struct{}),\n\t\tsystemID:         systemID,\n\t}\n\tgo conn.sendLoop()\n\tgo conn.receiveLoop()\n\treturn conn\n}\n\nfunc (conn *Connection) receiveLoop() {\n\tfor !conn.closed {\n\n\t\tpacket, err := Receive(conn.wrappedConn)\n\t\tif err != nil {\n\t\t\tif LogAllErrors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\tconn.close() \/\/ make sure everything is in closed state\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tconn.channel <- &Packet{Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcomponent := packet.Header.ComponentID\n\t\tloss := int(packet.Header.PacketSequence) - int(conn.remoteComponentSeq[component]) - 1\n\t\tif loss < 0 {\n\t\t\tloss = 255 - loss\n\t\t}\n\t\tif loss > 0 {\n\t\t\terr := ErrPacketLoss(loss)\n\t\t\tif LogAllErrors {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tconn.channel <- &Packet{Err: err}\n\t\t}\n\n\t\tconn.channel <- packet\n\t}\n}\n\nfunc (conn *Connection) sendLoop() {\n\tfor !conn.closed || time.Now().Before(conn.closeTimeout) {\n\t\tselect {\n\t\tcase packet := <-conn.channel:\n\t\t\tconn.localComponentSeq[packet.Header.ComponentID]++\n\t\t\tpacket.Header.PacketSequence = conn.localComponentSeq[packet.Header.ComponentID]\n\n\t\t\t_, packet.Err = packet.WriteTo(conn.wrappedConn)\n\t\t\tif packet.Err != nil {\n\t\t\t\tif LogAllErrors {\n\t\t\t\t\tlog.Println(packet.Err)\n\t\t\t\t}\n\t\t\t\tif packet.OnErr != nil {\n\t\t\t\t\tgo packet.OnErr(packet)\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tif conn.closed {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t}\n\t}\n\tconn.sendLoopFinished <- struct{}{}\n}\n\nfunc (conn *Connection) Send(componentID uint8, message Message, onErr func(*Packet)) {\n\tif conn.closed {\n\t\treturn\n\t}\n\n\tpacket := NewPacket(conn.systemID, componentID, 0, message)\n\tpacket.OnErr = onErr\n\n\tconn.channel <- packet\n}\n\nfunc (conn *Connection) Receive() *Packet {\n\tif conn.closed {\n\t\treturn nil\n\t}\n\n\treturn <-conn.channel\n}\n\nfunc (conn *Connection) close() (err error) {\n\tdefer func() { conn.closed = true }()\n\n\tif closer, ok := conn.wrappedConn.(io.Closer); ok {\n\t\terr = closer.Close()\n\t\tif err != nil && LogAllErrors {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\treturn err\n}\n\n\/\/ Close stops reading from wrappedConn after the current read finishes\n\/\/ and stops writing when there are no more buffered packets or\n\/\/ the current time has reached timeout.\n\/\/ After that, if wrappedConn implements io.Closer, its Close method will\n\/\/ be called and the result returned.\nfunc (conn *Connection) Close(timeout time.Time) error {\n\tconn.closeTimeout = timeout\n\tconn.closed = true\n\t<-conn.sendLoopFinished\n\treturn conn.close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package mailserver\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\nconst (\n\tmaxMessagesRequestPayloadLimit = 1000\n)\n\n\/\/ MessagesRequestPayload is a payload sent to the Mail Server.\ntype MessagesRequestPayload struct {\n\t\/\/ Lower is a lower bound of time range for which messages are requested.\n\tLower uint32\n\t\/\/ Upper is a lower bound of time range for which messages are requested.\n\tUpper uint32\n\t\/\/ Bloom is a bloom filter to filter envelopes.\n\tBloom []byte\n\t\/\/ Limit is the max number of envelopes to return.\n\tLimit uint32\n\t\/\/ Cursor is used for pagination of the results.\n\tCursor []byte\n\t\/\/ Batch set to true indicates that the client supports batched response.\n\tBatch bool\n}\n\nfunc (r *MessagesRequestPayload) SetDefaults() {\n\tif r.Limit == 0 {\n\t\tr.Limit = maxQueryLimit\n\t}\n\n\tif r.Upper == 0 {\n\t\tr.Upper = uint32(time.Now().Unix() + whisperTTLSafeThreshold)\n\t}\n}\n\nfunc (r MessagesRequestPayload) Validate() error {\n\tif r.Upper < r.Lower {\n\t\treturn errors.New(\"query range is invalid: lower > upper\")\n\t}\n\tif r.Upper-r.Lower > uint32(maxQueryRange.Seconds()) {\n\t\treturn errors.New(\"query range must be smaller or equal to 24 hours\")\n\t}\n\tif len(r.Bloom) == 0 {\n\t\treturn errors.New(\"bloom filter is empty\")\n\t}\n\tif r.Limit > maxMessagesRequestPayloadLimit {\n\t\treturn errors.New(\"limit exceeds the maximum allowed value\")\n\t}\n\treturn nil\n}\n<commit_msg>Remove 24h time range validation from maislerver request (#1792)<commit_after>package mailserver\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\nconst (\n\tmaxMessagesRequestPayloadLimit = 1000\n)\n\n\/\/ MessagesRequestPayload is a payload sent to the Mail Server.\ntype MessagesRequestPayload struct {\n\t\/\/ Lower is a lower bound of time range for which messages are requested.\n\tLower uint32\n\t\/\/ Upper is a lower bound of time range for which messages are requested.\n\tUpper uint32\n\t\/\/ Bloom is a bloom filter to filter envelopes.\n\tBloom []byte\n\t\/\/ Limit is the max number of envelopes to return.\n\tLimit uint32\n\t\/\/ Cursor is used for pagination of the results.\n\tCursor []byte\n\t\/\/ Batch set to true indicates that the client supports batched response.\n\tBatch bool\n}\n\nfunc (r *MessagesRequestPayload) SetDefaults() {\n\tif r.Limit == 0 {\n\t\tr.Limit = maxQueryLimit\n\t}\n\n\tif r.Upper == 0 {\n\t\tr.Upper = uint32(time.Now().Unix() + whisperTTLSafeThreshold)\n\t}\n}\n\nfunc (r MessagesRequestPayload) Validate() error {\n\tif r.Upper < r.Lower {\n\t\treturn errors.New(\"query range is invalid: lower > upper\")\n\t}\n\tif len(r.Bloom) == 0 {\n\t\treturn errors.New(\"bloom filter is empty\")\n\t}\n\tif r.Limit > maxMessagesRequestPayloadLimit {\n\t\treturn errors.New(\"limit exceeds the maximum allowed value\")\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\ntype ContactStore struct {\n}\n\nfunc NewContactStore() *ContactStore {\n\treturn &ContactStore{}\n}\n\nfunc (c *ContactStore) AddContact(userId string, contactId string) bool {\n\treturn true\n}\n\nfunc (c *ContactStore) RemoveContact(userId string, contactId string) bool {\n\treturn true\n}\n\nfunc (c *ContactStore) ListContacts(userId string) ([]string, bool) {\n\treturn []string{}, true\n}\n\nfunc (c *ContactStore) SearchContact(userId string, contactName string) string {\n\treturn \"\"\n}\n<commit_msg>Implement inmemory contact store<commit_after>package server\n\nimport \"log\"\n\ntype ContactStore struct {\n\tcontacts map[string][]string\n}\n\nfunc NewContactStore() *ContactStore {\n\treturn &ContactStore{\n\t\tcontacts: make(map[string][]string),\n\t}\n}\n\nfunc (c *ContactStore) AddContact(userId string, contactId string) bool {\n\tuserContacts, ok := c.contacts[userId]\n\tif !ok {\n\t\tc.contacts[userId] = []string{}\n\t\tuserContacts = c.contacts[userId]\n\t}\n\n\tuserContacts = append(userContacts, contactId)\n\treturn true\n}\n\nfunc (c *ContactStore) RemoveContact(userId string, contactId string) bool {\n\tuserContacts, ok := c.contacts[userId]\n\tif !ok {\n\t\tlog.Println(\"No contacts for user\", userId)\n\t\treturn false\n\t}\n\n\tfor i, uc := range userContacts {\n\t\tif uc == contactId {\n\t\t\tuserContacts = append(userContacts[:i], userContacts[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (c *ContactStore) ListContacts(userId string) ([]string, bool) {\n\tuserContacts, ok := c.contacts[userId]\n\tif !ok {\n\t\treturn []string{}, false\n\t}\n\n\treturn userContacts, true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Email is designed to be a package providing an \"email interface for humans.\"\n\/\/Designed to be robust and flexible, the email package will make sending email easy without getting in the way.\npackage email\n\nimport (\n\t\"net\/mail\"\n)\n\n\/\/Email is the type used for email messages\ntype Email struct {\n\tFrom        string\n\tTo          []string\n\tBcc         []string\n\tCc          []string\n\tSubject     []string\n\tText        []byte \/\/Plaintext message (optional)\n\tHtml        []byte \/\/Html message (optional)\n\tHeaders     []mail.Header\n\tAttachments []Attachment \/\/Might be a map soon - stay tuned.\n}\n\n\/\/Send an email using the given host and SMTP auth (optional)\nfunc (e Email) Send() {\n\n}\n\ntype Attachment struct {\n\tFilename string\n}\n<commit_msg>Update email.go<commit_after>\/\/Email is designed to be a package providing an \"email interface for humans.\"\n\/\/Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.\npackage email\n\nimport (\n\t\"net\/mail\"\n)\n\n\/\/Email is the type used for email messages\ntype Email struct {\n\tFrom        string\n\tTo          []string\n\tBcc         []string\n\tCc          []string\n\tSubject     []string\n\tText        []byte \/\/Plaintext message (optional)\n\tHtml        []byte \/\/Html message (optional)\n\tHeaders     []mail.Header\n\tAttachments []Attachment \/\/Might be a map soon - stay tuned.\n}\n\n\/\/Send an email using the given host and SMTP auth (optional)\nfunc (e Email) Send() {\n\n}\n\ntype Attachment struct {\n\tFilename string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ClientStarter\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/jzipfler\/htw\/ava\/client\"\n\t\"github.com\/jzipfler\/htw\/ava\/server\"\n\t\"log\"\n)\n\nvar (\n\tloggingBuffer bytes.Buffer\n\tlogger        *log.Logger\n)\n\nfunc main() {\n\tinitializeLogger(\"LOG::: \")\n\tclient := client.New()\n\tserverObject := server.New()\n\tlogger.Printf(\"%T\\n\", client)\n\tlogger.Printf(\"%T\\n\", serverObject)\n\tlogger.Println(\"Client: \" + client.String() + \"\\nServer: \" + serverObject.String())\n\terror := client.SetIpAddressAsString(\"1.2.3.4\")\n\tif error != nil {\n\t\tlogger.Fatalln(error)\n\t\treturn\n\t}\n\tclient.SetClientName(\"First\")\n\tlogger.Println(client)\n\n\tprintAndClearLoggerContent()\n}\n\nfunc initializeLogger(preface string) {\n\tlogger = log.New(&loggingBuffer, preface, log.Lshortfile)\n}\n\nfunc printAndClearLoggerContent() {\n\tif loggingBuffer.Len() != 0 {\n\t\tfmt.Println(&loggingBuffer)\n\t\tloggingBuffer.Reset()\n\t}\n}\n<commit_msg>Implemented the first tries to the ClientStarter.<commit_after>\/\/ ClientStarter\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/jzipfler\/htw\/ava\/client\"\n\t\"github.com\/jzipfler\/htw\/ava\/server\"\n\t\"log\"\n)\n\nvar (\n\tloggingBuffer bytes.Buffer\n\tlogger        *log.Logger\n)\n\nfunc main() {\n\t\/\/initializeLogger(\"LOG::: \")\n\tclient := client.New()\n\tserverObject := server.New()\n\tprintMessage(\"Client: \" + client.String() + \"\\n\\t\\tServer: \" + serverObject.String())\n\terror := client.SetIpAddressAsString(\"1.2.3.4\")\n\tif error != nil {\n\t\tprintMessage(error.Error())\n\t\treturn\n\t}\n\tclient.SetClientName(\"First\")\n\tprintMessage(client.String())\n\n\tdoServerStuff(serverObject)\n\n\tprintAndClearLoggerContent()\n}\n\nfunc doServerStuff(serverObject server.NetworkServer) {\n\tserverObject.SetClientName(\"Server1\")\n\tserverObject.SetIpAddressAsString(\"127.0.0.1\")\n\tserverObject.SetPort(15108)\n\tserverObject.SetUsedProtocol(\"tcp\")\n\tprintMessage(serverObject.String())\n\terr := server.StartServer(serverObject, logger)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer server.StopServer()\n\t\/\/for {\n\t\/\/\tconnection := server.ReceiveMessage()\n\t\/\/\tprintMessage(connection.LocalAddr().String())\n\t\/\/}\n}\n\n\/\/ Creates a new logger which uses a buffer where he collects the messages.\nfunc initializeLogger(preface string) {\n\tlogger = log.New(&loggingBuffer, preface, log.Lshortfile)\n}\n\nfunc printMessage(message string) {\n\tif logger == nil {\n\t\tlog.Println(message)\n\t} else {\n\t\tlogger.Println(message)\n\t}\n}\n\nfunc printAndClearLoggerContent() {\n\tif loggingBuffer.Len() != 0 {\n\t\tfmt.Println(&loggingBuffer)\n\t\tloggingBuffer.Reset()\n\t}\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>package aws\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\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\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/arn\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/rds\"\n)\n\nfunc resourceAwsDbParameterGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsDbParameterGroupCreate,\n\t\tRead:   resourceAwsDbParameterGroupRead,\n\t\tUpdate: resourceAwsDbParameterGroupUpdate,\n\t\tDelete: resourceAwsDbParameterGroupDelete,\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\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"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\tConflictsWith: []string{\"name_prefix\"},\n\t\t\t\tValidateFunc:  validateDbParamGroupName,\n\t\t\t},\n\t\t\t\"name_prefix\": &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\tValidateFunc: validateDbParamGroupNamePrefix,\n\t\t\t},\n\t\t\t\"family\": &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\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDefault:  \"Managed by Terraform\",\n\t\t\t},\n\t\t\t\"parameter\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: false,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"name\": &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},\n\t\t\t\t\t\t\"value\": &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},\n\t\t\t\t\t\t\"apply_method\": &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:  \"immediate\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSet: resourceAwsDbParameterHash,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsDbParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\ttags := tagsFromMapRDS(d.Get(\"tags\").(map[string]interface{}))\n\n\tvar groupName string\n\tif v, ok := d.GetOk(\"name\"); ok {\n\t\tgroupName = v.(string)\n\t} else if v, ok := d.GetOk(\"name_prefix\"); ok {\n\t\tgroupName = resource.PrefixedUniqueId(v.(string))\n\t} else {\n\t\tgroupName = resource.UniqueId()\n\t}\n\td.Set(\"name\", groupName)\n\n\tcreateOpts := rds.CreateDBParameterGroupInput{\n\t\tDBParameterGroupName:   aws.String(groupName),\n\t\tDBParameterGroupFamily: aws.String(d.Get(\"family\").(string)),\n\t\tDescription:            aws.String(d.Get(\"description\").(string)),\n\t\tTags:                   tags,\n\t}\n\n\tlog.Printf(\"[DEBUG] Create DB Parameter Group: %#v\", createOpts)\n\t_, err := rdsconn.CreateDBParameterGroup(&createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating DB Parameter Group: %s\", err)\n\t}\n\n\td.Partial(true)\n\td.SetPartial(\"name\")\n\td.SetPartial(\"family\")\n\td.SetPartial(\"description\")\n\td.Partial(false)\n\n\td.SetId(*createOpts.DBParameterGroupName)\n\tlog.Printf(\"[INFO] DB Parameter Group ID: %s\", d.Id())\n\n\treturn resourceAwsDbParameterGroupUpdate(d, meta)\n}\n\nfunc resourceAwsDbParameterGroupRead(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\n\tdescribeOpts := rds.DescribeDBParameterGroupsInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\n\tdescribeResp, err := rdsconn.DescribeDBParameterGroups(&describeOpts)\n\tif err != nil {\n\t\tif isAWSErr(err, rds.ErrCodeDBParameterGroupNotFoundFault, \"\") {\n\t\t\tlog.Printf(\"[WARN] DB Parameter Group (%s) not found, removing from state\", d.Id())\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif len(describeResp.DBParameterGroups) != 1 ||\n\t\t*describeResp.DBParameterGroups[0].DBParameterGroupName != d.Id() {\n\t\treturn fmt.Errorf(\"Unable to find Parameter Group: %#v\", describeResp.DBParameterGroups)\n\t}\n\n\td.Set(\"name\", describeResp.DBParameterGroups[0].DBParameterGroupName)\n\td.Set(\"family\", describeResp.DBParameterGroups[0].DBParameterGroupFamily)\n\td.Set(\"description\", describeResp.DBParameterGroups[0].Description)\n\n\tconfigParams := d.Get(\"parameter\").(*schema.Set)\n\tdescribeParametersOpts := rds.DescribeDBParametersInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\tif configParams.Len() < 1 {\n\t\t\/\/ if we don't have any params in the ResourceData already, two possibilities\n\t\t\/\/ first, we don't have a config available to us. Second, we do, but it has\n\t\t\/\/ no parameters. We're going to assume the first, to be safe. In this case,\n\t\t\/\/ we're only going to ask for the user-modified values, because any defaults\n\t\t\/\/ the user may have _also_ set are indistinguishable from the hundreds of\n\t\t\/\/ defaults AWS sets. If the user hasn't set any parameters, this will return\n\t\t\/\/ an empty list anyways, so we just make some unnecessary requests. But in\n\t\t\/\/ the more common case (I assume) of an import, this will make fewer requests\n\t\t\/\/ and \"do the right thing\".\n\t\tdescribeParametersOpts.Source = aws.String(\"user\")\n\t}\n\n\tvar parameters []*rds.Parameter\n\terr = rdsconn.DescribeDBParametersPages(&describeParametersOpts,\n\t\tfunc(describeParametersResp *rds.DescribeDBParametersOutput, lastPage bool) bool {\n\t\t\tparameters = append(parameters, describeParametersResp.Parameters...)\n\t\t\treturn !lastPage\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar userParams []*rds.Parameter\n\tif configParams.Len() < 1 {\n\t\t\/\/ if we have no config\/no parameters in config, we've already asked for only\n\t\t\/\/ user-modified values, so we can just use the entire response.\n\t\tuserParams = parameters\n\t} else {\n\t\t\/\/ if we have a config available to us, we have two possible classes of value\n\t\t\/\/ in the config. On the one hand, the user could have specified a parameter\n\t\t\/\/ that _actually_ changed things, in which case its Source would be set to\n\t\t\/\/ user. On the other, they may have specified a parameter that coincides with\n\t\t\/\/ the default value. In that case, the Source will be set to \"system\" or\n\t\t\/\/ \"engine-default\". We need to set the union of all \"user\" Source parameters\n\t\t\/\/ _and_ the \"system\"\/\"engine-default\" Source parameters _that appear in the\n\t\t\/\/ config_ in the state, or the user gets a perpetual diff. See\n\t\t\/\/ terraform-providers\/terraform-provider-aws#593 for more context and details.\n\t\tconfParams, err := expandParameters(configParams.List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, param := range parameters {\n\t\t\tif param.Source == nil || param.ParameterName == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif *param.Source == \"user\" {\n\t\t\t\tuserParams = append(userParams, param)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar paramFound bool\n\t\t\tfor _, cp := range confParams {\n\t\t\t\tif cp.ParameterName == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif *cp.ParameterName == *param.ParameterName {\n\t\t\t\t\tuserParams = append(userParams, param)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !paramFound {\n\t\t\t\tlog.Printf(\"[DEBUG] Not persisting %s to state, as its source is %q and it isn't in the config\", *param.ParameterName, *param.Source)\n\t\t\t}\n\t\t}\n\t}\n\n\terr = d.Set(\"parameter\", flattenParameters(userParams))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error setting 'parameter' in state: %#v\", err)\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: meta.(*AWSClient).partition,\n\t\tService:   \"rds\",\n\t\tRegion:    meta.(*AWSClient).region,\n\t\tAccountID: meta.(*AWSClient).accountid,\n\t\tResource:  fmt.Sprintf(\"pg:%s\", d.Id()),\n\t}.String()\n\td.Set(\"arn\", arn)\n\tresp, err := rdsconn.ListTagsForResource(&rds.ListTagsForResourceInput{\n\t\tResourceName: aws.String(arn),\n\t})\n\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error retrieving tags for ARN: %s\", arn)\n\t}\n\n\tvar dt []*rds.Tag\n\tif len(resp.TagList) > 0 {\n\t\tdt = resp.TagList\n\t}\n\td.Set(\"tags\", tagsToMapRDS(dt))\n\n\treturn nil\n}\n\nfunc resourceAwsDbParameterGroupUpdate(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\n\td.Partial(true)\n\n\tif d.HasChange(\"parameter\") {\n\t\to, n := d.GetChange(\"parameter\")\n\t\tif o == nil {\n\t\t\to = new(schema.Set)\n\t\t}\n\t\tif n == nil {\n\t\t\tn = new(schema.Set)\n\t\t}\n\n\t\tos := o.(*schema.Set)\n\t\tns := n.(*schema.Set)\n\n\t\t\/\/ Expand the \"parameter\" set to aws-sdk-go compat []rds.Parameter\n\t\tparameters, err := expandParameters(ns.Difference(os).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(parameters) > 0 {\n\t\t\t\/\/ We can only modify 20 parameters at a time, so walk them until\n\t\t\t\/\/ we've got them all.\n\t\t\tmaxParams := 20\n\t\t\tfor parameters != nil {\n\t\t\t\tparamsToModify := make([]*rds.Parameter, 0)\n\t\t\t\tif len(parameters) <= maxParams {\n\t\t\t\t\tparamsToModify, parameters = parameters[:], nil\n\t\t\t\t} else {\n\t\t\t\t\tparamsToModify, parameters = parameters[:maxParams], parameters[maxParams:]\n\t\t\t\t}\n\t\t\t\tmodifyOpts := rds.ModifyDBParameterGroupInput{\n\t\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\t\tParameters:           paramsToModify,\n\t\t\t\t}\n\n\t\t\t\tlog.Printf(\"[DEBUG] Modify DB Parameter Group: %s\", modifyOpts)\n\t\t\t\t_, err = rdsconn.ModifyDBParameterGroup(&modifyOpts)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error modifying DB Parameter Group: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\td.SetPartial(\"parameter\")\n\t\t}\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: meta.(*AWSClient).partition,\n\t\tService:   \"rds\",\n\t\tRegion:    meta.(*AWSClient).region,\n\t\tAccountID: meta.(*AWSClient).accountid,\n\t\tResource:  fmt.Sprintf(\"pg:%s\", d.Id()),\n\t}.String()\n\tif err := setTagsRDS(rdsconn, d, arn); err != nil {\n\t\treturn err\n\t} else {\n\t\td.SetPartial(\"tags\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsDbParameterGroupRead(d, meta)\n}\n\nfunc resourceAwsDbParameterGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).rdsconn\n\treturn resource.Retry(3*time.Minute, func() *resource.RetryError {\n\t\tdeleteOpts := rds.DeleteDBParameterGroupInput{\n\t\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\t}\n\n\t\t_, err := conn.DeleteDBParameterGroup(&deleteOpts)\n\t\tif err != nil {\n\t\t\tawsErr, ok := err.(awserr.Error)\n\t\t\tif ok && awsErr.Code() == \"DBParameterGroupNotFoundFault\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif ok && awsErr.Code() == \"InvalidDBParameterGroupState\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t}\n\t\treturn resource.NonRetryableError(err)\n\t})\n}\n\nfunc resourceAwsDbParameterHash(v interface{}) int {\n\tvar buf bytes.Buffer\n\tm := v.(map[string]interface{})\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"name\"].(string)))\n\t\/\/ Store the value as a lower case string, to match how we store them in flattenParameters\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", strings.ToLower(m[\"value\"].(string))))\n\n\treturn hashcode.String(buf.String())\n}\n<commit_msg>set arn from parameter group response<commit_after>package aws\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\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\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)\n\nfunc resourceAwsDbParameterGroup() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsDbParameterGroupCreate,\n\t\tRead:   resourceAwsDbParameterGroupRead,\n\t\tUpdate: resourceAwsDbParameterGroupUpdate,\n\t\tDelete: resourceAwsDbParameterGroupDelete,\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\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"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\tConflictsWith: []string{\"name_prefix\"},\n\t\t\t\tValidateFunc:  validateDbParamGroupName,\n\t\t\t},\n\t\t\t\"name_prefix\": &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\tValidateFunc: validateDbParamGroupNamePrefix,\n\t\t\t},\n\t\t\t\"family\": &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\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDefault:  \"Managed by Terraform\",\n\t\t\t},\n\t\t\t\"parameter\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: false,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"name\": &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},\n\t\t\t\t\t\t\"value\": &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},\n\t\t\t\t\t\t\"apply_method\": &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:  \"immediate\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSet: resourceAwsDbParameterHash,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsDbParameterGroupCreate(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\ttags := tagsFromMapRDS(d.Get(\"tags\").(map[string]interface{}))\n\n\tvar groupName string\n\tif v, ok := d.GetOk(\"name\"); ok {\n\t\tgroupName = v.(string)\n\t} else if v, ok := d.GetOk(\"name_prefix\"); ok {\n\t\tgroupName = resource.PrefixedUniqueId(v.(string))\n\t} else {\n\t\tgroupName = resource.UniqueId()\n\t}\n\td.Set(\"name\", groupName)\n\n\tcreateOpts := rds.CreateDBParameterGroupInput{\n\t\tDBParameterGroupName:   aws.String(groupName),\n\t\tDBParameterGroupFamily: aws.String(d.Get(\"family\").(string)),\n\t\tDescription:            aws.String(d.Get(\"description\").(string)),\n\t\tTags:                   tags,\n\t}\n\n\tlog.Printf(\"[DEBUG] Create DB Parameter Group: %#v\", createOpts)\n\tresp, err := rdsconn.CreateDBParameterGroup(&createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating DB Parameter Group: %s\", err)\n\t}\n\n\td.Partial(true)\n\td.SetPartial(\"name\")\n\td.SetPartial(\"family\")\n\td.SetPartial(\"description\")\n\td.Partial(false)\n\n\td.SetId(aws.StringValue(resp.DBParameterGroup.DBParameterGroupName))\n\td.Set(\"arn\", resp.DBParameterGroup.DBParameterGroupArn)\n\tlog.Printf(\"[INFO] DB Parameter Group ID: %s\", d.Id())\n\n\treturn resourceAwsDbParameterGroupUpdate(d, meta)\n}\n\nfunc resourceAwsDbParameterGroupRead(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\n\tdescribeOpts := rds.DescribeDBParameterGroupsInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\n\tdescribeResp, err := rdsconn.DescribeDBParameterGroups(&describeOpts)\n\tif err != nil {\n\t\tif isAWSErr(err, rds.ErrCodeDBParameterGroupNotFoundFault, \"\") {\n\t\t\tlog.Printf(\"[WARN] DB Parameter Group (%s) not found, removing from state\", d.Id())\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif len(describeResp.DBParameterGroups) != 1 ||\n\t\t*describeResp.DBParameterGroups[0].DBParameterGroupName != d.Id() {\n\t\treturn fmt.Errorf(\"Unable to find Parameter Group: %#v\", describeResp.DBParameterGroups)\n\t}\n\n\td.Set(\"name\", describeResp.DBParameterGroups[0].DBParameterGroupName)\n\td.Set(\"family\", describeResp.DBParameterGroups[0].DBParameterGroupFamily)\n\td.Set(\"description\", describeResp.DBParameterGroups[0].Description)\n\n\tconfigParams := d.Get(\"parameter\").(*schema.Set)\n\tdescribeParametersOpts := rds.DescribeDBParametersInput{\n\t\tDBParameterGroupName: aws.String(d.Id()),\n\t}\n\tif configParams.Len() < 1 {\n\t\t\/\/ if we don't have any params in the ResourceData already, two possibilities\n\t\t\/\/ first, we don't have a config available to us. Second, we do, but it has\n\t\t\/\/ no parameters. We're going to assume the first, to be safe. In this case,\n\t\t\/\/ we're only going to ask for the user-modified values, because any defaults\n\t\t\/\/ the user may have _also_ set are indistinguishable from the hundreds of\n\t\t\/\/ defaults AWS sets. If the user hasn't set any parameters, this will return\n\t\t\/\/ an empty list anyways, so we just make some unnecessary requests. But in\n\t\t\/\/ the more common case (I assume) of an import, this will make fewer requests\n\t\t\/\/ and \"do the right thing\".\n\t\tdescribeParametersOpts.Source = aws.String(\"user\")\n\t}\n\n\tvar parameters []*rds.Parameter\n\terr = rdsconn.DescribeDBParametersPages(&describeParametersOpts,\n\t\tfunc(describeParametersResp *rds.DescribeDBParametersOutput, lastPage bool) bool {\n\t\t\tparameters = append(parameters, describeParametersResp.Parameters...)\n\t\t\treturn !lastPage\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar userParams []*rds.Parameter\n\tif configParams.Len() < 1 {\n\t\t\/\/ if we have no config\/no parameters in config, we've already asked for only\n\t\t\/\/ user-modified values, so we can just use the entire response.\n\t\tuserParams = parameters\n\t} else {\n\t\t\/\/ if we have a config available to us, we have two possible classes of value\n\t\t\/\/ in the config. On the one hand, the user could have specified a parameter\n\t\t\/\/ that _actually_ changed things, in which case its Source would be set to\n\t\t\/\/ user. On the other, they may have specified a parameter that coincides with\n\t\t\/\/ the default value. In that case, the Source will be set to \"system\" or\n\t\t\/\/ \"engine-default\". We need to set the union of all \"user\" Source parameters\n\t\t\/\/ _and_ the \"system\"\/\"engine-default\" Source parameters _that appear in the\n\t\t\/\/ config_ in the state, or the user gets a perpetual diff. See\n\t\t\/\/ terraform-providers\/terraform-provider-aws#593 for more context and details.\n\t\tconfParams, err := expandParameters(configParams.List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, param := range parameters {\n\t\t\tif param.Source == nil || param.ParameterName == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif *param.Source == \"user\" {\n\t\t\t\tuserParams = append(userParams, param)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar paramFound bool\n\t\t\tfor _, cp := range confParams {\n\t\t\t\tif cp.ParameterName == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif *cp.ParameterName == *param.ParameterName {\n\t\t\t\t\tuserParams = append(userParams, param)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !paramFound {\n\t\t\t\tlog.Printf(\"[DEBUG] Not persisting %s to state, as its source is %q and it isn't in the config\", *param.ParameterName, *param.Source)\n\t\t\t}\n\t\t}\n\t}\n\n\terr = d.Set(\"parameter\", flattenParameters(userParams))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error setting 'parameter' in state: %#v\", err)\n\t}\n\n\tarn := aws.StringValue(describeResp.DBParameterGroups[0].DBParameterGroupArn)\n\td.Set(\"arn\", arn)\n\n\tresp, err := rdsconn.ListTagsForResource(&rds.ListTagsForResourceInput{\n\t\tResourceName: aws.String(arn),\n\t})\n\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error retrieving tags for ARN: %s\", arn)\n\t}\n\n\tvar dt []*rds.Tag\n\tif len(resp.TagList) > 0 {\n\t\tdt = resp.TagList\n\t}\n\td.Set(\"tags\", tagsToMapRDS(dt))\n\n\treturn nil\n}\n\nfunc resourceAwsDbParameterGroupUpdate(d *schema.ResourceData, meta interface{}) error {\n\trdsconn := meta.(*AWSClient).rdsconn\n\n\td.Partial(true)\n\n\tif d.HasChange(\"parameter\") {\n\t\to, n := d.GetChange(\"parameter\")\n\t\tif o == nil {\n\t\t\to = new(schema.Set)\n\t\t}\n\t\tif n == nil {\n\t\t\tn = new(schema.Set)\n\t\t}\n\n\t\tos := o.(*schema.Set)\n\t\tns := n.(*schema.Set)\n\n\t\t\/\/ Expand the \"parameter\" set to aws-sdk-go compat []rds.Parameter\n\t\tparameters, err := expandParameters(ns.Difference(os).List())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(parameters) > 0 {\n\t\t\t\/\/ We can only modify 20 parameters at a time, so walk them until\n\t\t\t\/\/ we've got them all.\n\t\t\tmaxParams := 20\n\t\t\tfor parameters != nil {\n\t\t\t\tparamsToModify := make([]*rds.Parameter, 0)\n\t\t\t\tif len(parameters) <= maxParams {\n\t\t\t\t\tparamsToModify, parameters = parameters[:], nil\n\t\t\t\t} else {\n\t\t\t\t\tparamsToModify, parameters = parameters[:maxParams], parameters[maxParams:]\n\t\t\t\t}\n\t\t\t\tmodifyOpts := rds.ModifyDBParameterGroupInput{\n\t\t\t\t\tDBParameterGroupName: aws.String(d.Get(\"name\").(string)),\n\t\t\t\t\tParameters:           paramsToModify,\n\t\t\t\t}\n\n\t\t\t\tlog.Printf(\"[DEBUG] Modify DB Parameter Group: %s\", modifyOpts)\n\t\t\t\t_, err = rdsconn.ModifyDBParameterGroup(&modifyOpts)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error modifying DB Parameter Group: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\td.SetPartial(\"parameter\")\n\t\t}\n\t}\n\n\tif err := setTagsRDS(rdsconn, d, d.Get(\"arn\").(string)); err != nil {\n\t\treturn err\n\t} else {\n\t\td.SetPartial(\"tags\")\n\t}\n\n\td.Partial(false)\n\n\treturn resourceAwsDbParameterGroupRead(d, meta)\n}\n\nfunc resourceAwsDbParameterGroupDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).rdsconn\n\treturn resource.Retry(3*time.Minute, func() *resource.RetryError {\n\t\tdeleteOpts := rds.DeleteDBParameterGroupInput{\n\t\t\tDBParameterGroupName: aws.String(d.Id()),\n\t\t}\n\n\t\t_, err := conn.DeleteDBParameterGroup(&deleteOpts)\n\t\tif err != nil {\n\t\t\tawsErr, ok := err.(awserr.Error)\n\t\t\tif ok && awsErr.Code() == \"DBParameterGroupNotFoundFault\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t\tif ok && awsErr.Code() == \"InvalidDBParameterGroupState\" {\n\t\t\t\treturn resource.RetryableError(err)\n\t\t\t}\n\t\t}\n\t\treturn resource.NonRetryableError(err)\n\t})\n}\n\nfunc resourceAwsDbParameterHash(v interface{}) int {\n\tvar buf bytes.Buffer\n\tm := v.(map[string]interface{})\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"name\"].(string)))\n\t\/\/ Store the value as a lower case string, to match how we store them in flattenParameters\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", strings.ToLower(m[\"value\"].(string))))\n\n\treturn hashcode.String(buf.String())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2015, UPMC Enterprises\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    * 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 copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name UPMC Enterprises nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL UPMC ENTERPRISES BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON 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*\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"k8s.io\/client-go\/1.4\/kubernetes\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/rest\"\n)\n\nvar (\n\targListenPort        = flag.Int(\"listen-port\", 9080, \"port to have API listen\")\n\targDockerRegistry    = flag.String(\"docker-registry\", \"\", \"docker registry to use\")\n\targKubecfgFile       = flag.String(\"kubecfg-file\", \"\", \"Location of kubecfg file for access to kubernetes master service; --kube_master_url overrides the URL part of this; if neither this nor --kube_master_url are provided, defaults to service account tokens\")\n\targKubeMasterURL     = flag.String(\"kube-master-url\", \"\", \"URL to reach kubernetes master. Env variables in this flag will be expanded.\")\n\targTemplateNamespace = flag.String(\"template-namespace\", \"template\", \"Namespace to 'clone from when creating new deployments'\")\n\targPathToTokens      = flag.String(\"path-to-tokens\", \"\", \"Full path including file name to tokens file for authorization, setting to empty string will disable.\")\n\targSubDomain         = flag.String(\"subdomain\", \"k8s.local.com\", \"Subdomain used to configure external routing to branch (e.g. namespace.ci.k8s.local)\")\n\tclient               *kubernetes.Clientset\n\tdefaultReplicaCount  *int32\n)\n\nconst (\n\tappVersion = \"0.0.3\"\n)\n\n\/\/ Default (GET \"\/\")\nfunc indexRoute(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, %s\", \"welcome to Emmie!\")\n}\n\n\/\/ Version (GET \"\/version\")\nfunc versionRoute(w http.ResponseWriter, r *http.Request) {\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%q\", appVersion)\n}\n\n\/\/ Deploy (POST \"\/deploy\/namespace\/branchName\")\nfunc deployRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\timageNamespace := vars[\"namespace\"]\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\tlog.Println(\"[Emmie] is deploying branch:\", branchName)\n\n\t\/\/ create namespace\n\terr := createNamespace(branchName)\n\n\tif err != nil {\n\t\t\/\/ TODO: Don't use error for logic\n\t\t\/\/ Existing namespace, do an update\n\t\tlog.Println(\"Existing namespace found: \", branchName, \" deleting pods.\")\n\n\t\tdeletePodsByNamespace(branchName)\n\t} else {\n\t\tlog.Println(\"Namespace created, deploying new app...\")\n\n\t\t\/\/ copy controllers \/ services based on label query\n\t\trcs, _ := listReplicationControllersByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(rcs.Items), \" template replication controllers to copy.\")\n\n\t\tdeployments, _ := listDeploymentsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(deployments.Items), \" template deployments to copy.\")\n\n\t\tsvcs, _ := listServicesByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(svcs.Items), \" template services to copy.\")\n\n\t\tsecrets, _ := listSecretsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(secrets.Items), \" template secrets to copy.\")\n\n\t\tconfigmaps, _ := listConfigMapsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(configmaps.Items), \" template configmaps to copy.\")\n\n\t\t\/\/ create configmaps\n\t\tfor _, configmap := range configmaps.Items {\n\n\t\t\trequestConfigMap := &v1.ConfigMap{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      configmap.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t\tData: configmap.Data,\n\t\t\t}\n\n\t\t\tcreateConfigMap(branchName, requestConfigMap)\n\t\t}\n\n\t\t\/\/ create secrets\n\t\tfor _, secret := range secrets.Items {\n\n\t\t\t\/\/ skip service accounts\n\t\t\tif secret.Type != \"kubernetes.io\/service-account-token\" {\n\n\t\t\t\trequestSecret := &v1.Secret{\n\t\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\t\tName:      secret.Name,\n\t\t\t\t\t\tNamespace: branchName,\n\t\t\t\t\t},\n\t\t\t\t\tType: secret.Type,\n\t\t\t\t\tData: secret.Data,\n\t\t\t\t}\n\n\t\t\t\tcreateSecret(branchName, requestSecret)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ create services\n\t\tfor _, svc := range svcs.Items {\n\n\t\t\t\/\/ Create annotations for Deis router\n\t\t\tannotations := make(map[string]string)\n\t\t\tannotations[\"router.deis.io\/domains\"] = fmt.Sprintf(\"%s,www.%s.%s\", branchName, branchName, argSubDomain)\n\n\t\t\t\/\/ Add Deis router label\n\t\t\tsvc.Labels[\"router.deis.io\/routable\"] = \"true\"\n\n\t\t\trequestService := &v1.Service{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:        svc.ObjectMeta.Name,\n\t\t\t\t\tNamespace:   branchName,\n\t\t\t\t\tAnnotations: annotations,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tports := []v1.ServicePort{}\n\t\t\tfor _, port := range svc.Spec.Ports {\n\t\t\t\tnewPort := v1.ServicePort{\n\t\t\t\t\tName:       port.Name,\n\t\t\t\t\tProtocol:   port.Protocol,\n\t\t\t\t\tPort:       port.Port,\n\t\t\t\t\tTargetPort: port.TargetPort,\n\t\t\t\t}\n\n\t\t\t\tports = append(ports, newPort)\n\t\t\t}\n\n\t\t\trequestService.Spec.Ports = ports\n\t\t\trequestService.Spec.Selector = svc.Spec.Selector\n\t\t\trequestService.Spec.Type = svc.Spec.Type\n\t\t\trequestService.Labels = svc.Labels\n\n\t\t\tcreateService(branchName, requestService)\n\t\t}\n\n\t\t\/\/ now that we have all replicationControllers, update them to have new image name\n\t\tfor _, rc := range rcs.Items {\n\n\t\t\tcontainerNameToUpdate := \"\"\n\n\t\t\t\/\/ Looks for annotations to know which container to replace\n\t\t\tfor key, value := range rc.Annotations {\n\t\t\t\tif key == \"emmie-update\" {\n\t\t\t\t\tcontainerNameToUpdate = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Find the container which matches the annotation\n\t\t\tfor i, container := range rc.Spec.Template.Spec.Containers {\n\n\t\t\t\timageName := \"\"\n\n\t\t\t\tif containerNameToUpdate == \"\" {\n\t\t\t\t\t\/\/default to current image tag if no annotations found\n\t\t\t\t\timageName = container.Image\n\t\t\t\t} else {\n\t\t\t\t\timageName = fmt.Sprintf(\"%s%s\/%s:%s\", *argDockerRegistry, imageNamespace, rc.ObjectMeta.Labels[\"name\"], branchName)\n\t\t\t\t}\n\n\t\t\t\trc.Spec.Template.Spec.Containers[i].Image = imageName\n\n\t\t\t\t\/\/ Set the image pull policy to \"Always\"\n\t\t\t\trc.Spec.Template.Spec.Containers[i].ImagePullPolicy = \"Always\"\n\t\t\t}\n\n\t\t\trequestController := &v1.ReplicationController{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      rc.ObjectMeta.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\trequestController.Spec = rc.Spec\n\t\t\trequestController.Spec.Replicas = defaultReplicaCount\n\n\t\t\t\/\/ create new replication controller\n\t\t\tcreateReplicationController(branchName, requestController)\n\t\t}\n\n\t\t\/\/ now that we have all deployments, update them to have new image name\n\t\tfor _, dply := range deployments.Items {\n\n\t\t\tcontainerNameToUpdate := \"\"\n\n\t\t\t\/\/ Looks for annotations to know which container to replace\n\t\t\tfor key, value := range dply.Annotations {\n\t\t\t\tif key == \"emmie-update\" {\n\t\t\t\t\tcontainerNameToUpdate = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Find the container which matches the annotation\n\t\t\tfor i, container := range dply.Spec.Template.Spec.Containers {\n\n\t\t\t\timageName := \"\"\n\n\t\t\t\tif containerNameToUpdate == \"\" {\n\t\t\t\t\t\/\/default to current image tag if no annotations found\n\t\t\t\t\timageName = container.Image\n\t\t\t\t} else {\n\t\t\t\t\timageName = fmt.Sprintf(\"%s%s\/%s:%s\", *argDockerRegistry, imageNamespace, dply.ObjectMeta.Labels[\"name\"], branchName)\n\t\t\t\t}\n\n\t\t\t\tdply.Spec.Template.Spec.Containers[i].Image = imageName\n\n\t\t\t\t\/\/ Set the image pull policy to \"Always\"\n\t\t\t\tdply.Spec.Template.Spec.Containers[i].ImagePullPolicy = \"Always\"\n\t\t\t}\n\n\t\t\tdeployment := &v1beta1.Deployment{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      dply.ObjectMeta.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tdeployment.Spec = dply.Spec\n\t\t\tdeployment.Spec.Replicas = defaultReplicaCount\n\n\t\t\t\/\/ create new replication controller\n\t\t\tcreateDeployment(branchName, deployment)\n\t\t}\n\t}\n\tlog.Println(\"[Emmie] is finished deploying branch!\")\n}\n\n\/\/ Put (PUT \"\/deploy\")\nfunc updateRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\tlog.Println(w, \"[Emmie] is updating branch:\", branchName)\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\n\tdeletePodsByNamespace(branchName)\n\n\tlog.Println(\"Finished updating branch!\")\n}\n\n\/\/ Delete (DELETE \"\/deploy\")\nfunc deleteRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\tlog.Println(\"[Emmie] is deleting branch:\", branchName)\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\n\t\/\/ get controllers \/ services \/ secrets in namespace\n\trcs, _ := listReplicationControllersByNamespace(*argTemplateNamespace)\n\tfor _, rc := range rcs.Items {\n\t\tdeleteReplicationController(branchName, rc.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted replicationController:\", rc.ObjectMeta.Name)\n\t}\n\n\tdeployments, _ := listDeploymentsByNamespace(*argTemplateNamespace)\n\tfor _, dply := range deployments.Items {\n\t\tdeleteDeployment(branchName, dply.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted deployment:\", dply.ObjectMeta.Name)\n\t}\n\n\tsvcs, _ := listServicesByNamespace(*argTemplateNamespace)\n\tfor _, svc := range svcs.Items {\n\t\tdeleteService(branchName, svc.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted service:\", svc.ObjectMeta.Name)\n\t}\n\n\tsecrets, _ := listSecretsByNamespace(*argTemplateNamespace)\n\tfor _, secret := range secrets.Items {\n\t\tdeleteSecret(branchName, secret.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted secret:\", secret.ObjectMeta.Name)\n\t}\n\n\tconfigmaps, _ := listConfigMapsByNamespace(*argTemplateNamespace)\n\tfor _, configmap := range configmaps.Items {\n\t\tdeleteSecret(branchName, configmap.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted configmap:\", configmap.ObjectMeta.Name)\n\t}\n\n\tdeleteNamespace(branchName)\n\tlog.Println(\"[Emmie] is done deleting branch.\")\n}\n\nfunc tokenIsValid(token string) bool {\n\t\/\/ If no path is passed, then auth is disabled\n\tif *argPathToTokens == \"\" {\n\t\treturn true\n\t}\n\n\tfile, err := os.Open(*argPathToTokens)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tif token == scanner.Text() {\n\t\t\tfmt.Println(\"Token IS valid!\")\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Token is NOT valid! =(\")\n\treturn false\n}\n\nfunc main() {\n\tflag.Parse()\n\tlog.Println(\"[Emmie] is up and running!\", time.Now())\n\n\t\/\/ Sanitize docker registry\n\tif *argDockerRegistry != \"\" {\n\t\t*argDockerRegistry = fmt.Sprintf(\"%s\/\", *argDockerRegistry)\n\t}\n\n\t\/\/ Configure router\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"\/\", indexRoute)\n\trouter.HandleFunc(\"\/deploy\/{namespace}\/{branchName}\", deployRoute).Methods(\"POST\")\n\trouter.HandleFunc(\"\/deploy\/{branchName}\", deleteRoute).Methods(\"DELETE\")\n\trouter.HandleFunc(\"\/deploy\/{branchName}\", updateRoute).Methods(\"PUT\")\n\trouter.HandleFunc(\"\/deploy\", getDeploymentsRoute).Methods(\"GET\")\n\n\t\/\/ Services\n\t\/\/ router.HandleFunc(\"\/services\/{namespace}\/{serviceName}\", getServiceRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/services\/{namespace}\/{key}\/{value}\", getServicesRoute).Methods(\"GET\")\n\n\t\/\/ ReplicationControllers\n\t\/\/ router.HandleFunc(\"\/replicationControllers\/{namespace}\/{rcName}\", getReplicationControllerRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/replicationControllers\/{namespace}\/{key}\/{value}\", getReplicationControllersRoute).Methods(\"GET\")\n\n\t\/\/ Deployments\n\t\/\/ router.HandleFunc(\"\/deployments\/{namespace}\/{deploymentName}\", getDeploymentRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/deployments\/{namespace}\/{key}\/{value}\", getDeploymentsRoute).Methods(\"GET\")\n\n\t\/\/ Version\n\trouter.HandleFunc(\"\/version\", versionRoute)\n\n\t\/\/ Create k8s client\n\tconfig, err := rest.InClusterConfig()\n\t\/\/config, err := clientcmd.BuildConfigFromFlags(\"\", *argKubecfgFile)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t\/\/ creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tclient = clientset\n\n\t\/\/ Start server\n\tlog.Fatal(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", *argListenPort), \"certs\/cert.pem\", \"certs\/key.pem\", router))\n\t\/\/log.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", *argListenPort), router))\n}\n<commit_msg>Bug fix on router subdomain<commit_after>\/*\nCopyright (c) 2015, UPMC Enterprises\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    * 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 copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and\/or other materials provided with the distribution.\n    * Neither the name UPMC Enterprises nor the\n      names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL UPMC ENTERPRISES BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON 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*\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"k8s.io\/client-go\/1.4\/kubernetes\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/rest\"\n)\n\nvar (\n\targListenPort        = flag.Int(\"listen-port\", 9080, \"port to have API listen\")\n\targDockerRegistry    = flag.String(\"docker-registry\", \"\", \"docker registry to use\")\n\targKubecfgFile       = flag.String(\"kubecfg-file\", \"\", \"Location of kubecfg file for access to kubernetes master service; --kube_master_url overrides the URL part of this; if neither this nor --kube_master_url are provided, defaults to service account tokens\")\n\targKubeMasterURL     = flag.String(\"kube-master-url\", \"\", \"URL to reach kubernetes master. Env variables in this flag will be expanded.\")\n\targTemplateNamespace = flag.String(\"template-namespace\", \"template\", \"Namespace to 'clone from when creating new deployments'\")\n\targPathToTokens      = flag.String(\"path-to-tokens\", \"\", \"Full path including file name to tokens file for authorization, setting to empty string will disable.\")\n\targSubDomain         = flag.String(\"subdomain\", \"k8s.local.com\", \"Subdomain used to configure external routing to branch (e.g. namespace.ci.k8s.local)\")\n\tclient               *kubernetes.Clientset\n\tdefaultReplicaCount  *int32\n)\n\nconst (\n\tappVersion = \"0.0.3\"\n)\n\n\/\/ Default (GET \"\/\")\nfunc indexRoute(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, %s\", \"welcome to Emmie!\")\n}\n\n\/\/ Version (GET \"\/version\")\nfunc versionRoute(w http.ResponseWriter, r *http.Request) {\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%q\", appVersion)\n}\n\n\/\/ Deploy (POST \"\/deploy\/namespace\/branchName\")\nfunc deployRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\timageNamespace := vars[\"namespace\"]\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\tlog.Println(\"[Emmie] is deploying branch:\", branchName)\n\n\t\/\/ create namespace\n\terr := createNamespace(branchName)\n\n\tif err != nil {\n\t\t\/\/ TODO: Don't use error for logic\n\t\t\/\/ Existing namespace, do an update\n\t\tlog.Println(\"Existing namespace found: \", branchName, \" deleting pods.\")\n\n\t\tdeletePodsByNamespace(branchName)\n\t} else {\n\t\tlog.Println(\"Namespace created, deploying new app...\")\n\n\t\t\/\/ copy controllers \/ services based on label query\n\t\trcs, _ := listReplicationControllersByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(rcs.Items), \" template replication controllers to copy.\")\n\n\t\tdeployments, _ := listDeploymentsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(deployments.Items), \" template deployments to copy.\")\n\n\t\tsvcs, _ := listServicesByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(svcs.Items), \" template services to copy.\")\n\n\t\tsecrets, _ := listSecretsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(secrets.Items), \" template secrets to copy.\")\n\n\t\tconfigmaps, _ := listConfigMapsByNamespace(*argTemplateNamespace)\n\t\tlog.Println(\"Found \", len(configmaps.Items), \" template configmaps to copy.\")\n\n\t\t\/\/ create configmaps\n\t\tfor _, configmap := range configmaps.Items {\n\n\t\t\trequestConfigMap := &v1.ConfigMap{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      configmap.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t\tData: configmap.Data,\n\t\t\t}\n\n\t\t\tcreateConfigMap(branchName, requestConfigMap)\n\t\t}\n\n\t\t\/\/ create secrets\n\t\tfor _, secret := range secrets.Items {\n\n\t\t\t\/\/ skip service accounts\n\t\t\tif secret.Type != \"kubernetes.io\/service-account-token\" {\n\n\t\t\t\trequestSecret := &v1.Secret{\n\t\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\t\tName:      secret.Name,\n\t\t\t\t\t\tNamespace: branchName,\n\t\t\t\t\t},\n\t\t\t\t\tType: secret.Type,\n\t\t\t\t\tData: secret.Data,\n\t\t\t\t}\n\n\t\t\t\tcreateSecret(branchName, requestSecret)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ create services\n\t\tfor _, svc := range svcs.Items {\n\n\t\t\t\/\/ Create annotations for Deis router\n\t\t\tannotations := make(map[string]string)\n\t\t\tannotations[\"router.deis.io\/domains\"] = fmt.Sprintf(\"%s,www.%s.%s\", branchName, branchName, *argSubDomain)\n\n\t\t\t\/\/ Add Deis router label\n\t\t\tsvc.Labels[\"router.deis.io\/routable\"] = \"true\"\n\n\t\t\trequestService := &v1.Service{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:        svc.ObjectMeta.Name,\n\t\t\t\t\tNamespace:   branchName,\n\t\t\t\t\tAnnotations: annotations,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tports := []v1.ServicePort{}\n\t\t\tfor _, port := range svc.Spec.Ports {\n\t\t\t\tnewPort := v1.ServicePort{\n\t\t\t\t\tName:       port.Name,\n\t\t\t\t\tProtocol:   port.Protocol,\n\t\t\t\t\tPort:       port.Port,\n\t\t\t\t\tTargetPort: port.TargetPort,\n\t\t\t\t}\n\n\t\t\t\tports = append(ports, newPort)\n\t\t\t}\n\n\t\t\trequestService.Spec.Ports = ports\n\t\t\trequestService.Spec.Selector = svc.Spec.Selector\n\t\t\trequestService.Spec.Type = svc.Spec.Type\n\t\t\trequestService.Labels = svc.Labels\n\n\t\t\tcreateService(branchName, requestService)\n\t\t}\n\n\t\t\/\/ now that we have all replicationControllers, update them to have new image name\n\t\tfor _, rc := range rcs.Items {\n\n\t\t\tcontainerNameToUpdate := \"\"\n\n\t\t\t\/\/ Looks for annotations to know which container to replace\n\t\t\tfor key, value := range rc.Annotations {\n\t\t\t\tif key == \"emmie-update\" {\n\t\t\t\t\tcontainerNameToUpdate = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Find the container which matches the annotation\n\t\t\tfor i, container := range rc.Spec.Template.Spec.Containers {\n\n\t\t\t\timageName := \"\"\n\n\t\t\t\tif containerNameToUpdate == \"\" {\n\t\t\t\t\t\/\/default to current image tag if no annotations found\n\t\t\t\t\timageName = container.Image\n\t\t\t\t} else {\n\t\t\t\t\timageName = fmt.Sprintf(\"%s%s\/%s:%s\", *argDockerRegistry, imageNamespace, rc.ObjectMeta.Labels[\"name\"], branchName)\n\t\t\t\t}\n\n\t\t\t\trc.Spec.Template.Spec.Containers[i].Image = imageName\n\n\t\t\t\t\/\/ Set the image pull policy to \"Always\"\n\t\t\t\trc.Spec.Template.Spec.Containers[i].ImagePullPolicy = \"Always\"\n\t\t\t}\n\n\t\t\trequestController := &v1.ReplicationController{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      rc.ObjectMeta.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\trequestController.Spec = rc.Spec\n\t\t\trequestController.Spec.Replicas = defaultReplicaCount\n\n\t\t\t\/\/ create new replication controller\n\t\t\tcreateReplicationController(branchName, requestController)\n\t\t}\n\n\t\t\/\/ now that we have all deployments, update them to have new image name\n\t\tfor _, dply := range deployments.Items {\n\n\t\t\tcontainerNameToUpdate := \"\"\n\n\t\t\t\/\/ Looks for annotations to know which container to replace\n\t\t\tfor key, value := range dply.Annotations {\n\t\t\t\tif key == \"emmie-update\" {\n\t\t\t\t\tcontainerNameToUpdate = value\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Find the container which matches the annotation\n\t\t\tfor i, container := range dply.Spec.Template.Spec.Containers {\n\n\t\t\t\timageName := \"\"\n\n\t\t\t\tif containerNameToUpdate == \"\" {\n\t\t\t\t\t\/\/default to current image tag if no annotations found\n\t\t\t\t\timageName = container.Image\n\t\t\t\t} else {\n\t\t\t\t\timageName = fmt.Sprintf(\"%s%s\/%s:%s\", *argDockerRegistry, imageNamespace, dply.ObjectMeta.Labels[\"name\"], branchName)\n\t\t\t\t}\n\n\t\t\t\tdply.Spec.Template.Spec.Containers[i].Image = imageName\n\n\t\t\t\t\/\/ Set the image pull policy to \"Always\"\n\t\t\t\tdply.Spec.Template.Spec.Containers[i].ImagePullPolicy = \"Always\"\n\t\t\t}\n\n\t\t\tdeployment := &v1beta1.Deployment{\n\t\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\t\tName:      dply.ObjectMeta.Name,\n\t\t\t\t\tNamespace: branchName,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tdeployment.Spec = dply.Spec\n\t\t\tdeployment.Spec.Replicas = defaultReplicaCount\n\n\t\t\t\/\/ create new replication controller\n\t\t\tcreateDeployment(branchName, deployment)\n\t\t}\n\t}\n\tlog.Println(\"[Emmie] is finished deploying branch!\")\n}\n\n\/\/ Put (PUT \"\/deploy\")\nfunc updateRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\tlog.Println(w, \"[Emmie] is updating branch:\", branchName)\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\n\tdeletePodsByNamespace(branchName)\n\n\tlog.Println(\"Finished updating branch!\")\n}\n\n\/\/ Delete (DELETE \"\/deploy\")\nfunc deleteRoute(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tbranchName := vars[\"branchName\"]\n\tlog.Println(\"[Emmie] is deleting branch:\", branchName)\n\n\tif !tokenIsValid(r.FormValue(\"token\")) {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ sanitize BranchName\n\tbranchName = strings.Replace(branchName, \"_\", \"-\", -1)\n\n\t\/\/ get controllers \/ services \/ secrets in namespace\n\trcs, _ := listReplicationControllersByNamespace(*argTemplateNamespace)\n\tfor _, rc := range rcs.Items {\n\t\tdeleteReplicationController(branchName, rc.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted replicationController:\", rc.ObjectMeta.Name)\n\t}\n\n\tdeployments, _ := listDeploymentsByNamespace(*argTemplateNamespace)\n\tfor _, dply := range deployments.Items {\n\t\tdeleteDeployment(branchName, dply.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted deployment:\", dply.ObjectMeta.Name)\n\t}\n\n\tsvcs, _ := listServicesByNamespace(*argTemplateNamespace)\n\tfor _, svc := range svcs.Items {\n\t\tdeleteService(branchName, svc.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted service:\", svc.ObjectMeta.Name)\n\t}\n\n\tsecrets, _ := listSecretsByNamespace(*argTemplateNamespace)\n\tfor _, secret := range secrets.Items {\n\t\tdeleteSecret(branchName, secret.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted secret:\", secret.ObjectMeta.Name)\n\t}\n\n\tconfigmaps, _ := listConfigMapsByNamespace(*argTemplateNamespace)\n\tfor _, configmap := range configmaps.Items {\n\t\tdeleteSecret(branchName, configmap.ObjectMeta.Name)\n\t\tlog.Println(\"Deleted configmap:\", configmap.ObjectMeta.Name)\n\t}\n\n\tdeleteNamespace(branchName)\n\tlog.Println(\"[Emmie] is done deleting branch.\")\n}\n\nfunc tokenIsValid(token string) bool {\n\t\/\/ If no path is passed, then auth is disabled\n\tif *argPathToTokens == \"\" {\n\t\treturn true\n\t}\n\n\tfile, err := os.Open(*argPathToTokens)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tif token == scanner.Text() {\n\t\t\tfmt.Println(\"Token IS valid!\")\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Token is NOT valid! =(\")\n\treturn false\n}\n\nfunc main() {\n\tflag.Parse()\n\tlog.Println(\"[Emmie] is up and running!\", time.Now())\n\n\t\/\/ Sanitize docker registry\n\tif *argDockerRegistry != \"\" {\n\t\t*argDockerRegistry = fmt.Sprintf(\"%s\/\", *argDockerRegistry)\n\t}\n\n\t\/\/ Configure router\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"\/\", indexRoute)\n\trouter.HandleFunc(\"\/deploy\/{namespace}\/{branchName}\", deployRoute).Methods(\"POST\")\n\trouter.HandleFunc(\"\/deploy\/{branchName}\", deleteRoute).Methods(\"DELETE\")\n\trouter.HandleFunc(\"\/deploy\/{branchName}\", updateRoute).Methods(\"PUT\")\n\trouter.HandleFunc(\"\/deploy\", getDeploymentsRoute).Methods(\"GET\")\n\n\t\/\/ Services\n\t\/\/ router.HandleFunc(\"\/services\/{namespace}\/{serviceName}\", getServiceRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/services\/{namespace}\/{key}\/{value}\", getServicesRoute).Methods(\"GET\")\n\n\t\/\/ ReplicationControllers\n\t\/\/ router.HandleFunc(\"\/replicationControllers\/{namespace}\/{rcName}\", getReplicationControllerRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/replicationControllers\/{namespace}\/{key}\/{value}\", getReplicationControllersRoute).Methods(\"GET\")\n\n\t\/\/ Deployments\n\t\/\/ router.HandleFunc(\"\/deployments\/{namespace}\/{deploymentName}\", getDeploymentRoute).Methods(\"GET\")\n\t\/\/ router.HandleFunc(\"\/deployments\/{namespace}\/{key}\/{value}\", getDeploymentsRoute).Methods(\"GET\")\n\n\t\/\/ Version\n\trouter.HandleFunc(\"\/version\", versionRoute)\n\n\t\/\/ Create k8s client\n\tconfig, err := rest.InClusterConfig()\n\t\/\/config, err := clientcmd.BuildConfigFromFlags(\"\", *argKubecfgFile)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t\/\/ creates the clientset\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\tclient = clientset\n\n\t\/\/ Start server\n\tlog.Fatal(http.ListenAndServeTLS(fmt.Sprintf(\":%d\", *argListenPort), \"certs\/cert.pem\", \"certs\/key.pem\", router))\n\t\/\/log.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", *argListenPort), router))\n}\n<|endoftext|>"}
{"text":"<commit_before>package writesplitter\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tKilobyte  = 1024                \/\/ const for specifying ByteLimit\n\tMegabyte  = Kilobyte * Kilobyte \/\/ const for specifying ByteLimit\n\tformatStr = \"2006-01-02T15.04.05.999999999Z0700.log\"\n)\n\nvar (\n\tErrNotAFile = errors.New(\"WriteSplitter: invalid memory address or nil pointer dereference\") \/\/ a custom error to signal that no file was closed\n)\n\n\/\/ WriteSplitter represents a disk bound io.WriteCloser that splits the input\n\/\/ across consecutively named files based on either the number of bytes or the\n\/\/ number of lines. Splitting does not guarantee true byte\/line split\n\/\/ precision as it does not parse the incoming data. The decision to split is\n\/\/ before the underlying write operation based on the previous invocation. In\n\/\/ other words, if a []byte sent to `Write()` contains enough bytes or new\n\/\/ lines ('\\n') to exceed the given limit, a new file won't be generated until\n\/\/ the *next* invocation of `Write()`. If both LineLimit and ByteLimit are set,\n\/\/ preference is given to LineLimit. By default, no splitting occurs because\n\/\/ both LineLimit and ByteLimit are zero (0).\ntype WriteSplitter struct {\n\tLineLimit int            \/\/ how many write ops (typically one per line) before splitting the file\n\tByteLimit int            \/\/ how many bytes before splitting the file\n\tPrefix    string         \/\/ files are named: $prefix + $nano-precision-timestamp + '.log'\n\tnumBytes  int            \/\/ internal byte count\n\tnumLines  int            \/\/ internal line count\n\thandle    io.WriteCloser \/\/ embedded file\n}\n\n\/\/ LineSplitter returns a WriteSplitter set to split at the given number of lines\nfunc LineSplitter(limit int, prefix string) io.WriteCloser {\n\treturn &WriteSplitter{LineLimit: limit, Prefix: prefix}\n}\n\n\/\/ ByteSplitter returns a WriteSplitter set to split at the given number of bytes\nfunc ByteSplitter(limit int, prefix string) io.WriteCloser {\n\treturn &WriteSplitter{ByteLimit: limit, Prefix: prefix}\n}\n\n\/\/ Close is a passthru and satisfies io.Closer. Subsequent writes will return an\n\/\/ error.\nfunc (ws *WriteSplitter) Close() error {\n\tif ws.handle != nil { \/\/ do not try to close nil\n\t\treturn ws.handle.Close()\n\t}\n\treturn ErrNotAFile \/\/ do not hide errors, but signal it's a WriteSplit error as opposed to an underlying os.* error\n}\n\n\/\/ Write satisfies io.Writer and internally manages file io. Write also limits\n\/\/ each WriteSplitter to only one open file at a time.\nfunc (ws *WriteSplitter) Write(p []byte) (int, error) {\n\n\tvar n int\n\tvar e error\n\n\tif ws.handle == nil {\n\t\tws.handle, e = createFile(ws.Prefix)\n\t}\n\n\tswitch {\n\tcase ws.LineLimit > 0 && ws.numLines >= ws.LineLimit:\n\t\tfallthrough\n\tcase ws.ByteLimit > 0 && ws.numBytes >= ws.ByteLimit:\n\t\tws.Close()\n\t\tws.handle, e = createFile(ws.Prefix)\n\t\tws.numLines, ws.numBytes = 0, 0\n\t}\n\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\n\tn, e = ws.handle.Write(p)\n\tws.numLines += 1\n\tws.numBytes += n\n\treturn n, e\n}\n\n\/\/ TestFileIO creates and removes a file to ensure that the location is writable.\nfunc TestFileIO(prefix string) error {\n\tfn := prefix + \"test.log\"\n\t\/\/ It doesn't use the fs layer because it should be used to test the\n\t\/\/ writability of the actual filesystem. This test is unnecessary for mock filesystems\n\tif _, err := createFile(fn); err != nil {\n\t\treturn err\n\t}\n\tremoveFile(fn)\n\treturn nil\n}\n\n\/\/\/ This is for mocking the file IO. Used exclusively for testing\n\/\/\/-----------------------------------------------------------------------------\n\n\/\/ createFile is the file creating function that wraps os.Create\nvar createFile = func(prefix string) (io.WriteCloser, error) {\n\tname := prefix + time.Now().Format(formatStr)\n\treturn os.Create(name)\n}\n\n\/\/ removeFile is the file removing function that wraps os.Remove\nvar removeFile = func(name string) error {\n\treturn os.Remove(name)\n}\n<commit_msg>func for naming things<commit_after>package writesplitter\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\t\/\/ \"path\/filepath\"\n)\n\nconst (\n\tKilobyte  = 1024                \/\/ const for specifying ByteLimit\n\tMegabyte  = Kilobyte * Kilobyte \/\/ const for specifying ByteLimit\n\tformatStr = \"2006-01-02T15.04.05.999999999Z0700.log\"\n)\n\nvar (\n\tErrNotAFile = errors.New(\"WriteSplitter: invalid memory address or nil pointer dereference\") \/\/ a custom error to signal that no file was closed\n)\n\n\/\/ WriteSplitter represents a disk bound io.WriteCloser that splits the input\n\/\/ across consecutively named files based on either the number of bytes or the\n\/\/ number of lines. Splitting does not guarantee true byte\/line split\n\/\/ precision as it does not parse the incoming data. The decision to split is\n\/\/ before the underlying write operation based on the previous invocation. In\n\/\/ other words, if a []byte sent to `Write()` contains enough bytes or new\n\/\/ lines ('\\n') to exceed the given limit, a new file won't be generated until\n\/\/ the *next* invocation of `Write()`. If both LineLimit and ByteLimit are set,\n\/\/ preference is given to LineLimit. By default, no splitting occurs because\n\/\/ both LineLimit and ByteLimit are zero (0).\ntype WriteSplitter struct {\n\tLineLimit int            \/\/ how many write ops (typically one per line) before splitting the file\n\tByteLimit int            \/\/ how many bytes before splitting the file\n\tPrefix    string         \/\/ files are named: $prefix + $nano-precision-timestamp + '.log'\n\tnumBytes  int            \/\/ internal byte count\n\tnumLines  int            \/\/ internal line count\n\thandle    io.WriteCloser \/\/ embedded file\n}\n\n\/\/ LineSplitter returns a WriteSplitter set to split at the given number of lines\nfunc LineSplitter(limit int, prefix string) io.WriteCloser {\n\treturn &WriteSplitter{LineLimit: limit, Prefix: prefix}\n}\n\n\/\/ ByteSplitter returns a WriteSplitter set to split at the given number of bytes\nfunc ByteSplitter(limit int, prefix string) io.WriteCloser {\n\treturn &WriteSplitter{ByteLimit: limit, Prefix: prefix}\n}\n\n\/\/ Close is a passthru and satisfies io.Closer. Subsequent writes will return an\n\/\/ error.\nfunc (ws *WriteSplitter) Close() error {\n\tif ws.handle != nil { \/\/ do not try to close nil\n\t\treturn ws.handle.Close()\n\t}\n\treturn ErrNotAFile \/\/ do not hide errors, but signal it's a WriteSplit error as opposed to an underlying os.* error\n}\n\n\/\/ Write satisfies io.Writer and internally manages file io. Write also limits\n\/\/ each WriteSplitter to only one open file at a time.\nfunc (ws *WriteSplitter) Write(p []byte) (int, error) {\n\n\tvar n int\n\tvar e error\n\n\tif ws.handle == nil {\n\t\tws.handle, e = createFile(fileName(ws.Prefix))\n\t}\n\n\tswitch {\n\tcase ws.LineLimit > 0 && ws.numLines >= ws.LineLimit:\n\t\tfallthrough\n\tcase ws.ByteLimit > 0 && ws.numBytes >= ws.ByteLimit:\n\t\tws.Close()\n\t\tws.handle, e = createFile(fileName(ws.Prefix))\n\t\tws.numLines, ws.numBytes = 0, 0\n\t}\n\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\n\tn, e = ws.handle.Write(p)\n\tws.numLines += 1\n\tws.numBytes += n\n\treturn n, e\n}\n\n\/\/ TestFileIO creates and removes a file to ensure that the location is writable.\nfunc TestFileIO(prefix string) error {\n\tfn := fileName(prefix + \"testlog-\")\n\t\/\/ It doesn't use the fs layer because it should be used to test the\n\t\/\/ writability of the actual filesystem. This test is unnecessary for mock filesystems\n\tif _, err := createFile(fn); err != nil {\n\t\treturn err\n\t}\n\tremoveFile(fn)\n\treturn nil\n}\n\n\/\/ homogenize how filenames are generated\nfunc fileName(prefix string) string {\n\treturn prefix + time.Now().Format(formatStr)\n}\n\n\/\/\/ This is for mocking the file IO. Used exclusively for testing\n\/\/\/-----------------------------------------------------------------------------\n\n\/\/ createFile is the file creating function that wraps os.Create\nvar createFile = func(name string) (io.WriteCloser, error) {\n\treturn os.Create(name)\n}\n\n\/\/ removeFile is the file removing function that wraps os.Remove\nvar removeFile = func(name string) error {\n\treturn os.Remove(name)\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\n\/\/ Package metrics provides a library to post status metrics.\npackage metrics\n\nimport \"sync\"\n\n\/\/ MetricData stores metric information.\ntype MetricData struct {\n\tName    string\n\tservice string\n\tmu      sync.Mutex\n\tFields  map[string]interface{}\n}\n\n\/\/ AddStringField adds a string field to a metric.\nfunc (m *MetricData) AddStringField(name, value string) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tm.Fields[name] = value\n}\n\n\/\/ Bool implements a Bool-type metric.\ntype Bool struct {\n\tValue bool\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewBool sets the metric to a new Bool value.\nfunc NewBool(name, service string) (*Bool, error) {\n\treturn &Bool{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new bool value.\nfunc (b *Bool) Set(value bool) error {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.Value = value\n\treturn nil\n}\n\n\/\/ Int implements a Int-type metric.\ntype Int struct {\n\tValue int64\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewInt sets the metric to a new Int value.\nfunc NewInt(name, service string) (*Int, error) {\n\treturn &Int{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new int value.\nfunc (i *Int) Set(value int64) error {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\ti.Value = value\n\treturn nil\n}\n\n\/\/ NewCounter sets the metric to a new Int value.\nfunc NewCounter(name, service string) (*Int, error) {\n\treturn &Int{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Increment adds to the current int metric value.\nfunc (i *Int) Increment() error {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\ti.Value++\n\treturn nil\n}\n\n\/\/ String implements a String-type metric.\ntype String struct {\n\tValue string\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewString sets the metric to a new string value.\nfunc NewString(name, service string) (*String, error) {\n\treturn &String{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new string value.\nfunc (s *String) Set(value string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.Value = value\n\treturn nil\n}\n<commit_msg>Add AddBoolField and ensure MetricData.Fields is initialized.<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\n\/\/ Package metrics provides a library to post status metrics.\npackage metrics\n\nimport \"sync\"\n\n\/\/ MetricData stores metric information.\ntype MetricData struct {\n\tName    string\n\tservice string\n\tmu      sync.Mutex\n\tFields  map[string]interface{}\n}\n\n\/\/ AddBoolField adds a bool field to a metric.\nfunc (m *MetricData) AddBoolField(name string, value bool) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif m.Fields == nil {\n\t\tm.Fields = make(map[string]interface{})\n\t}\n\tm.Fields[name] = value\n}\n\n\/\/ AddStringField adds a string field to a metric.\nfunc (m *MetricData) AddStringField(name, value string) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tif m.Fields == nil {\n\t\tm.Fields = make(map[string]interface{})\n\t}\n\tm.Fields[name] = value\n}\n\n\/\/ Bool implements a Bool-type metric.\ntype Bool struct {\n\tValue bool\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewBool sets the metric to a new Bool value.\nfunc NewBool(name, service string) (*Bool, error) {\n\treturn &Bool{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new bool value.\nfunc (b *Bool) Set(value bool) error {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.Value = value\n\treturn nil\n}\n\n\/\/ Int implements a Int-type metric.\ntype Int struct {\n\tValue int64\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewInt sets the metric to a new Int value.\nfunc NewInt(name, service string) (*Int, error) {\n\treturn &Int{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new int value.\nfunc (i *Int) Set(value int64) error {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\ti.Value = value\n\treturn nil\n}\n\n\/\/ NewCounter sets the metric to a new Int value.\nfunc NewCounter(name, service string) (*Int, error) {\n\treturn &Int{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Increment adds to the current int metric value.\nfunc (i *Int) Increment() error {\n\ti.mu.Lock()\n\tdefer i.mu.Unlock()\n\n\ti.Value++\n\treturn nil\n}\n\n\/\/ String implements a String-type metric.\ntype String struct {\n\tValue string\n\tmu    sync.Mutex\n\tData  *MetricData\n}\n\n\/\/ NewString sets the metric to a new string value.\nfunc NewString(name, service string) (*String, error) {\n\treturn &String{\n\t\tData: &MetricData{\n\t\t\tName:    name,\n\t\t\tservice: service,\n\t\t},\n\t}, nil\n}\n\n\/\/ Set sets the metric to a new string value.\nfunc (s *String) Set(value string) error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\ts.Value = value\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package rpc\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/ethereum\/go-ethereum\/logger\"\n\t\"github.com\/ethereum\/go-ethereum\/logger\/glog\"\n\t\"github.com\/ethereum\/go-ethereum\/xeth\"\n\t\"github.com\/rs\/cors\"\n)\n\nvar rpclistener *stoppableTCPListener\n\nconst (\n\tjsonrpcver       = \"2.0\"\n\tmaxSizeReqLength = 1024 * 1024 \/\/ 1MB\n)\n\nfunc Start(pipe *xeth.XEth, config RpcConfig) error {\n\tif rpclistener != nil {\n\t\tif fmt.Sprintf(\"%s:%d\", config.ListenAddress, config.ListenPort) != rpclistener.Addr().String() {\n\t\t\treturn fmt.Errorf(\"RPC service already running on %s \", rpclistener.Addr().String())\n\t\t}\n\t\treturn nil \/\/ RPC service already running on given host\/port\n\t}\n\n\tl, err := newStoppableTCPListener(fmt.Sprintf(\"%s:%d\", config.ListenAddress, config.ListenPort))\n\tif err != nil {\n\t\tglog.V(logger.Error).Infof(\"Can't listen on %s:%d: %v\", config.ListenAddress, config.ListenPort, err)\n\t\treturn err\n\t}\n\trpclistener = l\n\n\tvar handler http.Handler\n\tif len(config.CorsDomain) > 0 {\n\t\tvar opts cors.Options\n\t\topts.AllowedMethods = []string{\"POST\"}\n\t\topts.AllowedOrigins = []string{config.CorsDomain}\n\n\t\tc := cors.New(opts)\n\t\thandler = newStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop)\n\t} else {\n\t\thandler = newStoppableHandler(JSONRPC(pipe), l.stop)\n\t}\n\n\tgo http.Serve(l, handler)\n\n\treturn nil\n}\n\nfunc Stop() error {\n\tif rpclistener != nil {\n\t\trpclistener.Stop()\n\t\trpclistener = nil\n\t}\n\n\treturn nil\n}\n\n\/\/ JSONRPC returns a handler that implements the Ethereum JSON-RPC API.\nfunc JSONRPC(pipe *xeth.XEth) http.Handler {\n\tapi := NewEthereumApi(pipe)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\t\t\/\/ Limit request size to resist DoS\n\t\tif req.ContentLength > maxSizeReqLength {\n\t\t\tjsonerr := &RpcErrorObject{-32700, \"Request too large\"}\n\t\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Read request body\n\t\tdefer req.Body.Close()\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\tjsonerr := &RpcErrorObject{-32700, \"Could not read request body\"}\n\t\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t\t}\n\n\t\t\/\/ Try to parse the request as a single\n\t\tvar reqSingle RpcRequest\n\t\tif err := json.Unmarshal(body, &reqSingle); err == nil {\n\t\t\tresponse := RpcResponse(api, &reqSingle)\n\t\t\tsend(w, &response)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Try to parse the request to batch\n\t\tvar reqBatch []RpcRequest\n\t\tif err := json.Unmarshal(body, &reqBatch); err == nil {\n\t\t\t\/\/ Build response batch\n\t\t\tresBatch := make([]*interface{}, len(reqBatch))\n\t\t\tfor i, request := range reqBatch {\n\t\t\t\tresponse := RpcResponse(api, &request)\n\t\t\t\tresBatch[i] = response\n\t\t\t}\n\t\t\tsend(w, resBatch)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Not a batch or single request, error\n\t\tjsonerr := &RpcErrorObject{-32600, \"Could not decode request\"}\n\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t})\n}\n\nfunc RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {\n\tvar reply, response interface{}\n\treserr := api.GetRequestReply(request, &reply)\n\tswitch reserr.(type) {\n\tcase nil:\n\t\tresponse = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}\n\tcase *NotImplementedError, *NotAvailableError:\n\t\tjsonerr := &RpcErrorObject{-32601, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\tcase *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:\n\t\tjsonerr := &RpcErrorObject{-32602, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\tdefault:\n\t\tjsonerr := &RpcErrorObject{-32603, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\t}\n\n\tglog.V(logger.Detail).Infof(\"Generated response: %T %s\", response, response)\n\treturn &response\n}\n\nfunc send(writer io.Writer, v interface{}) (n int, err error) {\n\tvar payload []byte\n\tpayload, err = json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tglog.V(logger.Error).Infoln(\"Error marshalling JSON\", err)\n\t\treturn 0, err\n\t}\n\tglog.V(logger.Detail).Infof(\"Sending payload: %s\", payload)\n\n\treturn writer.Write(payload)\n}\n<commit_msg>Omit replies for notification requests<commit_after>package rpc\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/ethereum\/go-ethereum\/logger\"\n\t\"github.com\/ethereum\/go-ethereum\/logger\/glog\"\n\t\"github.com\/ethereum\/go-ethereum\/xeth\"\n\t\"github.com\/rs\/cors\"\n)\n\nvar rpclistener *stoppableTCPListener\n\nconst (\n\tjsonrpcver       = \"2.0\"\n\tmaxSizeReqLength = 1024 * 1024 \/\/ 1MB\n)\n\nfunc Start(pipe *xeth.XEth, config RpcConfig) error {\n\tif rpclistener != nil {\n\t\tif fmt.Sprintf(\"%s:%d\", config.ListenAddress, config.ListenPort) != rpclistener.Addr().String() {\n\t\t\treturn fmt.Errorf(\"RPC service already running on %s \", rpclistener.Addr().String())\n\t\t}\n\t\treturn nil \/\/ RPC service already running on given host\/port\n\t}\n\n\tl, err := newStoppableTCPListener(fmt.Sprintf(\"%s:%d\", config.ListenAddress, config.ListenPort))\n\tif err != nil {\n\t\tglog.V(logger.Error).Infof(\"Can't listen on %s:%d: %v\", config.ListenAddress, config.ListenPort, err)\n\t\treturn err\n\t}\n\trpclistener = l\n\n\tvar handler http.Handler\n\tif len(config.CorsDomain) > 0 {\n\t\tvar opts cors.Options\n\t\topts.AllowedMethods = []string{\"POST\"}\n\t\topts.AllowedOrigins = []string{config.CorsDomain}\n\n\t\tc := cors.New(opts)\n\t\thandler = newStoppableHandler(c.Handler(JSONRPC(pipe)), l.stop)\n\t} else {\n\t\thandler = newStoppableHandler(JSONRPC(pipe), l.stop)\n\t}\n\n\tgo http.Serve(l, handler)\n\n\treturn nil\n}\n\nfunc Stop() error {\n\tif rpclistener != nil {\n\t\trpclistener.Stop()\n\t\trpclistener = nil\n\t}\n\n\treturn nil\n}\n\n\/\/ JSONRPC returns a handler that implements the Ethereum JSON-RPC API.\nfunc JSONRPC(pipe *xeth.XEth) http.Handler {\n\tapi := NewEthereumApi(pipe)\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\t\t\/\/ Limit request size to resist DoS\n\t\tif req.ContentLength > maxSizeReqLength {\n\t\t\tjsonerr := &RpcErrorObject{-32700, \"Request too large\"}\n\t\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Read request body\n\t\tdefer req.Body.Close()\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\t\tif err != nil {\n\t\t\tjsonerr := &RpcErrorObject{-32700, \"Could not read request body\"}\n\t\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t\t}\n\n\t\t\/\/ Try to parse the request as a single\n\t\tvar reqSingle RpcRequest\n\t\tif err := json.Unmarshal(body, &reqSingle); err == nil {\n\t\t\tresponse := RpcResponse(api, &reqSingle)\n\t\t\tif reqSingle.Id != nil {\n\t\t\t\tsend(w, &response)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Try to parse the request to batch\n\t\tvar reqBatch []RpcRequest\n\t\tif err := json.Unmarshal(body, &reqBatch); err == nil {\n\t\t\t\/\/ Build response batch\n\t\t\tresBatch := make([]*interface{}, len(reqBatch))\n\t\t\tresCount := 0\n\n\t\t\tfor i, request := range reqBatch {\n\t\t\t\tresponse := RpcResponse(api, &request)\n\t\t\t\t\/\/ this leaves nil entries in the response batch for later removal\n\t\t\t\tif request.Id != nil {\n\t\t\t\t\tresBatch[i] = response\n\t\t\t\t\tresCount = resCount + 1\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ make response omitting nil entries\n\t\t\trespBatchComp := make([]*interface{}, resCount)\n\t\t\tresCount = resCount - 1\n\t\t\tfor _, v := range resBatch {\n\t\t\t\tif v != nil {\n\t\t\t\t\trespBatchComp[resCount] = v\n\t\t\t\t\tresCount = resCount - 1\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsend(w, respBatchComp)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Not a batch or single request, error\n\t\tjsonerr := &RpcErrorObject{-32600, \"Could not decode request\"}\n\t\tsend(w, &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: nil, Error: jsonerr})\n\t})\n}\n\nfunc RpcResponse(api *EthereumApi, request *RpcRequest) *interface{} {\n\tvar reply, response interface{}\n\treserr := api.GetRequestReply(request, &reply)\n\tswitch reserr.(type) {\n\tcase nil:\n\t\tresponse = &RpcSuccessResponse{Jsonrpc: jsonrpcver, Id: request.Id, Result: reply}\n\tcase *NotImplementedError, *NotAvailableError:\n\t\tjsonerr := &RpcErrorObject{-32601, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\tcase *DecodeParamError, *InsufficientParamsError, *ValidationError, *InvalidTypeError:\n\t\tjsonerr := &RpcErrorObject{-32602, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\tdefault:\n\t\tjsonerr := &RpcErrorObject{-32603, reserr.Error()}\n\t\tresponse = &RpcErrorResponse{Jsonrpc: jsonrpcver, Id: request.Id, Error: jsonerr}\n\t}\n\n\tglog.V(logger.Detail).Infof(\"Generated response: %T %s\", response, response)\n\treturn &response\n}\n\nfunc send(writer io.Writer, v interface{}) (n int, err error) {\n\tvar payload []byte\n\tpayload, err = json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tglog.V(logger.Error).Infoln(\"Error marshalling JSON\", err)\n\t\treturn 0, err\n\t}\n\tglog.V(logger.Detail).Infof(\"Sending payload: %s\", payload)\n\n\treturn writer.Write(payload)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 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 id3\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Id3v24Tag struct {\n\tHeader         Id3v24Header\n\tExtendedHeader Id3v24ExtendedHeader\n\tFrames         map[string][]*Id3v24Frame\n}\n\nfunc id3v24Err(format string, args ...interface{}) error {\n\treturn &ErrFormat{\n\t\tFormat: \"ID3 version 2.4\",\n\t\tErr:    fmt.Errorf(format, args...),\n\t}\n}\n\nfunc getSimpleId3v24TextFrame(frames []*Id3v24Frame) string {\n\tif len(frames) == 0 {\n\t\treturn \"\"\n\t}\n\tfields, err := GetId3v24TextIdentificationFrame(frames[0])\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(fields, \" \")\n}\n\nfunc (t *Id3v24Tag) Title() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TIT2\"])\n}\n\nfunc (t *Id3v24Tag) Artist() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TPE1\"])\n}\n\nfunc (t *Id3v24Tag) Album() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TALB\"])\n}\n\nfunc (t *Id3v24Tag) Comment() string {\n\treturn \"\"\n}\n\nfunc (t *Id3v24Tag) Genre() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TCON\"])\n}\n\nfunc (t *Id3v24Tag) Year() time.Time {\n\tyearStr := getSimpleId3v24TextFrame(t.Frames[\"TDRC\"])\n\tif len(yearStr) < 4 {\n\t\treturn time.Time{}\n\t}\n\n\tyearInt, err := strconv.Atoi(yearStr[0:4])\n\tif err != nil {\n\t\treturn time.Time{}\n\t}\n\n\treturn time.Date(yearInt, time.January, 1, 0, 0, 0, 0, time.UTC)\n}\n\nfunc (t *Id3v24Tag) Track() uint32 {\n\ttrack, err := parseLeadingInt(getSimpleId3v24TextFrame(t.Frames[\"TRCK\"]))\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn uint32(track)\n}\n\nfunc (t *Id3v24Tag) Disc() uint32 {\n\tdisc, err := parseLeadingInt(getSimpleId3v24TextFrame(t.Frames[\"TPOS\"]))\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn uint32(disc)\n}\n\nfunc (t *Id3v24Tag) CustomFrames() map[string]string {\n\tinfo := make(map[string]string)\n\tfor _, frame := range t.Frames[\"TXXX\"] {\n\t\t\/\/ See \"4.2.6. User defined text information frame\" at\n\t\t\/\/ http:\/\/id3.org\/id3v2.4.0-frames. TXXX frames contain\n\t\t\/\/ NUL-separated descriptions and values.\n\t\tparts, err := GetId3v24TextIdentificationFrame(frame)\n\t\tif err == nil && len(parts) == 2 {\n\t\t\tinfo[parts[0]] = parts[1]\n\t\t}\n\t}\n\treturn info\n}\n\nfunc (t *Id3v24Tag) TagSize() uint32 {\n\treturn 10 + t.Header.Size\n}\n\ntype Id3v24Header struct {\n\tMinorVersion byte\n\tFlags        Id3v24HeaderFlags\n\tSize         uint32\n}\n\ntype Id3v24HeaderFlags struct {\n\tUnsynchronization     bool\n\tExtendedHeader        bool\n\tExperimentalIndicator bool\n\tFooterPresent         bool\n}\n\ntype Id3v24ExtendedHeader struct {\n\tSize  uint32\n\tFlags Id3v24ExtendedHeaderFlags\n}\n\ntype Id3v24ExtendedHeaderFlags struct {\n\tUpdate          bool\n\tCrcDataPresent  bool\n\tTagRestrictions bool\n}\n\ntype Id3v24Frame struct {\n\tHeader  Id3v24FrameHeader\n\tContent []byte\n}\n\ntype Id3v24FrameHeader struct {\n\tId    string\n\tSize  uint32\n\tFlags Id3v24FrameHeaderFlags\n}\n\ntype Id3v24FrameHeaderFlags struct {\n\tTagAlterPreservation  bool\n\tFileAlterPreservation bool\n\tReadOnly              bool\n\n\tGroupingIdentity    bool\n\tCompression         bool\n\tEncryption          bool\n\tUnsynchronization   bool\n\tDataLengthIndicator bool\n}\n\nfunc Decode24(r io.ReaderAt) (*Id3v24Tag, error) {\n\theaderBytes := make([]byte, 10)\n\tif _, err := r.ReadAt(headerBytes, 0); err != nil {\n\t\treturn nil, err\n\t}\n\n\theader, err := parseId3v24Header(headerBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbr := bufio.NewReader(io.NewSectionReader(r, 10, int64(header.Size)))\n\n\tvar extendedHeader Id3v24ExtendedHeader\n\tif header.Flags.ExtendedHeader {\n\t\tvar err error\n\t\tif extendedHeader, err = parseId3v24ExtendedHeader(br); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tresult := &Id3v24Tag{\n\t\tHeader:         header,\n\t\tExtendedHeader: extendedHeader,\n\t\tFrames:         make(map[string][]*Id3v24Frame),\n\t}\n\n\tvar totalSize uint32\n\ttotalSize += extendedHeader.Size\n\n\tfor totalSize < header.Size {\n\t\thasFrame, err := hasId3v24Frame(br)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !hasFrame {\n\t\t\tbreak\n\t\t}\n\n\t\tframe, err := parseId3v24Frame(br)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ 10 bytes for the frame header, and the body.\n\t\ttotalSize += 10 + frame.Header.Size\n\n\t\tresult.Frames[frame.Header.Id] = append(result.Frames[frame.Header.Id], frame)\n\t}\n\treturn result, nil\n}\n\nfunc parseId3v24Header(headerBytes []byte) (result Id3v24Header, err error) {\n\tif !bytes.Equal(headerBytes[0:4], []byte{'I', 'D', '3', 4}) {\n\t\terr = id3v24Err(\"invalid magic numbers\")\n\t\treturn\n\t}\n\n\tresult.MinorVersion = headerBytes[4]\n\n\tflags := headerBytes[5]\n\n\tresult.Flags.Unsynchronization = (flags & (1 << 7)) != 0\n\tresult.Flags.ExtendedHeader = (flags & (1 << 6)) != 0\n\tresult.Flags.ExperimentalIndicator = (flags & (1 << 5)) != 0\n\tresult.Flags.FooterPresent = (flags & (1 << 4)) != 0\n\n\tresult.Size = uint32(parseBase128Int(headerBytes[6:10]))\n\treturn\n}\n\nfunc parseId3v24ExtendedHeader(br *bufio.Reader) (result Id3v24ExtendedHeader, err error) {\n\tsizeBytes, err := br.Peek(4)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult.Size = uint32(parseBase128Int(sizeBytes))\n\n\theaderBytes := make([]byte, result.Size)\n\tif _, err = io.ReadFull(br, headerBytes); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Discard size and number of flags bytes, and store flags.\n\t_, _, flags, headerBytes := headerBytes[:4], headerBytes[4], headerBytes[5], headerBytes[5:]\n\n\tresult.Flags.Update = (flags & (1 << 6)) != 0\n\tresult.Flags.CrcDataPresent = (flags & (1 << 5)) != 0\n\tresult.Flags.TagRestrictions = (flags & (1 << 4)) != 0\n\n\t\/\/ Don't do anything with the rest of the extended header for now.\n\n\treturn\n}\n\nfunc hasId3v24Frame(br *bufio.Reader) (bool, error) {\n\tdata, err := br.Peek(4)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, c := range data {\n\t\tif (c < 'A' || 'Z' < c) && (c < '0' || '9' < c) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc parseId3v24Frame(br *bufio.Reader) (*Id3v24Frame, error) {\n\theader, err := parseId3v24FrameHeader(br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontent := make([]byte, header.Size)\n\tif _, err := io.ReadFull(br, content); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Id3v24Frame{\n\t\tHeader:  header,\n\t\tContent: content,\n\t}, nil\n}\n\nfunc parseId3v24FrameHeader(br *bufio.Reader) (result Id3v24FrameHeader, err error) {\n\theaderBytes := make([]byte, 10)\n\tif _, err = io.ReadFull(br, headerBytes); err != nil {\n\t\treturn\n\t}\n\n\tidBytes, sizeBytes, flags := headerBytes[0:4], headerBytes[4:8], headerBytes[8:10]\n\tresult.Id = string(idBytes)\n\n\t\/\/ Read the size as 4 base128 bytes.\n\tresult.Size = uint32(parseBase128Int(sizeBytes))\n\n\tresult.Flags.TagAlterPreservation = (flags[0] & (1 << 6)) != 0\n\tresult.Flags.FileAlterPreservation = (flags[0] & (1 << 5)) != 0\n\tresult.Flags.ReadOnly = (flags[0] & (1 << 4)) != 0\n\n\tresult.Flags.GroupingIdentity = (flags[1] & (1 << 6)) != 0\n\tresult.Flags.Compression = (flags[1] & (1 << 3)) != 0\n\tresult.Flags.Encryption = (flags[1] & (1 << 2)) != 0\n\tresult.Flags.Unsynchronization = (flags[1] & (1 << 1)) != 0\n\tresult.Flags.DataLengthIndicator = (flags[1] & (1 << 0)) != 0\n\n\treturn result, nil\n}\n<commit_msg>Permit sub-4-byte padding in ID3 v2.4 tags<commit_after>\/\/ Copyright 2013 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 id3\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Id3v24Tag struct {\n\tHeader         Id3v24Header\n\tExtendedHeader Id3v24ExtendedHeader\n\tFrames         map[string][]*Id3v24Frame\n}\n\nfunc id3v24Err(format string, args ...interface{}) error {\n\treturn &ErrFormat{\n\t\tFormat: \"ID3 version 2.4\",\n\t\tErr:    fmt.Errorf(format, args...),\n\t}\n}\n\nfunc getSimpleId3v24TextFrame(frames []*Id3v24Frame) string {\n\tif len(frames) == 0 {\n\t\treturn \"\"\n\t}\n\tfields, err := GetId3v24TextIdentificationFrame(frames[0])\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(fields, \" \")\n}\n\nfunc (t *Id3v24Tag) Title() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TIT2\"])\n}\n\nfunc (t *Id3v24Tag) Artist() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TPE1\"])\n}\n\nfunc (t *Id3v24Tag) Album() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TALB\"])\n}\n\nfunc (t *Id3v24Tag) Comment() string {\n\treturn \"\"\n}\n\nfunc (t *Id3v24Tag) Genre() string {\n\treturn getSimpleId3v24TextFrame(t.Frames[\"TCON\"])\n}\n\nfunc (t *Id3v24Tag) Year() time.Time {\n\tyearStr := getSimpleId3v24TextFrame(t.Frames[\"TDRC\"])\n\tif len(yearStr) < 4 {\n\t\treturn time.Time{}\n\t}\n\n\tyearInt, err := strconv.Atoi(yearStr[0:4])\n\tif err != nil {\n\t\treturn time.Time{}\n\t}\n\n\treturn time.Date(yearInt, time.January, 1, 0, 0, 0, 0, time.UTC)\n}\n\nfunc (t *Id3v24Tag) Track() uint32 {\n\ttrack, err := parseLeadingInt(getSimpleId3v24TextFrame(t.Frames[\"TRCK\"]))\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn uint32(track)\n}\n\nfunc (t *Id3v24Tag) Disc() uint32 {\n\tdisc, err := parseLeadingInt(getSimpleId3v24TextFrame(t.Frames[\"TPOS\"]))\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn uint32(disc)\n}\n\nfunc (t *Id3v24Tag) CustomFrames() map[string]string {\n\tinfo := make(map[string]string)\n\tfor _, frame := range t.Frames[\"TXXX\"] {\n\t\t\/\/ See \"4.2.6. User defined text information frame\" at\n\t\t\/\/ http:\/\/id3.org\/id3v2.4.0-frames. TXXX frames contain\n\t\t\/\/ NUL-separated descriptions and values.\n\t\tparts, err := GetId3v24TextIdentificationFrame(frame)\n\t\tif err == nil && len(parts) == 2 {\n\t\t\tinfo[parts[0]] = parts[1]\n\t\t}\n\t}\n\treturn info\n}\n\nfunc (t *Id3v24Tag) TagSize() uint32 {\n\treturn 10 + t.Header.Size\n}\n\ntype Id3v24Header struct {\n\tMinorVersion byte\n\tFlags        Id3v24HeaderFlags\n\tSize         uint32\n}\n\ntype Id3v24HeaderFlags struct {\n\tUnsynchronization     bool\n\tExtendedHeader        bool\n\tExperimentalIndicator bool\n\tFooterPresent         bool\n}\n\ntype Id3v24ExtendedHeader struct {\n\tSize  uint32\n\tFlags Id3v24ExtendedHeaderFlags\n}\n\ntype Id3v24ExtendedHeaderFlags struct {\n\tUpdate          bool\n\tCrcDataPresent  bool\n\tTagRestrictions bool\n}\n\ntype Id3v24Frame struct {\n\tHeader  Id3v24FrameHeader\n\tContent []byte\n}\n\ntype Id3v24FrameHeader struct {\n\tId    string\n\tSize  uint32\n\tFlags Id3v24FrameHeaderFlags\n}\n\ntype Id3v24FrameHeaderFlags struct {\n\tTagAlterPreservation  bool\n\tFileAlterPreservation bool\n\tReadOnly              bool\n\n\tGroupingIdentity    bool\n\tCompression         bool\n\tEncryption          bool\n\tUnsynchronization   bool\n\tDataLengthIndicator bool\n}\n\nfunc Decode24(r io.ReaderAt) (*Id3v24Tag, error) {\n\theaderBytes := make([]byte, 10)\n\tif _, err := r.ReadAt(headerBytes, 0); err != nil {\n\t\treturn nil, err\n\t}\n\n\theader, err := parseId3v24Header(headerBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbr := bufio.NewReader(io.NewSectionReader(r, 10, int64(header.Size)))\n\n\tvar extendedHeader Id3v24ExtendedHeader\n\tif header.Flags.ExtendedHeader {\n\t\tvar err error\n\t\tif extendedHeader, err = parseId3v24ExtendedHeader(br); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tresult := &Id3v24Tag{\n\t\tHeader:         header,\n\t\tExtendedHeader: extendedHeader,\n\t\tFrames:         make(map[string][]*Id3v24Frame),\n\t}\n\n\tvar totalSize uint32\n\ttotalSize += extendedHeader.Size\n\n\tfor totalSize < header.Size {\n\t\thasFrame, err := hasId3v24Frame(br)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !hasFrame {\n\t\t\tbreak\n\t\t}\n\n\t\tframe, err := parseId3v24Frame(br)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ 10 bytes for the frame header, and the body.\n\t\ttotalSize += 10 + frame.Header.Size\n\n\t\tresult.Frames[frame.Header.Id] = append(result.Frames[frame.Header.Id], frame)\n\t}\n\treturn result, nil\n}\n\nfunc parseId3v24Header(headerBytes []byte) (result Id3v24Header, err error) {\n\tif !bytes.Equal(headerBytes[0:4], []byte{'I', 'D', '3', 4}) {\n\t\terr = id3v24Err(\"invalid magic numbers\")\n\t\treturn\n\t}\n\n\tresult.MinorVersion = headerBytes[4]\n\n\tflags := headerBytes[5]\n\n\tresult.Flags.Unsynchronization = (flags & (1 << 7)) != 0\n\tresult.Flags.ExtendedHeader = (flags & (1 << 6)) != 0\n\tresult.Flags.ExperimentalIndicator = (flags & (1 << 5)) != 0\n\tresult.Flags.FooterPresent = (flags & (1 << 4)) != 0\n\n\tresult.Size = uint32(parseBase128Int(headerBytes[6:10]))\n\treturn\n}\n\nfunc parseId3v24ExtendedHeader(br *bufio.Reader) (result Id3v24ExtendedHeader, err error) {\n\tsizeBytes, err := br.Peek(4)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresult.Size = uint32(parseBase128Int(sizeBytes))\n\n\theaderBytes := make([]byte, result.Size)\n\tif _, err = io.ReadFull(br, headerBytes); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Discard size and number of flags bytes, and store flags.\n\t_, _, flags, headerBytes := headerBytes[:4], headerBytes[4], headerBytes[5], headerBytes[5:]\n\n\tresult.Flags.Update = (flags & (1 << 6)) != 0\n\tresult.Flags.CrcDataPresent = (flags & (1 << 5)) != 0\n\tresult.Flags.TagRestrictions = (flags & (1 << 4)) != 0\n\n\t\/\/ Don't do anything with the rest of the extended header for now.\n\n\treturn\n}\n\nfunc hasId3v24Frame(br *bufio.Reader) (bool, error) {\n\tdata, err := br.Peek(4)\n\tif err == io.EOF {\n\t\t\/\/ If there are fewer than 4 bytes remaining, assume that they're\n\t\t\/\/ padding after the final frame (see section 3.3 of\n\t\t\/\/ http:\/\/id3.org\/id3v2.4.0-structure).\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\n\tfor _, c := range data {\n\t\tif (c < 'A' || 'Z' < c) && (c < '0' || '9' < c) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc parseId3v24Frame(br *bufio.Reader) (*Id3v24Frame, error) {\n\theader, err := parseId3v24FrameHeader(br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontent := make([]byte, header.Size)\n\tif _, err := io.ReadFull(br, content); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Id3v24Frame{\n\t\tHeader:  header,\n\t\tContent: content,\n\t}, nil\n}\n\nfunc parseId3v24FrameHeader(br *bufio.Reader) (result Id3v24FrameHeader, err error) {\n\theaderBytes := make([]byte, 10)\n\tif _, err = io.ReadFull(br, headerBytes); err != nil {\n\t\treturn\n\t}\n\n\tidBytes, sizeBytes, flags := headerBytes[0:4], headerBytes[4:8], headerBytes[8:10]\n\tresult.Id = string(idBytes)\n\n\t\/\/ Read the size as 4 base128 bytes.\n\tresult.Size = uint32(parseBase128Int(sizeBytes))\n\n\tresult.Flags.TagAlterPreservation = (flags[0] & (1 << 6)) != 0\n\tresult.Flags.FileAlterPreservation = (flags[0] & (1 << 5)) != 0\n\tresult.Flags.ReadOnly = (flags[0] & (1 << 4)) != 0\n\n\tresult.Flags.GroupingIdentity = (flags[1] & (1 << 6)) != 0\n\tresult.Flags.Compression = (flags[1] & (1 << 3)) != 0\n\tresult.Flags.Encryption = (flags[1] & (1 << 2)) != 0\n\tresult.Flags.Unsynchronization = (flags[1] & (1 << 1)) != 0\n\tresult.Flags.DataLengthIndicator = (flags[1] & (1 << 0)) != 0\n\n\treturn result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 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\/\/ \t\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 main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype commit struct {\n\tcategory string\n\tmessage  string\n}\n\nfunc newCommit(line string) *commit {\n\tvar cat, msg string\n\tlineSplit := strings.SplitN(line, \":\", 2)\n\tif len(lineSplit) > 1 {\n\t\tcat = strings.TrimSpace(lineSplit[0])\n\t\tmsg = strings.TrimSpace(lineSplit[1])\n\t} else {\n\t\tcat = \"other\"\n\t\tmsg = strings.TrimSpace(lineSplit[0])\n\t}\n\treturn &commit{category: cat, message: msg}\n}\n\nfunc (c *commit) String() string {\n\treturn c.message\n}\n\ntype changelog struct {\n\tgapic  []*commit\n\tbazel  []*commit\n\tgencli []*commit\n\tchore  []*commit\n\tother  []*commit\n}\n\nfunc newChangelog(gitlog string) *changelog {\n\tvar gapic, bazel, gencli, chore, other []*commit\n\tvar hasDeps bool\n\tfor _, line := range strings.Split(gitlog, \"\\n\") {\n\t\tcmt := newCommit(line)\n\t\tswitch cmt.category {\n\t\tcase \"gapic\":\n\t\t\tgapic = append(gapic, cmt)\n\t\tcase \"bazel\":\n\t\t\tbazel = append(bazel, cmt)\n\t\tcase \"gencli\":\n\t\t\tgencli = append(gencli, cmt)\n\t\tcase \"chore(deps)\":\n\t\t\thasDeps = true\n\t\tcase \"chore\":\n\t\t\tchore = append(chore, cmt)\n\t\tdefault:\n\t\t\tother = append(other, cmt)\n\t\t}\n\t}\n\n\tif hasDeps {\n\t\tchore = append(chore, &commit{category: \"chore\", message: \"update dependencies (see history)\"})\n\t}\n\n\treturn &changelog{\n\t\tgapic:  gapic,\n\t\tbazel:  bazel,\n\t\tgencli: gencli,\n\t\tchore:  chore,\n\t\tother:  other,\n\t}\n}\n\nfunc (cl *changelog) notes() string {\n\tsection := func(title string, commits []*commit) string {\n\t\tif len(commits) > 0 {\n\t\t\t\/\/ %0A is newline: https:\/\/github.community\/t\/set-output-truncates-multiline-strings\/16852\n\t\t\tanswer := fmt.Sprintf(\"## %s%%0A%%0A\", title)\n\t\t\tfor _, cmt := range commits {\n\t\t\t\tanswer += fmt.Sprintf(\"* %s%%0A\", cmt)\n\t\t\t}\n\t\t\treturn answer + \"%0A\"\n\t\t}\n\t\treturn \"\"\n\t}\n\treturn strings.TrimSuffix(\n\t\tsection(\"gapic\", cl.gapic)+section(\"bazel\", cl.bazel)+section(\"gencli\", cl.gencli)+section(\"chore\", cl.chore)+section(\"other\", cl.other),\n\t\t\"%0A\",\n\t)\n}\n<commit_msg>chore: group fix(deps) with chore(deps) in notes (#578)<commit_after>\/\/ Copyright 2021 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\/\/ \t\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 main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype commit struct {\n\tcategory string\n\tmessage  string\n}\n\nfunc newCommit(line string) *commit {\n\tvar cat, msg string\n\tlineSplit := strings.SplitN(line, \":\", 2)\n\tif len(lineSplit) > 1 {\n\t\tcat = strings.TrimSpace(lineSplit[0])\n\t\tmsg = strings.TrimSpace(lineSplit[1])\n\t} else {\n\t\tcat = \"other\"\n\t\tmsg = strings.TrimSpace(lineSplit[0])\n\t}\n\treturn &commit{category: cat, message: msg}\n}\n\nfunc (c *commit) String() string {\n\treturn c.message\n}\n\ntype changelog struct {\n\tgapic  []*commit\n\tbazel  []*commit\n\tgencli []*commit\n\tchore  []*commit\n\tother  []*commit\n}\n\nfunc newChangelog(gitlog string) *changelog {\n\tvar gapic, bazel, gencli, chore, other []*commit\n\tvar hasDeps bool\n\tfor _, line := range strings.Split(gitlog, \"\\n\") {\n\t\tcmt := newCommit(line)\n\t\tswitch cmt.category {\n\t\tcase \"gapic\":\n\t\t\tgapic = append(gapic, cmt)\n\t\tcase \"bazel\":\n\t\t\tbazel = append(bazel, cmt)\n\t\tcase \"gencli\":\n\t\t\tgencli = append(gencli, cmt)\n\t\tcase \"fix(deps)\":\n\t\t\tfallthrough\n\t\tcase \"chore(deps)\":\n\t\t\thasDeps = true\n\t\tcase \"chore\":\n\t\t\tchore = append(chore, cmt)\n\t\tdefault:\n\t\t\tother = append(other, cmt)\n\t\t}\n\t}\n\n\tif hasDeps {\n\t\tchore = append(chore, &commit{category: \"chore\", message: \"update dependencies (see history)\"})\n\t}\n\n\treturn &changelog{\n\t\tgapic:  gapic,\n\t\tbazel:  bazel,\n\t\tgencli: gencli,\n\t\tchore:  chore,\n\t\tother:  other,\n\t}\n}\n\nfunc (cl *changelog) notes() string {\n\tsection := func(title string, commits []*commit) string {\n\t\tif len(commits) > 0 {\n\t\t\t\/\/ %0A is newline: https:\/\/github.community\/t\/set-output-truncates-multiline-strings\/16852\n\t\t\tanswer := fmt.Sprintf(\"## %s%%0A%%0A\", title)\n\t\t\tfor _, cmt := range commits {\n\t\t\t\tanswer += fmt.Sprintf(\"* %s%%0A\", cmt)\n\t\t\t}\n\t\t\treturn answer + \"%0A\"\n\t\t}\n\t\treturn \"\"\n\t}\n\treturn strings.TrimSuffix(\n\t\tsection(\"gapic\", cl.gapic)+section(\"bazel\", cl.bazel)+section(\"gencli\", cl.gencli)+section(\"chore\", cl.chore)+section(\"other\", cl.other),\n\t\t\"%0A\",\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package lib\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestStatusCountOnNew(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, count)\n}\n\nfunc TestStatusCountOnEdit(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"b\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, count)\n}\n\nfunc TestStatusCountOnRename(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.Rename(\"app-a\/foo\", \"app-a\/bar\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 2, count)\n}\n\nfunc TestInvalidBranch(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tc, err := getBranchCommit(repo.Repo, \"foo\")\n\n\tassert.Nil(t, c)\n\tassert.EqualError(t, err, \"mbt: no reference found for shorthand 'foo'\")\n}\n\nfunc TestBranchName(t *testing.T) {\n\tclean()\n\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\tcheck(t, repo.SwitchToBranch(\"feature\"))\n\n\tbranch, err := getBranchName(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, \"feature\", branch)\n}\n\nfunc TestDiffByIndex(t *testing.T) {\n\tclean()\n\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/test.txt\", \"test contents\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.WriteContent(\"app-a\/test.txt\", \"ammend contents\"))\n\n\tdiff, err := getDiffFromIndex(repo.Repo)\n\tcheck(t, err)\n\n\tn, err := diff.NumDeltas()\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, n)\n}\n<commit_msg>Fix: typo<commit_after>package lib\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestStatusCountOnNew(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, count)\n}\n\nfunc TestStatusCountOnEdit(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"b\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, count)\n}\n\nfunc TestStatusCountOnRename(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/foo\", \"a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.Rename(\"app-a\/foo\", \"app-a\/bar\"))\n\n\tcount, err := statusCount(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, 2, count)\n}\n\nfunc TestInvalidBranch(t *testing.T) {\n\tclean()\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tc, err := getBranchCommit(repo.Repo, \"foo\")\n\n\tassert.Nil(t, c)\n\tassert.EqualError(t, err, \"mbt: no reference found for shorthand 'foo'\")\n}\n\nfunc TestBranchName(t *testing.T) {\n\tclean()\n\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.Commit(\"first\"))\n\tcheck(t, repo.SwitchToBranch(\"feature\"))\n\n\tbranch, err := getBranchName(repo.Repo)\n\tcheck(t, err)\n\n\tassert.Equal(t, \"feature\", branch)\n}\n\nfunc TestDiffByIndex(t *testing.T) {\n\tclean()\n\n\trepo, err := createTestRepository(\".tmp\/repo\")\n\tcheck(t, err)\n\n\tcheck(t, repo.InitModule(\"app-a\"))\n\tcheck(t, repo.WriteContent(\"app-a\/test.txt\", \"test contents\"))\n\tcheck(t, repo.Commit(\"first\"))\n\n\tcheck(t, repo.WriteContent(\"app-a\/test.txt\", \"amend contents\"))\n\n\tdiff, err := getDiffFromIndex(repo.Repo)\n\tcheck(t, err)\n\n\tn, err := diff.NumDeltas()\n\tcheck(t, err)\n\n\tassert.Equal(t, 1, n)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Encoding: utf-8\n\/\/ Cloud Foundry Java Buildpack\n\/\/ Copyright (c) 2015 the original author or 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 memory\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype MemSize struct {\n\tsizeInBytes int64\n}\n\nconst (\n\tbYTE = 1\n\tkILO = 1024 * bYTE\n\tmEGA = 1024 * kILO\n\tgIGA = 1024 * mEGA\n)\n\nvar MS_ZERO *MemSize\n\nfunc init() {\n\tMS_ZERO, _ = NewMemSize(\"0\")\n}\n\nfunc NewMemSize(ms string) (*MemSize, error) {\n\tms = strings.TrimSpace(ms)\n\tvar bytes int64 = 0\n\tif ms != \"0\" {\n\t\tfactor, intStr := int64(1), ms[:len(ms)-1]\n\t\tswitch ms[len(ms)-1] {\n\t\tcase 'b', 'B':\n\t\t\tfactor = bYTE\n\t\tcase 'k', 'K':\n\t\t\tfactor = kILO\n\t\tcase 'm', 'M':\n\t\t\tfactor = mEGA\n\t\tcase 'g', 'G':\n\t\t\tfactor = gIGA\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid memory size string '%s'\", ms)\n\t\t}\n\n\t\tnum, err := strconv.ParseInt(intStr, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbytes = num * factor\n\t}\n\treturn &MemSize{bytes}, nil\n}\n\nfunc (ms *MemSize) Bytes() int64 {\n\treturn ms.sizeInBytes\n}\n\nfunc (ms *MemSize) Kilos() int64 {\n\treturn ms.sizeInBytes \/ kILO\n}\n\nfunc (ms *MemSize) Megas() int64 {\n\treturn ms.sizeInBytes \/ mEGA\n}\n\nfunc (ms *MemSize) Gigas() int64 {\n\treturn ms.sizeInBytes \/ gIGA\n}\n\nfunc (ms *MemSize) String() string {\n\tvar (\n\t\tval  int64\n\t\tsuff string\n\t)\n\tif v := ms.Gigas(); v > 0 {\n\t\tval, suff = v, \"G\"\n\t} else if v := ms.Megas(); v > 0 {\n\t\tval, suff = v, \"M\"\n\t} else if v := ms.Kilos(); v > 0 {\n\t\tval, suff = v, \"K\"\n\t} else {\n\t\treturn \"0\"\n\t}\n\treturn fmt.Sprintf(\"%d%s\", val, suff)\n}\n\nfunc (ms *MemSize) LessThan(other *MemSize) bool {\n\treturn ms.Bytes() < other.Bytes()\n}\n\nfunc (ms *MemSize) Add(other *MemSize) *MemSize {\n\treturn &MemSize{ms.sizeInBytes + other.sizeInBytes}\n}\n\nfunc (ms *MemSize) Scale(factor float64) *MemSize {\n\treturn &MemSize{int64(factor*float64(ms.sizeInBytes) + 0.5)}\n}\n\nfunc (ms *MemSize) Equals(other *MemSize) bool {\n\treturn ms.sizeInBytes == other.sizeInBytes\n}\n\nfunc (ms *MemSize) Empty() bool {\n\treturn ms.sizeInBytes == 0\n}\n\nfunc (ms *MemSize) DividedBy(other *MemSize) float64 {\n\treturn float64(ms.sizeInBytes) \/ float64(other.sizeInBytes)\n}\n<commit_msg>Some doc for MemSize exported functions in memory_size.go.<commit_after>\/\/ Encoding: utf-8\n\/\/ Cloud Foundry Java Buildpack\n\/\/ Copyright (c) 2015 the original author or 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 memory\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ memory_size.go defines the MemSize struct which captures a memory size\n\/\/ allocation. It understands the normal nK, nM, nG string representations,\n\/\/ and permits scaling and comparison operations.  The methods are described\n\/\/ in-line.\n\/\/ type MemSize is exported, all the methods take *MemSize\n\ntype MemSize struct {\n\tsizeInBytes int64\n}\n\nconst (\n\tbYTE = 1\n\tkILO = 1024 * bYTE\n\tmEGA = 1024 * kILO\n\tgIGA = 1024 * mEGA\n)\n\n\/\/ The empty memory allocation (not nil).\nvar MS_ZERO *MemSize\n\nfunc init() {\n\tMS_ZERO, _ = NewMemSize(\"0\")\n}\n\n\/\/ Construct a new MemSize object from a string description\n\/\/\n\/\/ Errors include:\n\/\/\terrors from ParseInt\n\/\/\terror invalid memory size string '%s'\nfunc NewMemSize(ms string) (*MemSize, error) {\n\tms = strings.TrimSpace(ms)\n\tvar bytes int64 = 0\n\tif ms != \"0\" {\n\t\tfactor, intStr := int64(1), ms[:len(ms)-1]\n\t\tswitch ms[len(ms)-1] {\n\t\tcase 'b', 'B':\n\t\t\tfactor = bYTE\n\t\tcase 'k', 'K':\n\t\t\tfactor = kILO\n\t\tcase 'm', 'M':\n\t\t\tfactor = mEGA\n\t\tcase 'g', 'G':\n\t\t\tfactor = gIGA\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid memory size string '%s'\", ms)\n\t\t}\n\n\t\tnum, err := strconv.ParseInt(intStr, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tbytes = num * factor\n\t}\n\treturn &MemSize{bytes}, nil\n}\n\n\/\/ The number of bytes in the MemSize\nfunc (ms *MemSize) Bytes() int64 {\n\treturn ms.sizeInBytes\n}\n\n\/\/ The number of (whole) kilobytes in the MemSize\nfunc (ms *MemSize) Kilos() int64 {\n\treturn ms.sizeInBytes \/ kILO\n}\n\n\/\/ The number of (whole) megabytes in the MemSize\nfunc (ms *MemSize) Megas() int64 {\n\treturn ms.sizeInBytes \/ mEGA\n}\n\n\/\/ The number of (whole) gigabytes in the MemSize\nfunc (ms *MemSize) Gigas() int64 {\n\treturn ms.sizeInBytes \/ gIGA\n}\n\n\/\/ A string presentation of the MemSize rounded down to whole numbers\n\/\/ of giga-, mega-, kilo- bytes, and using the K,M,G suffices.\n\/\/ Less than 1K produces \"0\" as the string output.\nfunc (ms *MemSize) String() string {\n\tvar (\n\t\tval  int64\n\t\tsuff string\n\t)\n\tif v := ms.Gigas(); v > 0 {\n\t\tval, suff = v, \"G\"\n\t} else if v := ms.Megas(); v > 0 {\n\t\tval, suff = v, \"M\"\n\t} else if v := ms.Kilos(); v > 0 {\n\t\tval, suff = v, \"K\"\n\t} else {\n\t\treturn \"0\"\n\t}\n\treturn fmt.Sprintf(\"%d%s\", val, suff)\n}\n\n\/\/ True if the receiver has less bytes in it than does other.\nfunc (ms *MemSize) LessThan(other *MemSize) bool {\n\treturn ms.Bytes() < other.Bytes()\n}\n\n\/\/ Produce a new MemSize with the sum of the number of bytes in receiver and other.\nfunc (ms *MemSize) Add(other *MemSize) *MemSize {\n\treturn &MemSize{ms.sizeInBytes + other.sizeInBytes}\n}\n\n\/\/ Produce a new MemSize with factor times the number of bytes in it (rounded to nearest integer).\nfunc (ms *MemSize) Scale(factor float64) *MemSize {\n\treturn &MemSize{int64(factor*float64(ms.sizeInBytes) + 0.5)}\n}\n\n\/\/ True if the receiver has exactly the same number of bytes in it as does other.\nfunc (ms *MemSize) Equals(other *MemSize) bool {\n\treturn ms.sizeInBytes == other.sizeInBytes\n}\n\n\/\/ True if the receiver has exactly zero bytes in it.\nfunc (ms *MemSize) Empty() bool {\n\treturn ms.sizeInBytes == 0\n}\n\n\/\/ The ratio of the sizes in receiver and other as a floating point number.\n\/\/ twoGig.DividedBy(oneGig) should return 2.0.\n\/\/ oneGig.DividedBy(twoGig) should return 0.5.\nfunc (ms *MemSize) DividedBy(other *MemSize) float64 {\n\treturn float64(ms.sizeInBytes) \/ float64(other.sizeInBytes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\tsm \"github.com\/ifn\/go-statemachine\"\n)\n\ntype DeskMsg struct {\n\tDesk []string `json:\"desk\"`\n}\n\ntype PlayerMsg struct {\n\tCmd  sm.EventType `json:\"command\"`\n\tCard string       `json:\"card\"`\n}\n\n\/\/\n\nvar Suits []string = []string{\n\t\"S\",\n\t\"C\",\n\t\"H\",\n\t\"D\",\n}\n\nvar CardValues map[string]int = map[string]int{\n\t\"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"10\": 10,\n\t\"J\": 11,\n\t\"Q\": 12,\n\t\"K\": 13,\n\t\"A\": 14,\n}\n\nfunc higher(c0, c1, t string) int {\n\t\/\/ c0 and c1 have the same suit\n\tif c0[0] == c1[0] {\n\t\tif CardValues[c0[1:]] > CardValues[c1[1:]] {\n\t\t\treturn 1\n\t\t}\n\t\tif CardValues[c0[1:]] < CardValues[c1[1:]] {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t}\n\t\/\/ c0 is trump, c1 is not\n\tif c0[:1] == t {\n\t\treturn 1\n\t}\n\t\/\/ c1 is trump, c0 is not\n\tif c1[:1] == t {\n\t\treturn -1\n\t}\n\t\/\/ suits are different, both are not trump\n\treturn -2\n}\n\nvar CardRE *regexp.Regexp = regexp.MustCompile(`[SCHD]([6-9JQKA]|10)`)\n\nfunc isValid(c string) bool {\n\treturn CardRE.MatchString(c)\n}\n\n\/\/\n\nconst (\n\tcmdStart sm.EventType = iota\n\tcmdMove\n\n\tcmdCount\n)\n\nconst (\n\tstateCollection sm.State = iota\n\n\tstateAttack\n\tstateDefense\n\n\tstateCount\n)\n\ntype roundResult int\n\nconst (\n\tNone roundResult = iota\n\tBeat\n\tNotBeat\n)\n\nfunc stateToString(s sm.State) string {\n\treturn [...]string{\n\t\tstateCollection: \"COLLECTION\",\n\t\tstateDefense:    \"DEFENSE\",\n\t\tstateAttack:     \"ATTACK\",\n\t}[s]\n}\n\nfunc cmdToString(t sm.EventType) string {\n\treturn [...]string{\n\t\tcmdStart: \"START\",\n\t\tcmdMove:  \"MOVE\",\n\t}[t]\n}\n\n\/\/\n\ntype cmdArgs struct {\n\tconn *playerConn\n\tcard string\n}\n\n\/\/\n\nfunc logOutOfTurn(pconn *playerConn) {\n\tlog.Printf(\"out of turn: %v\", pconn.conn.RemoteAddr())\n}\n\nfunc logWontBeat(c1, c2, t string) {\n\tlog.Printf(\"%v won't bit %v, trump is %v\", c1, c2, t)\n}\n\nfunc logWrongNumber(n int) {\n\tlog.Printf(\"wrong number of players: %v\", n)\n}\n\nfunc logStrangeCard(c string, pc *playerConn) {\n\tlog.Printf(\"%v doesn't own %v\", pc, c)\n}\n\n\/\/\n\ntype gameState struct {\n\t\/\/ 1. fields that don't change during a game\n\n\tsm  *sm.StateMachine\n\thub *hub\n\n\t\/\/ trump suit\n\ttrump string\n\n\t\/\/ 2. fields that don't change during a round\n\n\tdeck []string\n\n\t\/\/ attacker that started a round\n\taconnStart *playerConn\n\t\/\/ defender\n\tdconn *playerConn\n\n\t\/\/ 3. fields that change during a round\n\n\tdesk []string\n\n\t\/\/ attacker\n\taconn *playerConn\n\t\/\/ card that should be beaten\n\tcardToBeat string\n}\n\nfunc (self *gameState) popCard() (card string) {\n\tif deck := self.deck; len(deck) > 0 {\n\t\tcard = deck[0]\n\t\tself.deck = deck[1:]\n\t}\n\treturn\n}\n\nfunc (self *gameState) initDeck() {\n\tnumCards := len(Suits) * len(CardValues)\n\n\tdeck := make([]string, 0, numCards)\n\tfor _, suit := range Suits {\n\t\tfor cv := range CardValues {\n\t\t\tdeck = append(deck, suit+cv)\n\t\t}\n\t}\n\n\torder := rand.Perm(numCards)\n\tfor _, pos := range order {\n\t\tself.deck = append(self.deck, deck[pos])\n\t}\n}\n\n\/\/TODO: don't like it\nfunc (self *gameState) setTrump(card string) {\n\ttcard := self.popCard()\n\tif tcard == \"\" {\n\t\ttcard = card\n\t} else {\n\t\tself.deck = append(self.deck, tcard)\n\t}\n\tself.trump = tcard[:1]\n}\n\nfunc (self *gameState) nextPlayer(c *playerConn) *playerConn {\n\treturn self.hub.conns.(*mapRing).Next(c).(*playerConn)\n}\n\nfunc (self *gameState) chooseStarting() *playerConn {\n\tconns := self.hub.conns.(*mapRing)\n\n\treturn conns.Nth(rand.Intn(conns.Len())).(*playerConn)\n}\n\nfunc (self *gameState) markInactive() {\n\tif len(self.deck) == 0 {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tif pc := pc.(*playerConn); len(pc.cards) == 0 {\n\t\t\t\tpc.active = false\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *gameState) firstActive(c *playerConn) *playerConn {\n\tfor pc := range self.hub.conns.(*mapRing).EnumerateFrom(c) {\n\t\tif pc := pc.(*playerConn); pc.active {\n\t\t\treturn pc\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (self *gameState) setRoles(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.aconn = self.chooseStarting()\n\tcase Beat:\n\t\tself.aconn = self.dconn\n\tcase NotBeat:\n\t\tself.aconn = self.nextPlayer(self.dconn)\n\t}\n\tself.dconn = self.nextPlayer(self.aconn)\n\tself.aconnStart = self.aconn\n}\n\nfunc (self *gameState) dealCards() (card string) {\n\tfor i := 0; i < 6; i++ {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tcard = pc.(*playerConn).fromDeck()\n\t\t}\n\t}\n\treturn\n}\n\nfunc (self *gameState) takeCards() {\n\tconns := self.hub.conns.(*mapRing)\n\n\ttakeCards := func(pc *playerConn) {\n\t\tfor len(self.deck) > 0 && len(pc.cards) < 6 {\n\t\t\tpc.fromDeck()\n\t\t}\n\t}\n\n\tfor pc := range conns.EnumerateFrom(self.aconnStart) {\n\t\tif pc := pc.(*playerConn); pc != self.dconn {\n\t\t\ttakeCards(pc)\n\t\t}\n\t}\n\ttakeCards(self.dconn)\n}\n\nfunc (self *gameState) newRound(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.initDeck()\n\t\tcard := self.dealCards()\n\t\tself.setTrump(card)\n\tcase NotBeat:\n\t\tself.dconn.fromDesk()\n\t\tself.takeCards()\n\tcase Beat:\n\t\tself.desk = self.desk[:0]\n\t\tself.takeCards()\n\t}\n\tself.markInactive()\n\tself.setRoles(res)\n\tself.cardToBeat = \"\"\n}\n\n\/\/ event handlers\n\/\/ event handlers are actually transition functions.\n\/\/ in case error event handler should neither change the gameState,\n\/\/ nor return the state value different from passed to it as an argument.\n\nfunc (self *gameState) handleStartInCollection(s sm.State, e *sm.Event) sm.State {\n\tif n := self.hub.conns.(*mapRing).Len(); n < 2 || n > 6 {\n\t\tlogWrongNumber(n)\n\t\treturn s\n\t}\n\n\tself.newRound(None)\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInAttack(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.aconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ attacker sent the card\n\tif card != \"\" {\n\t\t\/\/ throw card to desk\n\t\tif _, ok := conn.cards[card]; !ok {\n\t\t\tlogStrangeCard(card, conn)\n\t\t\treturn s\n\t\t}\n\t\tconn.toDesk(card)\n\n\t\tself.cardToBeat = card\n\t\treturn stateDefense\n\t}\n\n\t\/\/ attacker sent no card\n\n\taconn := self.nextPlayer(self.aconn)\n\tif aconn == self.dconn {\n\t\taconn = self.nextPlayer(aconn)\n\t}\n\n\t\/\/ check if all attackers have been polled\n\tif aconn == self.aconnStart {\n\t\tself.newRound(Beat)\n\t\treturn stateAttack\n\t}\n\n\tself.aconn = aconn\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInDefense(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.dconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ defender takes the cards\n\tif card == \"\" {\n\t\tself.newRound(NotBeat)\n\t\treturn stateAttack\n\t}\n\n\t\/\/ check that the sent card is capable to beat\n\tif higher(card, self.cardToBeat, self.trump) != 1 {\n\t\tlogWontBeat(card, self.cardToBeat, self.trump)\n\t\treturn s\n\t}\n\n\t\/\/ throw card to desk\n\tif _, ok := conn.cards[card]; !ok {\n\t\tlogStrangeCard(card, conn)\n\t\treturn s\n\t}\n\tconn.toDesk(card)\n\n\treturn stateAttack\n}\n\nfunc (self *gameState) showDesk(s sm.State, e *sm.Event) sm.State {\n\tdesk, err := json.Marshal(DeskMsg{self.desk})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn s\n\t}\n\n\tself.hub.bcastChan <- desk\n\n\treturn s\n}\n\nfunc (self *gameState) log(s sm.State, e *sm.Event) sm.State {\n\tlog.Println(self)\n\treturn s\n}\n\n\/\/\n\nfunc NewGameState() *gameState {\n\tgst := new(gameState)\n\n\tgst.sm = sm.New(stateCollection, uint(stateCount), uint(cmdCount))\n\n\tgst.sm.OnChain(cmdStart,\n\t\t[]sm.State{stateCollection},\n\t\t[]sm.EventHandler{\n\t\t\tgst.handleStartInCollection,\n\t\t\tgst.showDesk,\n\t\t\tgst.log,\n\t\t},\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack},\n\t\tgst.handleMoveInAttack,\n\t)\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateDefense},\n\t\tgst.handleMoveInDefense,\n\t)\n\n\tgst.sm.OnChain(cmdMove,\n\t\t[]sm.State{stateAttack, stateDefense},\n\t\t[]sm.EventHandler{\n\t\t\tgst.showDesk,\n\t\t\tgst.log,\n\t\t},\n\t)\n\n\tgst.deck = make([]string, 0, len(Suits)*len(CardValues)+ \/*for trump*\/ 1)\n\tgst.desk = make([]string, 0, 12)\n\n\tgst.hub = NewHub()\n\n\treturn gst\n}\n\n\/\/\n\ntype playerConn struct {\n\tgst *gameState\n\n\tcards  map[string]struct{}\n\tactive bool\n\n\tconn      *websocket.Conn\n\thubToConn chan []byte\n}\n\nfunc (self *playerConn) fromDeck() (card string) {\n\tif card = self.gst.popCard(); card != \"\" {\n\t\tself.cards[card] = struct{}{}\n\t}\n\treturn\n}\n\nfunc (self *playerConn) toDesk(card string) {\n\tdelete(self.cards, card)\n\n\tself.gst.desk = append(self.gst.desk, card)\n}\n\nfunc (self *playerConn) fromDesk() {\n\tfor _, card := range self.gst.desk {\n\t\tself.cards[card] = struct{}{}\n\t}\n\n\tself.gst.desk = self.gst.desk[:0]\n}\n\nfunc (self *playerConn) write() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-self.hubToConn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/TODO: text or binary?\n\t\t\terr := self.conn.WriteMessage(websocket.TextMessage, m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *playerConn) read() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tvar m PlayerMsg\n\n\t\terr := self.conn.ReadJSON(&m)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tvar event *sm.Event\n\t\tswitch m.Cmd {\n\t\tcase cmdStart:\n\t\t\tevent = &sm.Event{cmdStart, nil}\n\t\tcase cmdMove:\n\t\t\tevent = &sm.Event{cmdMove, cmdArgs{self, m.Card}}\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown command: %v\", m.Cmd)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = self.gst.sm.Emit(event)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\nfunc playerHandler(gst *gameState) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tp := &playerConn{gst, make(map[string]struct{}), true, conn, make(chan []byte)}\n\n\t\tgst.hub.regChan <- p\n\t\tdefer func() {\n\t\t\tgst.hub.unregChan <- p\n\t\t}()\n\n\t\tgo p.write()\n\t\tp.read()\n\t}\n}\n\n\/\/\n\nfunc startDurakSrv() error {\n\tgst := NewGameState()\n\n\thttp.HandleFunc(\"\/\", playerHandler(gst))\n\n\treturn http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n}\n\nfunc main() {\n\terr := startDurakSrv()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n<commit_msg>minor changes<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\tsm \"github.com\/ifn\/go-statemachine\"\n)\n\ntype DeskMsg struct {\n\tDesk []string `json:\"desk\"`\n}\n\ntype PlayerMsg struct {\n\tCmd  sm.EventType `json:\"command\"`\n\tCard string       `json:\"card\"`\n}\n\n\/\/\n\nvar Suits []string = []string{\n\t\"S\",\n\t\"C\",\n\t\"H\",\n\t\"D\",\n}\n\nvar CardValues map[string]int = map[string]int{\n\t\"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"10\": 10,\n\t\"J\": 11,\n\t\"Q\": 12,\n\t\"K\": 13,\n\t\"A\": 14,\n}\n\nfunc higher(c0, c1, t string) int {\n\t\/\/ c0 and c1 have the same suit\n\tif c0[0] == c1[0] {\n\t\tif CardValues[c0[1:]] > CardValues[c1[1:]] {\n\t\t\treturn 1\n\t\t}\n\t\tif CardValues[c0[1:]] < CardValues[c1[1:]] {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t}\n\t\/\/ c0 is trump, c1 is not\n\tif c0[:1] == t {\n\t\treturn 1\n\t}\n\t\/\/ c1 is trump, c0 is not\n\tif c1[:1] == t {\n\t\treturn -1\n\t}\n\t\/\/ suits are different, both are not trump\n\treturn -2\n}\n\nvar CardRE *regexp.Regexp = regexp.MustCompile(`[SCHD]([6-9JQKA]|10)`)\n\nfunc isValid(c string) bool {\n\treturn CardRE.MatchString(c)\n}\n\n\/\/\n\nconst (\n\tcmdStart sm.EventType = iota\n\tcmdMove\n\n\tcmdCount\n)\n\nconst (\n\tstateCollection sm.State = iota\n\n\tstateAttack\n\tstateDefense\n\n\tstateCount\n)\n\ntype roundResult int\n\nconst (\n\tNone roundResult = iota\n\tBeat\n\tNotBeat\n)\n\nfunc stateToString(s sm.State) string {\n\treturn [...]string{\n\t\tstateCollection: \"COLLECTION\",\n\t\tstateDefense:    \"DEFENSE\",\n\t\tstateAttack:     \"ATTACK\",\n\t}[s]\n}\n\nfunc cmdToString(t sm.EventType) string {\n\treturn [...]string{\n\t\tcmdStart: \"START\",\n\t\tcmdMove:  \"MOVE\",\n\t}[t]\n}\n\n\/\/\n\ntype cmdArgs struct {\n\tconn *playerConn\n\tcard string\n}\n\n\/\/\n\nfunc logOutOfTurn(pconn *playerConn) {\n\tlog.Printf(\"out of turn: %v\", pconn.conn.RemoteAddr())\n}\n\nfunc logWontBeat(c1, c2, t string) {\n\tlog.Printf(\"%v won't bit %v, trump is %v\", c1, c2, t)\n}\n\nfunc logWrongNumber(n int) {\n\tlog.Printf(\"wrong number of players: %v\", n)\n}\n\nfunc logStrangeCard(c string, pc *playerConn) {\n\tlog.Printf(\"%v doesn't own %v\", pc, c)\n}\n\n\/\/\n\ntype gameState struct {\n\t\/\/ 1. fields that don't change during a game\n\n\tsm  *sm.StateMachine\n\thub *hub\n\n\t\/\/ trump suit\n\ttrump string\n\n\t\/\/ 2. fields that don't change during a round\n\n\tdeck []string\n\n\t\/\/ attacker that started a round\n\taconnStart *playerConn\n\t\/\/ defender\n\tdconn *playerConn\n\n\t\/\/ 3. fields that change during a round\n\n\tdesk []string\n\n\t\/\/ attacker\n\taconn *playerConn\n\t\/\/ card that should be beaten\n\tcardToBeat string\n}\n\nfunc (self *gameState) markInactive() {\n\tif len(self.deck) == 0 {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tif pc := pc.(*playerConn); len(pc.cards) == 0 {\n\t\t\t\tpc.active = false\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *gameState) firstActive(c *playerConn) *playerConn {\n\tfor pc := range self.hub.conns.(*mapRing).EnumerateFrom(c) {\n\t\tif pc := pc.(*playerConn); pc.active {\n\t\t\treturn pc\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/\n\nfunc (self *gameState) nextPlayer(c *playerConn) *playerConn {\n\treturn self.hub.conns.(*mapRing).Next(c).(*playerConn)\n}\n\nfunc (self *gameState) nextActivePlayer(c *playerConn) *playerConn {\n\treturn self.firstActive(self.nextPlayer(c))\n}\n\n\/\/\n\nfunc (self *gameState) initDeck() {\n\tnumCards := len(Suits) * len(CardValues)\n\n\tdeck := make([]string, 0, numCards)\n\tfor _, suit := range Suits {\n\t\tfor cv := range CardValues {\n\t\t\tdeck = append(deck, suit+cv)\n\t\t}\n\t}\n\n\torder := rand.Perm(numCards)\n\tfor _, pos := range order {\n\t\tself.deck = append(self.deck, deck[pos])\n\t}\n}\n\nfunc (self *gameState) popCard() (card string) {\n\tif deck := self.deck; len(deck) > 0 {\n\t\tcard = deck[0]\n\t\tself.deck = deck[1:]\n\t}\n\treturn\n}\n\nfunc (self *gameState) dealCards() (card string) {\n\tfor i := 0; i < 6; i++ {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tcard = pc.(*playerConn).fromDeck()\n\t\t}\n\t}\n\treturn\n}\n\nfunc (self *gameState) takeCards() {\n\tconns := self.hub.conns.(*mapRing)\n\n\ttakeCards := func(pc *playerConn) {\n\t\tfor len(self.deck) > 0 && len(pc.cards) < 6 {\n\t\t\tpc.fromDeck()\n\t\t}\n\t}\n\n\tfor pc := range conns.EnumerateFrom(self.aconnStart) {\n\t\tif pc := pc.(*playerConn); pc != self.dconn {\n\t\t\ttakeCards(pc)\n\t\t}\n\t}\n\ttakeCards(self.dconn)\n}\n\n\/\/\n\n\/\/TODO: don't like it\nfunc (self *gameState) setTrump(card string) {\n\ttcard := self.popCard()\n\tif tcard == \"\" {\n\t\ttcard = card\n\t} else {\n\t\tself.deck = append(self.deck, tcard)\n\t}\n\tself.trump = tcard[:1]\n}\n\nfunc (self *gameState) chooseStarting() *playerConn {\n\tconns := self.hub.conns.(*mapRing)\n\n\treturn conns.Nth(rand.Intn(conns.Len())).(*playerConn)\n}\n\n\/\/\n\nfunc (self *gameState) setRoles(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.aconn = self.chooseStarting()\n\tcase Beat:\n\t\tself.aconn = self.dconn\n\tcase NotBeat:\n\t\tself.aconn = self.nextPlayer(self.dconn)\n\t}\n\tself.dconn = self.nextPlayer(self.aconn)\n\tself.aconnStart = self.aconn\n}\n\nfunc (self *gameState) newRound(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.initDeck()\n\t\tcard := self.dealCards()\n\t\tself.setTrump(card)\n\tcase NotBeat:\n\t\tself.dconn.fromDesk()\n\t\tself.takeCards()\n\tcase Beat:\n\t\tself.desk = self.desk[:0]\n\t\tself.takeCards()\n\t}\n\tself.markInactive()\n\tself.setRoles(res)\n\tself.cardToBeat = \"\"\n}\n\n\/\/ event handlers\n\/\/ event handlers are actually transition functions.\n\/\/ in case error event handler should neither change the gameState,\n\/\/ nor return the state value different from passed to it as an argument.\n\nfunc (self *gameState) handleStartInCollection(s sm.State, e *sm.Event) sm.State {\n\tif n := self.hub.conns.(*mapRing).Len(); n < 2 || n > 6 {\n\t\tlogWrongNumber(n)\n\t\treturn s\n\t}\n\n\tself.newRound(None)\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInAttack(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.aconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ attacker sent the card\n\tif card != \"\" {\n\t\t\/\/ throw card to desk\n\t\tif _, ok := conn.cards[card]; !ok {\n\t\t\tlogStrangeCard(card, conn)\n\t\t\treturn s\n\t\t}\n\t\tconn.toDesk(card)\n\n\t\tself.cardToBeat = card\n\t\treturn stateDefense\n\t}\n\n\t\/\/ attacker sent no card\n\n\taconn := self.nextPlayer(self.aconn)\n\tif aconn == self.dconn {\n\t\taconn = self.nextPlayer(aconn)\n\t}\n\n\t\/\/ check if all attackers have been polled\n\tif aconn == self.aconnStart {\n\t\tself.newRound(Beat)\n\t\treturn stateAttack\n\t}\n\n\tself.aconn = aconn\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInDefense(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.dconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ defender takes the cards\n\tif card == \"\" {\n\t\tself.newRound(NotBeat)\n\t\treturn stateAttack\n\t}\n\n\t\/\/ check that the sent card is capable to beat\n\tif higher(card, self.cardToBeat, self.trump) != 1 {\n\t\tlogWontBeat(card, self.cardToBeat, self.trump)\n\t\treturn s\n\t}\n\n\t\/\/ throw card to desk\n\tif _, ok := conn.cards[card]; !ok {\n\t\tlogStrangeCard(card, conn)\n\t\treturn s\n\t}\n\tconn.toDesk(card)\n\n\treturn stateAttack\n}\n\nfunc (self *gameState) showDesk(s sm.State, e *sm.Event) sm.State {\n\tdesk, err := json.Marshal(DeskMsg{self.desk})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn s\n\t}\n\n\tself.hub.bcastChan <- desk\n\n\treturn s\n}\n\nfunc (self *gameState) log(s sm.State, e *sm.Event) sm.State {\n\tlog.Println(self)\n\treturn s\n}\n\n\/\/\n\nfunc NewGameState() *gameState {\n\tgst := new(gameState)\n\n\tgst.sm = sm.New(stateCollection, uint(stateCount), uint(cmdCount))\n\n\tgst.sm.OnChain(cmdStart,\n\t\t[]sm.State{stateCollection},\n\t\t[]sm.EventHandler{\n\t\t\tgst.handleStartInCollection,\n\t\t\tgst.showDesk,\n\t\t\tgst.log,\n\t\t},\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack},\n\t\tgst.handleMoveInAttack,\n\t)\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateDefense},\n\t\tgst.handleMoveInDefense,\n\t)\n\n\tgst.sm.OnChain(cmdMove,\n\t\t[]sm.State{stateAttack, stateDefense},\n\t\t[]sm.EventHandler{\n\t\t\tgst.showDesk,\n\t\t\tgst.log,\n\t\t},\n\t)\n\n\tgst.deck = make([]string, 0, len(Suits)*len(CardValues)+ \/*for trump*\/ 1)\n\tgst.desk = make([]string, 0, 12)\n\n\tgst.hub = NewHub()\n\n\treturn gst\n}\n\n\/\/\n\ntype playerConn struct {\n\tgst *gameState\n\n\tcards  map[string]struct{}\n\tactive bool\n\n\tconn      *websocket.Conn\n\thubToConn chan []byte\n}\n\nfunc (self *playerConn) fromDeck() (card string) {\n\tif card = self.gst.popCard(); card != \"\" {\n\t\tself.cards[card] = struct{}{}\n\t}\n\treturn\n}\n\nfunc (self *playerConn) toDesk(card string) {\n\tdelete(self.cards, card)\n\n\tself.gst.desk = append(self.gst.desk, card)\n}\n\nfunc (self *playerConn) fromDesk() {\n\tfor _, card := range self.gst.desk {\n\t\tself.cards[card] = struct{}{}\n\t}\n\n\tself.gst.desk = self.gst.desk[:0]\n}\n\nfunc (self *playerConn) write() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-self.hubToConn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/TODO: text or binary?\n\t\t\terr := self.conn.WriteMessage(websocket.TextMessage, m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *playerConn) read() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tvar m PlayerMsg\n\n\t\terr := self.conn.ReadJSON(&m)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tvar event *sm.Event\n\t\tswitch m.Cmd {\n\t\tcase cmdStart:\n\t\t\tevent = &sm.Event{cmdStart, nil}\n\t\tcase cmdMove:\n\t\t\tevent = &sm.Event{cmdMove, cmdArgs{self, m.Card}}\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown command: %v\", m.Cmd)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = self.gst.sm.Emit(event)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\nfunc playerHandler(gst *gameState) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tp := &playerConn{gst, make(map[string]struct{}), true, conn, make(chan []byte)}\n\n\t\tgst.hub.regChan <- p\n\t\tdefer func() {\n\t\t\tgst.hub.unregChan <- p\n\t\t}()\n\n\t\tgo p.write()\n\t\tp.read()\n\t}\n}\n\n\/\/\n\nfunc startDurakSrv() error {\n\tgst := NewGameState()\n\n\thttp.HandleFunc(\"\/\", playerHandler(gst))\n\n\treturn http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n}\n\nfunc main() {\n\terr := startDurakSrv()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n<|endoftext|>"}
{"text":"<commit_before>package gaestatic\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"net\/http\"\n\t\"text\/template\"\n\t\"bytes\"\n\t\"net\/url\"\n)\n\nconst PLIST_TEMPLATE string = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-\/\/Apple\/\/DTD PLIST 1.0\/\/EN\" \"http:\/\/www.apple.com\/DTDs\/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n\t<dict>\n\t\t<key>items<\/key>\n\t\t<array>\n\t\t\t<dict>\n\t\t\t\t<key>assets<\/key>\n\t\t\t\t<array>\n\t\t\t\t\t{{if .IpaUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>software-package<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.IpaUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .DisplayImageUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>display-image<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.DisplayImageUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .FullSizeImageUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>full-size-image<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.FullSizeImageUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/array>\n\t\t\t\t<key>metadata<\/key>\n\t\t\t\t<dict>\n\t\t\t\t\t{{if .BundleIdentifer}}\n\t\t\t\t\t<key>bundle-identifier<\/key>\n\t\t\t\t\t<string>{{.BundleIdentifer}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .BundleVersion}}\n\t\t\t\t\t<key>bundle-version<\/key>\n\t\t\t\t\t<string>{{.BundleVersion}}<\/string>\n\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .Title}}\n\t\t\t\t\t<string>software<\/string>\n\t\t\t\t\t<key>title<\/key>\n\t\t\t\t\t<string>{{.Title}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/dict>\n\t\t\t<\/dict>\n\t\t<\/array>\n\t<\/dict>\n<\/plist>\n`\n\ntype PlistTemplateParams struct {\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/sample.ipa\n\tIpaUrl string\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/image.png\n\tDisplayImageUrl string\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/full-image.png\n\tFullSizeImageUrl string\n\t\/\/ eg. com.example.sample\n\tBundleIdentifer string\n\t\/\/ eg. 1.0\n\tBundleVersion string\n\t\/\/ eg. Sample App\n\tTitle string\n}\n\n\/**\n * Dynamic Plist Handler\n *\/\nfunc plistHandler(w http.ResponseWriter, r *http.Request) bool {\n\n\tisDone := true\n\n\tconfig := GetAppConfig()\n\tif config == nil {\n\t\t\/\/ Internal Server Errror\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"No Config\"))\n\t\treturn isDone\n\t}\n\n\tfilePath := strings.Replace(r.URL.Path, config.PlistDir, \"\", 1)\n\ttmp := strings.SplitN(filePath, \"\/\", 3)\n\tif len(tmp) < 3 {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #1\"))\n\t\treturn isDone\n\t}\n\tif tmp[2] != \"x.plist\" {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #2\"))\n\t\treturn isDone\n\t}\n\tbundleIdentifer := tmp[0]\n\tif strings.Contains(tmp[1], \"..\") {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #3\"))\n\t\treturn isDone\n\t}\n\n\tipaUrl, _ := url.Parse(r.RequestURI)\n\tif !r.URL.IsAbs() {\n\t\tipaUrl.Scheme = \"https\"\n\t\tipaUrl.Host = r.Host\n\t}\n\tipaUrl.Path = \"\/\" + tmp[1]\n\n\tparams := PlistTemplateParams{}\n\t\/\/ http:\/\/example.com\/{filePath}\/{bundleId}\/{IpaPath}?title={title}&version={bundleVersion}\n\tparams.Title = r.URL.Query().Get(\"title\")\n\tparams.BundleVersion = r.URL.Query().Get(\"version\")\n\tparams.BundleIdentifer = bundleIdentifer\n\tparams.IpaUrl = ipaUrl.String()\n\n\ttmpl, err := template.New(\"plist\").Parse(PLIST_TEMPLATE)\n\n\tif err != nil {\n\t\t\/\/ Not Found\n\t\tw.WriteHeader(501)\n\t\tw.Write([]byte(fmt.Sprintf(\"plist template is invalid.\")))\n\t\treturn isDone\n\t}\n\n\twriter := new(bytes.Buffer)\n\terr\t= tmpl.Execute(writer, params)\n\n\tvar contentLength string\n\tif err != nil {\n\t\t\/\/ Forbidden : サイズ取得失敗\n\t\tw.WriteHeader(403)\n\t\tw.Write([]byte(fmt.Sprintf(\"plist params is invalid.\")))\n\t\treturn isDone\n\t} else {\n\t\tcontentLength = strconv.FormatInt(int64(writer.Len()), 10)\n\t}\n\tcontentLength = contentLength + \"bytes\"\n\n\tcontentType := GetContentType(\"_.plist\")\n\tif contentType != \"\" {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t}\n\tw.Write(writer.Bytes())\n\tisDone = true\n\treturn isDone\n}\n<commit_msg>dynamic plist : snapshot<commit_after>package gaestatic\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"net\/http\"\n\t\"text\/template\"\n\t\"bytes\"\n\t\"net\/url\"\n)\n\nconst PLIST_TEMPLATE string = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-\/\/Apple\/\/DTD PLIST 1.0\/\/EN\" \"http:\/\/www.apple.com\/DTDs\/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n\t<dict>\n\t\t<key>items<\/key>\n\t\t<array>\n\t\t\t<dict>\n\t\t\t\t<key>assets<\/key>\n\t\t\t\t<array>\n\t\t\t\t\t{{if .IpaUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>software-package<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.IpaUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .DisplayImageUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>display-image<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.DisplayImageUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .FullSizeImageUrl}}\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t\t<string>full-size-image<\/string>\n\t\t\t\t\t\t<key>url<\/key>\n\t\t\t\t\t\t<string>{{.FullSizeImageUrl}}<\/string>\n\t\t\t\t\t<\/dict>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/array>\n\t\t\t\t<key>metadata<\/key>\n\t\t\t\t<dict>\n\t\t\t\t\t{{if .BundleIdentifer}}\n\t\t\t\t\t<key>bundle-identifier<\/key>\n\t\t\t\t\t<string>{{.BundleIdentifer}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .BundleVersion}}\n\t\t\t\t\t<key>bundle-version<\/key>\n\t\t\t\t\t<string>{{.BundleVersion}}<\/string>\n\t\t\t\t\t<key>kind<\/key>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .Title}}\n\t\t\t\t\t<string>software<\/string>\n\t\t\t\t\t<key>title<\/key>\n\t\t\t\t\t<string>{{.Title}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/dict>\n\t\t\t<\/dict>\n\t\t<\/array>\n\t<\/dict>\n<\/plist>\n`\n\ntype PlistTemplateParams struct {\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/sample.ipa\n\tIpaUrl string\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/image.png\n\tDisplayImageUrl string\n\t\/\/ eg. https:\/\/example.com\/apps\/ios\/full-image.png\n\tFullSizeImageUrl string\n\t\/\/ eg. com.example.sample\n\tBundleIdentifer string\n\t\/\/ eg. 1.0\n\tBundleVersion string\n\t\/\/ eg. Sample App\n\tTitle string\n}\n\n\/**\n * Dynamic Plist Handler\n *\/\nfunc plistHandler(w http.ResponseWriter, r *http.Request) bool {\n\tconst DYNAMIC_PLIST_POSTFIX = \"x.plist\"\n\tisDone := true\n\n\tconfig := GetAppConfig()\n\tif config == nil {\n\t\t\/\/ Internal Server Errror\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"No Config\"))\n\t\treturn isDone\n\t}\n\n\tfilePath := strings.Replace(r.URL.Path, config.PlistDir, \"\", 1)\n\ttmp := strings.SplitN(filePath, \"\/\", 2)\n\tif len(tmp) < 2 {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #1\"))\n\t\treturn isDone\n\t}\n\tfilePath = tmp[1]\n\tpostfix := filePath[strings.LastIndex(filePath, DYNAMIC_PLIST_POSTFIX):]\n\tif postfix != DYNAMIC_PLIST_POSTFIX {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #2\"))\n\t\treturn isDone\n\t}\n\n\tfilePath = filePath[0:len(filePath)-len(DYNAMIC_PLIST_POSTFIX)]\n\ttmp = strings.SplitN(filePath, \"\/\", 2)\n\tbundleIdentifer := tmp[0]\n\tif strings.Contains(tmp[1], \"..\") {\n\t\t\/\/ Bad Request\n\t\tw.WriteHeader(400)\n\t\tw.Write([]byte(\"invalid path #3\"))\n\t\treturn isDone\n\t}\n\n\tipaUrl, _ := url.Parse(r.RequestURI)\n\tif !r.URL.IsAbs() {\n\t\tipaUrl.Scheme = \"https\"\n\t\tipaUrl.Host = r.Host\n\t}\n\tipaUrl.Path = \"\/\" + tmp[1]\n\n\tparams := PlistTemplateParams{}\n\t\/\/ http:\/\/example.com\/{filePath}\/{bundleId}\/{IpaPath}?title={title}&version={bundleVersion}\n\tparams.Title = r.URL.Query().Get(\"title\")\n\tparams.BundleVersion = r.URL.Query().Get(\"version\")\n\tparams.BundleIdentifer = bundleIdentifer\n\tparams.IpaUrl = ipaUrl.String()\n\n\ttmpl, err := template.New(\"plist\").Parse(PLIST_TEMPLATE)\n\n\tif err != nil {\n\t\t\/\/ Not Found\n\t\tw.WriteHeader(501)\n\t\tw.Write([]byte(fmt.Sprintf(\"plist template is invalid.\")))\n\t\treturn isDone\n\t}\n\n\twriter := new(bytes.Buffer)\n\terr\t= tmpl.Execute(writer, params)\n\n\tvar contentLength string\n\tif err != nil {\n\t\t\/\/ Forbidden : サイズ取得失敗\n\t\tw.WriteHeader(403)\n\t\tw.Write([]byte(fmt.Sprintf(\"plist params is invalid.\")))\n\t\treturn isDone\n\t} else {\n\t\tcontentLength = strconv.FormatInt(int64(writer.Len()), 10)\n\t}\n\tcontentLength = contentLength + \"bytes\"\n\n\tcontentType := GetContentType(\"_.plist\")\n\tif contentType != \"\" {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t}\n\tw.Write(writer.Bytes())\n\tisDone = true\n\treturn isDone\n}\n<|endoftext|>"}
{"text":"<commit_before>package elasticthought\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"time\"\n\n\t\"github.com\/couchbaselabs\/cbfs\/client\"\n\t\"github.com\/couchbaselabs\/logg\"\n)\n\nfunc EnvironmentSanityCheck(config Configuration) error {\n\n\tif err := CbfsSanityCheck(config); err != nil {\n\t\treturn err\n\t}\n\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check passed\")\n\n\treturn nil\n\n}\n\nfunc CbfsReadWriteFile(config Configuration, destPath, content string) error {\n\n\t\/\/ get cbfs client\n\t\/\/ Create a cbfs client\n\tcbfs, err := cbfsclient.New(config.CbfsUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ write to random cbfs file\n\toptions := cbfsclient.PutOptions{\n\t\tContentType: \"text\/plain\",\n\t}\n\n\tbuffer := bytes.NewBuffer([]byte(content))\n\n\tif err := cbfs.Put(\"\", destPath, buffer, options); err != nil {\n\t\treturn fmt.Errorf(\"Error writing %v to cbfs: %v\", destPath, err)\n\t}\n\n\t\/\/ read contents from cbfs file\n\treader, err := cbfs.Get(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tbytes, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif string(bytes) != content {\n\t\treturn fmt.Errorf(\"Content did not match expected\")\n\t}\n\n\t\/\/ delete contents on cbfs\n\tif err := cbfs.Rm(destPath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\nfunc CbfsSanityCheck(config Configuration) error {\n\n\tuuid := NewUuid() \/\/ use uuid so other nodes on cluster don't conflict\n\tnumAttempts := 10\n\tfor i := 0; i < numAttempts; i++ {\n\t\tfilename := fmt.Sprintf(\"env_check_%v_%v\", uuid, i)\n\t\tcontent := fmt.Sprintf(\"Hello %v_%v\", uuid, i)\n\t\terr := CbfsReadWriteFile(config, filename, content)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity failed attempt # %s\", i)\n\t\tif i >= (numAttempts - 1) {\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check giving up\")\n\t\t\treturn err\n\t\t} else {\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check sleeping ..\")\n\t\t\ttime.Sleep(time.Duration(i) * time.Second)\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check done sleeping\")\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Exhausted attempts\")\n\n}\n<commit_msg>string printf issue<commit_after>package elasticthought\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"time\"\n\n\t\"github.com\/couchbaselabs\/cbfs\/client\"\n\t\"github.com\/couchbaselabs\/logg\"\n)\n\nfunc EnvironmentSanityCheck(config Configuration) error {\n\n\tif err := CbfsSanityCheck(config); err != nil {\n\t\treturn err\n\t}\n\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check passed\")\n\n\treturn nil\n\n}\n\nfunc CbfsReadWriteFile(config Configuration, destPath, content string) error {\n\n\t\/\/ get cbfs client\n\t\/\/ Create a cbfs client\n\tcbfs, err := cbfsclient.New(config.CbfsUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ write to random cbfs file\n\toptions := cbfsclient.PutOptions{\n\t\tContentType: \"text\/plain\",\n\t}\n\n\tbuffer := bytes.NewBuffer([]byte(content))\n\n\tif err := cbfs.Put(\"\", destPath, buffer, options); err != nil {\n\t\treturn fmt.Errorf(\"Error writing %v to cbfs: %v\", destPath, err)\n\t}\n\n\t\/\/ read contents from cbfs file\n\treader, err := cbfs.Get(destPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer reader.Close()\n\n\tbytes, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif string(bytes) != content {\n\t\treturn fmt.Errorf(\"Content did not match expected\")\n\t}\n\n\t\/\/ delete contents on cbfs\n\tif err := cbfs.Rm(destPath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\nfunc CbfsSanityCheck(config Configuration) error {\n\n\tuuid := NewUuid() \/\/ use uuid so other nodes on cluster don't conflict\n\tnumAttempts := 10\n\tfor i := 0; i < numAttempts; i++ {\n\t\tfilename := fmt.Sprintf(\"env_check_%v_%v\", uuid, i)\n\t\tcontent := fmt.Sprintf(\"Hello %v_%v\", uuid, i)\n\t\terr := CbfsReadWriteFile(config, filename, content)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity failed attempt # %v\", i)\n\t\tif i >= (numAttempts - 1) {\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check giving up\")\n\t\t\treturn err\n\t\t} else {\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check sleeping ..\")\n\t\t\ttime.Sleep(time.Duration(i) * time.Second)\n\t\t\tlogg.LogTo(\"ELASTIC_THOUGHT\", \"Cbfs sanity check done sleeping\")\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Exhausted attempts\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) - Damien Fontaine <damien.fontaine@lineolia.net>\n\/\/\n\/\/ This program 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\/\/ 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 General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n\npackage mongo\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/mongodb\/mongo-go-driver\/mongo\"\n)\n\n\/\/Mongo is a datasource.\ntype Mongo struct {\n\tClient  *mongo.Client\n\tcontext context.Context\n}\n\n\/\/NewMongo creates a newinstance of Mongo\nfunc NewMongo(filename string, environment string) (*Mongo, error) {\n\tctx := context.Background()\n\tcnf, err := GetMongo(filename, environment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar uri string\n\tif len(cnf.Username) > 0 && len(cnf.Password) > 0 {\n\t\turi = fmt.Sprintf(`mongodb:\/\/%s:%s@%s:%d\/%s`,\n\t\t\tcnf.Username,\n\t\t\tcnf.Password,\n\t\t\tcnf.Host,\n\t\t\tcnf.Port,\n\t\t\tcnf.Database,\n\t\t)\n\t} else {\n\t\turi = fmt.Sprintf(`mongodb:\/\/%s:%d\/%s`,\n\t\t\tcnf.Host,\n\t\t\tcnf.Port,\n\t\t\tcnf.Database,\n\t\t)\n\t}\n\tclient, err := mongo.NewClient(uri)\n\tif err != nil {\n\t\tlog.Printf(\"L'URI du serveur MongoDB est incorrect: %s\", uri)\n\t\treturn nil, err\n\t}\n\tclient.Connect(ctx)\n\tif err != nil {\n\t\tlog.Print(\"Impossible d'utiliser ce context\")\n\t\treturn nil, err\n\t}\n\terr = client.Ping(ctx, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Impossible de contacter %v sur le port %d\", cnf.Host, cnf.Port)\n\t\treturn nil, err\n\t}\n\treturn &Mongo{Client: client, context: ctx}, nil\n}\n\n\/\/Disconnect a Mongo client\nfunc (m *Mongo) Disconnect() error {\n\terr := m.Client.Disconnect(m.context)\n\tif err != nil {\n\t\tlog.Printf(\"Impossible de fermer la connexion\")\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>ListCollections to test connection in Mongo<commit_after>\/\/ Copyright (c) - Damien Fontaine <damien.fontaine@lineolia.net>\n\/\/\n\/\/ This program 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\/\/ 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 General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n\npackage mongo\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/mongodb\/mongo-go-driver\/mongo\"\n)\n\n\/\/Mongo is a datasource.\ntype Mongo struct {\n\tClient  *mongo.Client\n\tcontext context.Context\n}\n\n\/\/NewMongo creates a newinstance of Mongo\nfunc NewMongo(filename string, environment string) (*Mongo, error) {\n\tctx := context.Background()\n\tcnf, err := GetMongo(filename, environment)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar uri string\n\tif len(cnf.Username) > 0 && len(cnf.Password) > 0 {\n\t\turi = fmt.Sprintf(`mongodb:\/\/%s:%s@%s:%d\/%s`,\n\t\t\tcnf.Username,\n\t\t\tcnf.Password,\n\t\t\tcnf.Host,\n\t\t\tcnf.Port,\n\t\t\tcnf.Database,\n\t\t)\n\t} else {\n\t\turi = fmt.Sprintf(`mongodb:\/\/%s:%d\/%s`,\n\t\t\tcnf.Host,\n\t\t\tcnf.Port,\n\t\t\tcnf.Database,\n\t\t)\n\t}\n\tclient, err := mongo.NewClient(uri)\n\tif err != nil {\n\t\tlog.Printf(\"L'URI du serveur MongoDB est incorrect: %s\", uri)\n\t\treturn nil, err\n\t}\n\terr = client.Connect(ctx)\n\tif err != nil {\n\t\tlog.Print(\"Impossible d'utiliser ce context\")\n\t\treturn nil, err\n\t}\n\n\tdb := client.Database(cnf.Database)\n\t_, err = db.ListCollections(ctx, nil, nil)\n\tif err != nil {\n\t\tlog.Printf(\"%v\", err)\n\t\treturn nil, err\n\t}\n\n\terr = client.Ping(ctx, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Impossible de contacter %v sur le port %d\", cnf.Host, cnf.Port)\n\t\treturn nil, err\n\t}\n\treturn &Mongo{Client: client, context: ctx}, nil\n}\n\n\/\/Disconnect a Mongo client\nfunc (m *Mongo) Disconnect() error {\n\terr := m.Client.Disconnect(m.context)\n\tif err != nil {\n\t\tlog.Printf(\"Impossible de fermer la connexion\")\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Copyright 2012 The Gorilla Authors. All rights reserved.\n\/\/ Copyright 2014 Ninja Blocks 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 rpc\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sync\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\nvar (\n\t\/\/ Precompute the reflect.Type of error and mqtt.Message\n\ttypeOfError   = reflect.TypeOf((*error)(nil)).Elem()\n\ttypeOfRequest = reflect.TypeOf((*mqtt.Message)(nil)).Elem()\n)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ service\n\/\/ ----------------------------------------------------------------------------\n\ntype service struct {\n\tname     string                    \/\/ name of service\n\trcvr     reflect.Value             \/\/ receiver of methods for the service\n\trcvrType reflect.Type              \/\/ type of the receiver\n\tmethods  map[string]*serviceMethod \/\/ registered methods\n}\n\ntype serviceMethod struct {\n\tmethod    reflect.Method \/\/ receiver method\n\targsType  reflect.Type   \/\/ type of the request argument\n\treplyType reflect.Type   \/\/ type of the response argument\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ serviceMap\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ serviceMap is a registry for services.\ntype serviceMap struct {\n\tmutex    sync.Mutex\n\tservices map[string]*service\n}\n\n\/\/ register adds a new service using reflection to extract its methods.\nfunc (m *serviceMap) register(rcvr interface{}, name string) (methods []string, err error) {\n\n\tlog.Infof(\"ADDING SERVICE '%s'\", name)\n\n\t\/\/ Setup service.\n\ts := &service{\n\t\tname:     name,\n\t\trcvr:     reflect.ValueOf(rcvr),\n\t\trcvrType: reflect.TypeOf(rcvr),\n\t\tmethods:  make(map[string]*serviceMethod),\n\t}\n\tif name == \"\" {\n\t\ts.name = reflect.Indirect(s.rcvr).Type().Name()\n\t\tif !isExported(s.name) {\n\t\t\treturn nil, fmt.Errorf(\"rpc: type %q is not exported\", s.name)\n\t\t}\n\t}\n\tif s.name == \"\" {\n\t\treturn nil, fmt.Errorf(\"rpc: no service name for type %q\", s.rcvrType.String())\n\t}\n\t\/\/ Setup methods.\n\tfor i := 0; i < s.rcvrType.NumMethod(); i++ {\n\t\tmethod := s.rcvrType.Method(i)\n\t\tmtype := method.Type\n\t\t\/\/ Method must be exported.\n\t\tif method.PkgPath != \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Method needs four ins: receiver, *mqtt.Message, *args, *reply.\n\t\tif mtype.NumIn() != 4 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ First argument must be a pointer and must be mqtt.Message.\n\t\treqType := mtype.In(1)\n\t\tif reqType != typeOfRequest {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Second argument must be a pointer and must be exported.\n\t\targs := mtype.In(2)\n\t\tif args.Kind() != reflect.Ptr || !isExportedOrBuiltin(args) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Third argument must be a pointer and must be exported.\n\t\treply := mtype.In(3)\n\t\tif reply.Kind() != reflect.Ptr || !isExportedOrBuiltin(reply) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Method needs one out: error.\n\t\tif mtype.NumOut() != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif returnType := mtype.Out(0); returnType != typeOfError {\n\t\t\tcontinue\n\t\t}\n\t\ts.methods[method.Name] = &serviceMethod{\n\t\t\tmethod:    method,\n\t\t\targsType:  args.Elem(),\n\t\t\treplyType: reply.Elem(),\n\t\t}\n\t}\n\tif len(s.methods) == 0 {\n\t\treturn nil, fmt.Errorf(\"rpc: %q has no exported methods of suitable type\", s.name)\n\t}\n\t\/\/ Add to the map.\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tif m.services == nil {\n\t\tm.services = make(map[string]*service)\n\t} else if _, ok := m.services[s.name]; ok {\n\t\treturn nil, fmt.Errorf(\"rpc: service already defined: %q\", s.name)\n\t}\n\tm.services[s.name] = s\n\n\texportedMethods := make([]string, len(s.methods))\n\ti := 0\n\tfor name := range s.methods {\n\t\texportedMethods[i] = name\n\t\ti++\n\t}\n\treturn exportedMethods, nil\n}\n\n\/\/ get returns a registered service given a method name.\nfunc (m *serviceMap) get(topic string, method string) (*service, *serviceMethod, error) {\n\tm.mutex.Lock()\n\tservice := m.services[topic]\n\tspew.Dump(m.services)\n\tm.mutex.Unlock()\n\tif service == nil {\n\t\terr := fmt.Errorf(\"rpc: can't find service %q\", topic)\n\t\treturn nil, nil, err\n\t}\n\tserviceMethod := service.methods[method]\n\tif serviceMethod == nil {\n\t\terr := fmt.Errorf(\"rpc: can't find method %q\", method)\n\t\treturn nil, nil, err\n\t}\n\treturn service, serviceMethod, nil\n}\n\n\/\/ isExported returns true of a string is an exported (upper case) name.\nfunc isExported(name string) bool {\n\trune, _ := utf8.DecodeRuneInString(name)\n\treturn unicode.IsUpper(rune)\n}\n\n\/\/ isExportedOrBuiltin returns true if a type is exported or a builtin.\nfunc isExportedOrBuiltin(t reflect.Type) bool {\n\tfor t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\t\/\/ PkgPath will be non-empty even for an exported type,\n\t\/\/ so we need to check the type name as well.\n\treturn isExported(t.Name()) || t.PkgPath() == \"\"\n}\n<commit_msg>Clean up logging<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Copyright 2012 The Gorilla Authors. All rights reserved.\n\/\/ Copyright 2014 Ninja Blocks 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 rpc\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sync\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n)\n\nvar (\n\t\/\/ Precompute the reflect.Type of error and mqtt.Message\n\ttypeOfError   = reflect.TypeOf((*error)(nil)).Elem()\n\ttypeOfRequest = reflect.TypeOf((*mqtt.Message)(nil)).Elem()\n)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ service\n\/\/ ----------------------------------------------------------------------------\n\ntype service struct {\n\tname     string                    \/\/ name of service\n\trcvr     reflect.Value             \/\/ receiver of methods for the service\n\trcvrType reflect.Type              \/\/ type of the receiver\n\tmethods  map[string]*serviceMethod \/\/ registered methods\n}\n\ntype serviceMethod struct {\n\tmethod    reflect.Method \/\/ receiver method\n\targsType  reflect.Type   \/\/ type of the request argument\n\treplyType reflect.Type   \/\/ type of the response argument\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ serviceMap\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ serviceMap is a registry for services.\ntype serviceMap struct {\n\tmutex    sync.Mutex\n\tservices map[string]*service\n}\n\n\/\/ register adds a new service using reflection to extract its methods.\nfunc (m *serviceMap) register(rcvr interface{}, name string) (methods []string, err error) {\n\n\t\/\/ Setup service.\n\ts := &service{\n\t\tname:     name,\n\t\trcvr:     reflect.ValueOf(rcvr),\n\t\trcvrType: reflect.TypeOf(rcvr),\n\t\tmethods:  make(map[string]*serviceMethod),\n\t}\n\tif name == \"\" {\n\t\ts.name = reflect.Indirect(s.rcvr).Type().Name()\n\t\tif !isExported(s.name) {\n\t\t\treturn nil, fmt.Errorf(\"rpc: type %q is not exported\", s.name)\n\t\t}\n\t}\n\tif s.name == \"\" {\n\t\treturn nil, fmt.Errorf(\"rpc: no service name for type %q\", s.rcvrType.String())\n\t}\n\t\/\/ Setup methods.\n\tfor i := 0; i < s.rcvrType.NumMethod(); i++ {\n\t\tmethod := s.rcvrType.Method(i)\n\t\tmtype := method.Type\n\t\t\/\/ Method must be exported.\n\t\tif method.PkgPath != \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Method needs four ins: receiver, *mqtt.Message, *args, *reply.\n\t\tif mtype.NumIn() != 4 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ First argument must be a pointer and must be mqtt.Message.\n\t\treqType := mtype.In(1)\n\t\tif reqType != typeOfRequest {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Second argument must be a pointer and must be exported.\n\t\targs := mtype.In(2)\n\t\tif args.Kind() != reflect.Ptr || !isExportedOrBuiltin(args) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Third argument must be a pointer and must be exported.\n\t\treply := mtype.In(3)\n\t\tif reply.Kind() != reflect.Ptr || !isExportedOrBuiltin(reply) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Method needs one out: error.\n\t\tif mtype.NumOut() != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tif returnType := mtype.Out(0); returnType != typeOfError {\n\t\t\tcontinue\n\t\t}\n\t\ts.methods[method.Name] = &serviceMethod{\n\t\t\tmethod:    method,\n\t\t\targsType:  args.Elem(),\n\t\t\treplyType: reply.Elem(),\n\t\t}\n\t}\n\tif len(s.methods) == 0 {\n\t\treturn nil, fmt.Errorf(\"rpc: %q has no exported methods of suitable type\", s.name)\n\t}\n\t\/\/ Add to the map.\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\tif m.services == nil {\n\t\tm.services = make(map[string]*service)\n\t} else if _, ok := m.services[s.name]; ok {\n\t\treturn nil, fmt.Errorf(\"rpc: service already defined: %q\", s.name)\n\t}\n\tm.services[s.name] = s\n\n\texportedMethods := make([]string, len(s.methods))\n\ti := 0\n\tfor name := range s.methods {\n\t\texportedMethods[i] = name\n\t\ti++\n\t}\n\treturn exportedMethods, nil\n}\n\n\/\/ get returns a registered service given a method name.\nfunc (m *serviceMap) get(topic string, method string) (*service, *serviceMethod, error) {\n\tm.mutex.Lock()\n\tservice := m.services[topic]\n\tm.mutex.Unlock()\n\tif service == nil {\n\t\terr := fmt.Errorf(\"rpc: can't find service %q\", topic)\n\t\treturn nil, nil, err\n\t}\n\tserviceMethod := service.methods[method]\n\tif serviceMethod == nil {\n\t\terr := fmt.Errorf(\"rpc: can't find method %q\", method)\n\t\treturn nil, nil, err\n\t}\n\treturn service, serviceMethod, nil\n}\n\n\/\/ isExported returns true of a string is an exported (upper case) name.\nfunc isExported(name string) bool {\n\trune, _ := utf8.DecodeRuneInString(name)\n\treturn unicode.IsUpper(rune)\n}\n\n\/\/ isExportedOrBuiltin returns true if a type is exported or a builtin.\nfunc isExportedOrBuiltin(t reflect.Type) bool {\n\tfor t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\t\/\/ PkgPath will be non-empty even for an exported type,\n\t\/\/ so we need to check the type name as well.\n\treturn isExported(t.Name()) || t.PkgPath() == \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package errors\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\terr := New(CertificateError, Unknown)\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != \"Unknown certificate error\" {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n\n\tcode := New(OCSPError, ReadFailed).ErrorCode\n\tif code != 8001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(OCSPError, IssuerMismatch).ErrorCode\n\tif code != 8100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(OCSPError, InvalidStatus).ErrorCode\n\tif code != 8200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(CertificateError, Unknown).ErrorCode\n\tif code != 1000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, ReadFailed).ErrorCode\n\tif code != 1001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, DecodeFailed).ErrorCode\n\tif code != 1002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, ParseFailed).ErrorCode\n\tif code != 1003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, SelfSigned).ErrorCode\n\tif code != 1100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, VerifyFailed).ErrorCode\n\tif code != 1200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, BadRequest).ErrorCode\n\tif code != 1300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, MissingSerial).ErrorCode\n\tif code != 1400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(PrivateKeyError, Unknown).ErrorCode\n\tif code != 2000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, ReadFailed).ErrorCode\n\tif code != 2001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, DecodeFailed).ErrorCode\n\tif code != 2002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, ParseFailed).ErrorCode\n\tif code != 2003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, Encrypted).ErrorCode\n\tif code != 2100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, NotRSAOrECC).ErrorCode\n\tif code != 2200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, KeyMismatch).ErrorCode\n\tif code != 2300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, GenerationFailed).ErrorCode\n\tif code != 2400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, Unavailable).ErrorCode\n\tif code != 2500 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(IntermediatesError, Unknown).ErrorCode\n\tif code != 3000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, ReadFailed).ErrorCode\n\tif code != 3001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, DecodeFailed).ErrorCode\n\tif code != 3002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, ParseFailed).ErrorCode\n\tif code != 3003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(RootError, Unknown).ErrorCode\n\tif code != 4000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, ReadFailed).ErrorCode\n\tif code != 4001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, DecodeFailed).ErrorCode\n\tif code != 4002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, ParseFailed).ErrorCode\n\tif code != 4003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(PolicyError, Unknown).ErrorCode\n\tif code != 5000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, NoKeyUsages).ErrorCode\n\tif code != 5100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, InvalidPolicy).ErrorCode\n\tif code != 5200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, InvalidRequest).ErrorCode\n\tif code != 5300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(DialError, Unknown).ErrorCode\n\tif code != 6000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(APIClientError, AuthenticationFailure).ErrorCode\n\tif code != 7100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, JSONError).ErrorCode\n\tif code != 7200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, ClientHTTPError).ErrorCode\n\tif code != 7400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, IOError).ErrorCode\n\tif code != 7300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, ServerRequestFailed).ErrorCode\n\tif code != 7500 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(CSRError, Unknown).ErrorCode\n\tif code != 9000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, ReadFailed).ErrorCode\n\tif code != 9001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, DecodeFailed).ErrorCode\n\tif code != 9002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, ParseFailed).ErrorCode\n\tif code != 9003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, KeyMismatch).ErrorCode\n\tif code != 9300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, BadRequest).ErrorCode\n\tif code != 9300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n}\n\nfunc TestWrap(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != msg {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n\n\terr = Wrap(CertificateError, VerifyFailed, x509.CertificateInvalidError{Reason: x509.Expired})\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(VerifyFailed)+certificateInvalid+int(x509.Expired) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != \"x509: certificate has expired or is not yet valid\" {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n}\n\nfunc TestMarshal(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tbytes, _ := json.Marshal(err)\n\tvar received Error\n\tjson.Unmarshal(bytes, &received)\n\tif received.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif received.Message != msg {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n}\n\nfunc TestErrorString(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tstr := err.Error()\n\tif str != `{\"code\":1000,\"message\":\"`+msg+`\"}` {\n\t\tt.Fatal(\"Incorrect Error():\", str)\n\t}\n}\n<commit_msg>error package code coverage<commit_after>package errors\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestNew(t *testing.T) {\n\terr := New(CertificateError, Unknown)\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != \"Unknown certificate error\" {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n\n\tcode := New(OCSPError, ReadFailed).ErrorCode\n\tif code != 8001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(OCSPError, IssuerMismatch).ErrorCode\n\tif code != 8100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(OCSPError, InvalidStatus).ErrorCode\n\tif code != 8200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(CertificateError, Unknown).ErrorCode\n\tif code != 1000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, ReadFailed).ErrorCode\n\tif code != 1001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, DecodeFailed).ErrorCode\n\tif code != 1002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, ParseFailed).ErrorCode\n\tif code != 1003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, SelfSigned).ErrorCode\n\tif code != 1100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, VerifyFailed).ErrorCode\n\tif code != 1200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, BadRequest).ErrorCode\n\tif code != 1300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CertificateError, MissingSerial).ErrorCode\n\tif code != 1400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(PrivateKeyError, Unknown).ErrorCode\n\tif code != 2000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, ReadFailed).ErrorCode\n\tif code != 2001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, DecodeFailed).ErrorCode\n\tif code != 2002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, ParseFailed).ErrorCode\n\tif code != 2003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, Encrypted).ErrorCode\n\tif code != 2100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, NotRSAOrECC).ErrorCode\n\tif code != 2200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, KeyMismatch).ErrorCode\n\tif code != 2300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, GenerationFailed).ErrorCode\n\tif code != 2400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PrivateKeyError, Unavailable).ErrorCode\n\tif code != 2500 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(IntermediatesError, Unknown).ErrorCode\n\tif code != 3000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, ReadFailed).ErrorCode\n\tif code != 3001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, DecodeFailed).ErrorCode\n\tif code != 3002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(IntermediatesError, ParseFailed).ErrorCode\n\tif code != 3003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(RootError, Unknown).ErrorCode\n\tif code != 4000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, ReadFailed).ErrorCode\n\tif code != 4001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, DecodeFailed).ErrorCode\n\tif code != 4002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(RootError, ParseFailed).ErrorCode\n\tif code != 4003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(PolicyError, Unknown).ErrorCode\n\tif code != 5000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, NoKeyUsages).ErrorCode\n\tif code != 5100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, InvalidPolicy).ErrorCode\n\tif code != 5200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(PolicyError, InvalidRequest).ErrorCode\n\tif code != 5300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(DialError, Unknown).ErrorCode\n\tif code != 6000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(APIClientError, AuthenticationFailure).ErrorCode\n\tif code != 7100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, JSONError).ErrorCode\n\tif code != 7200 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, ClientHTTPError).ErrorCode\n\tif code != 7400 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, IOError).ErrorCode\n\tif code != 7300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(APIClientError, ServerRequestFailed).ErrorCode\n\tif code != 7500 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(CSRError, Unknown).ErrorCode\n\tif code != 9000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, ReadFailed).ErrorCode\n\tif code != 9001 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, DecodeFailed).ErrorCode\n\tif code != 9002 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, ParseFailed).ErrorCode\n\tif code != 9003 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, KeyMismatch).ErrorCode\n\tif code != 9300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CSRError, BadRequest).ErrorCode\n\tif code != 9300 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\n\tcode = New(CTError, Unknown).ErrorCode\n\tif code != 10000 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n\tcode = New(CTError, PrecertSubmissionFailed).ErrorCode\n\tif code != 10100 {\n\t\tt.Fatal(\"Improper error code\")\n\t}\n}\n\nfunc TestWrap(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != msg {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n\n\terr = Wrap(CertificateError, VerifyFailed, x509.CertificateInvalidError{Reason: x509.Expired})\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(CertificateError)+int(VerifyFailed)+certificateInvalid+int(x509.Expired) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != \"x509: certificate has expired or is not yet valid\" {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n\n\terr = Wrap(CertificateError, VerifyFailed, x509.UnknownAuthorityError{})\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\n\terr = Wrap(RootError, Unknown, errors.New(msg))\n\tif err == nil {\n\t\tt.Fatal(\"Error creation failed.\")\n\t}\n\tif err.ErrorCode != int(RootError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif err.Message != msg {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n}\n\nfunc TestMarshal(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tbytes, _ := json.Marshal(err)\n\tvar received Error\n\tjson.Unmarshal(bytes, &received)\n\tif received.ErrorCode != int(CertificateError)+int(Unknown) {\n\t\tt.Fatal(\"Error code construction failed.\")\n\t}\n\tif received.Message != msg {\n\t\tt.Fatal(\"Error message construction failed.\")\n\t}\n}\n\nfunc TestErrorString(t *testing.T) {\n\tmsg := \"Arbitrary error message\"\n\terr := Wrap(CertificateError, Unknown, errors.New(msg))\n\tstr := err.Error()\n\tif str != `{\"code\":1000,\"message\":\"`+msg+`\"}` {\n\t\tt.Fatal(\"Incorrect Error():\", str)\n\t}\n}\n\nfunc TestHTTP(t *testing.T) {\n\terr := NewMethodNotAllowed(\"GET\")\n\tif err == nil {\n\t\tt.Fatal(\"New Mathod Check failed\")\n\t}\n\n\terr = NewBadRequest(errors.New(\"Bad Request\"))\n\tif err == nil {\n\t\tt.Fatal(\"New Bad Request Check failed\")\n\t}\n\n\tif err.StatusCode != 400 {\n\t\tt.Fatal(\"New Bad Request error code construction failed\")\n\t}\n\n\terr = NewBadRequestString(\"Bad Request String\")\n\tif err == nil {\n\t\tt.Fatal(\"New Bad Request String Check failed\")\n\t}\n\n\tif err.StatusCode != 400 {\n\t\tt.Fatal(\"New Bad Request String error code construction failed\")\n\t}\n\n\terr = NewBadRequestMissingParameter(\"Request Missing Parameter\")\n\tif err == nil {\n\t\tt.Fatal(\"New Bad Request Missing Parameter Check failed\")\n\t}\n\n\tif err.StatusCode != 400 {\n\t\tt.Fatal(\"New Bad Request Missing Parameter error code construction failed\")\n\t}\n\n\terr = NewBadRequestUnwantedParameter(\"Unwanted Parameter Present In Request\")\n\tif err == nil {\n\t\tt.Fatal(\"New Bad Request Unwanted Parameter Check failed\")\n\t}\n\n\tif err.StatusCode != 400 {\n\t\tt.Fatal(\"New Bad Request Unwanted Parameter error code construction failed\")\n\t}\n\n}\n\nfunc TestHTTPErrorString(t *testing.T) {\n\tmethod := \"GET\"\n\terr := NewMethodNotAllowed(method)\n\tstr := err.Error()\n\tif str != `Method is not allowed:\"`+method+`\"` {\n\t\tt.Fatal(\"Incorrect Error():\", str)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package metrics\n\nimport (\n\tgmetrics \"github.com\/armon\/go-metrics\"\n\t\"github.com\/bakins\/go-metrics-map\"\n\t\"github.com\/bakins\/go-metrics-middleware\"\n\t\"github.com\/mistifyio\/mistify-operator-admin\/config\"\n)\n\n\/\/ Context contains information necessary to add time and count metrics\n\/\/ to routes, show collected metrics, or emit custom metrics from within a route\ntype Context struct {\n\tMetrics    *gmetrics.Metrics\n\tMiddleware *mmw.Middleware\n\tMapSink    *mapsink.MapSink\n\tStatsdSink *gmetrics.StatsdSink\n}\n\n\/\/ One context only\nvar context *Context\nvar contextLoaded = false\n\n\/\/ LoadContext loads the context from config\nfunc LoadContext() error {\n\tconf := config.Get()\n\tapiConfig := &conf.Metrics\n\tc, err := NewContext(apiConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext = c\n\tcontextLoaded = true\n\treturn nil\n}\n\n\/\/ GetContext retrieves the context, loading if it has not yet\nfunc GetContext() *Context {\n\tif !contextLoaded {\n\t\t_ = LoadContext()\n\t}\n\treturn context\n}\n\n\/\/ NewContext creates a new context given a statsd address and service name\nfunc NewContext(apiConfig *config.Metrics) (*Context, error) {\n\t\/\/ Use the loaded default if one is not provided\n\tif apiConfig == nil {\n\t\tconf := config.Get()\n\t\tapiConfig = &conf.Metrics\n\t}\n\n\t\/\/ Build the fanout sink, with statsd if required\n\tvar mainSink *gmetrics.FanoutSink\n\tvar statsdSink *gmetrics.StatsdSink\n\tvar err error\n\tmapSink := mapsink.New()\n\tif apiConfig.StatsdAddress != \"\" {\n\t\tstatsdSink, err = gmetrics.NewStatsdSink(apiConfig.StatsdAddress)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmainSink = &gmetrics.FanoutSink{statsdSink, mapSink}\n\t} else {\n\t\tmainSink = &gmetrics.FanoutSink{mapSink}\n\t}\n\n\t\/\/ Build the metrics object\n\tcfg := gmetrics.DefaultConfig(apiConfig.ServiceName)\n\tcfg.EnableHostname = false\n\tmetrics, err := gmetrics.New(cfg, mainSink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the middleware and return everything\n\tmmw := mmw.New(metrics)\n\treturn &Context{metrics, mmw, mapSink, statsdSink}, nil\n}\n<commit_msg>Update NewContext comment<commit_after>package metrics\n\nimport (\n\tgmetrics \"github.com\/armon\/go-metrics\"\n\t\"github.com\/bakins\/go-metrics-map\"\n\t\"github.com\/bakins\/go-metrics-middleware\"\n\t\"github.com\/mistifyio\/mistify-operator-admin\/config\"\n)\n\n\/\/ Context contains information necessary to add time and count metrics\n\/\/ to routes, show collected metrics, or emit custom metrics from within a route\ntype Context struct {\n\tMetrics    *gmetrics.Metrics\n\tMiddleware *mmw.Middleware\n\tMapSink    *mapsink.MapSink\n\tStatsdSink *gmetrics.StatsdSink\n}\n\n\/\/ One context only\nvar context *Context\nvar contextLoaded = false\n\n\/\/ LoadContext loads the context from config\nfunc LoadContext() error {\n\tconf := config.Get()\n\tapiConfig := &conf.Metrics\n\tc, err := NewContext(apiConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext = c\n\tcontextLoaded = true\n\treturn nil\n}\n\n\/\/ GetContext retrieves the context, loading if it has not yet\nfunc GetContext() *Context {\n\tif !contextLoaded {\n\t\t_ = LoadContext()\n\t}\n\treturn context\n}\n\n\/\/ NewContext creates a new context from the config\nfunc NewContext(apiConfig *config.Metrics) (*Context, error) {\n\t\/\/ Use the loaded default if one is not provided\n\tif apiConfig == nil {\n\t\tconf := config.Get()\n\t\tapiConfig = &conf.Metrics\n\t}\n\n\t\/\/ Build the fanout sink, with statsd if required\n\tvar mainSink *gmetrics.FanoutSink\n\tvar statsdSink *gmetrics.StatsdSink\n\tvar err error\n\tmapSink := mapsink.New()\n\tif apiConfig.StatsdAddress != \"\" {\n\t\tstatsdSink, err = gmetrics.NewStatsdSink(apiConfig.StatsdAddress)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmainSink = &gmetrics.FanoutSink{statsdSink, mapSink}\n\t} else {\n\t\tmainSink = &gmetrics.FanoutSink{mapSink}\n\t}\n\n\t\/\/ Build the metrics object\n\tcfg := gmetrics.DefaultConfig(apiConfig.ServiceName)\n\tcfg.EnableHostname = false\n\tmetrics, err := gmetrics.New(cfg, mainSink)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the middleware and return everything\n\tmmw := mmw.New(metrics)\n\treturn &Context{metrics, mmw, mapSink, statsdSink}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 NDP Systèmes. 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 models\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/npiganeau\/yep\/yep\/models\/security\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestConditions(t *testing.T) {\n\tConvey(\"Testing SQL building for queries\", t, func() {\n\t\tif dbArgs.Driver == \"postgres\" {\n\t\t\tSimulateInNewEnvironment(security.SuperUserID, func(env Environment) {\n\t\t\t\trs := env.Pool(\"User\")\n\t\t\t\trs = rs.Search(rs.Model().FilteredOn(\"Profile\", env.Pool(\"Profile\").Model().FilteredOn(\"BestPost\", env.Pool(\"Post\").Model().Field(\"Title\").Equals(\"foo\"))))\n\t\t\t\tfields := []string{\"name\", \"profile_id.best_post_id.title\"}\n\t\t\t\tConvey(\"Simple query with database field names\", func() {\n\t\t\t\t\trs = env.Pool(\"User\").Search(rs.Model().FilteredOn(\"profile_id\", env.Pool(\"Profile\").Model().Field(\"best_post_id.title\").Equals(\"foo\")))\n\t\t\t\t\tsql, args := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Simple query with struct field names\", func() {\n\t\t\t\t\tfields := []string{\"Name\", \"Profile.BestPost.Title\"}\n\t\t\t\t\tsql, args := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Simple query with args inflation\", func() {\n\t\t\t\t\tgetUserID := func(rc RecordCollection) int64 {\n\t\t\t\t\t\treturn rc.Env().Uid()\n\t\t\t\t\t}\n\t\t\t\t\trs2 := env.Pool(\"User\").Search(rs.Model().Field(\"Nums\").Equals(getUserID))\n\t\t\t\t\tfields := []string{\"Name\"}\n\t\t\t\t\tsql, args := rs2.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name FROM \"user\" \"user\"  WHERE (\"user\".nums = ? ) `)\n\t\t\t\t\tSo(len(args), ShouldEqual, 1)\n\t\t\t\t\tSo(args, ShouldContain, security.SuperUserID)\n\t\t\t\t})\n\t\t\t\tConvey(\"Check WHERE clause with additionnal filter\", func() {\n\t\t\t\t\trs = rs.Search(rs.Model().Field(\"Profile.Age\").GreaterOrEqual(12))\n\t\t\t\t\tsql, args := rs.query.sqlWhereClause()\n\t\t\t\t\tSo(sql, ShouldEqual, `WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, 12)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Check full query with all conditions\", func() {\n\t\t\t\t\trs = rs.Search(rs.Model().Field(\"Profile.Age\").GreaterOrEqual(12))\n\t\t\t\t\tc2 := rs.Model().Field(\"name\").Like(\"jane\").Or().Field(\"Profile.Money\").Lower(1234.56)\n\t\t\t\t\trs = rs.Search(c2)\n\t\t\t\t\tsql, args := rs.query.sqlWhereClause()\n\t\t\t\t\tSo(sql, ShouldEqual, `WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) AND (\"user\".name LIKE ? OR \"user__profile\".money < ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, \"%jane%\")\n\t\t\t\t\tSo(args, ShouldContain, 1234.56)\n\t\t\t\t\tsql, _ = rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) AND (\"user\".name LIKE ? OR \"user__profile\".money < ? ) `)\n\t\t\t\t})\n\t\t\t\tConvey(\"Testing query without WHERE clause\", func() {\n\t\t\t\t\trs = env.Pool(\"User\").Load()\n\t\t\t\t\tfields := []string{\"name\"}\n\t\t\t\t\tsql, _ := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name FROM \"user\" \"user\"  `)\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t})\n}\n<commit_msg>Fix tests<commit_after>\/\/ Copyright 2016 NDP Systèmes. 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 models\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/npiganeau\/yep\/yep\/models\/security\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestConditions(t *testing.T) {\n\tConvey(\"Testing SQL building for queries\", t, func() {\n\t\tif dbArgs.Driver == \"postgres\" {\n\t\t\tSimulateInNewEnvironment(security.SuperUserID, func(env Environment) {\n\t\t\t\trs := env.Pool(\"User\")\n\t\t\t\trs = rs.Search(rs.Model().FilteredOn(\"Profile\", env.Pool(\"Profile\").Model().FilteredOn(\"BestPost\", env.Pool(\"Post\").Model().Field(\"Title\").Equals(\"foo\"))))\n\t\t\t\tfields := []string{\"name\", \"profile_id.best_post_id.title\"}\n\t\t\t\tConvey(\"Simple query with database field names\", func() {\n\t\t\t\t\trs = env.Pool(\"User\").Search(rs.Model().FilteredOn(\"profile_id\", env.Pool(\"Profile\").Model().Field(\"best_post_id.title\").Equals(\"foo\")))\n\t\t\t\t\tsql, args := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) ORDER BY id `)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Simple query with struct field names\", func() {\n\t\t\t\t\tfields := []string{\"Name\", \"Profile.BestPost.Title\"}\n\t\t\t\t\tsql, args := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) ORDER BY id `)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Simple query with args inflation\", func() {\n\t\t\t\t\tgetUserID := func(rc RecordCollection) int64 {\n\t\t\t\t\t\treturn rc.Env().Uid()\n\t\t\t\t\t}\n\t\t\t\t\trs2 := env.Pool(\"User\").Search(rs.Model().Field(\"Nums\").Equals(getUserID))\n\t\t\t\t\tfields := []string{\"Name\"}\n\t\t\t\t\tsql, args := rs2.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name FROM \"user\" \"user\"  WHERE (\"user\".nums = ? ) ORDER BY id `)\n\t\t\t\t\tSo(len(args), ShouldEqual, 1)\n\t\t\t\t\tSo(args, ShouldContain, security.SuperUserID)\n\t\t\t\t})\n\t\t\t\tConvey(\"Check WHERE clause with additionnal filter\", func() {\n\t\t\t\t\trs = rs.Search(rs.Model().Field(\"Profile.Age\").GreaterOrEqual(12))\n\t\t\t\t\tsql, args := rs.query.sqlWhereClause()\n\t\t\t\t\tSo(sql, ShouldEqual, `WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, 12)\n\t\t\t\t\tSo(args, ShouldContain, \"foo\")\n\t\t\t\t})\n\t\t\t\tConvey(\"Check full query with all conditions\", func() {\n\t\t\t\t\trs = rs.Search(rs.Model().Field(\"Profile.Age\").GreaterOrEqual(12))\n\t\t\t\t\tc2 := rs.Model().Field(\"name\").Like(\"jane\").Or().Field(\"Profile.Money\").Lower(1234.56)\n\t\t\t\t\trs = rs.Search(c2)\n\t\t\t\t\tsql, args := rs.query.sqlWhereClause()\n\t\t\t\t\tSo(sql, ShouldEqual, `WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) AND (\"user\".name LIKE ? OR \"user__profile\".money < ? ) `)\n\t\t\t\t\tSo(args, ShouldContain, \"%jane%\")\n\t\t\t\t\tSo(args, ShouldContain, 1234.56)\n\t\t\t\t\tsql, _ = rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name, \"user__profile__post\".title AS profile_id__best_post_id__title FROM \"user\" \"user\" LEFT JOIN \"profile\" \"user__profile\" ON \"user\".profile_id=\"user__profile\".id LEFT JOIN \"post\" \"user__profile__post\" ON \"user__profile\".best_post_id=\"user__profile__post\".id  WHERE (\"user__profile__post\".title = ? ) AND (\"user__profile\".age >= ? ) AND (\"user\".name LIKE ? OR \"user__profile\".money < ? ) ORDER BY id `)\n\t\t\t\t})\n\t\t\t\tConvey(\"Testing query without WHERE clause\", func() {\n\t\t\t\t\trs = env.Pool(\"User\").Load()\n\t\t\t\t\tfields := []string{\"name\"}\n\t\t\t\t\tsql, _ := rs.query.selectQuery(fields)\n\t\t\t\t\tSo(sql, ShouldEqual, `SELECT DISTINCT \"user\".name AS name FROM \"user\" \"user\"  ORDER BY id `)\n\t\t\t\t})\n\t\t\t})\n\t\t}\n\t})\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\n\/* This test check that SecurityContext parameters specified at the\n * pod or the container level work as intended. These tests cannot be\n * run when the 'SecurityContextDeny' admission controller is not used\n * so they are skipped by default.\n *\/\n\npackage node\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/uuid\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\timageutils \"k8s.io\/kubernetes\/test\/utils\/image\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc scTestPod(hostIPC bool, hostPID bool) *v1.Pod {\n\tpodName := \"security-context-\" + string(uuid.NewUUID())\n\tpod := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:        podName,\n\t\t\tLabels:      map[string]string{\"name\": podName},\n\t\t\tAnnotations: map[string]string{},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tHostIPC:         hostIPC,\n\t\t\tHostPID:         hostPID,\n\t\t\tSecurityContext: &v1.PodSecurityContext{},\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName:  \"test-container\",\n\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.BusyBox),\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t},\n\t}\n\n\treturn pod\n}\n\nvar _ = SIGDescribe(\"Security Context [Feature:SecurityContext]\", func() {\n\tf := framework.NewDefaultFramework(\"security-context\")\n\n\tIt(\"should support pod.Spec.SecurityContext.SupplementalGroups\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tpod.Spec.Containers[0].Command = []string{\"id\", \"-G\"}\n\t\tpod.Spec.SecurityContext.SupplementalGroups = []int64{1234, 5678}\n\t\tgroups := []string{\"1234\", \"5678\"}\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.SupplementalGroups\", pod, 0, groups)\n\t})\n\n\tIt(\"should support pod.Spec.SecurityContext.RunAsUser\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id -u\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"%v\", userID),\n\t\t})\n\t})\n\n\tIt(\"should support pod.Spec.SecurityContext.RunAsUser And pod.Spec.SecurityContext.RunAsGroup [Feature:RunAsGroup]\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tgroupID := int64(2002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.SecurityContext.RunAsGroup = &groupID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", userID),\n\t\t\tfmt.Sprintf(\"gid=%v\", groupID),\n\t\t})\n\t})\n\n\tIt(\"should support container.SecurityContext.RunAsUser\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\toverrideUserID := int64(1002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id -u\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"%v\", overrideUserID),\n\t\t})\n\t})\n\n\tIt(\"should support container.SecurityContext.RunAsUser And container.SecurityContext.RunAsGroup [Feature:RunAsGroup]\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tgroupID := int64(2001)\n\t\toverrideUserID := int64(1002)\n\t\toverrideGroupID := int64(2002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.SecurityContext.RunAsGroup = &groupID\n\t\tpod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsGroup = &overrideGroupID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", overrideUserID),\n\t\t\tfmt.Sprintf(\"gid=%v\", overrideGroupID),\n\t\t})\n\t})\n\n\tIt(\"should support volume SELinux relabeling\", func() {\n\t\ttestPodSELinuxLabeling(f, false, false)\n\t})\n\n\tIt(\"should support volume SELinux relabeling when using hostIPC\", func() {\n\t\ttestPodSELinuxLabeling(f, true, false)\n\t})\n\n\tIt(\"should support volume SELinux relabeling when using hostPID\", func() {\n\t\ttestPodSELinuxLabeling(f, false, true)\n\t})\n\n\tIt(\"should support seccomp alpha unconfined annotation on the container [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+\"test-container\"] = \"unconfined\"\n\t\tpod.Annotations[v1.SeccompPodAnnotationKey] = v1.SeccompProfileRuntimeDefault\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n\n\tIt(\"should support seccomp alpha unconfined annotation on the pod [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompPodAnnotationKey] = \"unconfined\"\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n\n\tIt(\"should support seccomp alpha runtime\/default annotation [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+\"test-container\"] = v1.SeccompProfileRuntimeDefault\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"2\"}) \/\/ seccomp filtered\n\t})\n\n\tIt(\"should support seccomp default which is unconfined [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n})\n\nfunc testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) {\n\t\/\/ Write and read a file with an empty_dir volume\n\t\/\/ with a pod with the MCS label s0:c0,c1\n\tpod := scTestPod(hostIPC, hostPID)\n\tvolumeName := \"test-volume\"\n\tmountPath := \"\/mounted_volume\"\n\tpod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{\n\t\t{\n\t\t\tName:      volumeName,\n\t\t\tMountPath: mountPath,\n\t\t},\n\t}\n\tpod.Spec.Volumes = []v1.Volume{\n\t\t{\n\t\t\tName: volumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tEmptyDir: &v1.EmptyDirVolumeSource{\n\t\t\t\t\tMedium: v1.StorageMediumDefault,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c0,c1\",\n\t}\n\tpod.Spec.Containers[0].Command = []string{\"sleep\", \"6000\"}\n\n\tclient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)\n\tpod, err := client.Create(pod)\n\n\tframework.ExpectNoError(err, \"Error creating pod %v\", pod)\n\tframework.ExpectNoError(framework.WaitForPodRunningInNamespace(f.ClientSet, pod))\n\n\ttestContent := \"hello\"\n\ttestFilePath := mountPath + \"\/TEST\"\n\terr = f.WriteFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath, testContent)\n\tExpect(err).To(BeNil())\n\tcontent, err := f.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath)\n\tExpect(err).To(BeNil())\n\tExpect(content).To(ContainSubstring(testContent))\n\n\tfoundPod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\t\/\/ Confirm that the file can be accessed from a second\n\t\/\/ pod using host_path with the same MCS label\n\tvolumeHostPath := fmt.Sprintf(\"%s\/pods\/%s\/volumes\/kubernetes.io~empty-dir\/%s\", framework.TestContext.KubeVolumeDir, foundPod.UID, volumeName)\n\tBy(fmt.Sprintf(\"confirming a container with the same label can read the file under --volume-dir=%s\", framework.TestContext.KubeVolumeDir))\n\tpod = scTestPod(hostIPC, hostPID)\n\tpod.Spec.NodeName = foundPod.Spec.NodeName\n\tvolumeMounts := []v1.VolumeMount{\n\t\t{\n\t\t\tName:      volumeName,\n\t\t\tMountPath: mountPath,\n\t\t},\n\t}\n\tvolumes := []v1.Volume{\n\t\t{\n\t\t\tName: volumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tHostPath: &v1.HostPathVolumeSource{\n\t\t\t\t\tPath: volumeHostPath,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpod.Spec.Containers[0].VolumeMounts = volumeMounts\n\tpod.Spec.Volumes = volumes\n\tpod.Spec.Containers[0].Command = []string{\"cat\", testFilePath}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c0,c1\",\n\t}\n\n\tf.TestContainerOutput(\"Pod with same MCS label reading test file\", pod, 0, []string{testContent})\n\t\/\/ Confirm that the same pod with a different MCS\n\t\/\/ label cannot access the volume\n\tpod = scTestPod(hostIPC, hostPID)\n\tpod.Spec.Volumes = volumes\n\tpod.Spec.Containers[0].VolumeMounts = volumeMounts\n\tpod.Spec.Containers[0].Command = []string{\"sleep\", \"6000\"}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c2,c3\",\n\t}\n\t_, err = client.Create(pod)\n\tframework.ExpectNoError(err, \"Error creating pod %v\", pod)\n\n\terr = f.WaitForPodRunning(pod.Name)\n\tframework.ExpectNoError(err, \"Error waiting for pod to run %v\", pod)\n\n\tcontent, err = f.ReadFileViaContainer(pod.Name, \"test-container\", testFilePath)\n\tExpect(content).NotTo(ContainSubstring(testContent))\n}\n<commit_msg>verify gid in runasuser tests<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\n\/* This test check that SecurityContext parameters specified at the\n * pod or the container level work as intended. These tests cannot be\n * run when the 'SecurityContextDeny' admission controller is not used\n * so they are skipped by default.\n *\/\n\npackage node\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/uuid\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\timageutils \"k8s.io\/kubernetes\/test\/utils\/image\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc scTestPod(hostIPC bool, hostPID bool) *v1.Pod {\n\tpodName := \"security-context-\" + string(uuid.NewUUID())\n\tpod := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:        podName,\n\t\t\tLabels:      map[string]string{\"name\": podName},\n\t\t\tAnnotations: map[string]string{},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tHostIPC:         hostIPC,\n\t\t\tHostPID:         hostPID,\n\t\t\tSecurityContext: &v1.PodSecurityContext{},\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName:  \"test-container\",\n\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.BusyBox),\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t},\n\t}\n\n\treturn pod\n}\n\nvar _ = SIGDescribe(\"Security Context [Feature:SecurityContext]\", func() {\n\tf := framework.NewDefaultFramework(\"security-context\")\n\n\tIt(\"should support pod.Spec.SecurityContext.SupplementalGroups\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tpod.Spec.Containers[0].Command = []string{\"id\", \"-G\"}\n\t\tpod.Spec.SecurityContext.SupplementalGroups = []int64{1234, 5678}\n\t\tgroups := []string{\"1234\", \"5678\"}\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.SupplementalGroups\", pod, 0, groups)\n\t})\n\n\tIt(\"should support pod.Spec.SecurityContext.RunAsUser\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", userID),\n\t\t\tfmt.Sprintf(\"gid=%v\", 0),\n\t\t})\n\t})\n\n\tIt(\"should support pod.Spec.SecurityContext.RunAsUser And pod.Spec.SecurityContext.RunAsGroup [Feature:RunAsGroup]\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tgroupID := int64(2002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.SecurityContext.RunAsGroup = &groupID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", userID),\n\t\t\tfmt.Sprintf(\"gid=%v\", groupID),\n\t\t})\n\t})\n\n\tIt(\"should support container.SecurityContext.RunAsUser\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\toverrideUserID := int64(1002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", overrideUserID),\n\t\t\tfmt.Sprintf(\"gid=%v\", 0),\n\t\t})\n\t})\n\n\tIt(\"should support container.SecurityContext.RunAsUser And container.SecurityContext.RunAsGroup [Feature:RunAsGroup]\", func() {\n\t\tpod := scTestPod(false, false)\n\t\tuserID := int64(1001)\n\t\tgroupID := int64(2001)\n\t\toverrideUserID := int64(1002)\n\t\toverrideGroupID := int64(2002)\n\t\tpod.Spec.SecurityContext.RunAsUser = &userID\n\t\tpod.Spec.SecurityContext.RunAsGroup = &groupID\n\t\tpod.Spec.Containers[0].SecurityContext = new(v1.SecurityContext)\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsUser = &overrideUserID\n\t\tpod.Spec.Containers[0].SecurityContext.RunAsGroup = &overrideGroupID\n\t\tpod.Spec.Containers[0].Command = []string{\"sh\", \"-c\", \"id\"}\n\n\t\tf.TestContainerOutput(\"pod.Spec.SecurityContext.RunAsUser\", pod, 0, []string{\n\t\t\tfmt.Sprintf(\"uid=%v\", overrideUserID),\n\t\t\tfmt.Sprintf(\"gid=%v\", overrideGroupID),\n\t\t})\n\t})\n\n\tIt(\"should support volume SELinux relabeling\", func() {\n\t\ttestPodSELinuxLabeling(f, false, false)\n\t})\n\n\tIt(\"should support volume SELinux relabeling when using hostIPC\", func() {\n\t\ttestPodSELinuxLabeling(f, true, false)\n\t})\n\n\tIt(\"should support volume SELinux relabeling when using hostPID\", func() {\n\t\ttestPodSELinuxLabeling(f, false, true)\n\t})\n\n\tIt(\"should support seccomp alpha unconfined annotation on the container [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+\"test-container\"] = \"unconfined\"\n\t\tpod.Annotations[v1.SeccompPodAnnotationKey] = v1.SeccompProfileRuntimeDefault\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n\n\tIt(\"should support seccomp alpha unconfined annotation on the pod [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompPodAnnotationKey] = \"unconfined\"\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n\n\tIt(\"should support seccomp alpha runtime\/default annotation [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Annotations[v1.SeccompContainerAnnotationKeyPrefix+\"test-container\"] = v1.SeccompProfileRuntimeDefault\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"2\"}) \/\/ seccomp filtered\n\t})\n\n\tIt(\"should support seccomp default which is unconfined [Feature:Seccomp]\", func() {\n\t\t\/\/ TODO: port to SecurityContext as soon as seccomp is out of alpha\n\t\tpod := scTestPod(false, false)\n\t\tpod.Spec.Containers[0].Command = []string{\"grep\", \"ecc\", \"\/proc\/self\/status\"}\n\t\tf.TestContainerOutput(v1.SeccompPodAnnotationKey, pod, 0, []string{\"0\"}) \/\/ seccomp disabled\n\t})\n})\n\nfunc testPodSELinuxLabeling(f *framework.Framework, hostIPC bool, hostPID bool) {\n\t\/\/ Write and read a file with an empty_dir volume\n\t\/\/ with a pod with the MCS label s0:c0,c1\n\tpod := scTestPod(hostIPC, hostPID)\n\tvolumeName := \"test-volume\"\n\tmountPath := \"\/mounted_volume\"\n\tpod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{\n\t\t{\n\t\t\tName:      volumeName,\n\t\t\tMountPath: mountPath,\n\t\t},\n\t}\n\tpod.Spec.Volumes = []v1.Volume{\n\t\t{\n\t\t\tName: volumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tEmptyDir: &v1.EmptyDirVolumeSource{\n\t\t\t\t\tMedium: v1.StorageMediumDefault,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c0,c1\",\n\t}\n\tpod.Spec.Containers[0].Command = []string{\"sleep\", \"6000\"}\n\n\tclient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)\n\tpod, err := client.Create(pod)\n\n\tframework.ExpectNoError(err, \"Error creating pod %v\", pod)\n\tframework.ExpectNoError(framework.WaitForPodRunningInNamespace(f.ClientSet, pod))\n\n\ttestContent := \"hello\"\n\ttestFilePath := mountPath + \"\/TEST\"\n\terr = f.WriteFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath, testContent)\n\tExpect(err).To(BeNil())\n\tcontent, err := f.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, testFilePath)\n\tExpect(err).To(BeNil())\n\tExpect(content).To(ContainSubstring(testContent))\n\n\tfoundPod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(pod.Name, metav1.GetOptions{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\t\/\/ Confirm that the file can be accessed from a second\n\t\/\/ pod using host_path with the same MCS label\n\tvolumeHostPath := fmt.Sprintf(\"%s\/pods\/%s\/volumes\/kubernetes.io~empty-dir\/%s\", framework.TestContext.KubeVolumeDir, foundPod.UID, volumeName)\n\tBy(fmt.Sprintf(\"confirming a container with the same label can read the file under --volume-dir=%s\", framework.TestContext.KubeVolumeDir))\n\tpod = scTestPod(hostIPC, hostPID)\n\tpod.Spec.NodeName = foundPod.Spec.NodeName\n\tvolumeMounts := []v1.VolumeMount{\n\t\t{\n\t\t\tName:      volumeName,\n\t\t\tMountPath: mountPath,\n\t\t},\n\t}\n\tvolumes := []v1.Volume{\n\t\t{\n\t\t\tName: volumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tHostPath: &v1.HostPathVolumeSource{\n\t\t\t\t\tPath: volumeHostPath,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tpod.Spec.Containers[0].VolumeMounts = volumeMounts\n\tpod.Spec.Volumes = volumes\n\tpod.Spec.Containers[0].Command = []string{\"cat\", testFilePath}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c0,c1\",\n\t}\n\n\tf.TestContainerOutput(\"Pod with same MCS label reading test file\", pod, 0, []string{testContent})\n\t\/\/ Confirm that the same pod with a different MCS\n\t\/\/ label cannot access the volume\n\tpod = scTestPod(hostIPC, hostPID)\n\tpod.Spec.Volumes = volumes\n\tpod.Spec.Containers[0].VolumeMounts = volumeMounts\n\tpod.Spec.Containers[0].Command = []string{\"sleep\", \"6000\"}\n\tpod.Spec.SecurityContext.SELinuxOptions = &v1.SELinuxOptions{\n\t\tLevel: \"s0:c2,c3\",\n\t}\n\t_, err = client.Create(pod)\n\tframework.ExpectNoError(err, \"Error creating pod %v\", pod)\n\n\terr = f.WaitForPodRunning(pod.Name)\n\tframework.ExpectNoError(err, \"Error waiting for pod to run %v\", pod)\n\n\tcontent, err = f.ReadFileViaContainer(pod.Name, \"test-container\", testFilePath)\n\tExpect(content).NotTo(ContainSubstring(testContent))\n}\n<|endoftext|>"}
{"text":"<commit_before>package gpio\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gobot.io\/x\/gobot\"\n\t\"gobot.io\/x\/gobot\/gobottest\"\n)\n\nvar _ gobot.Driver = (*BuzzerDriver)(nil)\n\nfunc initTestBuzzerDriver(conn DigitalWriter) *BuzzerDriver {\n\ttestAdaptorDigitalWrite = func() (err error) {\n\t\treturn nil\n\t}\n\ttestAdaptorPwmWrite = func() (err error) {\n\t\treturn nil\n\t}\n\treturn NewBuzzerDriver(conn, \"1\")\n}\n\nfunc TestBuzzerDriverDefaultName(t *testing.T) {\n\tg := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, strings.HasPrefix(g.Name(), \"Buzzer\"), true)\n}\n\nfunc TestBuzzerDriverSetName(t *testing.T) {\n\tg := initTestBuzzerDriver(newGpioTestAdaptor())\n\tg.SetName(\"mybot\")\n\tgobottest.Assert(t, g.Name(), \"mybot\")\n}\n\nfunc TestBuzzerDriverStart(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, d.Start(), nil)\n}\n\nfunc TestBuzzerDriverHalt(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, d.Halt(), nil)\n}\n\nfunc TestBuzzerDriverToggle(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\td.Off()\n\td.Toggle()\n\tgobottest.Assert(t, d.State(), true)\n\td.Toggle()\n\tgobottest.Assert(t, d.State(), false)\n}\n<commit_msg>gpio: increase test coverage for buzzer driver<commit_after>package gpio\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gobot.io\/x\/gobot\"\n\t\"gobot.io\/x\/gobot\/gobottest\"\n)\n\nvar _ gobot.Driver = (*BuzzerDriver)(nil)\n\nfunc initTestBuzzerDriver(conn DigitalWriter) *BuzzerDriver {\n\ttestAdaptorDigitalWrite = func() (err error) {\n\t\treturn nil\n\t}\n\ttestAdaptorPwmWrite = func() (err error) {\n\t\treturn nil\n\t}\n\treturn NewBuzzerDriver(conn, \"1\")\n}\n\nfunc TestBuzzerDriverDefaultName(t *testing.T) {\n\tg := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, strings.HasPrefix(g.Name(), \"Buzzer\"), true)\n}\n\nfunc TestBuzzerDriverSetName(t *testing.T) {\n\tg := initTestBuzzerDriver(newGpioTestAdaptor())\n\tg.SetName(\"mybot\")\n\tgobottest.Assert(t, g.Name(), \"mybot\")\n}\n\nfunc TestBuzzerDriverStart(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, d.Start(), nil)\n}\n\nfunc TestBuzzerDriverHalt(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, d.Halt(), nil)\n}\n\nfunc TestBuzzerDriverToggle(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\td.Off()\n\td.Toggle()\n\tgobottest.Assert(t, d.State(), true)\n\td.Toggle()\n\tgobottest.Assert(t, d.State(), false)\n}\n\nfunc TestBuzzerDriverTone(t *testing.T) {\n\td := initTestBuzzerDriver(newGpioTestAdaptor())\n\tgobottest.Assert(t, d.Tone(100, 0.01), nil)\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\"exec\"\n\t\"flag\"\n\t\"http\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"template\"\n)\n\nvar (\n\thttpListen = flag.String(\"http\", \"127.0.0.1:3999\", \"host:port to listen on\")\n\thtmlOutput = flag.Bool(\"html\", false, \"render program output as HTML\")\n)\n\nvar (\n\t\/\/ a source of numbers, for naming temporary files\n\tuniq = make(chan int)\n\t\/\/ the architecture-identifying character of the tool chain, 5, 6, or 8\n\tarchChar string\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ set archChar\n\tswitch runtime.GOARCH {\n\tcase \"arm\":\n\t\tarchChar = \"5\"\n\tcase \"amd64\":\n\t\tarchChar = \"6\"\n\tcase \"386\":\n\t\tarchChar = \"8\"\n\tdefault:\n\t\tlog.Fatalln(\"unrecognized GOARCH:\", runtime.GOARCH)\n\t}\n\n\t\/\/ source of unique numbers\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tuniq <- i\n\t\t}\n\t}()\n\n\thttp.HandleFunc(\"\/\", FrontPage)\n\thttp.HandleFunc(\"\/compile\", Compile)\n\tlog.Fatal(http.ListenAndServe(*httpListen, nil))\n}\n\n\/\/ FrontPage is an HTTP handler that renders the goplay interface. \n\/\/ If a filename is supplied in the path component of the URI,\n\/\/ its contents will be put in the interface's text area.\n\/\/ Otherwise, the default \"hello, world\" program is displayed.\nfunc FrontPage(w http.ResponseWriter, req *http.Request) {\n\tdata, err := ioutil.ReadFile(req.URL.Path[1:])\n\tif err != nil {\n\t\tdata = helloWorld\n\t}\n\tfrontPage.Execute(w, data)\n}\n\n\/\/ Compile is an HTTP handler that reads Go source code from the request,\n\/\/ compiles and links the code (returning any errors), runs the program, \n\/\/ and sends the program's output as the HTTP response.\nfunc Compile(w http.ResponseWriter, req *http.Request) {\n\t\/\/ x is the base name for .go, .6, executable files\n\tx := os.TempDir() + \"\/compile\" + strconv.Itoa(<-uniq)\n\tsrc := x + \".go\"\n\tobj := x + \".\" + archChar\n\tbin := x\n\tif runtime.GOOS == \"windows\" {\n\t\tbin += \".exe\"\n\t}\n\n\t\/\/ write request Body to x.go\n\tf, err := os.Create(src)\n\tif err != nil {\n\t\terror(w, nil, err)\n\t\treturn\n\t}\n\tdefer os.Remove(src)\n\tdefer f.Close()\n\t_, err = io.Copy(f, req.Body)\n\tif err != nil {\n\t\terror(w, nil, err)\n\t\treturn\n\t}\n\tf.Close()\n\n\t\/\/ build x.go, creating x.6\n\tout, err := run(archChar+\"g\", \"-o\", obj, src)\n\tdefer os.Remove(obj)\n\tif err != nil {\n\t\terror(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ link x.6, creating x (the program binary)\n\tout, err = run(archChar+\"l\", \"-o\", bin, obj)\n\tdefer os.Remove(bin)\n\tif err != nil {\n\t\terror(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ run x\n\tout, err = run(bin)\n\tif err != nil {\n\t\terror(w, out, err)\n\t}\n\n\t\/\/ write the output of x as the http response\n\tif *htmlOutput {\n\t\tw.Write(out)\n\t} else {\n\t\toutput.Execute(w, out)\n\t}\n}\n\n\/\/ error writes compile, link, or runtime errors to the HTTP connection.\n\/\/ The JavaScript interface uses the 404 status code to identify the error.\nfunc error(w http.ResponseWriter, out []byte, err os.Error) {\n\tw.WriteHeader(404)\n\tif out != nil {\n\t\toutput.Execute(w, out)\n\t} else {\n\t\toutput.Execute(w, err.String())\n\t}\n}\n\n\/\/ run executes the specified command and returns its output and an error.\nfunc run(cmd ...string) ([]byte, os.Error) {\n\treturn exec.Command(cmd[0], cmd[1:]...).CombinedOutput()\n}\n\nvar frontPage = template.Must(template.New(\"frontPage\").Parse(frontPageText)) \/\/ HTML template\nvar output = template.Must(template.New(\"output\").Parse(outputText))          \/\/ HTML template\n\nvar outputText = `<pre>{{html .}}<\/pre>`\n\nvar frontPageText = `<!doctype html>\n<html>\n<head>\n<style>\npre, textarea {\n\tfont-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;\n\tfont-size: 100%;\n}\n.hints {\n\tfont-size: 0.8em;\n\ttext-align: right;\n}\n#edit, #output, #errors { width: 100%; text-align: left; }\n#edit { height: 500px; }\n#output { color: #00c; }\n#errors { color: #c00; }\n<\/style>\n<script>\n\nfunction insertTabs(n) {\n\t\/\/ find the selection start and end\n\tvar cont  = document.getElementById(\"edit\");\n\tvar start = cont.selectionStart;\n\tvar end   = cont.selectionEnd;\n\t\/\/ split the textarea content into two, and insert n tabs\n\tvar v = cont.value;\n\tvar u = v.substr(0, start);\n\tfor (var i=0; i<n; i++) {\n\t\tu += \"\\t\";\n\t}\n\tu += v.substr(end);\n\t\/\/ set revised content\n\tcont.value = u;\n\t\/\/ reset caret position after inserted tabs\n\tcont.selectionStart = start+n;\n\tcont.selectionEnd = start+n;\n}\n\nfunction autoindent(el) {\n\tvar curpos = el.selectionStart;\n\tvar tabs = 0;\n\twhile (curpos > 0) {\n\t\tcurpos--;\n\t\tif (el.value[curpos] == \"\\t\") {\n\t\t\ttabs++;\n\t\t} else if (tabs > 0 || el.value[curpos] == \"\\n\") {\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetTimeout(function() {\n\t\tinsertTabs(tabs);\n\t}, 1);\n}\n\nfunction keyHandler(event) {\n\tvar e = window.event || event;\n\tif (e.keyCode == 9) { \/\/ tab\n\t\tinsertTabs(1);\n\t\te.preventDefault();\n\t\treturn false;\n\t}\n\tif (e.keyCode == 13) { \/\/ enter\n\t\tif (e.shiftKey) { \/\/ +shift\n\t\t\tcompile(e.target);\n\t\t\te.preventDefault();\n\t\t\treturn false;\n\t\t} else {\n\t\t\tautoindent(e.target);\n\t\t}\n\t}\n\treturn true;\n}\n\nvar xmlreq;\n\nfunction autocompile() {\n\tif(!document.getElementById(\"autocompile\").checked) {\n\t\treturn;\n\t}\n\tcompile();\n}\n\nfunction compile() {\n\tvar prog = document.getElementById(\"edit\").value;\n\tvar req = new XMLHttpRequest();\n\txmlreq = req;\n\treq.onreadystatechange = compileUpdate;\n\treq.open(\"POST\", \"\/compile\", true);\n\treq.setRequestHeader(\"Content-Type\", \"text\/plain; charset=utf-8\");\n\treq.send(prog);\t\n}\n\nfunction compileUpdate() {\n\tvar req = xmlreq;\n\tif(!req || req.readyState != 4) {\n\t\treturn;\n\t}\n\tif(req.status == 200) {\n\t\tdocument.getElementById(\"output\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"errors\").innerHTML = \"\";\n\t} else {\n\t\tdocument.getElementById(\"errors\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"output\").innerHTML = \"\";\n\t}\n}\n<\/script>\n<\/head>\n<body>\n<table width=\"100%\"><tr><td width=\"60%\" valign=\"top\">\n<textarea autofocus=\"true\" id=\"edit\" spellcheck=\"false\" onkeydown=\"keyHandler(event);\" onkeyup=\"autocompile();\">{{html .}}<\/textarea>\n<div class=\"hints\">\n(Shift-Enter to compile and run.)&nbsp;&nbsp;&nbsp;&nbsp;\n<input type=\"checkbox\" id=\"autocompile\" value=\"checked\" \/> Compile and run after each keystroke\n<\/div>\n<td width=\"3%\">\n<td width=\"27%\" align=\"right\" valign=\"top\">\n<div id=\"output\"><\/div>\n<\/table>\n<div id=\"errors\"><\/div>\n<\/body>\n<\/html>\n`\n\nvar helloWorld = []byte(`package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hello, world\")\n}\n`)\n<commit_msg>misc\/goplay: Fix template output<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\"exec\"\n\t\"flag\"\n\t\"http\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"template\"\n)\n\nvar (\n\thttpListen = flag.String(\"http\", \"127.0.0.1:3999\", \"host:port to listen on\")\n\thtmlOutput = flag.Bool(\"html\", false, \"render program output as HTML\")\n)\n\nvar (\n\t\/\/ a source of numbers, for naming temporary files\n\tuniq = make(chan int)\n\t\/\/ the architecture-identifying character of the tool chain, 5, 6, or 8\n\tarchChar string\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ set archChar\n\tswitch runtime.GOARCH {\n\tcase \"arm\":\n\t\tarchChar = \"5\"\n\tcase \"amd64\":\n\t\tarchChar = \"6\"\n\tcase \"386\":\n\t\tarchChar = \"8\"\n\tdefault:\n\t\tlog.Fatalln(\"unrecognized GOARCH:\", runtime.GOARCH)\n\t}\n\n\t\/\/ source of unique numbers\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tuniq <- i\n\t\t}\n\t}()\n\n\thttp.HandleFunc(\"\/\", FrontPage)\n\thttp.HandleFunc(\"\/compile\", Compile)\n\tlog.Fatal(http.ListenAndServe(*httpListen, nil))\n}\n\n\/\/ FrontPage is an HTTP handler that renders the goplay interface. \n\/\/ If a filename is supplied in the path component of the URI,\n\/\/ its contents will be put in the interface's text area.\n\/\/ Otherwise, the default \"hello, world\" program is displayed.\nfunc FrontPage(w http.ResponseWriter, req *http.Request) {\n\tdata, err := ioutil.ReadFile(req.URL.Path[1:])\n\tif err != nil {\n\t\tdata = helloWorld\n\t}\n\tfrontPage.Execute(w, data)\n}\n\n\/\/ Compile is an HTTP handler that reads Go source code from the request,\n\/\/ compiles and links the code (returning any errors), runs the program, \n\/\/ and sends the program's output as the HTTP response.\nfunc Compile(w http.ResponseWriter, req *http.Request) {\n\t\/\/ x is the base name for .go, .6, executable files\n\tx := os.TempDir() + \"\/compile\" + strconv.Itoa(<-uniq)\n\tsrc := x + \".go\"\n\tobj := x + \".\" + archChar\n\tbin := x\n\tif runtime.GOOS == \"windows\" {\n\t\tbin += \".exe\"\n\t}\n\n\t\/\/ write request Body to x.go\n\tf, err := os.Create(src)\n\tif err != nil {\n\t\terror(w, nil, err)\n\t\treturn\n\t}\n\tdefer os.Remove(src)\n\tdefer f.Close()\n\t_, err = io.Copy(f, req.Body)\n\tif err != nil {\n\t\terror(w, nil, err)\n\t\treturn\n\t}\n\tf.Close()\n\n\t\/\/ build x.go, creating x.6\n\tout, err := run(archChar+\"g\", \"-o\", obj, src)\n\tdefer os.Remove(obj)\n\tif err != nil {\n\t\terror(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ link x.6, creating x (the program binary)\n\tout, err = run(archChar+\"l\", \"-o\", bin, obj)\n\tdefer os.Remove(bin)\n\tif err != nil {\n\t\terror(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ run x\n\tout, err = run(bin)\n\tif err != nil {\n\t\terror(w, out, err)\n\t}\n\n\t\/\/ write the output of x as the http response\n\tif *htmlOutput {\n\t\tw.Write(out)\n\t} else {\n\t\toutput.Execute(w, out)\n\t}\n}\n\n\/\/ error writes compile, link, or runtime errors to the HTTP connection.\n\/\/ The JavaScript interface uses the 404 status code to identify the error.\nfunc error(w http.ResponseWriter, out []byte, err os.Error) {\n\tw.WriteHeader(404)\n\tif out != nil {\n\t\toutput.Execute(w, out)\n\t} else {\n\t\toutput.Execute(w, err.String())\n\t}\n}\n\n\/\/ run executes the specified command and returns its output and an error.\nfunc run(cmd ...string) ([]byte, os.Error) {\n\treturn exec.Command(cmd[0], cmd[1:]...).CombinedOutput()\n}\n\nvar frontPage = template.Must(template.New(\"frontPage\").Parse(frontPageText)) \/\/ HTML template\nvar output = template.Must(template.New(\"output\").Parse(outputText))          \/\/ HTML template\n\nvar outputText = `<pre>{{html .}}<\/pre>`\n\nvar frontPageText = `<!doctype html>\n<html>\n<head>\n<style>\npre, textarea {\n\tfont-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;\n\tfont-size: 100%;\n}\n.hints {\n\tfont-size: 0.8em;\n\ttext-align: right;\n}\n#edit, #output, #errors { width: 100%; text-align: left; }\n#edit { height: 500px; }\n#output { color: #00c; }\n#errors { color: #c00; }\n<\/style>\n<script>\n\nfunction insertTabs(n) {\n\t\/\/ find the selection start and end\n\tvar cont  = document.getElementById(\"edit\");\n\tvar start = cont.selectionStart;\n\tvar end   = cont.selectionEnd;\n\t\/\/ split the textarea content into two, and insert n tabs\n\tvar v = cont.value;\n\tvar u = v.substr(0, start);\n\tfor (var i=0; i<n; i++) {\n\t\tu += \"\\t\";\n\t}\n\tu += v.substr(end);\n\t\/\/ set revised content\n\tcont.value = u;\n\t\/\/ reset caret position after inserted tabs\n\tcont.selectionStart = start+n;\n\tcont.selectionEnd = start+n;\n}\n\nfunction autoindent(el) {\n\tvar curpos = el.selectionStart;\n\tvar tabs = 0;\n\twhile (curpos > 0) {\n\t\tcurpos--;\n\t\tif (el.value[curpos] == \"\\t\") {\n\t\t\ttabs++;\n\t\t} else if (tabs > 0 || el.value[curpos] == \"\\n\") {\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetTimeout(function() {\n\t\tinsertTabs(tabs);\n\t}, 1);\n}\n\nfunction keyHandler(event) {\n\tvar e = window.event || event;\n\tif (e.keyCode == 9) { \/\/ tab\n\t\tinsertTabs(1);\n\t\te.preventDefault();\n\t\treturn false;\n\t}\n\tif (e.keyCode == 13) { \/\/ enter\n\t\tif (e.shiftKey) { \/\/ +shift\n\t\t\tcompile(e.target);\n\t\t\te.preventDefault();\n\t\t\treturn false;\n\t\t} else {\n\t\t\tautoindent(e.target);\n\t\t}\n\t}\n\treturn true;\n}\n\nvar xmlreq;\n\nfunction autocompile() {\n\tif(!document.getElementById(\"autocompile\").checked) {\n\t\treturn;\n\t}\n\tcompile();\n}\n\nfunction compile() {\n\tvar prog = document.getElementById(\"edit\").value;\n\tvar req = new XMLHttpRequest();\n\txmlreq = req;\n\treq.onreadystatechange = compileUpdate;\n\treq.open(\"POST\", \"\/compile\", true);\n\treq.setRequestHeader(\"Content-Type\", \"text\/plain; charset=utf-8\");\n\treq.send(prog);\t\n}\n\nfunction compileUpdate() {\n\tvar req = xmlreq;\n\tif(!req || req.readyState != 4) {\n\t\treturn;\n\t}\n\tif(req.status == 200) {\n\t\tdocument.getElementById(\"output\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"errors\").innerHTML = \"\";\n\t} else {\n\t\tdocument.getElementById(\"errors\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"output\").innerHTML = \"\";\n\t}\n}\n<\/script>\n<\/head>\n<body>\n<table width=\"100%\"><tr><td width=\"60%\" valign=\"top\">\n<textarea autofocus=\"true\" id=\"edit\" spellcheck=\"false\" onkeydown=\"keyHandler(event);\" onkeyup=\"autocompile();\">{{printf \"%s\" . |html}}<\/textarea>\n<div class=\"hints\">\n(Shift-Enter to compile and run.)&nbsp;&nbsp;&nbsp;&nbsp;\n<input type=\"checkbox\" id=\"autocompile\" value=\"checked\" \/> Compile and run after each keystroke\n<\/div>\n<td width=\"3%\">\n<td width=\"27%\" align=\"right\" valign=\"top\">\n<div id=\"output\"><\/div>\n<\/table>\n<div id=\"errors\"><\/div>\n<\/body>\n<\/html>\n`\n\nvar helloWorld = []byte(`package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hello, world\")\n}\n`)\n<|endoftext|>"}
{"text":"<commit_before>package mettbot\n\nimport (\n\ta \".\/answers\"\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\tirc \"github.com\/fluffle\/goirc\/client\"\n\t\"html\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar Host *string = flag.String(\"host\", \"irc.ps0ke.de:2342\", \"IRC server\")\nvar Channel *string = flag.String(\"channel\", \"#metttest\", \"IRC channel\")\nvar Nick *string = flag.String(\"nick\", \"rohmett\", \"IRC nick\")\nvar Longnick *string = flag.String(\"longnick\", \"Le MettBot\", \"IRC fullname\")\nvar Timeformat *string = flag.String(\"timeformat\", \"2006-01-02T15:04\", \"Time format string (standard date: 2006-01-02T15:04:05)\")\nvar Quotes *string = flag.String(\"quotes\", \"mett_quotes.txt\", \"Quote database file\")\nvar Metts *string = flag.String(\"metts\", \"mett_metts.txt\", \"Metts database file\")\nvar Offtime *int = flag.Int(\"offtime\", 4, \"Number of hours of offtopic content befor posting mett content\")\nvar Offmessages *int = flag.Int(\"offmessages\", 100, \"Number of messages of offtopic content befor posting mett content\")\nvar Probability *float64 = flag.Float64(\"probability\", 0.1, \"Probability that the bot ignores a command\")\nvar MumbleServer *string = flag.String(\"mumbleserver\", \"avidrain.de:64738\", \"Mumble server\")\nvar MumbleTopicregex *string = flag.String(\"mumbletopicregex\", \"((?:^|\\\\|)[^|]*)audiomett:[^|]*?(\\\\s*(?:$|\\\\|))\", \"The regex to match Mumble topic snippet\")\nvar Twitterregex *string = flag.String(\"twitterregex\", \"\\\\S*twitter\\\\.com\\\\\/\\\\S+\\\\\/status(es)?\\\\\/(\\\\d+)\\\\S*\", \"The regex to match Twitter URLs\")\nvar Firebird *float64 = flag.Float64(\"firebird\", 0.05, \"Probability firebird gets a question\")\n\nfunc init() {\n\tflag.Parse()\n\trand.Seed(time.Now().Unix())\n}\n\ntype Mettbot struct {\n\t*irc.Conn\n\tMumblePing *_mumbleping\n\tQuitted         chan bool\n\tQuotesPrnt      chan string\n\tMettsPrnt       chan string\n\tQuotesLinesPrnt chan int\n\tMettsLinesPrnt  chan int\n\tInput           chan string\n\tIsMett          chan bool\n\tReallyQuit      bool\n\tTopics          map[string]string\n\tMsgSinceMett    int\n}\n\nfunc NewMettbot(nick string, args ...string) *Mettbot {\n\tbot := &Mettbot{\n\t\tirc.SimpleClient(nick, args...), \/\/ *irc.Conn\n\t\tnew(_mumbleping), \/\/ MumblePing\n\t\tmake(chan bool),                 \/\/ Quitted\n\t\tmake(chan string),               \/\/ QuotesPrnt\n\t\tmake(chan string),               \/\/ MettsPrnt\n\t\tmake(chan int),                  \/\/ QuotesLinesPrnt\n\t\tmake(chan int),                  \/\/ MettsLinesPrnt\n\t\tmake(chan string, 4),            \/\/ Input\n\t\tmake(chan bool),                 \/\/ IsMett\n\t\tfalse,                           \/\/ ReallyQuit\n\t\tmake(map[string]string), \/\/ Topics\n\t\t0,                       \/\/ MsgSinceMett\n\t}\n\tbot.EnableStateTracking()\n\tbot.MumblePing.InitMumblePing(bot)\n\treturn bot\n}\n\nfunc (bot *Mettbot) Syntax(channel string) {\n\tbot.Notice(channel, a.RandStr(a.Syntax))\n}\n\nfunc (bot *Mettbot) Mentioned(channel string) {\n\tbot.Privmsg(channel, a.RandStr(a.Mention))\n}\n\nfunc (bot *Mettbot) Mett() {\n\tbot.MsgSinceMett = 0\n\tbot.IsMett <- true\n}\n\nfunc (bot *Mettbot) CheckMett() {\n\tfor {\n\t\tselect {\n\t\tcase <-bot.IsMett:\n\t\tcase <-time.After(time.Duration(*Offtime) * time.Hour):\n\t\t\thour := time.Now().Hour()\n\t\t\tif hour < 1 || hour >= 8 {\n\t\t\t\tbot.Notice(*Channel, fmt.Sprintf(a.RandStr(a.MettTime), bot.GetMett(*Channel)))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (bot *Mettbot) GetMett(channel string) string {\n\tfi, err := os.Open(*Metts)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tbot.Notice(channel, \"Failed to open mett database\")\n\t\treturn \"Error\"\n\t}\n\tdefer fi.Close()\n\n\treader := bufio.NewReader(fi)\n\tlines := 0\n\tfor {\n\t\t_, err = reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlines++\n\t}\n\n\tnum := rand.Intn(lines)\n\tmett := \"\"\n\n\t_, err = fi.Seek(0, 0)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tfor ; num >= 0; num-- {\n\t\tmett, err = reader.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tlog.Println(\"PostMett: reached EOF\")\n\t\t\treturn \"Error\"\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(channel, \"Failed to read from mett database\")\n\t\t\treturn \"Error\"\n\t\t}\n\t}\n\treturn mett\n}\n\nfunc (bot *Mettbot) diffTopic(oldTopic, newTopic string) string {\n\toldFile, err := ioutil.TempFile(\"\", \".mettbotWdiffOld\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tn, err := oldFile.WriteString(oldTopic)\n\tif n != len(oldTopic) || err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\toldFile.Close()\n\n\tnewFile, err := ioutil.TempFile(\"\", \".mettbotWdiffNew\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tn, err = newFile.WriteString(newTopic)\n\tif n != len(newTopic) || err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tnewFile.Close()\n\tdefer func() {\n\t\tos.Remove(oldFile.Name())\n\t\tos.Remove(newFile.Name())\n\t}()\n\n\tdb := \"❣\" \/\/ DeletionBegin\n\tde := \"❢\" \/\/ DeletionEnd\n\tib := \"¶\" \/\/ InsertionBegin\n\tie := \"⁋\" \/\/ InsertionEnd\n\n\tfor {\n\t\trdb := rune(rand.Intn(255-32) + 32)\n\t\trde := rune(rand.Intn(255-32) + 32)\n\t\trib := rune(rand.Intn(255-32) + 32)\n\t\trie := rune(rand.Intn(255-32) + 32)\n\n\t\tcontains := strings.ContainsRune(oldTopic, rdb)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rde)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rib)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rie)\n\n\t\tcontains = contains || strings.ContainsRune(newTopic, rdb)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rde)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rib)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rie)\n\n\t\tif contains == false {\n\t\t\tdb = fmt.Sprintf(\"%c\", rdb)\n\t\t\tde = fmt.Sprintf(\"%c\", rde)\n\t\t\tib = fmt.Sprintf(\"%c\", rib)\n\t\t\tie = fmt.Sprintf(\"%c\", rie)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tcoloring := map[string]string{ \/\/ http:\/\/oreilly.com\/pub\/h\/1953\n\t\tdb: \"\\x035\\x1F\\x02\",\n\t\tde: \"\\x0F\\x0315\",\n\t\tib: \"\\x033\\x02\",\n\t\tie: \"\\x0F\\x0315\",\n\t}\n\n\tcmd := exec.Command(\"wdiff\", \"-w\"+db, \"-x\"+de, \"-y\"+ib, \"-z\"+ie, oldFile.Name(), newFile.Name())\n\tout, _ := cmd.Output()\n\toutStr := string(out)\n\n\tfor n, v := range coloring {\n\t\toutStr = strings.Replace(outStr, n, v, -1)\n\t}\n\n\treturn outStr\n}\n\nfunc (bot *Mettbot) GetTweet(channel, url string) {\n\tregex, err := regexp.Compile(*Twitterregex)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tsub := regex.FindStringSubmatch(url)\n\ttweetUrl := fmt.Sprintf(\"https:\/\/api.twitter.com\/1\/statuses\/show.json?id=%v&trim_user=false&include_entities=no\", sub[2])\n\n\tresp, err := http.Get(tweetUrl)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\ttype usr struct {\n\t\tScreen_name string\n\t}\n\ttype tweet struct {\n\t\tText string\n\t\tUser usr\n\t}\n\n\tvar twt tweet\n\terr = json.Unmarshal(body, &twt)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\ttweetText := html.UnescapeString(twt.Text)\n\n\ttweetText = strings.Map(func(r rune) rune {\n\t\tif r < ' ' {\n\t\t\treturn ' '\n\t\t}\n\t\treturn r\n\t}, tweetText)\n\n\tbot.Notice(channel, \"@\"+twt.User.Screen_name+\": \"+tweetText)\n}\n\nfunc (bot *Mettbot) firebird(channel string) {\n\ttime.Sleep(time.Duration(rand.Intn(3)+3) * time.Second)\n\tbot.Notice(channel, \"\\x034\" + a.RandStr(a.Firebird))\n}\n\nfunc (bot *Mettbot) DongDong(channel, msg string) {\n\tcount := strings.Count(msg, \"\\\\a\")\n\tstr := a.RandStr(a.Dong)\n\tnotice := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tnotice += str + \" \"\n\t}\n\n\tif len(notice) > 400 {\n\t\tnotice = notice[:400]\n\t}\n\tbot.Notice(channel, notice)\n}\n\nfunc (bot *Mettbot) WriteQuote(filename string, prnt <-chan string, linesPrnt chan<- int) {\n\tfor message := range prnt {\n\t\tfo, err := os.OpenFile(filename, syscall.O_RDWR+syscall.O_CREAT, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(*Channel, \"Couldn't open quote database\")\n\t\t\tcontinue\n\t\t}\n\t\tdefer fo.Close()\n\n\t\tfoReader := bufio.NewReader(fo)\n\t\tlines := 0 \/\/last quote has no newline\n\n\t\tfor {\n\t\t\t_, err = foReader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlines++\n\t\t}\n\t\tlinesPrnt <- lines\n\n\t\t_, err = fo.WriteString(message)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(*Channel, \"Couldn't write to quote database\")\n\t\t}\n\t\tfo.Close()\n\t}\n}\n\nfunc (bot *Mettbot) ReadStdin() {\n\tcon := bufio.NewReader(os.Stdin)\n\tfor {\n\t\ts, err := con.ReadString('\\n')\n\t\tif err != nil {\n\t\t\t\/\/ wha?, maybe ctrl-D...\n\t\t\tclose(bot.Input)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ no point in sending empty lines down the channel\n\t\tif len(s) > 2 {\n\t\t\tbot.Input <- s[0 : len(s)-1]\n\t\t}\n\t}\n}\n\nfunc (bot *Mettbot) ParseStdin() {\n\tfor cmd := range bot.Input {\n\t\tif cmd[0] == ':' {\n\t\t\tidx := strings.Index(cmd, \" \")\n\t\t\tmsg := cmd[idx+1:]\n\n\t\t\tswitch {\n\t\t\tcase cmd[1] == 'd':\n\t\t\t\tfmt.Printf(bot.String())\n\t\t\tcase cmd[1] == 'f':\n\t\t\t\tif len(cmd) > 2 && cmd[2] == 'e' {\n\t\t\t\t\t\/\/ enable flooding\n\t\t\t\t\tbot.Flood = true\n\t\t\t\t} else if len(cmd) > 2 && cmd[2] == 'd' {\n\t\t\t\t\t\/\/ disable flooding\n\t\t\t\t\tbot.Flood = false\n\t\t\t\t}\n\t\t\t\tfor i := 0; i < 20; i++ {\n\t\t\t\t\tbot.Privmsg(*Channel, \"salami!1!\")\n\t\t\t\t}\n\t\t\tcase idx == -1:\n\t\t\t\tcontinue\n\t\t\tcase cmd[1] == 'q':\n\t\t\t\tbot.ReallyQuit = true\n\t\t\t\tbot.Quit(msg)\n\t\t\tcase cmd[1] == 'j':\n\t\t\t\tbot.Join(msg)\n\t\t\tcase cmd[1] == 'p':\n\t\t\t\tbot.Part(msg)\n\t\t\tcase cmd[1] == 'm':\n\t\t\t\tbot.Privmsg(*Channel, msg)\n\t\t\tcase cmd[1] == 'a':\n\t\t\t\tbot.Action(*Channel, msg)\n\t\t\tcase cmd[1] == 'n':\n\t\t\t\tbot.Notice(*Channel, msg)\n\t\t\tcase cmd[1] == 's':\n\t\t\t\tmidx := strings.Index(msg, \" \")\n\t\t\t\tif midx == -1 {\n\t\t\t\t\tfmt.Println(\"Wrong Syntax\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tval := msg[midx+1:]\n\t\t\t\tswitch msg[:midx] {\n\t\t\t\tcase \"channel\":\n\t\t\t\t\tbot.Join(val)\n\t\t\t\t\t*Channel = val\n\t\t\t\tcase \"nick\":\n\t\t\t\t\tbot.Nick(val)\n\t\t\t\t\t*Nick = val\n\t\t\t\tcase \"quotes\":\n\t\t\t\t\t*Quotes = val\n\t\t\t\tcase \"metts\":\n\t\t\t\t\t*Metts = val\n\t\t\t\tcase \"offtime\":\n\t\t\t\t\tnum, err := strconv.Atoi(val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Number\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Offtime = num\n\t\t\t\tcase \"offmessages\":\n\t\t\t\t\tnum, err := strconv.Atoi(val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Number\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Offmessages = num\n\t\t\t\tcase \"probability\":\n\t\t\t\t\tnum, err := strconv.ParseFloat(val, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Flaot\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Probability = num\n\t\t\t\tcase \"firebird\":\n\t\t\t\t\tnum, err := strconv.ParseFloat(val, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Flaot\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Firebird = num\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Println(\"Unknown variable\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbot.Raw(cmd)\n\t\t}\n\t}\n}\n<commit_msg>removed the posting loop after flooding state toggeling<commit_after>package mettbot\n\nimport (\n\ta \".\/answers\"\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\tirc \"github.com\/fluffle\/goirc\/client\"\n\t\"html\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar Host *string = flag.String(\"host\", \"irc.ps0ke.de:2342\", \"IRC server\")\nvar Channel *string = flag.String(\"channel\", \"#metttest\", \"IRC channel\")\nvar Nick *string = flag.String(\"nick\", \"rohmett\", \"IRC nick\")\nvar Longnick *string = flag.String(\"longnick\", \"Le MettBot\", \"IRC fullname\")\nvar Timeformat *string = flag.String(\"timeformat\", \"2006-01-02T15:04\", \"Time format string (standard date: 2006-01-02T15:04:05)\")\nvar Quotes *string = flag.String(\"quotes\", \"mett_quotes.txt\", \"Quote database file\")\nvar Metts *string = flag.String(\"metts\", \"mett_metts.txt\", \"Metts database file\")\nvar Offtime *int = flag.Int(\"offtime\", 4, \"Number of hours of offtopic content befor posting mett content\")\nvar Offmessages *int = flag.Int(\"offmessages\", 100, \"Number of messages of offtopic content befor posting mett content\")\nvar Probability *float64 = flag.Float64(\"probability\", 0.1, \"Probability that the bot ignores a command\")\nvar MumbleServer *string = flag.String(\"mumbleserver\", \"avidrain.de:64738\", \"Mumble server\")\nvar MumbleTopicregex *string = flag.String(\"mumbletopicregex\", \"((?:^|\\\\|)[^|]*)audiomett:[^|]*?(\\\\s*(?:$|\\\\|))\", \"The regex to match Mumble topic snippet\")\nvar Twitterregex *string = flag.String(\"twitterregex\", \"\\\\S*twitter\\\\.com\\\\\/\\\\S+\\\\\/status(es)?\\\\\/(\\\\d+)\\\\S*\", \"The regex to match Twitter URLs\")\nvar Firebird *float64 = flag.Float64(\"firebird\", 0.05, \"Probability firebird gets a question\")\n\nfunc init() {\n\tflag.Parse()\n\trand.Seed(time.Now().Unix())\n}\n\ntype Mettbot struct {\n\t*irc.Conn\n\tMumblePing *_mumbleping\n\tQuitted         chan bool\n\tQuotesPrnt      chan string\n\tMettsPrnt       chan string\n\tQuotesLinesPrnt chan int\n\tMettsLinesPrnt  chan int\n\tInput           chan string\n\tIsMett          chan bool\n\tReallyQuit      bool\n\tTopics          map[string]string\n\tMsgSinceMett    int\n}\n\nfunc NewMettbot(nick string, args ...string) *Mettbot {\n\tbot := &Mettbot{\n\t\tirc.SimpleClient(nick, args...), \/\/ *irc.Conn\n\t\tnew(_mumbleping), \/\/ MumblePing\n\t\tmake(chan bool),                 \/\/ Quitted\n\t\tmake(chan string),               \/\/ QuotesPrnt\n\t\tmake(chan string),               \/\/ MettsPrnt\n\t\tmake(chan int),                  \/\/ QuotesLinesPrnt\n\t\tmake(chan int),                  \/\/ MettsLinesPrnt\n\t\tmake(chan string, 4),            \/\/ Input\n\t\tmake(chan bool),                 \/\/ IsMett\n\t\tfalse,                           \/\/ ReallyQuit\n\t\tmake(map[string]string), \/\/ Topics\n\t\t0,                       \/\/ MsgSinceMett\n\t}\n\tbot.EnableStateTracking()\n\tbot.MumblePing.InitMumblePing(bot)\n\treturn bot\n}\n\nfunc (bot *Mettbot) Syntax(channel string) {\n\tbot.Notice(channel, a.RandStr(a.Syntax))\n}\n\nfunc (bot *Mettbot) Mentioned(channel string) {\n\tbot.Privmsg(channel, a.RandStr(a.Mention))\n}\n\nfunc (bot *Mettbot) Mett() {\n\tbot.MsgSinceMett = 0\n\tbot.IsMett <- true\n}\n\nfunc (bot *Mettbot) CheckMett() {\n\tfor {\n\t\tselect {\n\t\tcase <-bot.IsMett:\n\t\tcase <-time.After(time.Duration(*Offtime) * time.Hour):\n\t\t\thour := time.Now().Hour()\n\t\t\tif hour < 1 || hour >= 8 {\n\t\t\t\tbot.Notice(*Channel, fmt.Sprintf(a.RandStr(a.MettTime), bot.GetMett(*Channel)))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (bot *Mettbot) GetMett(channel string) string {\n\tfi, err := os.Open(*Metts)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tbot.Notice(channel, \"Failed to open mett database\")\n\t\treturn \"Error\"\n\t}\n\tdefer fi.Close()\n\n\treader := bufio.NewReader(fi)\n\tlines := 0\n\tfor {\n\t\t_, err = reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlines++\n\t}\n\n\tnum := rand.Intn(lines)\n\tmett := \"\"\n\n\t_, err = fi.Seek(0, 0)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tfor ; num >= 0; num-- {\n\t\tmett, err = reader.ReadString('\\n')\n\t\tif err == io.EOF {\n\t\t\tlog.Println(\"PostMett: reached EOF\")\n\t\t\treturn \"Error\"\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(channel, \"Failed to read from mett database\")\n\t\t\treturn \"Error\"\n\t\t}\n\t}\n\treturn mett\n}\n\nfunc (bot *Mettbot) diffTopic(oldTopic, newTopic string) string {\n\toldFile, err := ioutil.TempFile(\"\", \".mettbotWdiffOld\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tn, err := oldFile.WriteString(oldTopic)\n\tif n != len(oldTopic) || err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\toldFile.Close()\n\n\tnewFile, err := ioutil.TempFile(\"\", \".mettbotWdiffNew\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tn, err = newFile.WriteString(newTopic)\n\tif n != len(newTopic) || err != nil {\n\t\tlog.Println(err)\n\t\treturn \"\"\n\t}\n\n\tnewFile.Close()\n\tdefer func() {\n\t\tos.Remove(oldFile.Name())\n\t\tos.Remove(newFile.Name())\n\t}()\n\n\tdb := \"❣\" \/\/ DeletionBegin\n\tde := \"❢\" \/\/ DeletionEnd\n\tib := \"¶\" \/\/ InsertionBegin\n\tie := \"⁋\" \/\/ InsertionEnd\n\n\tfor {\n\t\trdb := rune(rand.Intn(255-32) + 32)\n\t\trde := rune(rand.Intn(255-32) + 32)\n\t\trib := rune(rand.Intn(255-32) + 32)\n\t\trie := rune(rand.Intn(255-32) + 32)\n\n\t\tcontains := strings.ContainsRune(oldTopic, rdb)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rde)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rib)\n\t\tcontains = contains || strings.ContainsRune(oldTopic, rie)\n\n\t\tcontains = contains || strings.ContainsRune(newTopic, rdb)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rde)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rib)\n\t\tcontains = contains || strings.ContainsRune(newTopic, rie)\n\n\t\tif contains == false {\n\t\t\tdb = fmt.Sprintf(\"%c\", rdb)\n\t\t\tde = fmt.Sprintf(\"%c\", rde)\n\t\t\tib = fmt.Sprintf(\"%c\", rib)\n\t\t\tie = fmt.Sprintf(\"%c\", rie)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tcoloring := map[string]string{ \/\/ http:\/\/oreilly.com\/pub\/h\/1953\n\t\tdb: \"\\x035\\x1F\\x02\",\n\t\tde: \"\\x0F\\x0315\",\n\t\tib: \"\\x033\\x02\",\n\t\tie: \"\\x0F\\x0315\",\n\t}\n\n\tcmd := exec.Command(\"wdiff\", \"-w\"+db, \"-x\"+de, \"-y\"+ib, \"-z\"+ie, oldFile.Name(), newFile.Name())\n\tout, _ := cmd.Output()\n\toutStr := string(out)\n\n\tfor n, v := range coloring {\n\t\toutStr = strings.Replace(outStr, n, v, -1)\n\t}\n\n\treturn outStr\n}\n\nfunc (bot *Mettbot) GetTweet(channel, url string) {\n\tregex, err := regexp.Compile(*Twitterregex)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tsub := regex.FindStringSubmatch(url)\n\ttweetUrl := fmt.Sprintf(\"https:\/\/api.twitter.com\/1\/statuses\/show.json?id=%v&trim_user=false&include_entities=no\", sub[2])\n\n\tresp, err := http.Get(tweetUrl)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\ttype usr struct {\n\t\tScreen_name string\n\t}\n\ttype tweet struct {\n\t\tText string\n\t\tUser usr\n\t}\n\n\tvar twt tweet\n\terr = json.Unmarshal(body, &twt)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\ttweetText := html.UnescapeString(twt.Text)\n\n\ttweetText = strings.Map(func(r rune) rune {\n\t\tif r < ' ' {\n\t\t\treturn ' '\n\t\t}\n\t\treturn r\n\t}, tweetText)\n\n\tbot.Notice(channel, \"@\"+twt.User.Screen_name+\": \"+tweetText)\n}\n\nfunc (bot *Mettbot) firebird(channel string) {\n\ttime.Sleep(time.Duration(rand.Intn(3)+3) * time.Second)\n\tbot.Notice(channel, \"\\x034\" + a.RandStr(a.Firebird))\n}\n\nfunc (bot *Mettbot) DongDong(channel, msg string) {\n\tcount := strings.Count(msg, \"\\\\a\")\n\tstr := a.RandStr(a.Dong)\n\tnotice := \"\"\n\n\tfor i := 0; i < count; i++ {\n\t\tnotice += str + \" \"\n\t}\n\n\tif len(notice) > 400 {\n\t\tnotice = notice[:400]\n\t}\n\tbot.Notice(channel, notice)\n}\n\nfunc (bot *Mettbot) WriteQuote(filename string, prnt <-chan string, linesPrnt chan<- int) {\n\tfor message := range prnt {\n\t\tfo, err := os.OpenFile(filename, syscall.O_RDWR+syscall.O_CREAT, 0644)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(*Channel, \"Couldn't open quote database\")\n\t\t\tcontinue\n\t\t}\n\t\tdefer fo.Close()\n\n\t\tfoReader := bufio.NewReader(fo)\n\t\tlines := 0 \/\/last quote has no newline\n\n\t\tfor {\n\t\t\t_, err = foReader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlines++\n\t\t}\n\t\tlinesPrnt <- lines\n\n\t\t_, err = fo.WriteString(message)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbot.Notice(*Channel, \"Couldn't write to quote database\")\n\t\t}\n\t\tfo.Close()\n\t}\n}\n\nfunc (bot *Mettbot) ReadStdin() {\n\tcon := bufio.NewReader(os.Stdin)\n\tfor {\n\t\ts, err := con.ReadString('\\n')\n\t\tif err != nil {\n\t\t\t\/\/ wha?, maybe ctrl-D...\n\t\t\tclose(bot.Input)\n\t\t\tbreak\n\t\t}\n\t\t\/\/ no point in sending empty lines down the channel\n\t\tif len(s) > 2 {\n\t\t\tbot.Input <- s[0 : len(s)-1]\n\t\t}\n\t}\n}\n\nfunc (bot *Mettbot) ParseStdin() {\n\tfor cmd := range bot.Input {\n\t\tif cmd[0] == ':' {\n\t\t\tidx := strings.Index(cmd, \" \")\n\t\t\tmsg := cmd[idx+1:]\n\n\t\t\tswitch {\n\t\t\tcase cmd[1] == 'd':\n\t\t\t\tfmt.Printf(bot.String())\n\t\t\tcase cmd[1] == 'f':\n\t\t\t\tif len(cmd) > 2 && cmd[2] == 'e' {\n\t\t\t\t\t\/\/ enable flooding\n\t\t\t\t\tbot.Flood = true\n\t\t\t\t} else if len(cmd) > 2 && cmd[2] == 'd' {\n\t\t\t\t\t\/\/ disable flooding\n\t\t\t\t\tbot.Flood = false\n\t\t\t\t}\n\t\t\tcase idx == -1:\n\t\t\t\tcontinue\n\t\t\tcase cmd[1] == 'q':\n\t\t\t\tbot.ReallyQuit = true\n\t\t\t\tbot.Quit(msg)\n\t\t\tcase cmd[1] == 'j':\n\t\t\t\tbot.Join(msg)\n\t\t\tcase cmd[1] == 'p':\n\t\t\t\tbot.Part(msg)\n\t\t\tcase cmd[1] == 'm':\n\t\t\t\tbot.Privmsg(*Channel, msg)\n\t\t\tcase cmd[1] == 'a':\n\t\t\t\tbot.Action(*Channel, msg)\n\t\t\tcase cmd[1] == 'n':\n\t\t\t\tbot.Notice(*Channel, msg)\n\t\t\tcase cmd[1] == 's':\n\t\t\t\tmidx := strings.Index(msg, \" \")\n\t\t\t\tif midx == -1 {\n\t\t\t\t\tfmt.Println(\"Wrong Syntax\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tval := msg[midx+1:]\n\t\t\t\tswitch msg[:midx] {\n\t\t\t\tcase \"channel\":\n\t\t\t\t\tbot.Join(val)\n\t\t\t\t\t*Channel = val\n\t\t\t\tcase \"nick\":\n\t\t\t\t\tbot.Nick(val)\n\t\t\t\t\t*Nick = val\n\t\t\t\tcase \"quotes\":\n\t\t\t\t\t*Quotes = val\n\t\t\t\tcase \"metts\":\n\t\t\t\t\t*Metts = val\n\t\t\t\tcase \"offtime\":\n\t\t\t\t\tnum, err := strconv.Atoi(val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Number\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Offtime = num\n\t\t\t\tcase \"offmessages\":\n\t\t\t\t\tnum, err := strconv.Atoi(val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Number\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Offmessages = num\n\t\t\t\tcase \"probability\":\n\t\t\t\t\tnum, err := strconv.ParseFloat(val, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Flaot\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Probability = num\n\t\t\t\tcase \"firebird\":\n\t\t\t\t\tnum, err := strconv.ParseFloat(val, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"No Flaot\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*Firebird = num\n\t\t\t\tdefault:\n\t\t\t\t\tfmt.Println(\"Unknown variable\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tbot.Raw(cmd)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Chef Software Inc. and\/or applicable 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\npackage v1beta1\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\thabv1beta1 \"github.com\/habitat-sh\/habitat-operator\/pkg\/apis\/habitat\/v1beta1\"\n\tutils \"github.com\/habitat-sh\/habitat-operator\/test\/e2e\/v1beta1\/framework\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n)\n\nconst (\n\tserviceStartupWaitTime = 1 * time.Minute\n\tsecretUpdateTimeout    = 2 * time.Minute\n\tsecretUpdateQueryTime  = 10 * time.Second\n\n\tconfigMapName = \"peer-watch-file\"\n)\n\n\/\/ TestBind tests that the operator correctly created two Habitat Services and bound them together.\nfunc TestBind(t *testing.T) {\n\t\/\/ Get Habitat object from Habitat go example.\n\tweb, err := utils.ConvertHabitat(\"resources\/bind-config\/webapp.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(web); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Get Habitat object from Habitat db example.\n\tdb, err := utils.ConvertHabitat(\"resources\/bind-config\/db.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(db); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Get Service object from example file.\n\tsvc, err := utils.ConvertService(\"resources\/bind-config\/service.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Create Service.\n\t_, err = framework.KubeClient.CoreV1().Services(utils.TestNs).Create(svc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Delete Service so it doesn't interfere with other tests.\n\tdefer (func(name string) {\n\t\tif err := framework.DeleteService(name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})(svc.Name)\n\n\t\/\/ Get Secret object from example file.\n\tsec, err := utils.ConvertSecret(\"resources\/bind-config\/secret.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Create Secret.\n\tsec, err = framework.KubeClient.CoreV1().Secrets(utils.TestNs).Create(sec)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be ready.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, web.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, db.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait until endpoints are ready.\n\tif err := framework.WaitForEndpoints(svc.ObjectMeta.Name); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttime.Sleep(serviceStartupWaitTime)\n\n\t\/\/ Get response from Habitat Service.\n\turl := fmt.Sprintf(\"http:\/\/%s:30001\/\", framework.ExternalIP)\n\n\tbody, err := utils.QueryService(url)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ This msg is set in the config of the habitat\/bindgo-hab Go Habitat Service.\n\texpectedMsg := \"hello from port: 4444\"\n\tactualMsg := body\n\t\/\/ actualMsg can contain whitespace and newlines or different formatting,\n\t\/\/ the only thing we need to check is it contains the expectedMsg.\n\tif !strings.Contains(actualMsg, expectedMsg) {\n\t\tt.Fatalf(\"Habitat Service msg does not match one in default.toml. Expected: \\\"%s\\\", got: \\\"%s\\\"\", expectedMsg, actualMsg)\n\t}\n\n\t\/\/ Test `user.toml` updates.\n\n\t\/\/ Update secret.\n\tnewPort := \"port = 6333\"\n\n\tsec.Data[\"user.toml\"] = []byte(newPort)\n\tif _, err = framework.KubeClient.CoreV1().Secrets(utils.TestNs).Update(sec); err != nil {\n\t\tt.Fatalf(\"Could not update Secret: \\\"%s\\\"\", err)\n\t}\n\n\t\/\/ Wait for SecretVolume to be updated.\n\tticker := time.NewTicker(secretUpdateQueryTime)\n\tdefer ticker.Stop()\n\ttimer := time.NewTimer(secretUpdateTimeout)\n\tdefer timer.Stop()\n\n\t\/\/ Update the message set in the config of the habitat\/bindgo-hab Go Habitat Service.\n\texpectedMsg = fmt.Sprintf(\"hello from port: %v\", 6333)\n\tfor {\n\t\t\/\/ Check that the port differs after the update.\n\t\tactualMsg, err := utils.QueryService(url)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t\/\/ actualMsg can contain whitespace and newlines or different formatting,\n\t\t\/\/ the only thing we need to check is it contains the expectedMsg.\n\t\tif strings.Contains(actualMsg, expectedMsg) {\n\t\t\tbreak\n\t\t}\n\n\t\tfail := func() {\n\t\t\tt.Fatalf(\"Configuration update did not go through. Expected: \\\"%s\\\", got: \\\"%s\\\"\", expectedMsg, actualMsg)\n\t\t}\n\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tfail()\n\t\tcase <-ticker.C:\n\t\t\t\/\/ This is to avoid infinite loops when go\n\t\t\t\/\/ decides to always pick the ticker channel,\n\t\t\t\/\/ even when timer channel is ready too.\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tfail()\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ TestHabitatDelete tests Habitat deletion.\nfunc TestHabitatDelete(t *testing.T) {\n\t\/\/ Get Habitat object from Habitat go example.\n\thabitat, err := utils.ConvertHabitat(\"resources\/standalone\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(habitat); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be ready.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, habitat.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Delete Habitat.\n\tif err := framework.DeleteHabitat(habitat.ObjectMeta.Name); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be deleted.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, habitat.ObjectMeta.Name, 0); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check if all the resources the operator creates are deleted.\n\t\/\/ We do not care about secrets being deleted, as the user needs to delete those manually.\n\td, err := framework.KubeClient.AppsV1beta1().Deployments(utils.TestNs).Get(habitat.ObjectMeta.Name, metav1.GetOptions{})\n\tif err == nil && d != nil {\n\t\tt.Fatal(\"Deployment was not deleted.\")\n\t}\n\n\t\/\/ The CM with the peer IP should still be alive, despite the Habitat being deleted as it was created outside of the scope of a Habitat.\n\t_, err = framework.KubeClient.CoreV1().ConfigMaps(utils.TestNs).Get(configMapName, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPersistentStorage(t *testing.T) {\n\t\/\/ We run minikube in a VM on Travis. In that environment, we cannot create PersistentVolumes.\n\tt.Skip(\"This test cannot be run successfully in our current testing setup\")\n\n\tephemeral, err := utils.ConvertHabitat(\"resources\/standalone\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tpersisted, err := utils.ConvertHabitat(\"resources\/persisted\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(ephemeral); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(persisted); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Delete all PVCs at the end of the test.\n\t\/\/ For dynamically provisioned PVs (as is the case on minikube), this will\n\t\/\/ also delete the PVs.\n\tdefer (func(name string) {\n\t\tls := labels.SelectorFromSet(labels.Set(map[string]string{\n\t\t\thabv1beta1.HabitatNameLabel: name,\n\t\t}))\n\n\t\tlo := metav1.ListOptions{\n\t\t\tLabelSelector: ls.String(),\n\t\t}\n\n\t\terr := framework.KubeClient.CoreV1().PersistentVolumeClaims(utils.TestNs).DeleteCollection(&metav1.DeleteOptions{}, lo)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})(persisted.Name)\n\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, persisted.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Test that persistence is only enabled if requested\n\tephemeralSTS, err := framework.KubeClient.AppsV1beta1().StatefulSets(utils.TestNs).Get(ephemeral.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(ephemeralSTS.Spec.VolumeClaimTemplates) != 0 {\n\t\tt.Fatal(\"PersistentVolumeClaims created for ephemeral StatefulSet\")\n\t}\n\n\tpersistedSTS, err := framework.KubeClient.AppsV1beta1().StatefulSets(utils.TestNs).Get(persisted.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(persistedSTS.Spec.VolumeClaimTemplates) == 0 {\n\t\tt.Fatal(\"No PersistentVolumeClaims created for persistent StatefulSet\")\n\t}\n}\n<commit_msg>e2e\/v1beta1: Add test for v1beta1 CustomVersion<commit_after>\/\/ Copyright (c) 2017 Chef Software Inc. and\/or applicable 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\npackage v1beta1\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\thabv1beta1 \"github.com\/habitat-sh\/habitat-operator\/pkg\/apis\/habitat\/v1beta1\"\n\tutils \"github.com\/habitat-sh\/habitat-operator\/test\/e2e\/v1beta1\/framework\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n)\n\nconst (\n\tserviceStartupWaitTime = 1 * time.Minute\n\tsecretUpdateTimeout    = 2 * time.Minute\n\tsecretUpdateQueryTime  = 10 * time.Second\n\n\tconfigMapName = \"peer-watch-file\"\n)\n\n\/\/ TestBind tests that the operator correctly created two Habitat Services and bound them together.\nfunc TestBind(t *testing.T) {\n\t\/\/ Get Habitat object from Habitat go example.\n\tweb, err := utils.ConvertHabitat(\"resources\/bind-config\/webapp.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(web); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Get Habitat object from Habitat db example.\n\tdb, err := utils.ConvertHabitat(\"resources\/bind-config\/db.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(db); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Get Service object from example file.\n\tsvc, err := utils.ConvertService(\"resources\/bind-config\/service.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Create Service.\n\t_, err = framework.KubeClient.CoreV1().Services(utils.TestNs).Create(svc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Delete Service so it doesn't interfere with other tests.\n\tdefer (func(name string) {\n\t\tif err := framework.DeleteService(name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})(svc.Name)\n\n\t\/\/ Get Secret object from example file.\n\tsec, err := utils.ConvertSecret(\"resources\/bind-config\/secret.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Create Secret.\n\tsec, err = framework.KubeClient.CoreV1().Secrets(utils.TestNs).Create(sec)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be ready.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, web.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, db.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait until endpoints are ready.\n\tif err := framework.WaitForEndpoints(svc.ObjectMeta.Name); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ttime.Sleep(serviceStartupWaitTime)\n\n\t\/\/ Get response from Habitat Service.\n\turl := fmt.Sprintf(\"http:\/\/%s:30001\/\", framework.ExternalIP)\n\n\tbody, err := utils.QueryService(url)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ This msg is set in the config of the habitat\/bindgo-hab Go Habitat Service.\n\texpectedMsg := \"hello from port: 4444\"\n\tactualMsg := body\n\t\/\/ actualMsg can contain whitespace and newlines or different formatting,\n\t\/\/ the only thing we need to check is it contains the expectedMsg.\n\tif !strings.Contains(actualMsg, expectedMsg) {\n\t\tt.Fatalf(\"Habitat Service msg does not match one in default.toml. Expected: \\\"%s\\\", got: \\\"%s\\\"\", expectedMsg, actualMsg)\n\t}\n\n\t\/\/ Test `user.toml` updates.\n\n\t\/\/ Update secret.\n\tnewPort := \"port = 6333\"\n\n\tsec.Data[\"user.toml\"] = []byte(newPort)\n\tif _, err = framework.KubeClient.CoreV1().Secrets(utils.TestNs).Update(sec); err != nil {\n\t\tt.Fatalf(\"Could not update Secret: \\\"%s\\\"\", err)\n\t}\n\n\t\/\/ Wait for SecretVolume to be updated.\n\tticker := time.NewTicker(secretUpdateQueryTime)\n\tdefer ticker.Stop()\n\ttimer := time.NewTimer(secretUpdateTimeout)\n\tdefer timer.Stop()\n\n\t\/\/ Update the message set in the config of the habitat\/bindgo-hab Go Habitat Service.\n\texpectedMsg = fmt.Sprintf(\"hello from port: %v\", 6333)\n\tfor {\n\t\t\/\/ Check that the port differs after the update.\n\t\tactualMsg, err := utils.QueryService(url)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t\/\/ actualMsg can contain whitespace and newlines or different formatting,\n\t\t\/\/ the only thing we need to check is it contains the expectedMsg.\n\t\tif strings.Contains(actualMsg, expectedMsg) {\n\t\t\tbreak\n\t\t}\n\n\t\tfail := func() {\n\t\t\tt.Fatalf(\"Configuration update did not go through. Expected: \\\"%s\\\", got: \\\"%s\\\"\", expectedMsg, actualMsg)\n\t\t}\n\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tfail()\n\t\tcase <-ticker.C:\n\t\t\t\/\/ This is to avoid infinite loops when go\n\t\t\t\/\/ decides to always pick the ticker channel,\n\t\t\t\/\/ even when timer channel is ready too.\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tfail()\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ TestHabitatDelete tests Habitat deletion.\nfunc TestHabitatDelete(t *testing.T) {\n\t\/\/ Get Habitat object from Habitat go example.\n\thabitat, err := utils.ConvertHabitat(\"resources\/standalone\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(habitat); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be ready.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, habitat.ObjectMeta.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Delete Habitat.\n\tif err := framework.DeleteHabitat(habitat.ObjectMeta.Name); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Wait for resources to be deleted.\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, habitat.ObjectMeta.Name, 0); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check if all the resources the operator creates are deleted.\n\t\/\/ We do not care about secrets being deleted, as the user needs to delete those manually.\n\td, err := framework.KubeClient.AppsV1beta1().Deployments(utils.TestNs).Get(habitat.ObjectMeta.Name, metav1.GetOptions{})\n\tif err == nil && d != nil {\n\t\tt.Fatal(\"Deployment was not deleted.\")\n\t}\n\n\t\/\/ The CM with the peer IP should still be alive, despite the Habitat being deleted as it was created outside of the scope of a Habitat.\n\t_, err = framework.KubeClient.CoreV1().ConfigMaps(utils.TestNs).Get(configMapName, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPersistentStorage(t *testing.T) {\n\t\/\/ We run minikube in a VM on Travis. In that environment, we cannot create PersistentVolumes.\n\tt.Skip(\"This test cannot be run successfully in our current testing setup\")\n\n\tephemeral, err := utils.ConvertHabitat(\"resources\/standalone\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tpersisted, err := utils.ConvertHabitat(\"resources\/persisted\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(ephemeral); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := framework.CreateHabitat(persisted); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Delete all PVCs at the end of the test.\n\t\/\/ For dynamically provisioned PVs (as is the case on minikube), this will\n\t\/\/ also delete the PVs.\n\tdefer (func(name string) {\n\t\tls := labels.SelectorFromSet(labels.Set(map[string]string{\n\t\t\thabv1beta1.HabitatNameLabel: name,\n\t\t}))\n\n\t\tlo := metav1.ListOptions{\n\t\t\tLabelSelector: ls.String(),\n\t\t}\n\n\t\terr := framework.KubeClient.CoreV1().PersistentVolumeClaims(utils.TestNs).DeleteCollection(&metav1.DeleteOptions{}, lo)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t})(persisted.Name)\n\n\tif err := framework.WaitForResources(habv1beta1.HabitatNameLabel, persisted.Name, 1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Test that persistence is only enabled if requested\n\tephemeralSTS, err := framework.KubeClient.AppsV1beta1().StatefulSets(utils.TestNs).Get(ephemeral.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(ephemeralSTS.Spec.VolumeClaimTemplates) != 0 {\n\t\tt.Fatal(\"PersistentVolumeClaims created for ephemeral StatefulSet\")\n\t}\n\n\tpersistedSTS, err := framework.KubeClient.AppsV1beta1().StatefulSets(utils.TestNs).Get(persisted.Name, metav1.GetOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(persistedSTS.Spec.VolumeClaimTemplates) == 0 {\n\t\tt.Fatal(\"No PersistentVolumeClaims created for persistent StatefulSet\")\n\t}\n}\n\nfunc TestV1beta1(t *testing.T) {\n\th, err := utils.ConvertHabitat(\"resources\/standalone\/habitat.yml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tv := \"v1beta1\"\n\th.CustomVersion = &v\n\n\tif err := framework.CreateHabitat(h); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := framework.KubeClient.AppsV1beta1().Deployments(utils.TestNs).Get(h.Name, metav1.GetOptions{}); err != nil {\n\t\tt.Fatal(\"Could not retrieve Deployment\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package buffalo\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/gobuffalo\/buffalo\/render\"\n\t\"github.com\/gobuffalo\/httptest\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ Test_App_Use tests that middleware gets added\nfunc Test_App_Use(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\ta.Use(func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"end\")\n\t\t\treturn err\n\t\t}\n\t})\n\n\ta.GET(\"\/\", func(c Context) error {\n\t\tlog = append(log, \"handler\")\n\t\treturn nil\n\t})\n\n\tw := httptest.New(a)\n\tw.HTML(\"\/\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"start\", \"handler\", \"end\"}, log)\n}\n\n\/\/ Test_Middleware_Replace tests that middleware gets added\nfunc Test_Middleware_Replace(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"m1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"m1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\tmw2 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"m2 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"m2 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\ta.Use(mw1)\n\ta.Middleware.Replace(mw1, mw2)\n\n\ta.GET(\"\/\", func(c Context) error {\n\t\tlog = append(log, \"handler\")\n\t\treturn nil\n\t})\n\n\tw := httptest.New(a)\n\tw.HTML(\"\/\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"m2 start\", \"handler\", \"m2 end\"}, log)\n}\n\n\/\/ Test_Middleware_Skip tests that middleware gets skipped\nfunc Test_Middleware_Skip(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\tmw2 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw2 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw2 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\ta.Use(mw1)\n\ta.Use(mw2)\n\n\th1 := func(c Context) error {\n\t\tlog = append(log, \"h1\")\n\t\treturn nil\n\t}\n\th2 := func(c Context) error {\n\t\tlog = append(log, \"h2\")\n\t\treturn nil\n\t}\n\n\ta.GET(\"\/h1\", h1)\n\ta.GET(\"\/h2\", h2)\n\n\ta.Middleware.Skip(mw2, h2)\n\n\tw := httptest.New(a)\n\n\tw.HTML(\"\/h2\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"mw1 start\", \"h2\", \"mw1 end\"}, log)\n\n\tlog = []string{}\n\tw.HTML(\"\/h1\").Get()\n\tr.Len(log, 5)\n\tr.Equal([]string{\"mw1 start\", \"mw2 start\", \"h1\", \"mw2 end\", \"mw1 end\"}, log)\n}\n\ntype carsResource struct {\n\tResource\n}\n\nfunc (ur *carsResource) Show(c Context) error {\n\treturn c.Render(http.StatusOK, render.String(\"show\"))\n}\n\nfunc (ur *carsResource) List(c Context) error {\n\treturn c.Render(http.StatusOK, render.String(\"list\"))\n}\n\n\/\/ Test_Middleware_Skip tests that middleware gets skipped\nfunc Test_Middleware_Skip_Resource(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\ta := New(Options{})\n\tvar cr Resource = &carsResource{}\n\tg := a.Resource(\"\/autos\", cr)\n\tg.Use(mw1)\n\n\tvar ur Resource = &carsResource{}\n\tg = a.Resource(\"\/cars\", ur)\n\tg.Use(mw1)\n\n\t\/\/ fmt.Println(\"set up skip\")\n\tg.Middleware.Skip(mw1, ur.Show)\n\n\tw := httptest.New(a)\n\n\t\/\/ fmt.Println(\"make autos call\")\n\tlog = []string{}\n\tres := w.HTML(\"\/autos\/1\").Get()\n\tr.Len(log, 2)\n\tr.Equal(\"show\", res.Body.String())\n\n\t\/\/ fmt.Println(\"make list call\")\n\tlog = []string{}\n\tres = w.HTML(\"\/cars\").Get()\n\tr.Len(log, 2)\n\tr.Equal([]string{\"mw1 start\", \"mw1 end\"}, log)\n\tr.Equal(\"list\", res.Body.String())\n\n\t\/\/ fmt.Println(\"make show call\")\n\tlog = []string{}\n\tres = w.HTML(\"\/cars\/1\").Get()\n\tr.Len(log, 0)\n\tr.Equal(\"show\", res.Body.String())\n\n}\n\n\/\/ Test_Middleware_Clear confirms that middle gets cleared\nfunc Test_Middleware_Clear(t *testing.T) {\n\tr := require.New(t)\n\tmws := newMiddlewareStack()\n\tmw := func(h Handler) Handler { return h }\n\tmws.Use(mw)\n\tmws.Skip(mw, voidHandler)\n\n\tr.Len(mws.stack, 1)\n\tr.Len(mws.skips, 1)\n\n\tmws.Clear()\n\n\tr.Len(mws.stack, 0)\n\tr.Len(mws.skips, 0)\n}\n\nfunc Test_Middleware_Remove(t *testing.T) {\n\tr := require.New(t)\n\tlog := []string{}\n\n\tmw1 := func(h Handler) Handler {\n\t\tlog = append(log, \"mw1\")\n\t\treturn h\n\t}\n\n\tmw2 := func(h Handler) Handler {\n\t\tlog = append(log, \"mw2\")\n\t\treturn h\n\t}\n\n\ta := New(Options{})\n\ta.Use(mw2)\n\ta.Use(mw1)\n\n\tvar cr Resource = &carsResource{}\n\tg := a.Resource(\"\/autos\", cr)\n\tg.Middleware.Remove(mw2)\n\n\ta.Resource(\"\/all_log_autos\", cr)\n\tw := httptest.New(a)\n\n\tng := a.Resource(\"\/no_log_autos\", cr)\n\tng.Middleware.Remove(mw1, mw2)\n\n\t_ = w.HTML(\"\/autos\/1\").Get()\n\tr.Len(log, 1)\n\tr.Equal(\"mw1\", log[0])\n\n\tlog = []string{}\n\t_ = w.HTML(\"\/all_log_autos\/1\").Get()\n\tr.Len(log, 2)\n\tr.Contains(log, \"mw2\")\n\tr.Contains(log, \"mw1\")\n\n\tlog = []string{}\n\t_ = w.HTML(\"\/no_log_autos\/1\").Get()\n\tr.Len(log, 0)\n}\n<commit_msg>added test cases for status checking<commit_after>package buffalo\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/gobuffalo\/buffalo\/render\"\n\t\"github.com\/gobuffalo\/httptest\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ Test_App_Use tests that middleware gets added\nfunc Test_App_Use(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\ta.Use(func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"end\")\n\t\t\treturn err\n\t\t}\n\t})\n\n\ta.GET(\"\/\", func(c Context) error {\n\t\tlog = append(log, \"handler\")\n\t\treturn nil\n\t})\n\n\tw := httptest.New(a)\n\tw.HTML(\"\/\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"start\", \"handler\", \"end\"}, log)\n}\n\n\/\/ Test_Middleware_Replace tests that middleware gets added\nfunc Test_Middleware_Replace(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"m1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"m1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\tmw2 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"m2 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"m2 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\ta.Use(mw1)\n\ta.Middleware.Replace(mw1, mw2)\n\n\ta.GET(\"\/\", func(c Context) error {\n\t\tlog = append(log, \"handler\")\n\t\treturn nil\n\t})\n\n\tw := httptest.New(a)\n\tw.HTML(\"\/\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"m2 start\", \"handler\", \"m2 end\"}, log)\n}\n\n\/\/ Test_Middleware_Skip tests that middleware gets skipped\nfunc Test_Middleware_Skip(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\ta := New(Options{})\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\tmw2 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw2 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw2 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\ta.Use(mw1)\n\ta.Use(mw2)\n\n\th1 := func(c Context) error {\n\t\tlog = append(log, \"h1\")\n\t\treturn nil\n\t}\n\th2 := func(c Context) error {\n\t\tlog = append(log, \"h2\")\n\t\treturn nil\n\t}\n\n\ta.GET(\"\/h1\", h1)\n\ta.GET(\"\/h2\", h2)\n\n\ta.Middleware.Skip(mw2, h2)\n\n\tw := httptest.New(a)\n\n\tw.HTML(\"\/h2\").Get()\n\tr.Len(log, 3)\n\tr.Equal([]string{\"mw1 start\", \"h2\", \"mw1 end\"}, log)\n\n\tlog = []string{}\n\tw.HTML(\"\/h1\").Get()\n\tr.Len(log, 5)\n\tr.Equal([]string{\"mw1 start\", \"mw2 start\", \"h1\", \"mw2 end\", \"mw1 end\"}, log)\n}\n\ntype carsResource struct {\n\tResource\n}\n\nfunc (ur *carsResource) Show(c Context) error {\n\treturn c.Render(http.StatusOK, render.String(\"show\"))\n}\n\nfunc (ur *carsResource) List(c Context) error {\n\treturn c.Render(http.StatusOK, render.String(\"list\"))\n}\n\n\/\/ Test_Middleware_Skip tests that middleware gets skipped\nfunc Test_Middleware_Skip_Resource(t *testing.T) {\n\tr := require.New(t)\n\n\tlog := []string{}\n\tmw1 := func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\tlog = append(log, \"mw1 start\")\n\t\t\terr := h(c)\n\t\t\tlog = append(log, \"mw1 end\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\ta := New(Options{})\n\tvar cr Resource = &carsResource{}\n\tg := a.Resource(\"\/autos\", cr)\n\tg.Use(mw1)\n\n\tvar ur Resource = &carsResource{}\n\tg = a.Resource(\"\/cars\", ur)\n\tg.Use(mw1)\n\n\t\/\/ fmt.Println(\"set up skip\")\n\tg.Middleware.Skip(mw1, ur.Show)\n\n\tw := httptest.New(a)\n\n\t\/\/ fmt.Println(\"make autos call\")\n\tlog = []string{}\n\tres := w.HTML(\"\/autos\/1\").Get()\n\tr.Len(log, 2)\n\tr.Equal(\"show\", res.Body.String())\n\n\t\/\/ fmt.Println(\"make list call\")\n\tlog = []string{}\n\tres = w.HTML(\"\/cars\").Get()\n\tr.Len(log, 2)\n\tr.Equal([]string{\"mw1 start\", \"mw1 end\"}, log)\n\tr.Equal(\"list\", res.Body.String())\n\n\t\/\/ fmt.Println(\"make show call\")\n\tlog = []string{}\n\tres = w.HTML(\"\/cars\/1\").Get()\n\tr.Len(log, 0)\n\tr.Equal(\"show\", res.Body.String())\n\n}\n\n\/\/ Test_Middleware_Clear confirms that middle gets cleared\nfunc Test_Middleware_Clear(t *testing.T) {\n\tr := require.New(t)\n\tmws := newMiddlewareStack()\n\tmw := func(h Handler) Handler { return h }\n\tmws.Use(mw)\n\tmws.Skip(mw, voidHandler)\n\n\tr.Len(mws.stack, 1)\n\tr.Len(mws.skips, 1)\n\n\tmws.Clear()\n\n\tr.Len(mws.stack, 0)\n\tr.Len(mws.skips, 0)\n}\n\nfunc Test_Middleware_Remove(t *testing.T) {\n\tr := require.New(t)\n\tlog := []string{}\n\n\tmw1 := func(h Handler) Handler {\n\t\tlog = append(log, \"mw1\")\n\t\treturn h\n\t}\n\n\tmw2 := func(h Handler) Handler {\n\t\tlog = append(log, \"mw2\")\n\t\treturn h\n\t}\n\n\ta := New(Options{})\n\ta.Use(mw2)\n\ta.Use(mw1)\n\n\tvar cr Resource = &carsResource{}\n\tg := a.Resource(\"\/autos\", cr)\n\tg.Middleware.Remove(mw2)\n\n\ta.Resource(\"\/all_log_autos\", cr)\n\tw := httptest.New(a)\n\n\tng := a.Resource(\"\/no_log_autos\", cr)\n\tng.Middleware.Remove(mw1, mw2)\n\n\t_ = w.HTML(\"\/autos\/1\").Get()\n\tr.Len(log, 1)\n\tr.Equal(\"mw1\", log[0])\n\n\tlog = []string{}\n\t_ = w.HTML(\"\/all_log_autos\/1\").Get()\n\tr.Len(log, 2)\n\tr.Contains(log, \"mw2\")\n\tr.Contains(log, \"mw1\")\n\n\tlog = []string{}\n\t_ = w.HTML(\"\/no_log_autos\/1\").Get()\n\tr.Len(log, 0)\n}\n\nfunc Test_AssertMiddleware_NilStatus200(t *testing.T) {\n\tr := require.New(t)\n\tvar status int\n\n\ta := New(Options{})\n\ta.Use(func(h Handler) Handler {\n\t\treturn func(c Context) error {\n\t\t\terr := h(c)\n\n\t\t\tres, ok := c.Response().(*Response)\n\t\t\tr.True(ok)\n\t\t\tstatus = res.Status\n\n\t\t\treturn err\n\t\t}\n\t})\n\n\ta.GET(\"\/200\", func(c Context) error {\n\t\tc.Response().WriteHeader(http.StatusOK) \/\/ explicitly set\n\t\treturn nil\n\t})\n\n\ta.GET(\"\/404\", func(c Context) error {\n\t\tc.Response().WriteHeader(http.StatusNotFound) \/\/explicitly set\n\t\treturn nil\n\t})\n\n\ta.GET(\"\/nil\", func(c Context) error {\n\t\treturn nil \/\/ return nil without setting response status. should be OK\n\t})\n\n\ta.GET(\"\/500\", func(c Context) error {\n\t\treturn fmt.Errorf(\"error\") \/\/ return error\n\t})\n\n\ta.GET(\"\/502\", func(c Context) error {\n\t\treturn HTTPError{Status: http.StatusBadGateway} \/\/ return HTTPError\n\t})\n\n\ta.GET(\"\/panic\", func(c Context) error {\n\t\tpanic(\"hoy hoy\")\n\t})\n\n\ttests := []struct {\n\t\tpath   string\n\t\tcode   int\n\t\tstatus int\n\t}{\n\t\t{\"\/200\", http.StatusOK, http.StatusOK}, \/\/ when the handler set response code explicitly (e.g. 200, 404)\n\t\t{\"\/404\", http.StatusNotFound, http.StatusNotFound},\n\t\t{\"\/nil\", http.StatusOK, http.StatusOK},        \/\/ when the handler returns nil without setting status code\n\t\t{\"\/502\", http.StatusBadGateway, 0},            \/\/ set by defaultErrorHandler, when the handler just returns error\n\t\t{\"\/500\", http.StatusInternalServerError, 0},   \/\/ set by defaultErrorHandler, when the handler returns HTTPError\n\t\t{\"\/panic\", http.StatusInternalServerError, 0}, \/\/ set by PanicHandler\n\t}\n\tw := httptest.New(a)\n\n\tfor _, tc := range tests {\n\t\tres := w.HTML(tc.path).Get()\n\t\tr.Equal(tc.status, status)\n\t\tr.Equal(tc.code, res.Code)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\tp0 \".\/bug0\"\n\tp1 \".\/bug1\"\n)\n\n\/\/ both p0.T and p1.T are struct { X, Y int }.\n\nvar v0 p0.T\nvar v1 p1.T\n\n\/\/ interfaces involving the two\n\ntype I0 interface {\n\tM(p0.T)\n}\n\ntype I1 interface {\n\tM(p1.T)\n}\n\n\/\/ t0 satisfies I0 and p0.I\ntype t0 int\n\nfunc (t0) M(p0.T) {}\n\n\/\/ t1 satisfies I1 and p1.I\ntype t1 float\n\nfunc (t1) M(p1.T) {}\n\n\/\/ check static interface assignments\nvar i0 I0 = t0(0) \/\/ ok\nvar i1 I1 = t1(0) \/\/ ok\n\nvar i2 I0 = t1(0) \/\/ ERROR \"is not\"\nvar i3 I1 = t0(0) \/\/ ERROR \"is not\"\n\nvar p0i p0.I = t0(0) \/\/ ok\nvar p1i p1.I = t1(0) \/\/ ok\n\nvar p0i1 p0.I = t1(0) \/\/ ERROR \"is not\"\nvar p0i2 p1.I = t0(0) \/\/ ERROR \"is not\"\n\nfunc main() {\n\t\/\/ check that cannot assign one to the other,\n\t\/\/ but can convert.\n\tv0 = v1 \/\/ ERROR \"assign\"\n\tv1 = v0 \/\/ ERROR \"assign\"\n\n\tv0 = p0.T(v1)\n\tv1 = p1.T(v0)\n\n\ti0 = i1   \/\/ ERROR \"need type assertion\"\n\ti1 = i0   \/\/ ERROR \"need type assertion\"\n\tp0i = i1  \/\/ ERROR \"need type assertion\"\n\tp1i = i0  \/\/ ERROR \"need type assertion\"\n\ti0 = p1i  \/\/ ERROR \"need type assertion\"\n\ti1 = p0i  \/\/ ERROR \"need type assertion\"\n\tp0i = p1i \/\/ ERROR \"need type assertion\"\n\tp1i = p0i \/\/ ERROR \"need type assertion\"\n\n\ti0 = p0i\n\tp0i = i0\n\n\ti1 = p1i\n\tp1i = i1\n}\n<commit_msg>Match gccgo error messages.<commit_after>package main\n\nimport (\n\tp0 \".\/bug0\"\n\tp1 \".\/bug1\"\n)\n\n\/\/ both p0.T and p1.T are struct { X, Y int }.\n\nvar v0 p0.T\nvar v1 p1.T\n\n\/\/ interfaces involving the two\n\ntype I0 interface {\n\tM(p0.T)\n}\n\ntype I1 interface {\n\tM(p1.T)\n}\n\n\/\/ t0 satisfies I0 and p0.I\ntype t0 int\n\nfunc (t0) M(p0.T) {}\n\n\/\/ t1 satisfies I1 and p1.I\ntype t1 float\n\nfunc (t1) M(p1.T) {}\n\n\/\/ check static interface assignments\nvar i0 I0 = t0(0) \/\/ ok\nvar i1 I1 = t1(0) \/\/ ok\n\nvar i2 I0 = t1(0) \/\/ ERROR \"is not|incompatible\"\nvar i3 I1 = t0(0) \/\/ ERROR \"is not|incompatible\"\n\nvar p0i p0.I = t0(0) \/\/ ok\nvar p1i p1.I = t1(0) \/\/ ok\n\nvar p0i1 p0.I = t1(0) \/\/ ERROR \"is not|incompatible\"\nvar p0i2 p1.I = t0(0) \/\/ ERROR \"is not|incompatible\"\n\nfunc main() {\n\t\/\/ check that cannot assign one to the other,\n\t\/\/ but can convert.\n\tv0 = v1 \/\/ ERROR \"assign\"\n\tv1 = v0 \/\/ ERROR \"assign\"\n\n\tv0 = p0.T(v1)\n\tv1 = p1.T(v0)\n\n\ti0 = i1   \/\/ ERROR \"need type assertion|incompatible\"\n\ti1 = i0   \/\/ ERROR \"need type assertion|incompatible\"\n\tp0i = i1  \/\/ ERROR \"need type assertion|incompatible\"\n\tp1i = i0  \/\/ ERROR \"need type assertion|incompatible\"\n\ti0 = p1i  \/\/ ERROR \"need type assertion|incompatible\"\n\ti1 = p0i  \/\/ ERROR \"need type assertion|incompatible\"\n\tp0i = p1i \/\/ ERROR \"need type assertion|incompatible\"\n\tp1i = p0i \/\/ ERROR \"need type assertion|incompatible\"\n\n\ti0 = p0i\n\tp0i = i0\n\n\ti1 = p1i\n\tp1i = i1\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/etsnunix implements an interface similar to etsn, but for listening\n\/\/for connections on a unix socket provided by the etsnsrv command.\npackage etsnunix\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/JImmyFrasche\/etsn\"\n\t\"github.com\/goerlang\/fd\"\n)\n\n\/\/Server encapsulates the state of an etsnsrv listener.\ntype Server struct {\n\tdir string\n\tlog func(error)\n}\n\n\/\/New creates a new server that advertises its protocols at dir.\n\/\/\n\/\/logger is called whenever there's an error establishing a connection\n\/\/within Listen. Note that the error may be nil.\n\/\/If logger is nil, a no op logger is used.\nfunc New(dir string, logger func(error)) *Server {\n\tif logger == nil {\n\t\tlogger = func(error) {}\n\t}\n\treturn &Server{\n\t\tdir: dir,\n\t\tlog: logger,\n\t}\n}\n\n\/\/Listen advertises a single protocol, proto, in the directory the server\n\/\/was created with. It will invoke handler in a new goroutine every time\n\/\/a fd representing a tcp socket is sent down the unix domain socket\n\/\/created at dir\/proto by an instance of etnsrv on dir.\n\/\/\n\/\/Warning: if there is an existing file named dir\/proto it will be deleted.\n\/\/\n\/\/It is safe to call multiple times on same server, with different proto.\nfunc (s *Server) Listen(proto string, handler func(*net.TCPConn) error) error {\n\tif len(proto) > 255 {\n\t\treturn etsn.ErrProtocolIdentifierTooLong\n\t}\n\tnm := filepath.Join(s.dir, proto)\n\tif err := os.Remove(nm); err != nil {\n\t\treturn err\n\t}\n\tc, err := net.Dial(\"unix\", nm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconn := c.(*net.UnixConn)\n\tfor {\n\t\tfs, err := fd.Get(conn, 1, nil)\n\t\tif err != nil {\n\t\t\t\/\/BUG(jmf) There are surely many an error that should lead to\n\t\t\t\/\/us breaking out of the listen loop. For example if another\n\t\t\t\/\/process deletes our socket\n\t\t\ts.log(err)\n\t\t\tcontinue\n\t\t}\n\t\tif len(fs) != 1 {\n\t\t\ts.log(errors.New(\"Did not receive exactly one fd\"))\n\t\t\tcontinue\n\t\t}\n\t\tf := fs[0]\n\t\tic, err := net.FileConn(f)\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\ts.log(err)\n\t\t\tcontinue\n\t\t}\n\t\ts.log(f.Close())\n\t\ttcp, ok := ic.(*net.TCPConn)\n\t\tif !ok {\n\t\t\ts.log(errors.New(\"Received invalid socket type\"))\n\t\t\tic.Close()\n\t\t\tcontinue\n\t\t}\n\t\tgo func() {\n\t\t\ts.log(handler(tcp))\n\t\t}()\n\t}\n}\n<commit_msg>os.Remove returns file not found error<commit_after>\/\/etsnunix implements an interface similar to etsn, but for listening\n\/\/for connections on a unix socket provided by the etsnsrv command.\npackage etsnunix\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/JImmyFrasche\/etsn\"\n\t\"github.com\/goerlang\/fd\"\n)\n\n\/\/Server encapsulates the state of an etsnsrv listener.\ntype Server struct {\n\tdir string\n\tlog func(error)\n}\n\n\/\/New creates a new server that advertises its protocols at dir.\n\/\/\n\/\/logger is called whenever there's an error establishing a connection\n\/\/within Listen. Note that the error may be nil.\n\/\/If logger is nil, a no op logger is used.\nfunc New(dir string, logger func(error)) *Server {\n\tif logger == nil {\n\t\tlogger = func(error) {}\n\t}\n\treturn &Server{\n\t\tdir: dir,\n\t\tlog: logger,\n\t}\n}\n\n\/\/Listen advertises a single protocol, proto, in the directory the server\n\/\/was created with. It will invoke handler in a new goroutine every time\n\/\/a fd representing a tcp socket is sent down the unix domain socket\n\/\/created at dir\/proto by an instance of etnsrv on dir.\n\/\/\n\/\/Warning: if there is an existing file named dir\/proto it will be deleted.\n\/\/\n\/\/It is safe to call multiple times on same server, with different proto.\nfunc (s *Server) Listen(proto string, handler func(*net.TCPConn) error) error {\n\tif len(proto) > 255 {\n\t\treturn etsn.ErrProtocolIdentifierTooLong\n\t}\n\tnm := filepath.Join(s.dir, proto)\n\tif err := os.Remove(nm); err != nil {\n\t\tpe := err.(*os.PathError)\n\t\tif pe.Err.Error() != \"no such file or directory\" {\n\t\t\treturn err\n\t\t}\n\t}\n\tc, err := net.Dial(\"unix\", nm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconn := c.(*net.UnixConn)\n\tfor {\n\t\tfs, err := fd.Get(conn, 1, nil)\n\t\tif err != nil {\n\t\t\t\/\/BUG(jmf) There are surely many an error that should lead to\n\t\t\t\/\/us breaking out of the listen loop. For example if another\n\t\t\t\/\/process deletes our socket\n\t\t\ts.log(err)\n\t\t\tcontinue\n\t\t}\n\t\tif len(fs) != 1 {\n\t\t\ts.log(errors.New(\"Did not receive exactly one fd\"))\n\t\t\tcontinue\n\t\t}\n\t\tf := fs[0]\n\t\tic, err := net.FileConn(f)\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\ts.log(err)\n\t\t\tcontinue\n\t\t}\n\t\ts.log(f.Close())\n\t\ttcp, ok := ic.(*net.TCPConn)\n\t\tif !ok {\n\t\t\ts.log(errors.New(\"Received invalid socket type\"))\n\t\t\tic.Close()\n\t\t\tcontinue\n\t\t}\n\t\tgo func() {\n\t\t\ts.log(handler(tcp))\n\t\t}()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ exaplains zookeeper session expires mechanism.\n\/\/ The code is extracted from zookeeper server code.\n\/\/\n\/\/ Session expiration is managed by the ZooKeeper cluster itself, not by the client.\n\/\/\n\/\/ When the ZK client establishes a session with the cluster it provides a \"timeout\" value.\n\/\/ This value is used by the cluster to determine when the client's session expires.\n\/\/\n\/\/ Expirations happens when the cluster does not hear from the client within the\n\/\/ specified session timeout period (i.e. no heartbeat).\n\/\/\n\/\/ At session expiration the cluster will delete any\/all ephemeral nodes owned by that session and\n\/\/ immediately notify any\/all connected clients of the change (anyone watching those znodes).\n\/\/ At this point the client of the expired session is still disconnected from the cluster, it\n\/\/ will not be notified of the session expiration until\/unless it is able to re-establish a\n\/\/ connection to the cluster.\n\/\/ The client will stay in disconnected state until the TCP connection is re-established with the\n\/\/ cluster, at which point the watcher of the expired session will receive the \"session expired\"\n\/\/ notification.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nvar (\n\ttickTime          = 3000 \/\/ zoo.cfg, default 3s\n\tminSessionTimeout = -1   \/\/ zoo.cfg\n\tmaxSessionTimeout = -1   \/\/ zoo.cfg\n)\n\nfunc getMinSessionTimeout() int {\n\tif minSessionTimeout == -1 {\n\t\treturn tickTime * 2\n\t} else {\n\t\treturn minSessionTimeout\n\t}\n}\n\nfunc getMaxSessionTimeout() int {\n\tif maxSessionTimeout == -1 {\n\t\treturn tickTime * 20\n\t} else {\n\t\treturn maxSessionTimeout\n\t}\n}\n\nfunc getRealSessionTimeout(clientSessionTimeout int) int {\n\tvar sessionTimeout = clientSessionTimeout\n\tmin, max := getMinSessionTimeout(), getMaxSessionTimeout()\n\tif sessionTimeout < min {\n\t\tsessionTimeout = min\n\t}\n\tif sessionTimeout > max {\n\t\tsessionTimeout = max\n\t}\n\n\treturn sessionTimeout\n}\n\nfunc main() {\n\tvar clientConfiggedSessionTimeout int\n\tflag.IntVar(&clientConfiggedSessionTimeout, \"c\", 30*1000, \"client side zk session timeout, which will be sent to zk for negotiation\")\n\tflag.IntVar(&tickTime, \"t\", 3000, \"tickTime in zoo.cfg\")\n\tflag.Parse()\n\n\tfmt.Printf(\"tickTime=%ds\\n\", tickTime\/1000)\n\tfmt.Printf(\"default between: %ds ~ %ds\\n\",\n\t\tgetRealSessionTimeout(-1)\/1000,\n\t\tgetRealSessionTimeout(1<<30)\/1000)\n\n\tfmt.Printf(\"client sent:%ds => got %ds\\n\",\n\t\tclientConfiggedSessionTimeout\/1000,\n\t\tgetRealSessionTimeout(clientConfiggedSessionTimeout)\/1000)\n}\n<commit_msg>update default tickTime to our production env<commit_after>\/\/ exaplains zookeeper session expires mechanism.\n\/\/ The code is extracted from zookeeper server code.\n\/\/\n\/\/ Session expiration is managed by the ZooKeeper cluster itself, not by the client.\n\/\/\n\/\/ When the ZK client establishes a session with the cluster it provides a \"timeout\" value.\n\/\/ This value is used by the cluster to determine when the client's session expires.\n\/\/\n\/\/ Expirations happens when the cluster does not hear from the client within the\n\/\/ specified session timeout period (i.e. no heartbeat).\n\/\/\n\/\/ At session expiration the cluster will delete any\/all ephemeral nodes owned by that session and\n\/\/ immediately notify any\/all connected clients of the change (anyone watching those znodes).\n\/\/ At this point the client of the expired session is still disconnected from the cluster, it\n\/\/ will not be notified of the session expiration until\/unless it is able to re-establish a\n\/\/ connection to the cluster.\n\/\/ The client will stay in disconnected state until the TCP connection is re-established with the\n\/\/ cluster, at which point the watcher of the expired session will receive the \"session expired\"\n\/\/ notification.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nvar (\n\ttickTime          = 2000 \/\/ zoo.cfg\n\tminSessionTimeout = -1   \/\/ zoo.cfg\n\tmaxSessionTimeout = -1   \/\/ zoo.cfg\n)\n\nfunc getMinSessionTimeout() int {\n\tif minSessionTimeout == -1 {\n\t\treturn tickTime * 2\n\t} else {\n\t\treturn minSessionTimeout\n\t}\n}\n\nfunc getMaxSessionTimeout() int {\n\tif maxSessionTimeout == -1 {\n\t\treturn tickTime * 20\n\t} else {\n\t\treturn maxSessionTimeout\n\t}\n}\n\nfunc getRealSessionTimeout(clientSessionTimeout int) int {\n\tvar sessionTimeout = clientSessionTimeout\n\tmin, max := getMinSessionTimeout(), getMaxSessionTimeout()\n\tif sessionTimeout < min {\n\t\tsessionTimeout = min\n\t}\n\tif sessionTimeout > max {\n\t\tsessionTimeout = max\n\t}\n\n\treturn sessionTimeout\n}\n\nfunc main() {\n\tvar clientConfiggedSessionTimeout int\n\tflag.IntVar(&clientConfiggedSessionTimeout, \"c\", 30*1000, \"client side zk session timeout, which will be sent to zk for negotiation\")\n\tflag.IntVar(&tickTime, \"t\", 2000, \"tickTime in zoo.cfg\")\n\tflag.Parse()\n\n\tfmt.Printf(\"tickTime=%ds\\n\", tickTime\/1000)\n\tfmt.Printf(\"default between: %ds ~ %ds\\n\",\n\t\tgetRealSessionTimeout(-1)\/1000,\n\t\tgetRealSessionTimeout(1<<30)\/1000)\n\n\tfmt.Printf(\"client sent:%ds => got %ds\\n\",\n\t\tclientConfiggedSessionTimeout\/1000,\n\t\tgetRealSessionTimeout(clientConfiggedSessionTimeout)\/1000)\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"errors\"\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\te \"github.com\/eirka\/eirka-libs\/errors\"\n)\n\nfunc TestAddTagIsValid(t *testing.T) {\n\n\tvar err error\n\n\ttag := AddTagModel{\n\t\tIb:    0,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tif assert.Error(t, err, \"An error was not expected\") {\n\t\tassert.Equal(t, err, errors.New(\"AddTagModel is not valid\"), \"Error should match\")\n\t}\n\n}\n\nfunc TestAddTagStatus(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n}\n\nfunc TestAddTagStatusNotFound(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tif assert.Error(t, err, \"An error was not expected\") {\n\t\tassert.Equal(t, err, e.ErrNotFound, \"Error should match\")\n\t}\n\n}\n\nfunc TestAddTagStatusDuplicate(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tif assert.Error(t, err, \"An error was not expected\") {\n\t\tassert.Equal(t, err, e.ErrDuplicateTag, \"Error should match\")\n\t}\n\n}\n\nfunc TestAddTagPost(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tmock.ExpectExec(\"INSERT into tagmap\").\n\t\tWithArgs(1, 1).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Post()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n}\n<commit_msg>add model tests<commit_after>package models\n\nimport (\n\t\"errors\"\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\te \"github.com\/eirka\/eirka-libs\/errors\"\n)\n\nfunc TestAddTagIsValid(t *testing.T) {\n\n\tvar err error\n\n\ttag := AddTagModel{\n\t\tIb:    0,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\tassert.False(t, tag.IsValid(), \"Should be false\")\n\n}\n\nfunc TestAddTagStatus(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n}\n\nfunc TestAddTagStatusNotFound(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(0)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tif assert.Error(t, err, \"An error was not expected\") {\n\t\tassert.Equal(t, err, e.ErrNotFound, \"Error should match\")\n\t}\n\n}\n\nfunc TestAddTagStatusDuplicate(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tstatusrows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`SELECT count\\(1\\) FROM images`).WillReturnRows(statusrows)\n\n\tduperows := sqlmock.NewRows([]string{\"count\"}).AddRow(1)\n\tmock.ExpectQuery(`select count\\(1\\) from tagmap`).WillReturnRows(duperows)\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Status()\n\tif assert.Error(t, err, \"An error was not expected\") {\n\t\tassert.Equal(t, err, e.ErrDuplicateTag, \"Error should match\")\n\t}\n\n}\n\nfunc TestAddTagPost(t *testing.T) {\n\n\tvar err error\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\tmock.ExpectExec(\"INSERT into tagmap\").\n\t\tWithArgs(1, 1).\n\t\tWillReturnResult(sqlmock.NewResult(1, 1))\n\n\ttag := AddTagModel{\n\t\tIb:    1,\n\t\tTag:   1,\n\t\tImage: 1,\n\t}\n\n\terr = tag.Post()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integration\n\n\/*\nCopyright 2018 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 integration\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/minikube\/pkg\/kapi\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/config\"\n\t\"k8s.io\/minikube\/pkg\/util\"\n\t\"k8s.io\/minikube\/pkg\/util\/retry\"\n)\n\nvar tunnelSession StartSession\n\nvar (\n\thostname = \"\"\n\tdomain   = \"nginx-svc.default.svc.cluster.local.\"\n)\n\nfunc validateTunnelCmd(ctx context.Context, t *testing.T, profile string) {\n\tctx, cancel := context.WithTimeout(ctx, Minutes(20))\n\ttype validateFunc func(context.Context, *testing.T, string)\n\tdefer cancel()\n\n\t\/\/ Serial tests\n\tt.Run(\"serial\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname      string\n\t\t\tvalidator validateFunc\n\t\t}{\n\t\t\t{\"StartTunnel\", validateTunnelStart},                   \/\/ Start tunnel\n\t\t\t{\"WaitService\", validateServiceStable},                 \/\/ Wait for service is stable\n\t\t\t{\"AccessDirect\", validateAccessDirect},                 \/\/ Access test for loadbalancer IP\n\t\t\t{\"DNSResolutionByDig\", validateDNSDig},                 \/\/ DNS forwarding test by dig\n\t\t\t{\"DNSResolutionByDscacheutil\", validateDNSDscacheutil}, \/\/ DNS forwarding test by dscacheutil\n\t\t\t{\"AccessThroughDNS\", validateAccessDNS},                \/\/ Access test for absolute dns name\n\t\t\t{\"DeleteTunnel\", validateTunnelDelete},                 \/\/ Stop tunnel and delete cluster\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\ttc := tc\n\t\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t\ttc.validator(ctx, t, profile)\n\t\t\t})\n\t\t}\n\t})\n}\n\n\/\/ checkRoutePassword skips tunnel test if sudo password required for route\nfunc checkRoutePassword(t *testing.T) {\n\tif !KicDriver() && runtime.GOOS != \"windows\" {\n\t\tif err := exec.Command(\"sudo\", \"-n\", \"ifconfig\").Run(); err != nil {\n\t\t\tt.Skipf(\"password required to execute 'route', skipping testTunnel: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ checkDNSForward skips DNS forwarding test if runtime is not supported\nfunc checkDNSForward(t *testing.T) {\n\t\/\/ Not all platforms support DNS forwarding\n\tif runtime.GOOS != \"darwin\" {\n\t\tt.Skip(\"DNS forwarding is supported for darwin only now, skipping test DNS forwarding\")\n\t}\n}\n\n\/\/ getKubeDNSIP returns kube-dns ClusterIP\nfunc getKubeDNSIP(t *testing.T, profile string) string {\n\t\/\/ Load ClusterConfig\n\tc, err := config.Load(profile)\n\tif err != nil {\n\t\tt.Errorf(\"failed to load cluster config: %v\", err)\n\t}\n\t\/\/ Get ipNet\n\t_, ipNet, err := net.ParseCIDR(c.KubernetesConfig.ServiceCIDR)\n\tif err != nil {\n\t\tt.Errorf(\"failed to parse service CIDR: %v\", err)\n\t}\n\t\/\/ Get kube-dns ClusterIP\n\tip, err := util.GetDNSIP(ipNet.String())\n\tif err != nil {\n\t\tt.Errorf(\"failed to get kube-dns IP: %v\", err)\n\t}\n\n\treturn ip.String()\n}\n\n\/\/ validateTunnelStart starts `minikube tunnel`\nfunc validateTunnelStart(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\n\targs := []string{\"-p\", profile, \"tunnel\", \"--alsologtostderr\"}\n\tss, err := Start(t, exec.CommandContext(ctx, Target(), args...))\n\tif err != nil {\n\t\tt.Errorf(\"failed to start a tunnel: args %q: %v\", args, err)\n\t}\n\ttunnelSession = *ss\n}\n\n\/\/ validateServiceStable starts nginx pod, nginx service and waits nginx having loadbalancer ingress IP\nfunc validateServiceStable(ctx context.Context, t *testing.T, profile string) {\n\tif HyperVDriver() {\n\t\tt.Skipf(\"skipping service test for hyperv driver \")\n\t}\n\tcheckRoutePassword(t)\n\n\tclient, err := kapi.Client(profile)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get Kubernetes client for %q: %v\", profile, err)\n\t}\n\n\t\/\/ Start the \"nginx\" pod.\n\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"apply\", \"-f\", filepath.Join(*testdataDir, \"testsvc.yaml\")))\n\tif err != nil {\n\t\tt.Fatalf(\"%s failed: %v\", rr.Command(), err)\n\t}\n\tif _, err := PodWait(ctx, t, profile, \"default\", \"run=nginx-svc\", Minutes(4)); err != nil {\n\t\tt.Fatalf(\"wait: %v\", err)\n\t}\n\n\tif err := kapi.WaitForService(client, \"default\", \"nginx-svc\", true, 1*time.Second, Minutes(2)); err != nil {\n\t\tt.Fatal(errors.Wrap(err, \"Error waiting for nginx service to be up\"))\n\t}\n\n\t\/\/ Wait until the nginx-svc has a loadbalancer ingress IP\n\terr = wait.PollImmediate(5*time.Second, Minutes(3), func() (bool, error) {\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\", \"-o\", \"jsonpath={.status.loadBalancer.ingress[0].ip}\"))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(rr.Stdout.String()) > 0 {\n\t\t\thostname = rr.Stdout.String()\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"nginx-svc svc.status.loadBalancer.ingress never got an IP\")\n\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"failed to kubectl get svc nginx-svc:\\n%s\", rr.Stdout)\n\t}\n}\n\n\/\/ validateAccessDirect validates if the test service can be accessed with LoadBalancer IP from host\nfunc validateAccessDirect(ctx context.Context, t *testing.T, profile string) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping: access direct test is broken on windows: https:\/\/github.com\/kubernetes\/minikube\/issues\/8304\")\n\t}\n\n\tcheckRoutePassword(t)\n\n\tgot := []byte{}\n\turl := fmt.Sprintf(\"http:\/\/%s\", hostname)\n\n\tfetch := func() error {\n\t\th := &http.Client{Timeout: time.Second * 10}\n\t\tresp, err := h.Get(url)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\tif resp.Body == nil {\n\t\t\treturn &retry.RetriableError{Err: fmt.Errorf(\"no body\")}\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tgot, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Check if the nginx service can be accessed\n\tif err := retry.Expo(fetch, 3*time.Second, Minutes(2), 13); err != nil {\n\t\tt.Errorf(\"failed to hit nginx at %q: %v\", url, err)\n\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"failed to kubectl get svc nginx-svc:\\n%s\", rr.Stdout)\n\t}\n\n\twant := \"Welcome to nginx!\"\n\tif strings.Contains(string(got), want) {\n\t\tt.Logf(\"tunnel at %s is working!\", url)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, got)\n\t}\n}\n\n\/\/ validateDNSDig validates if the DNS forwarding works by dig command DNS lookup\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateDNSDig(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\tip := getKubeDNSIP(t, profile)\n\tdnsIP := fmt.Sprintf(\"@%s\", ip)\n\n\t\/\/ Check if the dig DNS lookup works toward kube-dns IP\n\trr, err := Run(t, exec.CommandContext(ctx, \"dig\", \"+time=5\", \"+tries=3\", dnsIP, domain, \"A\"))\n\t\/\/ dig command returns its output for stdout only. So we don't check stderr output.\n\tif err != nil {\n\t\tt.Errorf(\"failed to resolve DNS name: %v\", err)\n\t}\n\n\twant := \"ANSWER: 1\"\n\tif strings.Contains(rr.Stdout.String(), want) {\n\t\tt.Logf(\"DNS resolution by dig for %s is working!\", domain)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, rr.Stdout.String())\n\n\t\t\/\/ debug DNS configuration\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"scutil\", \"--dns\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"debug for DNS configuration:\\n%s\", rr.Stdout.String())\n\t}\n}\n\n\/\/ validateDNSDscacheutil validates if the DNS forwarding works by dscacheutil command DNS lookup\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateDNSDscacheutil(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\t\/\/ Check if the dscacheutil DNS lookup works toward target domain\n\trr, err := Run(t, exec.CommandContext(ctx, \"dscacheutil\", \"-q\", \"host\", \"-a\", \"name\", domain))\n\t\/\/ If dscacheutil cannot lookup dns record, it returns no output. So we don't check stderr output.\n\tif err != nil {\n\t\tt.Errorf(\"failed to resolve DNS name: %v\", err)\n\t}\n\n\twant := hostname\n\tif strings.Contains(rr.Stdout.String(), want) {\n\t\tt.Logf(\"DNS resolution by dscacheutil for %s is working!\", domain)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, rr.Stdout.String())\n\t}\n}\n\n\/\/ validateAccessDNS validates if the test service can be accessed with DNS forwarding from host\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateAccessDNS(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\tgot := []byte{}\n\turl := fmt.Sprintf(\"http:\/\/%s\", domain)\n\n\tip := getKubeDNSIP(t, profile)\n\tdnsIP := fmt.Sprintf(\"%s:53\", ip)\n\n\t\/\/ Set kube-dns dial\n\tkubeDNSDial := func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\td := net.Dialer{}\n\t\treturn d.DialContext(ctx, \"udp\", dnsIP)\n\t}\n\n\t\/\/ Set kube-dns resolver\n\tr := net.Resolver{\n\t\tPreferGo: true,\n\t\tDial:     kubeDNSDial,\n\t}\n\tdialer := net.Dialer{Resolver: &r}\n\n\t\/\/ Use kube-dns resolver\n\ttransport := &http.Transport{\n\t\tDial:        dialer.Dial,\n\t\tDialContext: dialer.DialContext,\n\t}\n\n\tfetch := func() error {\n\t\th := &http.Client{Timeout: time.Second * 10, Transport: transport}\n\t\tresp, err := h.Get(url)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\tif resp.Body == nil {\n\t\t\treturn &retry.RetriableError{Err: fmt.Errorf(\"no body\")}\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tgot, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Access nginx-svc through DNS resolution\n\tif err := retry.Expo(fetch, 3*time.Second, Seconds(30), 10); err != nil {\n\t\tt.Errorf(\"failed to hit nginx with DNS forwarded %q: %v\", url, err)\n\t}\n\n\twant := \"Welcome to nginx!\"\n\tif strings.Contains(string(got), want) {\n\t\tt.Logf(\"tunnel at %s is working!\", url)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, got)\n\t}\n}\n\n\/\/ validateTunnelDelete stops `minikube tunnel`\nfunc validateTunnelDelete(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\t\/\/ Stop tunnel\n\ttunnelSession.Stop(t)\n}\n<commit_msg>skip tunnell<commit_after>\/\/ +build integration\n\n\/*\nCopyright 2018 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 integration\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/minikube\/pkg\/kapi\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/config\"\n\t\"k8s.io\/minikube\/pkg\/util\"\n\t\"k8s.io\/minikube\/pkg\/util\/retry\"\n)\n\nvar tunnelSession StartSession\n\nvar (\n\thostname = \"\"\n\tdomain   = \"nginx-svc.default.svc.cluster.local.\"\n)\n\nfunc validateTunnelCmd(ctx context.Context, t *testing.T, profile string) {\n\tctx, cancel := context.WithTimeout(ctx, Minutes(20))\n\ttype validateFunc func(context.Context, *testing.T, string)\n\tdefer cancel()\n\n\t\/\/ Serial tests\n\tt.Run(\"serial\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname      string\n\t\t\tvalidator validateFunc\n\t\t}{\n\t\t\t{\"StartTunnel\", validateTunnelStart},                   \/\/ Start tunnel\n\t\t\t{\"WaitService\", validateServiceStable},                 \/\/ Wait for service is stable\n\t\t\t{\"AccessDirect\", validateAccessDirect},                 \/\/ Access test for loadbalancer IP\n\t\t\t{\"DNSResolutionByDig\", validateDNSDig},                 \/\/ DNS forwarding test by dig\n\t\t\t{\"DNSResolutionByDscacheutil\", validateDNSDscacheutil}, \/\/ DNS forwarding test by dscacheutil\n\t\t\t{\"AccessThroughDNS\", validateAccessDNS},                \/\/ Access test for absolute dns name\n\t\t\t{\"DeleteTunnel\", validateTunnelDelete},                 \/\/ Stop tunnel and delete cluster\n\t\t}\n\t\tfor _, tc := range tests {\n\t\t\ttc := tc\n\t\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t\ttc.validator(ctx, t, profile)\n\t\t\t})\n\t\t}\n\t})\n}\n\n\/\/ checkRoutePassword skips tunnel test if sudo password required for route\nfunc checkRoutePassword(t *testing.T) {\n\tif !KicDriver() && runtime.GOOS != \"windows\" {\n\t\tif err := exec.Command(\"sudo\", \"-n\", \"ifconfig\").Run(); err != nil {\n\t\t\tt.Skipf(\"password required to execute 'route', skipping testTunnel: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ checkDNSForward skips DNS forwarding test if runtime is not supported\nfunc checkDNSForward(t *testing.T) {\n\t\/\/ Not all platforms support DNS forwarding\n\tif runtime.GOOS != \"darwin\" {\n\t\tt.Skip(\"DNS forwarding is supported for darwin only now, skipping test DNS forwarding\")\n\t}\n}\n\n\/\/ getKubeDNSIP returns kube-dns ClusterIP\nfunc getKubeDNSIP(t *testing.T, profile string) string {\n\t\/\/ Load ClusterConfig\n\tc, err := config.Load(profile)\n\tif err != nil {\n\t\tt.Errorf(\"failed to load cluster config: %v\", err)\n\t}\n\t\/\/ Get ipNet\n\t_, ipNet, err := net.ParseCIDR(c.KubernetesConfig.ServiceCIDR)\n\tif err != nil {\n\t\tt.Errorf(\"failed to parse service CIDR: %v\", err)\n\t}\n\t\/\/ Get kube-dns ClusterIP\n\tip, err := util.GetDNSIP(ipNet.String())\n\tif err != nil {\n\t\tt.Errorf(\"failed to get kube-dns IP: %v\", err)\n\t}\n\n\treturn ip.String()\n}\n\n\/\/ validateTunnelStart starts `minikube tunnel`\nfunc validateTunnelStart(ctx context.Context, t *testing.T, profile string) {\n\tif HyperVDriver() {\n\t\tt.Skipf(\"skipping tunnel for hyperv driver\")\n\t}\n\tcheckRoutePassword(t)\n\n\targs := []string{\"-p\", profile, \"tunnel\", \"--alsologtostderr\"}\n\tss, err := Start(t, exec.CommandContext(ctx, Target(), args...))\n\tif err != nil {\n\t\tt.Errorf(\"failed to start a tunnel: args %q: %v\", args, err)\n\t}\n\ttunnelSession = *ss\n}\n\n\/\/ validateServiceStable starts nginx pod, nginx service and waits nginx having loadbalancer ingress IP\nfunc validateServiceStable(ctx context.Context, t *testing.T, profile string) {\n\tif HyperVDriver() {\n\t\tt.Skipf(\"skipping service test for hyperv driver \")\n\t}\n\tcheckRoutePassword(t)\n\n\tclient, err := kapi.Client(profile)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get Kubernetes client for %q: %v\", profile, err)\n\t}\n\n\t\/\/ Start the \"nginx\" pod.\n\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"apply\", \"-f\", filepath.Join(*testdataDir, \"testsvc.yaml\")))\n\tif err != nil {\n\t\tt.Fatalf(\"%s failed: %v\", rr.Command(), err)\n\t}\n\tif _, err := PodWait(ctx, t, profile, \"default\", \"run=nginx-svc\", Minutes(4)); err != nil {\n\t\tt.Fatalf(\"wait: %v\", err)\n\t}\n\n\tif err := kapi.WaitForService(client, \"default\", \"nginx-svc\", true, 1*time.Second, Minutes(2)); err != nil {\n\t\tt.Fatal(errors.Wrap(err, \"Error waiting for nginx service to be up\"))\n\t}\n\n\t\/\/ Wait until the nginx-svc has a loadbalancer ingress IP\n\terr = wait.PollImmediate(5*time.Second, Minutes(3), func() (bool, error) {\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\", \"-o\", \"jsonpath={.status.loadBalancer.ingress[0].ip}\"))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(rr.Stdout.String()) > 0 {\n\t\t\thostname = rr.Stdout.String()\n\t\t\treturn true, nil\n\t\t}\n\t\treturn false, nil\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"nginx-svc svc.status.loadBalancer.ingress never got an IP\")\n\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"failed to kubectl get svc nginx-svc:\\n%s\", rr.Stdout)\n\t}\n}\n\n\/\/ validateAccessDirect validates if the test service can be accessed with LoadBalancer IP from host\nfunc validateAccessDirect(ctx context.Context, t *testing.T, profile string) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping: access direct test is broken on windows: https:\/\/github.com\/kubernetes\/minikube\/issues\/8304\")\n\t}\n\n\tcheckRoutePassword(t)\n\n\tgot := []byte{}\n\turl := fmt.Sprintf(\"http:\/\/%s\", hostname)\n\n\tfetch := func() error {\n\t\th := &http.Client{Timeout: time.Second * 10}\n\t\tresp, err := h.Get(url)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\tif resp.Body == nil {\n\t\t\treturn &retry.RetriableError{Err: fmt.Errorf(\"no body\")}\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tgot, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Check if the nginx service can be accessed\n\tif err := retry.Expo(fetch, 3*time.Second, Minutes(2), 13); err != nil {\n\t\tt.Errorf(\"failed to hit nginx at %q: %v\", url, err)\n\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"kubectl\", \"--context\", profile, \"get\", \"svc\", \"nginx-svc\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"failed to kubectl get svc nginx-svc:\\n%s\", rr.Stdout)\n\t}\n\n\twant := \"Welcome to nginx!\"\n\tif strings.Contains(string(got), want) {\n\t\tt.Logf(\"tunnel at %s is working!\", url)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, got)\n\t}\n}\n\n\/\/ validateDNSDig validates if the DNS forwarding works by dig command DNS lookup\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateDNSDig(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\tip := getKubeDNSIP(t, profile)\n\tdnsIP := fmt.Sprintf(\"@%s\", ip)\n\n\t\/\/ Check if the dig DNS lookup works toward kube-dns IP\n\trr, err := Run(t, exec.CommandContext(ctx, \"dig\", \"+time=5\", \"+tries=3\", dnsIP, domain, \"A\"))\n\t\/\/ dig command returns its output for stdout only. So we don't check stderr output.\n\tif err != nil {\n\t\tt.Errorf(\"failed to resolve DNS name: %v\", err)\n\t}\n\n\twant := \"ANSWER: 1\"\n\tif strings.Contains(rr.Stdout.String(), want) {\n\t\tt.Logf(\"DNS resolution by dig for %s is working!\", domain)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, rr.Stdout.String())\n\n\t\t\/\/ debug DNS configuration\n\t\trr, err := Run(t, exec.CommandContext(ctx, \"scutil\", \"--dns\"))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s failed: %v\", rr.Command(), err)\n\t\t}\n\t\tt.Logf(\"debug for DNS configuration:\\n%s\", rr.Stdout.String())\n\t}\n}\n\n\/\/ validateDNSDscacheutil validates if the DNS forwarding works by dscacheutil command DNS lookup\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateDNSDscacheutil(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\t\/\/ Check if the dscacheutil DNS lookup works toward target domain\n\trr, err := Run(t, exec.CommandContext(ctx, \"dscacheutil\", \"-q\", \"host\", \"-a\", \"name\", domain))\n\t\/\/ If dscacheutil cannot lookup dns record, it returns no output. So we don't check stderr output.\n\tif err != nil {\n\t\tt.Errorf(\"failed to resolve DNS name: %v\", err)\n\t}\n\n\twant := hostname\n\tif strings.Contains(rr.Stdout.String(), want) {\n\t\tt.Logf(\"DNS resolution by dscacheutil for %s is working!\", domain)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, rr.Stdout.String())\n\t}\n}\n\n\/\/ validateAccessDNS validates if the test service can be accessed with DNS forwarding from host\n\/\/ NOTE: DNS forwarding is experimental: https:\/\/minikube.sigs.k8s.io\/docs\/handbook\/accessing\/#dns-resolution-experimental\nfunc validateAccessDNS(ctx context.Context, t *testing.T, profile string) {\n\tcheckRoutePassword(t)\n\tcheckDNSForward(t)\n\n\tgot := []byte{}\n\turl := fmt.Sprintf(\"http:\/\/%s\", domain)\n\n\tip := getKubeDNSIP(t, profile)\n\tdnsIP := fmt.Sprintf(\"%s:53\", ip)\n\n\t\/\/ Set kube-dns dial\n\tkubeDNSDial := func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\td := net.Dialer{}\n\t\treturn d.DialContext(ctx, \"udp\", dnsIP)\n\t}\n\n\t\/\/ Set kube-dns resolver\n\tr := net.Resolver{\n\t\tPreferGo: true,\n\t\tDial:     kubeDNSDial,\n\t}\n\tdialer := net.Dialer{Resolver: &r}\n\n\t\/\/ Use kube-dns resolver\n\ttransport := &http.Transport{\n\t\tDial:        dialer.Dial,\n\t\tDialContext: dialer.DialContext,\n\t}\n\n\tfetch := func() error {\n\t\th := &http.Client{Timeout: time.Second * 10, Transport: transport}\n\t\tresp, err := h.Get(url)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\tif resp.Body == nil {\n\t\t\treturn &retry.RetriableError{Err: fmt.Errorf(\"no body\")}\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tgot, err = ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn &retry.RetriableError{Err: err}\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Access nginx-svc through DNS resolution\n\tif err := retry.Expo(fetch, 3*time.Second, Seconds(30), 10); err != nil {\n\t\tt.Errorf(\"failed to hit nginx with DNS forwarded %q: %v\", url, err)\n\t}\n\n\twant := \"Welcome to nginx!\"\n\tif strings.Contains(string(got), want) {\n\t\tt.Logf(\"tunnel at %s is working!\", url)\n\t} else {\n\t\tt.Errorf(\"expected body to contain %q, but got *%q*\", want, got)\n\t}\n}\n\n\/\/ validateTunnelDelete stops `minikube tunnel`\nfunc validateTunnelDelete(ctx context.Context, t *testing.T, profile string) {\n\tif HyperVDriver() {\n\t\tt.Skipf(\"skipping tunnel for hyperv driver\")\n\t}\n\tcheckRoutePassword(t)\n\t\/\/ Stop tunnel\n\ttunnelSession.Stop(t)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 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 evaluator\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/pingcap\/tidb\/ast\"\n\t\"github.com\/pingcap\/tidb\/context\"\n\t\"github.com\/pingcap\/tidb\/parser\/opcode\"\n\t\"github.com\/pingcap\/tidb\/util\/types\"\n)\n\n\/\/ BuiltinFunc is the function signature for builtin functions\ntype BuiltinFunc func([]types.Datum, context.Context) (types.Datum, error)\n\n\/\/ Func is for a builtin function.\ntype Func struct {\n\t\/\/ F is the specific calling function.\n\tF BuiltinFunc\n\t\/\/ MinArgs is the minimal arguments needed,\n\tMinArgs int\n\t\/\/ MaxArgs is the maximal arguments needed, -1 for infinity.\n\tMaxArgs int\n}\n\n\/\/ Funcs holds all registered builtin functions.\nvar Funcs = map[string]Func{\n\t\/\/ common functions\n\tast.Coalesce: {builtinCoalesce, 1, -1},\n\tast.IsNull:   {builtinIsNull, 1, 1},\n\tast.Greatest: {builtinGreatest, 2, -1},\n\n\t\/\/ math functions\n\tast.Abs:     {builtinAbs, 1, 1},\n\tast.Ceil:    {builtinCeil, 1, 1},\n\tast.Ceiling: {builtinCeil, 1, 1},\n\tast.Ln:      {builtinLog, 1, 1},\n\tast.Log:     {builtinLog, 1, 2},\n\tast.Log2:    {builtinLog2, 1, 1},\n\tast.Log10:   {builtinLog10, 1, 1},\n\tast.Pow:     {builtinPow, 2, 2},\n\tast.Power:   {builtinPow, 2, 2},\n\tast.Rand:    {builtinRand, 0, 1},\n\tast.Round:   {builtinRound, 1, 2},\n\n\t\/\/ time functions\n\tast.Curdate:          {builtinCurrentDate, 0, 0},\n\tast.CurrentDate:      {builtinCurrentDate, 0, 0},\n\tast.CurrentTime:      {builtinCurrentTime, 0, 1},\n\tast.Date:             {builtinDate, 1, 1},\n\tast.DateArith:        {builtinDateArith, 3, 3},\n\tast.DateFormat:       {builtinDateFormat, 2, 2},\n\tast.CurrentTimestamp: {builtinNow, 0, 1},\n\tast.Curtime:          {builtinCurrentTime, 0, 1},\n\tast.Day:              {builtinDay, 1, 1},\n\tast.DayName:          {builtinDayName, 1, 1},\n\tast.DayOfMonth:       {builtinDayOfMonth, 1, 1},\n\tast.DayOfWeek:        {builtinDayOfWeek, 1, 1},\n\tast.DayOfYear:        {builtinDayOfYear, 1, 1},\n\tast.Extract:          {builtinExtract, 2, 2},\n\tast.Hour:             {builtinHour, 1, 1},\n\tast.MicroSecond:      {builtinMicroSecond, 1, 1},\n\tast.Minute:           {builtinMinute, 1, 1},\n\tast.Month:            {builtinMonth, 1, 1},\n\tast.MonthName:        {builtinMonthName, 1, 1},\n\tast.Now:              {builtinNow, 0, 1},\n\tast.Second:           {builtinSecond, 1, 1},\n\tast.StrToDate:        {builtinStrToDate, 2, 2},\n\tast.Sysdate:          {builtinSysDate, 0, 1},\n\tast.Time:             {builtinTime, 1, 1},\n\tast.UTCDate:          {builtinUTCDate, 0, 0},\n\tast.Week:             {builtinWeek, 1, 2},\n\tast.Weekday:          {builtinWeekDay, 1, 1},\n\tast.WeekOfYear:       {builtinWeekOfYear, 1, 1},\n\tast.Year:             {builtinYear, 1, 1},\n\tast.YearWeek:         {builtinYearWeek, 1, 2},\n\tast.FromUnixTime:     {builtinFromUnixTime, 1, 2},\n\tast.TimeDiff:         {builtinTimeDiff, 2, 2},\n\n\t\/\/ string functions\n\tast.ASCII:          {builtinASCII, 1, 1},\n\tast.Concat:         {builtinConcat, 1, -1},\n\tast.ConcatWS:       {builtinConcatWS, 2, -1},\n\tast.Convert:        {builtinConvert, 2, 2},\n\tast.Lcase:          {builtinLower, 1, 1},\n\tast.Left:           {builtinLeft, 2, 2},\n\tast.Length:         {builtinLength, 1, 1},\n\tast.Locate:         {builtinLocate, 2, 3},\n\tast.Lower:          {builtinLower, 1, 1},\n\tast.Ltrim:          {trimFn(strings.TrimLeft, spaceChars), 1, 1},\n\tast.Repeat:         {builtinRepeat, 2, 2},\n\tast.Replace:        {builtinReplace, 3, 3},\n\tast.Reverse:        {builtinReverse, 1, 1},\n\tast.Rtrim:          {trimFn(strings.TrimRight, spaceChars), 1, 1},\n\tast.Space:          {builtinSpace, 1, 1},\n\tast.Strcmp:         {builtinStrcmp, 2, 2},\n\tast.Substring:      {builtinSubstring, 2, 3},\n\tast.SubstringIndex: {builtinSubstringIndex, 3, 3},\n\tast.Trim:           {builtinTrim, 1, 3},\n\tast.Upper:          {builtinUpper, 1, 1},\n\tast.Ucase:          {builtinUpper, 1, 1},\n\tast.Hex:            {builtinHex, 1, 1},\n\tast.Unhex:          {builtinUnHex, 1, 1},\n\tast.Rpad:           {builtinRpad, 3, 3},\n\n\t\/\/ information functions\n\tast.ConnectionID: {builtinConnectionID, 0, 0},\n\tast.CurrentUser:  {builtinCurrentUser, 0, 0},\n\tast.Database:     {builtinDatabase, 0, 0},\n\t\/\/ This function is a synonym for DATABASE().\n\t\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/information-functions.html#function_schema\n\tast.Schema:       {builtinDatabase, 0, 0},\n\tast.FoundRows:    {builtinFoundRows, 0, 0},\n\tast.LastInsertId: {builtinLastInsertID, 0, 1},\n\tast.User:         {builtinUser, 0, 0},\n\tast.Version:      {builtinVersion, 0, 0},\n\n\t\/\/ control functions\n\tast.If:     {builtinIf, 3, 3},\n\tast.Ifnull: {builtinIfNull, 2, 2},\n\tast.Nullif: {builtinNullIf, 2, 2},\n\n\t\/\/ miscellaneous functions\n\tast.Sleep: {builtinSleep, 1, 1},\n\n\t\/\/ get_lock() and release_lock() is parsed but do nothing.\n\t\/\/ It is used for preventing error in Ruby's activerecord migrations.\n\tast.GetLock:     {builtinLock, 2, 2},\n\tast.ReleaseLock: {builtinReleaseLock, 1, 1},\n\n\t\/\/ only used by new plan\n\tast.AndAnd:     {builtinAndAnd, 2, 2},\n\tast.OrOr:       {builtinOrOr, 2, 2},\n\tast.GE:         {compareFuncFactory(opcode.GE), 2, 2},\n\tast.LE:         {compareFuncFactory(opcode.LE), 2, 2},\n\tast.EQ:         {compareFuncFactory(opcode.EQ), 2, 2},\n\tast.NE:         {compareFuncFactory(opcode.NE), 2, 2},\n\tast.LT:         {compareFuncFactory(opcode.LT), 2, 2},\n\tast.GT:         {compareFuncFactory(opcode.GT), 2, 2},\n\tast.NullEQ:     {compareFuncFactory(opcode.NullEQ), 2, 2},\n\tast.Plus:       {arithmeticFuncFactory(opcode.Plus), 2, 2},\n\tast.Minus:      {arithmeticFuncFactory(opcode.Minus), 2, 2},\n\tast.Mod:        {arithmeticFuncFactory(opcode.Mod), 2, 2},\n\tast.Div:        {arithmeticFuncFactory(opcode.Div), 2, 2},\n\tast.Mul:        {arithmeticFuncFactory(opcode.Mul), 2, 2},\n\tast.IntDiv:     {arithmeticFuncFactory(opcode.IntDiv), 2, 2},\n\tast.LeftShift:  {bitOpFactory(opcode.LeftShift), 2, 2},\n\tast.RightShift: {bitOpFactory(opcode.RightShift), 2, 2},\n\tast.And:        {bitOpFactory(opcode.And), 2, 2},\n\tast.Or:         {bitOpFactory(opcode.Or), 2, 2},\n\tast.Xor:        {bitOpFactory(opcode.Xor), 2, 2},\n\tast.LogicXor:   {builtinLogicXor, 2, 2},\n\tast.UnaryNot:   {unaryOpFactory(opcode.Not), 1, 1},\n\tast.BitNeg:     {unaryOpFactory(opcode.BitNeg), 1, 1},\n\tast.UnaryPlus:  {unaryOpFactory(opcode.Plus), 1, 1},\n\tast.UnaryMinus: {unaryOpFactory(opcode.Minus), 1, 1},\n\tast.In:         {builtinIn, 1, -1},\n\tast.IsTruth:    {isTrueOpFactory(opcode.IsTruth), 1, 1},\n\tast.IsFalsity:  {isTrueOpFactory(opcode.IsFalsity), 1, 1},\n\tast.Like:       {builtinLike, 3, 3},\n\tast.Regexp:     {builtinRegexp, 2, 2},\n\tast.Case:       {builtinCaseWhen, 1, -1},\n\tast.RowFunc:    {builtinRow, 2, -1},\n\tast.SetVar:     {builtinSetVar, 2, 2},\n\tast.GetVar:     {builtinGetVar, 1, 1},\n}\n\n\/\/ DynamicFuncs are those functions that\n\/\/ use input parameter ctx or\n\/\/ return an uncertain result would not be constant folded\n\/\/ the value 0 means nothing\nvar DynamicFuncs = map[string]int{\n\t\"rand\":           0,\n\t\"connection_id\":  0,\n\t\"current_user\":   0,\n\t\"database\":       0,\n\t\"found_rows\":     0,\n\t\"last_insert_id\": 0,\n\t\"user\":           0,\n\t\"version\":        0,\n\t\"sleep\":          0,\n\tast.GetVar:       0,\n\tast.SetVar:       0,\n}\n\n\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_coalesce\nfunc builtinCoalesce(args []types.Datum, ctx context.Context) (d types.Datum, err error) {\n\tfor _, d = range args {\n\t\tif !d.IsNull() {\n\t\t\treturn d, nil\n\t\t}\n\t}\n\treturn d, nil\n}\n\n\/\/ See https:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_isnull\nfunc builtinIsNull(args []types.Datum, _ context.Context) (d types.Datum, err error) {\n\tif args[0].IsNull() {\n\t\td.SetInt64(1)\n\t} else {\n\t\td.SetInt64(0)\n\t}\n\treturn d, nil\n}\n\n\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_greatest\nfunc builtinGreatest(args []types.Datum, ctx context.Context) (d types.Datum, err error) {\n\tmax := 0\n\tsc := ctx.GetSessionVars().StmtCtx\n\tfor i := 0; i < len(args); i++ {\n\t\tif args[i].IsNull() {\n\t\t\td.SetNull()\n\t\t\treturn\n\t\t}\n\n\t\tvar cmp int\n\t\tif cmp, err = args[i].CompareDatum(sc, args[max]); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif cmp > 0 {\n\t\t\tmax = i\n\t\t}\n\t}\n\td = args[max]\n\treturn\n}\n<commit_msg>evaluator: makes `values` function dynamic. (#2320)<commit_after>\/\/ Copyright 2013 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 evaluator\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/pingcap\/tidb\/ast\"\n\t\"github.com\/pingcap\/tidb\/context\"\n\t\"github.com\/pingcap\/tidb\/parser\/opcode\"\n\t\"github.com\/pingcap\/tidb\/util\/types\"\n)\n\n\/\/ BuiltinFunc is the function signature for builtin functions\ntype BuiltinFunc func([]types.Datum, context.Context) (types.Datum, error)\n\n\/\/ Func is for a builtin function.\ntype Func struct {\n\t\/\/ F is the specific calling function.\n\tF BuiltinFunc\n\t\/\/ MinArgs is the minimal arguments needed,\n\tMinArgs int\n\t\/\/ MaxArgs is the maximal arguments needed, -1 for infinity.\n\tMaxArgs int\n}\n\n\/\/ Funcs holds all registered builtin functions.\nvar Funcs = map[string]Func{\n\t\/\/ common functions\n\tast.Coalesce: {builtinCoalesce, 1, -1},\n\tast.IsNull:   {builtinIsNull, 1, 1},\n\tast.Greatest: {builtinGreatest, 2, -1},\n\n\t\/\/ math functions\n\tast.Abs:     {builtinAbs, 1, 1},\n\tast.Ceil:    {builtinCeil, 1, 1},\n\tast.Ceiling: {builtinCeil, 1, 1},\n\tast.Ln:      {builtinLog, 1, 1},\n\tast.Log:     {builtinLog, 1, 2},\n\tast.Log2:    {builtinLog2, 1, 1},\n\tast.Log10:   {builtinLog10, 1, 1},\n\tast.Pow:     {builtinPow, 2, 2},\n\tast.Power:   {builtinPow, 2, 2},\n\tast.Rand:    {builtinRand, 0, 1},\n\tast.Round:   {builtinRound, 1, 2},\n\n\t\/\/ time functions\n\tast.Curdate:          {builtinCurrentDate, 0, 0},\n\tast.CurrentDate:      {builtinCurrentDate, 0, 0},\n\tast.CurrentTime:      {builtinCurrentTime, 0, 1},\n\tast.Date:             {builtinDate, 1, 1},\n\tast.DateArith:        {builtinDateArith, 3, 3},\n\tast.DateFormat:       {builtinDateFormat, 2, 2},\n\tast.CurrentTimestamp: {builtinNow, 0, 1},\n\tast.Curtime:          {builtinCurrentTime, 0, 1},\n\tast.Day:              {builtinDay, 1, 1},\n\tast.DayName:          {builtinDayName, 1, 1},\n\tast.DayOfMonth:       {builtinDayOfMonth, 1, 1},\n\tast.DayOfWeek:        {builtinDayOfWeek, 1, 1},\n\tast.DayOfYear:        {builtinDayOfYear, 1, 1},\n\tast.Extract:          {builtinExtract, 2, 2},\n\tast.Hour:             {builtinHour, 1, 1},\n\tast.MicroSecond:      {builtinMicroSecond, 1, 1},\n\tast.Minute:           {builtinMinute, 1, 1},\n\tast.Month:            {builtinMonth, 1, 1},\n\tast.MonthName:        {builtinMonthName, 1, 1},\n\tast.Now:              {builtinNow, 0, 1},\n\tast.Second:           {builtinSecond, 1, 1},\n\tast.StrToDate:        {builtinStrToDate, 2, 2},\n\tast.Sysdate:          {builtinSysDate, 0, 1},\n\tast.Time:             {builtinTime, 1, 1},\n\tast.UTCDate:          {builtinUTCDate, 0, 0},\n\tast.Week:             {builtinWeek, 1, 2},\n\tast.Weekday:          {builtinWeekDay, 1, 1},\n\tast.WeekOfYear:       {builtinWeekOfYear, 1, 1},\n\tast.Year:             {builtinYear, 1, 1},\n\tast.YearWeek:         {builtinYearWeek, 1, 2},\n\tast.FromUnixTime:     {builtinFromUnixTime, 1, 2},\n\tast.TimeDiff:         {builtinTimeDiff, 2, 2},\n\n\t\/\/ string functions\n\tast.ASCII:          {builtinASCII, 1, 1},\n\tast.Concat:         {builtinConcat, 1, -1},\n\tast.ConcatWS:       {builtinConcatWS, 2, -1},\n\tast.Convert:        {builtinConvert, 2, 2},\n\tast.Lcase:          {builtinLower, 1, 1},\n\tast.Left:           {builtinLeft, 2, 2},\n\tast.Length:         {builtinLength, 1, 1},\n\tast.Locate:         {builtinLocate, 2, 3},\n\tast.Lower:          {builtinLower, 1, 1},\n\tast.Ltrim:          {trimFn(strings.TrimLeft, spaceChars), 1, 1},\n\tast.Repeat:         {builtinRepeat, 2, 2},\n\tast.Replace:        {builtinReplace, 3, 3},\n\tast.Reverse:        {builtinReverse, 1, 1},\n\tast.Rtrim:          {trimFn(strings.TrimRight, spaceChars), 1, 1},\n\tast.Space:          {builtinSpace, 1, 1},\n\tast.Strcmp:         {builtinStrcmp, 2, 2},\n\tast.Substring:      {builtinSubstring, 2, 3},\n\tast.SubstringIndex: {builtinSubstringIndex, 3, 3},\n\tast.Trim:           {builtinTrim, 1, 3},\n\tast.Upper:          {builtinUpper, 1, 1},\n\tast.Ucase:          {builtinUpper, 1, 1},\n\tast.Hex:            {builtinHex, 1, 1},\n\tast.Unhex:          {builtinUnHex, 1, 1},\n\tast.Rpad:           {builtinRpad, 3, 3},\n\n\t\/\/ information functions\n\tast.ConnectionID: {builtinConnectionID, 0, 0},\n\tast.CurrentUser:  {builtinCurrentUser, 0, 0},\n\tast.Database:     {builtinDatabase, 0, 0},\n\t\/\/ This function is a synonym for DATABASE().\n\t\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/information-functions.html#function_schema\n\tast.Schema:       {builtinDatabase, 0, 0},\n\tast.FoundRows:    {builtinFoundRows, 0, 0},\n\tast.LastInsertId: {builtinLastInsertID, 0, 1},\n\tast.User:         {builtinUser, 0, 0},\n\tast.Version:      {builtinVersion, 0, 0},\n\n\t\/\/ control functions\n\tast.If:     {builtinIf, 3, 3},\n\tast.Ifnull: {builtinIfNull, 2, 2},\n\tast.Nullif: {builtinNullIf, 2, 2},\n\n\t\/\/ miscellaneous functions\n\tast.Sleep: {builtinSleep, 1, 1},\n\n\t\/\/ get_lock() and release_lock() is parsed but do nothing.\n\t\/\/ It is used for preventing error in Ruby's activerecord migrations.\n\tast.GetLock:     {builtinLock, 2, 2},\n\tast.ReleaseLock: {builtinReleaseLock, 1, 1},\n\n\t\/\/ only used by new plan\n\tast.AndAnd:     {builtinAndAnd, 2, 2},\n\tast.OrOr:       {builtinOrOr, 2, 2},\n\tast.GE:         {compareFuncFactory(opcode.GE), 2, 2},\n\tast.LE:         {compareFuncFactory(opcode.LE), 2, 2},\n\tast.EQ:         {compareFuncFactory(opcode.EQ), 2, 2},\n\tast.NE:         {compareFuncFactory(opcode.NE), 2, 2},\n\tast.LT:         {compareFuncFactory(opcode.LT), 2, 2},\n\tast.GT:         {compareFuncFactory(opcode.GT), 2, 2},\n\tast.NullEQ:     {compareFuncFactory(opcode.NullEQ), 2, 2},\n\tast.Plus:       {arithmeticFuncFactory(opcode.Plus), 2, 2},\n\tast.Minus:      {arithmeticFuncFactory(opcode.Minus), 2, 2},\n\tast.Mod:        {arithmeticFuncFactory(opcode.Mod), 2, 2},\n\tast.Div:        {arithmeticFuncFactory(opcode.Div), 2, 2},\n\tast.Mul:        {arithmeticFuncFactory(opcode.Mul), 2, 2},\n\tast.IntDiv:     {arithmeticFuncFactory(opcode.IntDiv), 2, 2},\n\tast.LeftShift:  {bitOpFactory(opcode.LeftShift), 2, 2},\n\tast.RightShift: {bitOpFactory(opcode.RightShift), 2, 2},\n\tast.And:        {bitOpFactory(opcode.And), 2, 2},\n\tast.Or:         {bitOpFactory(opcode.Or), 2, 2},\n\tast.Xor:        {bitOpFactory(opcode.Xor), 2, 2},\n\tast.LogicXor:   {builtinLogicXor, 2, 2},\n\tast.UnaryNot:   {unaryOpFactory(opcode.Not), 1, 1},\n\tast.BitNeg:     {unaryOpFactory(opcode.BitNeg), 1, 1},\n\tast.UnaryPlus:  {unaryOpFactory(opcode.Plus), 1, 1},\n\tast.UnaryMinus: {unaryOpFactory(opcode.Minus), 1, 1},\n\tast.In:         {builtinIn, 1, -1},\n\tast.IsTruth:    {isTrueOpFactory(opcode.IsTruth), 1, 1},\n\tast.IsFalsity:  {isTrueOpFactory(opcode.IsFalsity), 1, 1},\n\tast.Like:       {builtinLike, 3, 3},\n\tast.Regexp:     {builtinRegexp, 2, 2},\n\tast.Case:       {builtinCaseWhen, 1, -1},\n\tast.RowFunc:    {builtinRow, 2, -1},\n\tast.SetVar:     {builtinSetVar, 2, 2},\n\tast.GetVar:     {builtinGetVar, 1, 1},\n}\n\n\/\/ DynamicFuncs are those functions that\n\/\/ use input parameter ctx or\n\/\/ return an uncertain result would not be constant folded\n\/\/ the value 0 means nothing\nvar DynamicFuncs = map[string]int{\n\t\"rand\":           0,\n\t\"connection_id\":  0,\n\t\"current_user\":   0,\n\t\"database\":       0,\n\t\"found_rows\":     0,\n\t\"last_insert_id\": 0,\n\t\"user\":           0,\n\t\"version\":        0,\n\t\"sleep\":          0,\n\tast.GetVar:       0,\n\tast.SetVar:       0,\n\tast.Values:       0,\n}\n\n\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_coalesce\nfunc builtinCoalesce(args []types.Datum, ctx context.Context) (d types.Datum, err error) {\n\tfor _, d = range args {\n\t\tif !d.IsNull() {\n\t\t\treturn d, nil\n\t\t}\n\t}\n\treturn d, nil\n}\n\n\/\/ See https:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_isnull\nfunc builtinIsNull(args []types.Datum, _ context.Context) (d types.Datum, err error) {\n\tif args[0].IsNull() {\n\t\td.SetInt64(1)\n\t} else {\n\t\td.SetInt64(0)\n\t}\n\treturn d, nil\n}\n\n\/\/ See http:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/comparison-operators.html#function_greatest\nfunc builtinGreatest(args []types.Datum, ctx context.Context) (d types.Datum, err error) {\n\tmax := 0\n\tsc := ctx.GetSessionVars().StmtCtx\n\tfor i := 0; i < len(args); i++ {\n\t\tif args[i].IsNull() {\n\t\t\td.SetNull()\n\t\t\treturn\n\t\t}\n\n\t\tvar cmp int\n\t\tif cmp, err = args[i].CompareDatum(sc, args[max]); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif cmp > 0 {\n\t\t\tmax = i\n\t\t}\n\t}\n\td = args[max]\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2014 VMware, Inc.  All rights reserved.  Licensed under the Apache v2 License.\n *\/\n\npackage vmwarefusion\n\nconst vmx = `\n.encoding = \"UTF-8\"\nconfig.version = \"8\"\ndisplayName = \"{{.MachineName}}\"\nethernet0.present = \"TRUE\"\nethernet0.connectionType = \"nat\"\nethernet0.virtualDev = \"vmxnet3\"\nethernet0.wakeOnPcktRcv = \"FALSE\"\nethernet0.addressType = \"generated\"\nethernet0.linkStatePropagation.enable = \"TRUE\"\npciBridge0.present = \"TRUE\"\npciBridge4.present = \"TRUE\"\npciBridge4.virtualDev = \"pcieRootPort\"\npciBridge4.functions = \"8\"\npciBridge5.present = \"TRUE\"\npciBridge5.virtualDev = \"pcieRootPort\"\npciBridge5.functions = \"8\"\npciBridge6.present = \"TRUE\"\npciBridge6.virtualDev = \"pcieRootPort\"\npciBridge6.functions = \"8\"\npciBridge7.present = \"TRUE\"\npciBridge7.virtualDev = \"pcieRootPort\"\npciBridge7.functions = \"8\"\npciBridge0.pciSlotNumber = \"17\"\npciBridge4.pciSlotNumber = \"21\"\npciBridge5.pciSlotNumber = \"22\"\npciBridge6.pciSlotNumber = \"23\"\npciBridge7.pciSlotNumber = \"24\"\nscsi0.pciSlotNumber = \"160\"\nusb.pciSlotNumber = \"32\"\nethernet0.pciSlotNumber = \"192\"\nsound.pciSlotNumber = \"33\"\nvmci0.pciSlotNumber = \"35\"\nsata0.pciSlotNumber = \"36\"\nfloppy0.present = \"FALSE\"\nguestOS = \"other3xlinux-64\"\nhpet0.present = \"TRUE\"\nsata0.present = \"TRUE\"\nsata0:1.present = \"TRUE\"\nsata0:1.fileName = \"{{.ISO}}\"\nsata0:1.deviceType = \"cdrom-image\"\n{{ if .ConfigDriveURL }}\nsata0:2.present = \"TRUE\"\nsata0:2.fileName = \"{{.ConfigDriveISO}}\"\nsata0:2.deviceType = \"cdrom-image\"\n{{ end }}\nvmci0.present = \"TRUE\"\nmem.hotadd = \"TRUE\"\nmemsize = \"{{.Memory}}\"\npowerType.powerOff = \"soft\"\npowerType.powerOn = \"soft\"\npowerType.reset = \"soft\"\npowerType.suspend = \"soft\"\nscsi0.present = \"TRUE\"\nscsi0.virtualDev = \"pvscsi\"\nscsi0:0.fileName = \"{{.MachineName}}.vmdk\"\nscsi0:0.present = \"TRUE\"\nvirtualHW.productCompatibility = \"hosted\"\nvirtualHW.version = \"10\"\nmsg.autoanswer = \"TRUE\"\nuuid.action = \"create\"\nnumvcpus = \"{{.CPU}}\"\nhgfs.mapRootShare = \"FALSE\"\nhgfs.linkRootShare = \"FALSE\"\n`\n<commit_msg>Enable syncing time for VMWare Fusion guests<commit_after>\/*\n * Copyright 2014 VMware, Inc.  All rights reserved.  Licensed under the Apache v2 License.\n *\/\n\npackage vmwarefusion\n\nconst vmx = `\n.encoding = \"UTF-8\"\nconfig.version = \"8\"\ndisplayName = \"{{.MachineName}}\"\nethernet0.present = \"TRUE\"\nethernet0.connectionType = \"nat\"\nethernet0.virtualDev = \"vmxnet3\"\nethernet0.wakeOnPcktRcv = \"FALSE\"\nethernet0.addressType = \"generated\"\nethernet0.linkStatePropagation.enable = \"TRUE\"\npciBridge0.present = \"TRUE\"\npciBridge4.present = \"TRUE\"\npciBridge4.virtualDev = \"pcieRootPort\"\npciBridge4.functions = \"8\"\npciBridge5.present = \"TRUE\"\npciBridge5.virtualDev = \"pcieRootPort\"\npciBridge5.functions = \"8\"\npciBridge6.present = \"TRUE\"\npciBridge6.virtualDev = \"pcieRootPort\"\npciBridge6.functions = \"8\"\npciBridge7.present = \"TRUE\"\npciBridge7.virtualDev = \"pcieRootPort\"\npciBridge7.functions = \"8\"\npciBridge0.pciSlotNumber = \"17\"\npciBridge4.pciSlotNumber = \"21\"\npciBridge5.pciSlotNumber = \"22\"\npciBridge6.pciSlotNumber = \"23\"\npciBridge7.pciSlotNumber = \"24\"\nscsi0.pciSlotNumber = \"160\"\nusb.pciSlotNumber = \"32\"\nethernet0.pciSlotNumber = \"192\"\nsound.pciSlotNumber = \"33\"\nvmci0.pciSlotNumber = \"35\"\nsata0.pciSlotNumber = \"36\"\nfloppy0.present = \"FALSE\"\nguestOS = \"other3xlinux-64\"\nhpet0.present = \"TRUE\"\nsata0.present = \"TRUE\"\nsata0:1.present = \"TRUE\"\nsata0:1.fileName = \"{{.ISO}}\"\nsata0:1.deviceType = \"cdrom-image\"\n{{ if .ConfigDriveURL }}\nsata0:2.present = \"TRUE\"\nsata0:2.fileName = \"{{.ConfigDriveISO}}\"\nsata0:2.deviceType = \"cdrom-image\"\n{{ end }}\nvmci0.present = \"TRUE\"\nmem.hotadd = \"TRUE\"\nmemsize = \"{{.Memory}}\"\npowerType.powerOff = \"soft\"\npowerType.powerOn = \"soft\"\npowerType.reset = \"soft\"\npowerType.suspend = \"soft\"\nscsi0.present = \"TRUE\"\nscsi0.virtualDev = \"pvscsi\"\nscsi0:0.fileName = \"{{.MachineName}}.vmdk\"\nscsi0:0.present = \"TRUE\"\ntools.synctime = \"TRUE\"\nvirtualHW.productCompatibility = \"hosted\"\nvirtualHW.version = \"10\"\nmsg.autoanswer = \"TRUE\"\nuuid.action = \"create\"\nnumvcpus = \"{{.CPU}}\"\nhgfs.mapRootShare = \"FALSE\"\nhgfs.linkRootShare = \"FALSE\"\n`\n<|endoftext|>"}
{"text":"<commit_before>package survey\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"github.com\/curt-labs\/GoSurvey\/helpers\/database\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"time\"\n)\n\nvar (\n\tinsertUser = `insert into SurveyUser(fname, lname, email)\n\t\t\t\t\t\t\t\tvalues(?,?,?)`\n\tdeleteUser       = `delete from SurveyUser where id = ?`\n\tinsertUserAnswer = `insert into SurveyUserAnswer(userID, surveyID, questionID, answer)\n\t\t\t\t\t\t\t\t\tvalues(?,?,?,?)`\n\tgetAllSubmissions = `select su.id, su.fname, su.lname, su.email, su.date_added,\n\t\t\t\t\t\t\t\t\t\t\t\tsua.answer, sq.question, sua.date_answered, sua.surveyID\n\t\t\t\t\t\t\t\t\t\t\t\tfrom SurveyUserAnswer sua\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUser as su on sua.userID = su.id\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyQuestion as sq on sua.questionID = sq.id\n\t\t\t\t\t\t\t\t\t\t\t\torder by su.date_added desc\n\t\t\t\t\t\t\t\t\t\t\t\tlimit ?,?`\n\tgetAllSubmissionsBySurvey = `select su.id, su.fname, su.lname, su.email, su.date_added,\n\t\t\t\t\t\t\t\t\t\t\t\tsua.answer, sq.question, sua.date_answered, sua.surveyID\n\t\t\t\t\t\t\t\t\t\t\t\tfrom SurveyUserAnswer sua\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUser as su on sua.userID = su.id\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyQuestion as sq on sua.questionID = sq.id\n\t\t\t\t\t\t\t\t\t\t\t\twhere sua.surveyID = ?\n\t\t\t\t\t\t\t\t\t\t\t\torder by su.date_added desc\n\t\t\t\t\t\t\t\t\t\t\t\tlimit ?,?`\n\tgetSubmissionCount         = `select count(id) as count from SurveyUser`\n\tgetSubmissionCountBySurvey = `select count(distinct su.id) as count from SurveyUser as su\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUserAnswer as sua on su.id = sua.userID\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere sua.surveyID = ?`\n)\n\nconst (\n\tTIME_LAYOUT = \"2006-01-02 15:04:05 MST\"\n)\n\ntype SurveySubmission struct {\n\tID        int                      `json:\"id\"`\n\tUser      SurveyUser               `json:\"user\"`\n\tQuestions []SurveySubmissionAnswer `json:\"questions\"`\n\tSurvey    Survey                   `json:\"survey\"`\n}\n\ntype SurveyUser struct {\n\tID        int       `json:\"id\"`\n\tFirstName string    `json:\"fname\"`\n\tLastName  string    `json:\"lname\"`\n\tEmail     string    `json:\"email\"`\n\tDateAdded time.Time `json:\"date_added\"`\n}\n\ntype SurveySubmissionAnswer struct {\n\tID           int       `json:\"id\"`\n\tAnswer       string    `json:\"answer\"`\n\tQuestion     string    `json:\"question\"`\n\tDateAnswered time.Time `json:\"date_answered\"`\n}\n\nfunc GetAllSubmissions(skip, take, surveyID int) ([]SurveySubmission, error) {\n\tif take == 0 {\n\t\ttake = 25\n\t}\n\n\tif skip > 0 {\n\t\tskip = (skip - 1) * take\n\t}\n\n\tsubmissions := make([]SurveySubmission, 0)\n\tvar err error\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\tdefer db.Close()\n\n\tvar stmt *sql.Stmt\n\tif surveyID == 0 {\n\t\tstmt, err = db.Prepare(getAllSubmissions)\n\t} else {\n\t\tstmt, err = db.Prepare(getAllSubmissionsBySurvey)\n\t}\n\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\tdefer stmt.Close()\n\n\tvar res *sql.Rows\n\tif surveyID == 0 {\n\t\tres, err = stmt.Query(skip, take)\n\t} else {\n\t\tres, err = stmt.Query(surveyID, skip, take)\n\t}\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\n\tindexedSubmissions := make(map[int]SurveySubmission, 0)\n\n\tfor res.Next() {\n\t\tvar ans SurveySubmissionAnswer\n\t\tvar user SurveyUser\n\t\tvar s Survey\n\n\t\tif err = res.Scan(&user.ID, &user.FirstName, &user.LastName, &user.Email, &user.DateAdded, &ans.Answer, &ans.Question, &ans.DateAnswered, &s.ID); err == nil {\n\t\t\tif sm, _ := indexedSubmissions[user.ID]; sm.ID == 0 {\n\n\t\t\t\tss := SurveySubmission{\n\t\t\t\t\tID:   user.ID,\n\t\t\t\t\tUser: user,\n\t\t\t\t}\n\n\t\t\t\tif err := s.Get(); err == nil {\n\t\t\t\t\tss.Survey = s\n\t\t\t\t}\n\t\t\t\tindexedSubmissions[user.ID] = ss\n\t\t\t}\n\n\t\t\tsb := indexedSubmissions[user.ID]\n\t\t\tsb.Questions = append(sb.Questions, ans)\n\t\t\tindexedSubmissions[user.ID] = sb\n\t\t}\n\t}\n\n\tfor _, sb := range indexedSubmissions {\n\t\tsubmissions = append(submissions, sb)\n\t}\n\n\treturn submissions, nil\n}\n\nfunc SubmissionCount(surveyID int) int {\n\tvar err error\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tdefer db.Close()\n\n\tvar stmt *sql.Stmt\n\tif surveyID == 0 {\n\t\tstmt, err = db.Prepare(getSubmissionCount)\n\t} else {\n\t\tstmt, err = db.Prepare(getSubmissionCountBySurvey)\n\t}\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tdefer stmt.Close()\n\n\tvar total int\n\tif surveyID == 0 {\n\t\tstmt.QueryRow().Scan(&total)\n\t} else {\n\t\tstmt.QueryRow(surveyID).Scan(&total)\n\t}\n\n\treturn total\n}\n\nfunc (s *SurveySubmission) Submit() error {\n\n\tif len(s.Questions) == 0 {\n\t\treturn errors.New(\"cannot submit a survey without answers\")\n\t}\n\n\tsurv := Survey{\n\t\tID: s.ID,\n\t}\n\n\tif err := surv.Get(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.User.save(); err != nil {\n\t\treturn err\n\t}\n\n\tch := make(chan error)\n\n\tfor _, question := range s.Questions {\n\t\tgo func(ss *SurveySubmission, q SurveySubmissionAnswer) {\n\t\t\tch <- q.save(ss.User.ID, ss.ID)\n\t\t}(s, question)\n\t}\n\n\tfor _, _ = range s.Questions {\n\t\tif err := <-ch; err != nil {\n\t\t\ts.User.delete()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *SurveyUser) save() error {\n\tif s.FirstName == \"\" {\n\t\treturn errors.New(\"first name cannot be blank\")\n\t}\n\tif s.LastName == \"\" {\n\t\treturn errors.New(\"last name cannot be blank\")\n\t}\n\tif s.Email == \"\" {\n\t\treturn errors.New(\"e-mail name cannot be blank\")\n\t}\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(insertUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.Exec(s.FirstName, s.LastName, s.Email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.ID = int(id)\n\n\treturn nil\n}\n\nfunc (s *SurveySubmissionAnswer) save(userID, surveyID int) error {\n\tif s.Answer == \"\" {\n\t\treturn errors.New(\"answers cannot be blank\")\n\t}\n\tif userID == 0 {\n\t\treturn errors.New(\"failed to set name and\/or email\")\n\t}\n\tif s.ID == 0 {\n\t\treturn errors.New(\"failed to assign question\")\n\t}\n\tif surveyID == 0 {\n\t\treturn errors.New(\"failed to assign survey\")\n\t}\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(insertUserAnswer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(userID, surveyID, s.ID, s.Answer)\n\treturn err\n}\n\nfunc (s *SurveyUser) delete() error {\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(deleteUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(s.ID)\n\treturn err\n}\n<commit_msg>added get submission<commit_after>package survey\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"github.com\/curt-labs\/GoSurvey\/helpers\/database\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"time\"\n)\n\nvar (\n\tinsertUser = `insert into SurveyUser(fname, lname, email)\n\t\t\t\t\t\t\t\tvalues(?,?,?)`\n\tdeleteUser       = `delete from SurveyUser where id = ?`\n\tinsertUserAnswer = `insert into SurveyUserAnswer(userID, surveyID, questionID, answer)\n\t\t\t\t\t\t\t\t\tvalues(?,?,?,?)`\n\tgetAllSubmissions = `select su.id, su.fname, su.lname, su.email, su.date_added,\n\t\t\t\t\t\t\t\t\t\t\t\tsua.answer, sq.question, sua.date_answered, sua.surveyID\n\t\t\t\t\t\t\t\t\t\t\t\tfrom SurveyUserAnswer sua\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUser as su on sua.userID = su.id\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyQuestion as sq on sua.questionID = sq.id\n\t\t\t\t\t\t\t\t\t\t\t\torder by su.date_added desc\n\t\t\t\t\t\t\t\t\t\t\t\tlimit ?,?`\n\tgetAllSubmissionsBySurvey = `select su.id, su.fname, su.lname, su.email, su.date_added,\n\t\t\t\t\t\t\t\t\t\t\t\tsua.answer, sq.question, sua.date_answered, sua.surveyID\n\t\t\t\t\t\t\t\t\t\t\t\tfrom SurveyUserAnswer sua\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUser as su on sua.userID = su.id\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyQuestion as sq on sua.questionID = sq.id\n\t\t\t\t\t\t\t\t\t\t\t\twhere sua.surveyID = ?\n\t\t\t\t\t\t\t\t\t\t\t\torder by su.date_added desc\n\t\t\t\t\t\t\t\t\t\t\t\tlimit ?,?`\n\tgetSubmissionCount         = `select count(id) as count from SurveyUser`\n\tgetSubmissionCountBySurvey = `select count(distinct su.id) as count from SurveyUser as su\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUserAnswer as sua on su.id = sua.userID\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere sua.surveyID = ?`\n\tgetSubmission = `select su.id, su.fname, su.lname, su.email, su.date_added,\n\t\t\t\t\t\t\t\t\t\t\t\tsua.answer, sq.question, sua.date_answered, sua.surveyID\n\t\t\t\t\t\t\t\t\t\t\t\tfrom SurveyUserAnswer sua\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyUser as su on sua.userID = su.id\n\t\t\t\t\t\t\t\t\t\t\t\tjoin SurveyQuestion as sq on sua.questionID = sq.id\n\t\t\t\t\t\t\t\t\t\t\t\twhere su.id = ?`\n)\n\nconst (\n\tTIME_LAYOUT = \"2006-01-02 15:04:05 MST\"\n)\n\ntype SurveySubmission struct {\n\tID        int                      `json:\"id\"`\n\tUser      SurveyUser               `json:\"user\"`\n\tQuestions []SurveySubmissionAnswer `json:\"questions\"`\n\tSurvey    Survey                   `json:\"survey\"`\n}\n\ntype SurveyUser struct {\n\tID        int       `json:\"id\"`\n\tFirstName string    `json:\"fname\"`\n\tLastName  string    `json:\"lname\"`\n\tEmail     string    `json:\"email\"`\n\tDateAdded time.Time `json:\"date_added\"`\n}\n\ntype SurveySubmissionAnswer struct {\n\tID           int       `json:\"id\"`\n\tAnswer       string    `json:\"answer\"`\n\tQuestion     string    `json:\"question\"`\n\tDateAnswered time.Time `json:\"date_answered\"`\n}\n\nfunc GetAllSubmissions(skip, take, surveyID int) ([]SurveySubmission, error) {\n\tif take == 0 {\n\t\ttake = 25\n\t}\n\n\tif skip > 0 {\n\t\tskip = (skip - 1) * take\n\t}\n\n\tsubmissions := make([]SurveySubmission, 0)\n\tvar err error\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\tdefer db.Close()\n\n\tvar stmt *sql.Stmt\n\tif surveyID == 0 {\n\t\tstmt, err = db.Prepare(getAllSubmissions)\n\t} else {\n\t\tstmt, err = db.Prepare(getAllSubmissionsBySurvey)\n\t}\n\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\tdefer stmt.Close()\n\n\tvar res *sql.Rows\n\tif surveyID == 0 {\n\t\tres, err = stmt.Query(skip, take)\n\t} else {\n\t\tres, err = stmt.Query(surveyID, skip, take)\n\t}\n\tif err != nil {\n\t\treturn submissions, err\n\t}\n\n\tindexedSubmissions := make(map[int]SurveySubmission, 0)\n\n\tfor res.Next() {\n\t\tvar ans SurveySubmissionAnswer\n\t\tvar user SurveyUser\n\t\tvar s Survey\n\n\t\tif err = res.Scan(&user.ID, &user.FirstName, &user.LastName, &user.Email, &user.DateAdded, &ans.Answer, &ans.Question, &ans.DateAnswered, &s.ID); err == nil {\n\t\t\tif sm, _ := indexedSubmissions[user.ID]; sm.ID == 0 {\n\n\t\t\t\tss := SurveySubmission{\n\t\t\t\t\tID:   user.ID,\n\t\t\t\t\tUser: user,\n\t\t\t\t}\n\n\t\t\t\tif err := s.Get(); err == nil {\n\t\t\t\t\tss.Survey = s\n\t\t\t\t}\n\t\t\t\tindexedSubmissions[user.ID] = ss\n\t\t\t}\n\n\t\t\tsb := indexedSubmissions[user.ID]\n\t\t\tsb.Questions = append(sb.Questions, ans)\n\t\t\tindexedSubmissions[user.ID] = sb\n\t\t}\n\t}\n\n\tfor _, sb := range indexedSubmissions {\n\t\tsubmissions = append(submissions, sb)\n\t}\n\n\treturn submissions, nil\n}\n\nfunc SubmissionCount(surveyID int) int {\n\tvar err error\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tdefer db.Close()\n\n\tvar stmt *sql.Stmt\n\tif surveyID == 0 {\n\t\tstmt, err = db.Prepare(getSubmissionCount)\n\t} else {\n\t\tstmt, err = db.Prepare(getSubmissionCountBySurvey)\n\t}\n\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tdefer stmt.Close()\n\n\tvar total int\n\tif surveyID == 0 {\n\t\tstmt.QueryRow().Scan(&total)\n\t} else {\n\t\tstmt.QueryRow(surveyID).Scan(&total)\n\t}\n\n\treturn total\n}\n\nfunc (s *SurveySubmission) Get() error {\n\n\tvar err error\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(getSubmission)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.Query(s.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor res.Next() {\n\t\tvar ans SurveySubmissionAnswer\n\t\tvar sur Survey\n\n\t\tif err = res.Scan(&s.User.ID, &s.User.FirstName, &s.User.LastName, &s.User.Email, &s.User.DateAdded, &ans.Answer, &ans.Question, &ans.DateAnswered, &sur.ID); err == nil {\n\n\t\t\tif sur.Name == \"\" {\n\t\t\t\tif err := sur.Get(); err == nil {\n\t\t\t\t\ts.Survey = sur\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ts.Questions = append(s.Questions, ans)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *SurveySubmission) Submit() error {\n\n\tif len(s.Questions) == 0 {\n\t\treturn errors.New(\"cannot submit a survey without answers\")\n\t}\n\n\tsurv := Survey{\n\t\tID: s.ID,\n\t}\n\n\tif err := surv.Get(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.User.save(); err != nil {\n\t\treturn err\n\t}\n\n\tch := make(chan error)\n\n\tfor _, question := range s.Questions {\n\t\tgo func(ss *SurveySubmission, q SurveySubmissionAnswer) {\n\t\t\tch <- q.save(ss.User.ID, ss.ID)\n\t\t}(s, question)\n\t}\n\n\tfor _, _ = range s.Questions {\n\t\tif err := <-ch; err != nil {\n\t\t\ts.User.delete()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *SurveyUser) save() error {\n\tif s.FirstName == \"\" {\n\t\treturn errors.New(\"first name cannot be blank\")\n\t}\n\tif s.LastName == \"\" {\n\t\treturn errors.New(\"last name cannot be blank\")\n\t}\n\tif s.Email == \"\" {\n\t\treturn errors.New(\"e-mail name cannot be blank\")\n\t}\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(insertUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.Exec(s.FirstName, s.LastName, s.Email)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.ID = int(id)\n\n\treturn nil\n}\n\nfunc (s *SurveySubmissionAnswer) save(userID, surveyID int) error {\n\tif s.Answer == \"\" {\n\t\treturn errors.New(\"answers cannot be blank\")\n\t}\n\tif userID == 0 {\n\t\treturn errors.New(\"failed to set name and\/or email\")\n\t}\n\tif s.ID == 0 {\n\t\treturn errors.New(\"failed to assign question\")\n\t}\n\tif surveyID == 0 {\n\t\treturn errors.New(\"failed to assign survey\")\n\t}\n\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(insertUserAnswer)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(userID, surveyID, s.ID, s.Answer)\n\treturn err\n}\n\nfunc (s *SurveyUser) delete() error {\n\tdb, err := sql.Open(\"mysql\", database.ConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(deleteUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(s.ID)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\ntype RawGit struct {\n\tRawGitExport         `yaml:\",inline\"`\n\tAs                   string                `yaml:\"as,omitempty\"`\n\tUrl                  string                `yaml:\"url,omitempty\"`\n\tBranch               string                `yaml:\"branch,omitempty\"`\n\tCommit               string                `yaml:\"commit,omitempty\"`\n\tRawStageDependencies *RawStageDependencies `yaml:\"stageDependencies,omitempty\"`\n\n\tRawDimg *RawDimg `yaml:\"-\"` \/\/ parent\n\n\tUnsupportedAttributes map[string]interface{} `yaml:\",inline\"`\n}\n\nfunc (c *RawGit) ConfigSection() interface{} {\n\treturn c\n}\n\nfunc (c *RawGit) Doc() *Doc {\n\treturn c.RawDimg.Doc\n}\n\nfunc (c *RawGit) Type() string {\n\tif c.Url != \"\" {\n\t\treturn \"remote\"\n\t}\n\treturn \"local\"\n}\n\nfunc (c *RawGit) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tc.RawGitExport.RawExportBase = NewRawExportBase()\n\tif parent, ok := ParentStack.Peek().(*RawDimg); ok {\n\t\tc.RawDimg = parent\n\t}\n\n\tParentStack.Push(c)\n\ttype plain RawGit\n\terr := unmarshal((*plain)(c))\n\tParentStack.Pop()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RawGitExport.InlinedIntoRaw(c)\n\n\tif err := CheckOverflow(c.UnsupportedAttributes, c, c.RawDimg.Doc); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitLocalDirective() (gitLocal *GitLocal, err error) {\n\tgitLocal = &GitLocal{}\n\n\tif gitLocalExport, err := c.ToGitLocalExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitLocal.GitLocalExport = gitLocalExport\n\t}\n\n\tgitLocal.As = c.As\n\n\tgitLocal.Raw = c\n\n\tif err := c.ValidateGitLocalDirective(gitLocal); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitLocal, nil\n}\n\nfunc (c *RawGit) ValidateGitLocalDirective(gitLocal *GitLocal) (err error) {\n\tif err := gitLocal.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitLocalExportDirective() (gitLocalExport *GitLocalExport, err error) {\n\tgitLocalExport = &GitLocalExport{}\n\n\tgitLocalExport.GitExportBase = &GitExportBase{}\n\tif gitExport, err := c.RawGitExport.ToDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitLocalExport.GitExportBase.GitExport = gitExport\n\t}\n\n\tif c.RawStageDependencies != nil {\n\t\tif stageDependencies, err := c.RawStageDependencies.ToDirective(); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tgitLocalExport.StageDependencies = stageDependencies\n\t\t}\n\t}\n\n\tgitLocalExport.Raw = c\n\n\tif err := c.ValidateGitLocalExportDirective(gitLocalExport); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitLocalExport, nil\n}\n\nfunc (c *RawGit) ValidateGitLocalExportDirective(gitLocalExport *GitLocalExport) (err error) {\n\tif err := gitLocalExport.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitRemoteDirective() (gitRemote *GitRemote, err error) {\n\tgitRemote = &GitRemote{}\n\n\tif gitRemoteExport, err := c.ToGitRemoteExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitRemote.GitRemoteExport = gitRemoteExport\n\t}\n\n\tgitRemote.As = c.As\n\tgitRemote.Url = c.Url\n\n\tr := regexp.MustCompile(`.*?([^\/ ]+\/[^\/ ]+)(\\.git)?`)\n\tmatch := r.FindStringSubmatch(c.Url)\n\tif len(match) == 3 {\n\t\tgitRemote.Name = match[1]\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Cannot determine repo name from `url: %s`: url is not fit `.*?([^\/ ]+\/[^\/ ]+)(.git)?` regex!\\n\\n%s\\n%s\", c.Url, DumpConfigSection(c), DumpConfigDoc(c.RawDimg.Doc))\n\t}\n\n\tgitRemote.Raw = c\n\n\tif err := c.ValidateGitRemoteDirective(gitRemote); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitRemote, nil\n}\n\nfunc (c *RawGit) ValidateGitRemoteDirective(gitRemote *GitRemote) (err error) {\n\tif err := gitRemote.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitRemoteExportDirective() (gitRemoteExport *GitRemoteExport, err error) {\n\tgitRemoteExport = &GitRemoteExport{}\n\n\tif gitLocalExport, err := c.ToGitLocalExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitRemoteExport.GitLocalExport = gitLocalExport\n\t}\n\n\tgitRemoteExport.Branch = c.Branch\n\tgitRemoteExport.Commit = c.Commit\n\n\tgitRemoteExport.Raw = c\n\n\tif err := c.ValidateGitRemoteExportDirective(gitRemoteExport); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitRemoteExport, nil\n}\n\nfunc (c *RawGit) ValidateGitRemoteExportDirective(gitRemoteExport *GitRemoteExport) (err error) {\n\tif err := gitRemoteExport.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Config: fix git remote name from url regex<commit_after>package config\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\ntype RawGit struct {\n\tRawGitExport         `yaml:\",inline\"`\n\tAs                   string                `yaml:\"as,omitempty\"`\n\tUrl                  string                `yaml:\"url,omitempty\"`\n\tBranch               string                `yaml:\"branch,omitempty\"`\n\tCommit               string                `yaml:\"commit,omitempty\"`\n\tRawStageDependencies *RawStageDependencies `yaml:\"stageDependencies,omitempty\"`\n\n\tRawDimg *RawDimg `yaml:\"-\"` \/\/ parent\n\n\tUnsupportedAttributes map[string]interface{} `yaml:\",inline\"`\n}\n\nfunc (c *RawGit) ConfigSection() interface{} {\n\treturn c\n}\n\nfunc (c *RawGit) Doc() *Doc {\n\treturn c.RawDimg.Doc\n}\n\nfunc (c *RawGit) Type() string {\n\tif c.Url != \"\" {\n\t\treturn \"remote\"\n\t}\n\treturn \"local\"\n}\n\nfunc (c *RawGit) UnmarshalYAML(unmarshal func(interface{}) error) error {\n\tc.RawGitExport.RawExportBase = NewRawExportBase()\n\tif parent, ok := ParentStack.Peek().(*RawDimg); ok {\n\t\tc.RawDimg = parent\n\t}\n\n\tParentStack.Push(c)\n\ttype plain RawGit\n\terr := unmarshal((*plain)(c))\n\tParentStack.Pop()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RawGitExport.InlinedIntoRaw(c)\n\n\tif err := CheckOverflow(c.UnsupportedAttributes, c, c.RawDimg.Doc); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitLocalDirective() (gitLocal *GitLocal, err error) {\n\tgitLocal = &GitLocal{}\n\n\tif gitLocalExport, err := c.ToGitLocalExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitLocal.GitLocalExport = gitLocalExport\n\t}\n\n\tgitLocal.As = c.As\n\n\tgitLocal.Raw = c\n\n\tif err := c.ValidateGitLocalDirective(gitLocal); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitLocal, nil\n}\n\nfunc (c *RawGit) ValidateGitLocalDirective(gitLocal *GitLocal) (err error) {\n\tif err := gitLocal.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitLocalExportDirective() (gitLocalExport *GitLocalExport, err error) {\n\tgitLocalExport = &GitLocalExport{}\n\n\tgitLocalExport.GitExportBase = &GitExportBase{}\n\tif gitExport, err := c.RawGitExport.ToDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitLocalExport.GitExportBase.GitExport = gitExport\n\t}\n\n\tif c.RawStageDependencies != nil {\n\t\tif stageDependencies, err := c.RawStageDependencies.ToDirective(); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tgitLocalExport.StageDependencies = stageDependencies\n\t\t}\n\t}\n\n\tgitLocalExport.Raw = c\n\n\tif err := c.ValidateGitLocalExportDirective(gitLocalExport); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitLocalExport, nil\n}\n\nfunc (c *RawGit) ValidateGitLocalExportDirective(gitLocalExport *GitLocalExport) (err error) {\n\tif err := gitLocalExport.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitRemoteDirective() (gitRemote *GitRemote, err error) {\n\tgitRemote = &GitRemote{}\n\n\tif gitRemoteExport, err := c.ToGitRemoteExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitRemote.GitRemoteExport = gitRemoteExport\n\t}\n\n\tgitRemote.As = c.As\n\tgitRemote.Url = c.Url\n\n\tr := regexp.MustCompile(`.*?([^\/ ]+\/[^\/ ]+)(\\.git?)$`)\n\tmatch := r.FindStringSubmatch(c.Url)\n\tif len(match) == 3 {\n\t\tgitRemote.Name = match[1]\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Cannot determine repo name from `url: %s`: url is not fit `.*?([^\/ ]+\/[^\/ ]+)(.git)?` regex!\\n\\n%s\\n%s\", c.Url, DumpConfigSection(c), DumpConfigDoc(c.RawDimg.Doc))\n\t}\n\n\tgitRemote.Raw = c\n\n\tif err := c.ValidateGitRemoteDirective(gitRemote); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitRemote, nil\n}\n\nfunc (c *RawGit) ValidateGitRemoteDirective(gitRemote *GitRemote) (err error) {\n\tif err := gitRemote.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *RawGit) ToGitRemoteExportDirective() (gitRemoteExport *GitRemoteExport, err error) {\n\tgitRemoteExport = &GitRemoteExport{}\n\n\tif gitLocalExport, err := c.ToGitLocalExportDirective(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgitRemoteExport.GitLocalExport = gitLocalExport\n\t}\n\n\tgitRemoteExport.Branch = c.Branch\n\tgitRemoteExport.Commit = c.Commit\n\n\tgitRemoteExport.Raw = c\n\n\tif err := c.ValidateGitRemoteExportDirective(gitRemoteExport); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gitRemoteExport, nil\n}\n\nfunc (c *RawGit) ValidateGitRemoteExportDirective(gitRemoteExport *GitRemoteExport) (err error) {\n\tif err := gitRemoteExport.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package dialer\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/rancher\/norman\/types\/slice\"\n\t\"github.com\/rancher\/rancher\/pkg\/tunnelserver\"\n\t\"github.com\/rancher\/remotedialer\"\n\t\"github.com\/rancher\/rke\/k8s\"\n\t\"github.com\/rancher\/rke\/services\"\n\tv3 \"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\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n)\n\nfunc NewFactory(apiContext *config.ScaledContext) (*Factory, error) {\n\tauthorizer := tunnelserver.NewAuthorizer(apiContext)\n\ttunneler := tunnelserver.NewTunnelServer(authorizer)\n\n\treturn &Factory{\n\t\tclusterLister:    apiContext.Management.Clusters(\"\").Controller().Lister(),\n\t\tnodeLister:       apiContext.Management.Nodes(\"\").Controller().Lister(),\n\t\tTunnelServer:     tunneler,\n\t\tTunnelAuthorizer: authorizer,\n\t}, nil\n}\n\ntype Factory struct {\n\tnodeLister       v3.NodeLister\n\tclusterLister    v3.ClusterLister\n\tTunnelServer     *remotedialer.Server\n\tTunnelAuthorizer *tunnelserver.Authorizer\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, address)\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 isCloudDriver(cluster *v3.Cluster) bool {\n\treturn !cluster.Spec.Internal && cluster.Status.Driver != v3.ClusterDriverImported && cluster.Status.Driver != v3.ClusterDriverRKE\n}\n\nfunc (f *Factory) translateClusterAddress(cluster *v3.Cluster, clusterHostPort, address string) string {\n\tif clusterHostPort != address {\n\t\tlogrus.Debugf(\"dialerFactory: apiEndpoint clusterHostPort [%s] is not equal to address [%s]\", clusterHostPort, address)\n\t\treturn address\n\t}\n\n\thost, port, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn address\n\t}\n\n\t\/\/ Make sure that control plane node we are connecting to is not bad, also use internal address\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn address\n\t}\n\n\tclusterGood := v3.ClusterConditionReady.IsTrue(cluster)\n\tlogrus.Debugf(\"dialerFactory: ClusterConditionReady for cluster [%s] is [%t]\", cluster.Spec.DisplayName, clusterGood)\n\tlastGoodHost := \"\"\n\tlogrus.Debug(\"dialerFactory: finding a node to tunnel the cluster connection\")\n\tfor _, node := range nodes {\n\t\tvar (\n\t\t\tpublicIP  = node.Status.NodeAnnotations[k8s.ExternalAddressAnnotation]\n\t\t\tprivateIP = node.Status.NodeAnnotations[k8s.InternalAddressAnnotation]\n\t\t)\n\n\t\tfakeNode := &v1.Node{\n\t\t\tStatus: node.Status.InternalNodeStatus,\n\t\t}\n\n\t\tnodeGood := v3.NodeConditionRegistered.IsTrue(node) && v3.NodeConditionProvisioned.IsTrue(node) &&\n\t\t\t!v3.NodeConditionReady.IsUnknown(fakeNode) && node.DeletionTimestamp == nil\n\n\t\tif !nodeGood {\n\t\t\tlogrus.Debugf(\"dialerFactory: Skipping node [%s] for tunneling the cluster connection because nodeConditions are not as expected\", node.Spec.RequestedHostname)\n\t\t\tlogrus.Debugf(\"dialerFactory: Node conditions for node [%s]: %+v\", node.Status.NodeName, node.Status.Conditions)\n\t\t\tcontinue\n\t\t}\n\t\tif privateIP == \"\" {\n\t\t\tlogrus.Debugf(\"dialerFactory: Skipping node [%s] for tunneling the cluster connection because privateIP is empty\", node.Status.NodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tlogrus.Debugf(\"dialerFactory: IP addresses for node [%s]: publicIP [%s], privateIP [%s]\", node.Status.NodeName, publicIP, privateIP)\n\n\t\tif publicIP == host {\n\t\t\tlogrus.Debugf(\"dialerFactory: publicIP [%s] for node [%s] matches apiEndpoint host [%s], checking if cluster condition Ready is True\", publicIP, node.Status.NodeName, host)\n\t\t\tif clusterGood {\n\t\t\t\tlogrus.Debug(\"dialerFactory: cluster condition Ready is True\")\n\t\t\t\thost = privateIP\n\t\t\t\tlogrus.Debugf(\"dialerFactory: Using privateIP [%s] of node [%s] as node to tunnel the cluster connection\", privateIP, node.Status.NodeName)\n\t\t\t\treturn fmt.Sprintf(\"%s:%s\", host, port)\n\t\t\t}\n\t\t\tlogrus.Debug(\"dialerFactory: cluster condition Ready is False\")\n\t\t} else if node.Status.NodeConfig != nil && slice.ContainsString(node.Status.NodeConfig.Role, services.ControlRole) {\n\t\t\tlogrus.Debugf(\"dialerFactory: setting node [%s] with privateIP [%s] as option for the connection as it is a controlplane node\", node.Status.NodeName, privateIP)\n\t\t\tlastGoodHost = privateIP\n\t\t}\n\t}\n\n\tif lastGoodHost != \"\" {\n\t\tlogrus.Debugf(\"dialerFactory: returning [%s:%s] as last good option to tunnel the cluster connection\", lastGoodHost, port)\n\t\treturn fmt.Sprintf(\"%s:%s\", lastGoodHost, port)\n\t}\n\n\tlogrus.Debugf(\"dialerFactory: returning [%s], as no good option was found (no match with apiEndpoint or a controlplane node with correct conditions\", address)\n\treturn address\n}\n\nfunc (f *Factory) clusterDialer(clusterName, address 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 cluster.Spec.Internal {\n\t\t\/\/ For local (embedded, or import) we just assume we can connect directly\n\t\treturn native()\n\t}\n\n\thostPort := hostPort(cluster)\n\tlogrus.Debugf(\"dialerFactory: apiEndpoint hostPort for cluster [%s] is [%s]\", clusterName, hostPort)\n\tif address == hostPort && isCloudDriver(cluster) {\n\t\t\/\/ For cloud drivers we just connect directly to the k8s API, not through the tunnel.  All other go through tunnel\n\t\treturn native()\n\t}\n\n\tif f.TunnelServer.HasSession(cluster.Name) {\n\t\tlogrus.Debugf(\"dialerFactory: tunnel session found for cluster [%s]\", cluster.Name)\n\t\tcd := f.TunnelServer.Dialer(cluster.Name, 15*time.Second)\n\t\treturn func(network, address string) (net.Conn, error) {\n\t\t\tif cluster.Status.Driver == v3.ClusterDriverRKE {\n\t\t\t\taddress = f.translateClusterAddress(cluster, hostPort, address)\n\t\t\t}\n\t\t\tlogrus.Debugf(\"dialerFactory: returning network [%s] and address [%s] as clusterDialer\", network, address)\n\t\t\treturn cd(network, address)\n\t\t}, nil\n\t}\n\tlogrus.Debugf(\"dialerFactory: no tunnel session found for cluster [%s], falling back to nodeDialer\", cluster.Name)\n\n\t\/\/ Try to connect to a node for the cluster dialer\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localAPIEndpoint bool\n\tif cluster.Status.Driver == v3.ClusterDriverRKE {\n\t\tlocalAPIEndpoint = true\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.DeletionTimestamp == nil && v3.NodeConditionProvisioned.IsTrue(node) {\n\t\t\tlogrus.Debugf(\"dialerFactory: using node [%s]\/[%s] for nodeDialer\",\n\t\t\t\tnode.Labels[\"management.cattle.io\/nodename\"], node.Name)\n\t\t\tif nodeDialer, err := f.nodeDialer(clusterName, node.Name); err == nil {\n\t\t\t\treturn func(network, address string) (net.Conn, error) {\n\t\t\t\t\tif address == hostPort && localAPIEndpoint {\n\t\t\t\t\t\tlogrus.Debug(\"dialerFactory: rewriting address\/port to 127.0.0.1:6443 as node may not\" +\n\t\t\t\t\t\t\t\" have direct kube-api access\")\n\t\t\t\t\t\t\/\/ The node dialer may not have direct access to kube-api so we hit localhost:6443 instead\n\t\t\t\t\t\taddress = \"127.0.0.1:6443\"\n\t\t\t\t\t}\n\t\t\t\t\tlogrus.Debugf(\"dialerFactory: Returning network [%s] and address [%s] as nodeDialer\", network, address)\n\t\t\t\t\treturn nodeDialer(network, address)\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"waiting for cluster agent to connect\")\n}\n\nfunc hostPort(cluster *v3.Cluster) string {\n\tu, err := url.Parse(cluster.Status.APIEndpoint)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif strings.Contains(u.Host, \":\") {\n\t\treturn u.Host\n\t}\n\treturn u.Host + \":443\"\n}\n\nfunc native() (dialer.Dialer, error) {\n\tnetDialer := net.Dialer{\n\t\tTimeout:   30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\treturn netDialer.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\tsessionKey := machineSessionKey(machine)\n\tif f.TunnelServer.HasSession(sessionKey) {\n\t\tnetwork, address := \"unix\", \"\/var\/run\/docker.sock\"\n\t\tif machine.Status.InternalNodeStatus.NodeInfo.OperatingSystem == \"windows\" {\n\t\t\tnetwork, address = \"npipe\", \"\/\/.\/pipe\/docker_engine\"\n\t\t}\n\t\td := f.TunnelServer.Dialer(sessionKey, 15*time.Second)\n\t\treturn func(string, string) (net.Conn, error) {\n\t\t\treturn d(network, address)\n\t\t}, nil\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\tsessionKey := machineSessionKey(machine)\n\tif f.TunnelServer.HasSession(sessionKey) {\n\t\td := f.TunnelServer.Dialer(sessionKey, 15*time.Second)\n\t\treturn dialer.Dialer(d), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to [%s:%s]\", clusterName, machineName)\n}\n\nfunc machineSessionKey(machine *v3.Node) string {\n\treturn fmt.Sprintf(\"%s:%s\", machine.Namespace, machine.Name)\n}\n<commit_msg>Hosted cluster dialer fix to work with proxy<commit_after>package dialer\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/rancher\/norman\/types\/slice\"\n\t\"github.com\/rancher\/rancher\/pkg\/tunnelserver\"\n\t\"github.com\/rancher\/remotedialer\"\n\t\"github.com\/rancher\/rke\/k8s\"\n\t\"github.com\/rancher\/rke\/services\"\n\tv3 \"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\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n)\n\nfunc NewFactory(apiContext *config.ScaledContext) (*Factory, error) {\n\tauthorizer := tunnelserver.NewAuthorizer(apiContext)\n\ttunneler := tunnelserver.NewTunnelServer(authorizer)\n\n\treturn &Factory{\n\t\tclusterLister:    apiContext.Management.Clusters(\"\").Controller().Lister(),\n\t\tnodeLister:       apiContext.Management.Nodes(\"\").Controller().Lister(),\n\t\tTunnelServer:     tunneler,\n\t\tTunnelAuthorizer: authorizer,\n\t}, nil\n}\n\ntype Factory struct {\n\tnodeLister       v3.NodeLister\n\tclusterLister    v3.ClusterLister\n\tTunnelServer     *remotedialer.Server\n\tTunnelAuthorizer *tunnelserver.Authorizer\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, address)\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 isCloudDriver(cluster *v3.Cluster) bool {\n\treturn !cluster.Spec.Internal && cluster.Status.Driver != v3.ClusterDriverImported && cluster.Status.Driver != v3.ClusterDriverRKE\n}\n\nfunc (f *Factory) translateClusterAddress(cluster *v3.Cluster, clusterHostPort, address string) string {\n\tif clusterHostPort != address {\n\t\tlogrus.Debugf(\"dialerFactory: apiEndpoint clusterHostPort [%s] is not equal to address [%s]\", clusterHostPort, address)\n\t\treturn address\n\t}\n\n\thost, port, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn address\n\t}\n\n\t\/\/ Make sure that control plane node we are connecting to is not bad, also use internal address\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn address\n\t}\n\n\tclusterGood := v3.ClusterConditionReady.IsTrue(cluster)\n\tlogrus.Debugf(\"dialerFactory: ClusterConditionReady for cluster [%s] is [%t]\", cluster.Spec.DisplayName, clusterGood)\n\tlastGoodHost := \"\"\n\tlogrus.Debug(\"dialerFactory: finding a node to tunnel the cluster connection\")\n\tfor _, node := range nodes {\n\t\tvar (\n\t\t\tpublicIP  = node.Status.NodeAnnotations[k8s.ExternalAddressAnnotation]\n\t\t\tprivateIP = node.Status.NodeAnnotations[k8s.InternalAddressAnnotation]\n\t\t)\n\n\t\tfakeNode := &v1.Node{\n\t\t\tStatus: node.Status.InternalNodeStatus,\n\t\t}\n\n\t\tnodeGood := v3.NodeConditionRegistered.IsTrue(node) && v3.NodeConditionProvisioned.IsTrue(node) &&\n\t\t\t!v3.NodeConditionReady.IsUnknown(fakeNode) && node.DeletionTimestamp == nil\n\n\t\tif !nodeGood {\n\t\t\tlogrus.Debugf(\"dialerFactory: Skipping node [%s] for tunneling the cluster connection because nodeConditions are not as expected\", node.Spec.RequestedHostname)\n\t\t\tlogrus.Debugf(\"dialerFactory: Node conditions for node [%s]: %+v\", node.Status.NodeName, node.Status.Conditions)\n\t\t\tcontinue\n\t\t}\n\t\tif privateIP == \"\" {\n\t\t\tlogrus.Debugf(\"dialerFactory: Skipping node [%s] for tunneling the cluster connection because privateIP is empty\", node.Status.NodeName)\n\t\t\tcontinue\n\t\t}\n\n\t\tlogrus.Debugf(\"dialerFactory: IP addresses for node [%s]: publicIP [%s], privateIP [%s]\", node.Status.NodeName, publicIP, privateIP)\n\n\t\tif publicIP == host {\n\t\t\tlogrus.Debugf(\"dialerFactory: publicIP [%s] for node [%s] matches apiEndpoint host [%s], checking if cluster condition Ready is True\", publicIP, node.Status.NodeName, host)\n\t\t\tif clusterGood {\n\t\t\t\tlogrus.Debug(\"dialerFactory: cluster condition Ready is True\")\n\t\t\t\thost = privateIP\n\t\t\t\tlogrus.Debugf(\"dialerFactory: Using privateIP [%s] of node [%s] as node to tunnel the cluster connection\", privateIP, node.Status.NodeName)\n\t\t\t\treturn fmt.Sprintf(\"%s:%s\", host, port)\n\t\t\t}\n\t\t\tlogrus.Debug(\"dialerFactory: cluster condition Ready is False\")\n\t\t} else if node.Status.NodeConfig != nil && slice.ContainsString(node.Status.NodeConfig.Role, services.ControlRole) {\n\t\t\tlogrus.Debugf(\"dialerFactory: setting node [%s] with privateIP [%s] as option for the connection as it is a controlplane node\", node.Status.NodeName, privateIP)\n\t\t\tlastGoodHost = privateIP\n\t\t}\n\t}\n\n\tif lastGoodHost != \"\" {\n\t\tlogrus.Debugf(\"dialerFactory: returning [%s:%s] as last good option to tunnel the cluster connection\", lastGoodHost, port)\n\t\treturn fmt.Sprintf(\"%s:%s\", lastGoodHost, port)\n\t}\n\n\tlogrus.Debugf(\"dialerFactory: returning [%s], as no good option was found (no match with apiEndpoint or a controlplane node with correct conditions\", address)\n\treturn address\n}\n\nfunc (f *Factory) clusterDialer(clusterName, address 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 cluster.Spec.Internal {\n\t\t\/\/ For local (embedded, or import) we just assume we can connect directly\n\t\treturn native()\n\t}\n\n\thostPort := hostPort(cluster)\n\tlogrus.Debugf(\"dialerFactory: apiEndpoint hostPort for cluster [%s] is [%s]\", clusterName, hostPort)\n\tif (address == hostPort || isProxyAddress(address)) && isCloudDriver(cluster) {\n\t\t\/\/ For cloud drivers we just connect directly to the k8s API, not through the tunnel.  All other go through tunnel\n\t\treturn native()\n\t}\n\n\tif f.TunnelServer.HasSession(cluster.Name) {\n\t\tlogrus.Debugf(\"dialerFactory: tunnel session found for cluster [%s]\", cluster.Name)\n\t\tcd := f.TunnelServer.Dialer(cluster.Name, 15*time.Second)\n\t\treturn func(network, address string) (net.Conn, error) {\n\t\t\tif cluster.Status.Driver == v3.ClusterDriverRKE {\n\t\t\t\taddress = f.translateClusterAddress(cluster, hostPort, address)\n\t\t\t}\n\t\t\tlogrus.Debugf(\"dialerFactory: returning network [%s] and address [%s] as clusterDialer\", network, address)\n\t\t\treturn cd(network, address)\n\t\t}, nil\n\t}\n\tlogrus.Debugf(\"dialerFactory: no tunnel session found for cluster [%s], falling back to nodeDialer\", cluster.Name)\n\n\t\/\/ Try to connect to a node for the cluster dialer\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar localAPIEndpoint bool\n\tif cluster.Status.Driver == v3.ClusterDriverRKE {\n\t\tlocalAPIEndpoint = true\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.DeletionTimestamp == nil && v3.NodeConditionProvisioned.IsTrue(node) {\n\t\t\tlogrus.Debugf(\"dialerFactory: using node [%s]\/[%s] for nodeDialer\",\n\t\t\t\tnode.Labels[\"management.cattle.io\/nodename\"], node.Name)\n\t\t\tif nodeDialer, err := f.nodeDialer(clusterName, node.Name); err == nil {\n\t\t\t\treturn func(network, address string) (net.Conn, error) {\n\t\t\t\t\tif address == hostPort && localAPIEndpoint {\n\t\t\t\t\t\tlogrus.Debug(\"dialerFactory: rewriting address\/port to 127.0.0.1:6443 as node may not\" +\n\t\t\t\t\t\t\t\" have direct kube-api access\")\n\t\t\t\t\t\t\/\/ The node dialer may not have direct access to kube-api so we hit localhost:6443 instead\n\t\t\t\t\t\taddress = \"127.0.0.1:6443\"\n\t\t\t\t\t}\n\t\t\t\t\tlogrus.Debugf(\"dialerFactory: Returning network [%s] and address [%s] as nodeDialer\", network, address)\n\t\t\t\t\treturn nodeDialer(network, address)\n\t\t\t\t}, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"waiting for cluster agent to connect\")\n}\n\nfunc hostPort(cluster *v3.Cluster) string {\n\tu, err := url.Parse(cluster.Status.APIEndpoint)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif strings.Contains(u.Host, \":\") {\n\t\treturn u.Host\n\t}\n\treturn u.Host + \":443\"\n}\n\nfunc native() (dialer.Dialer, error) {\n\tnetDialer := net.Dialer{\n\t\tTimeout:   30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\treturn netDialer.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\tsessionKey := machineSessionKey(machine)\n\tif f.TunnelServer.HasSession(sessionKey) {\n\t\tnetwork, address := \"unix\", \"\/var\/run\/docker.sock\"\n\t\tif machine.Status.InternalNodeStatus.NodeInfo.OperatingSystem == \"windows\" {\n\t\t\tnetwork, address = \"npipe\", \"\/\/.\/pipe\/docker_engine\"\n\t\t}\n\t\td := f.TunnelServer.Dialer(sessionKey, 15*time.Second)\n\t\treturn func(string, string) (net.Conn, error) {\n\t\t\treturn d(network, address)\n\t\t}, nil\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\tsessionKey := machineSessionKey(machine)\n\tif f.TunnelServer.HasSession(sessionKey) {\n\t\td := f.TunnelServer.Dialer(sessionKey, 15*time.Second)\n\t\treturn dialer.Dialer(d), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to [%s:%s]\", clusterName, machineName)\n}\n\nfunc machineSessionKey(machine *v3.Node) string {\n\treturn fmt.Sprintf(\"%s:%s\", machine.Namespace, machine.Name)\n}\n\nfunc isProxyAddress(address string) bool {\n\tproxy := getEnvAny(\"HTTP_PROXY\", \"http_proxy\")\n\tif proxy == \"\" {\n\t\tproxy = getEnvAny(\"HTTPS_PROXY\", \"https_proxy\")\n\t}\n\n\tif proxy == \"\" {\n\t\treturn false\n\t}\n\n\tparsed, err := parseProxy(proxy)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to parse http_proxy url %s: %v\", proxy, err)\n\t\treturn false\n\t}\n\treturn parsed.Host == address\n}\n\nfunc getEnvAny(names ...string) string {\n\tfor _, n := range names {\n\t\tif val := os.Getenv(n); val != \"\" {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc parseProxy(proxy string) (*url.URL, error) {\n\tif proxy == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tproxyURL, err := url.Parse(proxy)\n\tif err != nil ||\n\t\t(proxyURL.Scheme != \"http\" &&\n\t\t\tproxyURL.Scheme != \"https\" &&\n\t\t\tproxyURL.Scheme != \"socks5\") {\n\t\t\/\/ proxy was bogus. Try pre-pending \"http:\/\/\" to it and\n\t\t\/\/ see if that parses correctly. If not, fall through\n\t\tif proxyURL, err := url.Parse(\"http:\/\/\" + proxy); err == nil {\n\t\t\treturn proxyURL, nil\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid proxy address %q: %v\", proxy, err)\n\t}\n\treturn proxyURL, 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 fuzz\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/api\/extensions\/v1beta1\"\n\tbackendconfig \"k8s.io\/ingress-gce\/pkg\/apis\/backendconfig\/v1beta1\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\/providers\/gce\/cloud\"\n)\n\n\/\/ pathForDefaultBackend is a unique string that will not match any path.\nconst pathForDefaultBackend = \"\/edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb\"\n\n\/\/ ValidatorEnv captures non-Ingress spec related environment that affect the\n\/\/ set of validations and Features.\ntype ValidatorEnv interface {\n\tBackendConfigs() (map[string]*backendconfig.BackendConfig, error)\n\tServices() (map[string]*v1.Service, error)\n\tCloud() cloud.Cloud\n}\n\n\/\/ MockValidatorEnv is an environment that is used for mock testing.\ntype MockValidatorEnv struct {\n\tBackendConfigsMap map[string]*backendconfig.BackendConfig\n\tServicesMap       map[string]*v1.Service\n\tMockCloud         *cloud.MockGCE\n}\n\n\/\/ BackendConfigs implements ValidatorEnv.\nfunc (e *MockValidatorEnv) BackendConfigs() (map[string]*backendconfig.BackendConfig, error) {\n\treturn e.BackendConfigsMap, nil\n}\n\n\/\/ Services implements ValidatorEnv.\nfunc (e *MockValidatorEnv) Services() (map[string]*v1.Service, error) {\n\treturn e.ServicesMap, nil\n}\n\n\/\/ Cloud implements ValidatorEnv.\nfunc (e *MockValidatorEnv) Cloud() cloud.Cloud {\n\treturn e.MockCloud\n}\n\n\/\/ IngressValidatorAttributes are derived attributes governing how the Ingress\n\/\/ is validated. Features will use this structure to express changes to the\n\/\/ standard checks by modifying this struct.\ntype IngressValidatorAttributes struct {\n\tCheckHTTP           bool\n\tCheckHTTPS          bool\n\tRejectInsecureCerts bool\n\tRequestTimeout      time.Duration\n\t\/\/ HTTPPort and HTTPSPort are used only for unit testing.\n\tHTTPPort  int\n\tHTTPSPort int\n}\n\nfunc (a *IngressValidatorAttributes) equal(b *IngressValidatorAttributes) bool {\n\treturn *a == *b\n}\n\nfunc (a *IngressValidatorAttributes) clone() *IngressValidatorAttributes {\n\tvar ret IngressValidatorAttributes\n\tret = *a\n\treturn &ret\n}\n\nfunc (a *IngressValidatorAttributes) schemes() []string {\n\tvar ret []string\n\tif a.CheckHTTP {\n\t\tret = append(ret, \"http\")\n\t}\n\tif a.CheckHTTPS {\n\t\tret = append(ret, \"https\")\n\t}\n\treturn ret\n}\n\n\/\/ baseAttributes apply settings for the vanilla Ingress spec.\nfunc (a *IngressValidatorAttributes) baseAttributes(ing *v1beta1.Ingress) {\n\ta.CheckHTTP = true\n\tif len(ing.Spec.TLS) != 0 {\n\t\ta.CheckHTTPS = true\n\t}\n}\n\n\/\/ applyFeatures applies the settings for each of the additional features.\nfunc (a *IngressValidatorAttributes) applyFeatures(env ValidatorEnv, ing *v1beta1.Ingress, features []FeatureValidator) error {\n\tfor _, f := range features {\n\t\tklog.V(4).Infof(\"Applying feature %q\", f.Name())\n\t\tif err := f.ConfigureAttributes(env, ing, a); err != nil {\n\t\t\tklog.Warningf(\"Feature %q could not be applied: %v\", f.Name(), err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Try to configure attributes again; no additional changes should occur.\n\t\/\/ If changes are detected, one of the features as written is not\n\t\/\/ commutative and should be fixed.\n\tcopy := a.clone()\n\tfor _, f := range features {\n\t\tif err := f.ConfigureAttributes(env, ing, copy); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !a.equal(copy) {\n\t\t\tklog.Errorf(\"Feature %q is unstable generating attributes, %+v becomes %+v\", f.Name(), *a, *copy)\n\t\t\treturn fmt.Errorf(\"feature %q is unstable generating attributes, %+v becomes %+v\", f.Name(), *a, *copy)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ IngressResult is the result of an Ingress validation.\ntype IngressResult struct {\n\tErr   error\n\tPaths []*PathResult\n}\n\n\/\/ PathResult is the result of validating a path.\ntype PathResult struct {\n\tScheme string\n\tHost   string\n\tPath   string\n\tErr    error\n}\n\n\/\/ defaultAttributes are the base attributes for validation.\nfunc defaultAttributes() *IngressValidatorAttributes {\n\treturn &IngressValidatorAttributes{\n\t\tCheckHTTP:      true,\n\t\tCheckHTTPS:     false,\n\t\tHTTPPort:       80,\n\t\tHTTPSPort:      443,\n\t\tRequestTimeout: 1 * time.Second,\n\t}\n}\n\n\/\/ NewIngressValidator returns a new validator for checking the correctness of\n\/\/ an Ingress spec against the behavior of the instantiated load balancer.\n\/\/ If attribs is nil, then the default set of attributes will be used.\nfunc NewIngressValidator(env ValidatorEnv, ing *v1beta1.Ingress, features []Feature, attribs *IngressValidatorAttributes) (*IngressValidator, error) {\n\tvar fvs []FeatureValidator\n\tfor _, f := range features {\n\t\tfvs = append(fvs, f.NewValidator())\n\t}\n\n\tif attribs == nil {\n\t\tattribs = defaultAttributes()\n\t}\n\tattribs.baseAttributes(ing)\n\tif err := attribs.applyFeatures(env, ing, fvs); err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\treturn &IngressValidator{\n\t\ting:      ing,\n\t\tfeatures: fvs,\n\t\tattribs:  attribs,\n\t\tclient:   client,\n\t}, nil\n}\n\n\/\/ IngressValidator encapsulates the logic required to validate a given configuration\n\/\/ is behaving correctly.\ntype IngressValidator struct {\n\ting      *v1beta1.Ingress\n\tfeatures []FeatureValidator\n\n\tattribs *IngressValidatorAttributes\n\tclient  *http.Client\n}\n\n\/\/ the right SSL certificate is presented\n\/\/ each path, each host returns the right contents\n\n\/\/ vip for the load balancer. This currently uses the first entry, returns nil\n\/\/ if the VIP is not available.\nfunc (v *IngressValidator) vip() *string {\n\tstatuses := v.ing.Status.LoadBalancer.Ingress\n\tif len(statuses) == 0 {\n\t\treturn nil\n\t}\n\tret := statuses[0].IP\n\treturn &ret\n}\n\n\/\/ Check runs all of the checks against the instantiated load balancer.\nfunc (v *IngressValidator) Check(ctx context.Context) *IngressResult {\n\tklog.V(3).Infof(\"Check Ingress %s\/%s attribs=%+v\", v.ing.Namespace, v.ing.Name, v.attribs)\n\tret := &IngressResult{}\n\tret.Err = v.CheckPaths(ctx, ret)\n\treturn ret\n}\n\n\/\/ CheckPaths checks the host, paths that have been configured. Checks are\n\/\/ run in parallel.\nfunc (v *IngressValidator) CheckPaths(ctx context.Context, vr *IngressResult) error {\n\tvar (\n\t\tthunks []func()\n\t\twg     sync.WaitGroup\n\t)\n\tfor _, scheme := range v.attribs.schemes() {\n\t\tif v.ing.Spec.Backend != nil {\n\t\t\tklog.V(2).Infof(\"Checking default backend for Ingress %s\/%s\", v.ing.Namespace, v.ing.Name)\n\t\t\t\/\/ Capture variables for the thunk.\n\t\t\tresult := &PathResult{Scheme: scheme}\n\t\t\tvr.Paths = append(vr.Paths, result)\n\t\t\tscheme := scheme\n\t\t\tctx, cancelFunc := context.WithTimeout(ctx, v.attribs.RequestTimeout)\n\t\t\tdefer cancelFunc()\n\t\t\tf := func() {\n\t\t\t\tresult.Err = v.checkPath(ctx, scheme, \"\", pathForDefaultBackend)\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t\tthunks = append(thunks, f)\n\t\t\twg.Add(1)\n\t\t}\n\n\t\tfor _, rule := range v.ing.Spec.Rules {\n\t\t\tif rule.HTTP == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, path := range rule.HTTP.Paths {\n\t\t\t\t\/\/ Capture variables for the thunk.\n\t\t\t\tresult := &PathResult{Scheme: scheme, Host: rule.Host, Path: path.Path}\n\t\t\t\tvr.Paths = append(vr.Paths, result)\n\t\t\t\tscheme, host, path := scheme, rule.Host, path.Path\n\t\t\t\tctx, cancelFunc := context.WithTimeout(ctx, v.attribs.RequestTimeout)\n\t\t\t\tdefer cancelFunc()\n\t\t\t\tf := func() {\n\t\t\t\t\tresult.Err = v.checkPath(ctx, scheme, host, path)\n\t\t\t\t\twg.Done()\n\t\t\t\t}\n\t\t\t\tthunks = append(thunks, f)\n\t\t\t\twg.Add(1)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, f := range thunks {\n\t\tgo f()\n\t}\n\tklog.V(2).Infof(\"Waiting for path checks for Ingress %s\/%s to finish\", v.ing.Namespace, v.ing.Name)\n\twg.Wait()\n\n\tfor _, r := range vr.Paths {\n\t\tif r.Err != nil {\n\t\t\tklog.V(2).Infof(\"Got an error checking paths for Ingress %s\/%s: %v\", v.ing.Namespace, v.ing.Name, r.Err)\n\t\t\treturn r.Err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ checkPath performs a check for scheme:\/\/host\/path.\nfunc (v *IngressValidator) checkPath(ctx context.Context, scheme, host, path string) error {\n\tif v.vip() == nil {\n\t\treturn fmt.Errorf(\"ingress %s\/%s does not have a VIP\", v.ing.Namespace, v.ing.Name)\n\t}\n\tvip := *v.vip()\n\n\turl := fmt.Sprintf(\"%s:\/\/%s%s%s\", scheme, vip, portStr(v.attribs, scheme), path)\n\tklog.V(3).Infof(\"Checking Ingress %s\/%s url=%q\", v.ing.Namespace, v.ing.Name, url)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif host != \"\" {\n\t\treq.Host = host\n\t}\n\treq = req.WithContext(ctx)\n\n\t\/\/ Apply modifications for the features.\n\tfor _, f := range v.features {\n\t\tf.ModifyRequest(host, path, req)\n\t}\n\n\tklog.V(3).Infof(\"Request is %+v\", *req)\n\n\tresp, err := v.client.Do(req)\n\tif err != nil && err != http.ErrUseLastResponse {\n\t\tklog.Infof(\"Ingress %s\/%s: %v\", v.ing.Namespace, v.ing.Name, err)\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Infof(\"Ingress %s\/%s reading body: %v\", v.ing.Namespace, v.ing.Name, err)\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"Ingress %s\/%s GET %q: %d (%d bytes)\", v.ing.Namespace, v.ing.Name, url, resp.StatusCode, len(body))\n\n\tdoStandardCheck := true\n\t\/\/ Perform the checks for each of the features.\n\tfor _, f := range v.features {\n\t\taction, err := f.CheckResponse(host, path, resp, body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch action {\n\t\tcase CheckResponseContinue:\n\t\tcase CheckResponseSkip:\n\t\t\tdoStandardCheck = false\n\t\t}\n\t}\n\n\tif doStandardCheck && resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"ingress %s\/%s: GET %q: %d, want 200\", v.ing.Namespace, v.ing.Name, url, resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n\/\/ portStr returns the \":<port>\" for the given scheme. If the port is default\n\/\/ or scheme is unknown then \"\" will be returned.\nfunc portStr(a *IngressValidatorAttributes, scheme string) string {\n\tswitch scheme {\n\tcase \"http\":\n\t\tif a.HTTPPort == 80 {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\":%d\", a.HTTPPort)\n\tcase \"https\":\n\t\tif a.HTTPSPort == 443 {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\":%d\", a.HTTPSPort)\n\t}\n\treturn \"\"\n}\n<commit_msg>Return name of validator in error from CheckResponse()<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 fuzz\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/api\/extensions\/v1beta1\"\n\tbackendconfig \"k8s.io\/ingress-gce\/pkg\/apis\/backendconfig\/v1beta1\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\/providers\/gce\/cloud\"\n)\n\n\/\/ pathForDefaultBackend is a unique string that will not match any path.\nconst pathForDefaultBackend = \"\/edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb\"\n\n\/\/ ValidatorEnv captures non-Ingress spec related environment that affect the\n\/\/ set of validations and Features.\ntype ValidatorEnv interface {\n\tBackendConfigs() (map[string]*backendconfig.BackendConfig, error)\n\tServices() (map[string]*v1.Service, error)\n\tCloud() cloud.Cloud\n}\n\n\/\/ MockValidatorEnv is an environment that is used for mock testing.\ntype MockValidatorEnv struct {\n\tBackendConfigsMap map[string]*backendconfig.BackendConfig\n\tServicesMap       map[string]*v1.Service\n\tMockCloud         *cloud.MockGCE\n}\n\n\/\/ BackendConfigs implements ValidatorEnv.\nfunc (e *MockValidatorEnv) BackendConfigs() (map[string]*backendconfig.BackendConfig, error) {\n\treturn e.BackendConfigsMap, nil\n}\n\n\/\/ Services implements ValidatorEnv.\nfunc (e *MockValidatorEnv) Services() (map[string]*v1.Service, error) {\n\treturn e.ServicesMap, nil\n}\n\n\/\/ Cloud implements ValidatorEnv.\nfunc (e *MockValidatorEnv) Cloud() cloud.Cloud {\n\treturn e.MockCloud\n}\n\n\/\/ IngressValidatorAttributes are derived attributes governing how the Ingress\n\/\/ is validated. Features will use this structure to express changes to the\n\/\/ standard checks by modifying this struct.\ntype IngressValidatorAttributes struct {\n\tCheckHTTP           bool\n\tCheckHTTPS          bool\n\tRejectInsecureCerts bool\n\tRequestTimeout      time.Duration\n\t\/\/ HTTPPort and HTTPSPort are used only for unit testing.\n\tHTTPPort  int\n\tHTTPSPort int\n}\n\nfunc (a *IngressValidatorAttributes) equal(b *IngressValidatorAttributes) bool {\n\treturn *a == *b\n}\n\nfunc (a *IngressValidatorAttributes) clone() *IngressValidatorAttributes {\n\tvar ret IngressValidatorAttributes\n\tret = *a\n\treturn &ret\n}\n\nfunc (a *IngressValidatorAttributes) schemes() []string {\n\tvar ret []string\n\tif a.CheckHTTP {\n\t\tret = append(ret, \"http\")\n\t}\n\tif a.CheckHTTPS {\n\t\tret = append(ret, \"https\")\n\t}\n\treturn ret\n}\n\n\/\/ baseAttributes apply settings for the vanilla Ingress spec.\nfunc (a *IngressValidatorAttributes) baseAttributes(ing *v1beta1.Ingress) {\n\ta.CheckHTTP = true\n\tif len(ing.Spec.TLS) != 0 {\n\t\ta.CheckHTTPS = true\n\t}\n}\n\n\/\/ applyFeatures applies the settings for each of the additional features.\nfunc (a *IngressValidatorAttributes) applyFeatures(env ValidatorEnv, ing *v1beta1.Ingress, features []FeatureValidator) error {\n\tfor _, f := range features {\n\t\tklog.V(4).Infof(\"Applying feature %q\", f.Name())\n\t\tif err := f.ConfigureAttributes(env, ing, a); err != nil {\n\t\t\tklog.Warningf(\"Feature %q could not be applied: %v\", f.Name(), err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Try to configure attributes again; no additional changes should occur.\n\t\/\/ If changes are detected, one of the features as written is not\n\t\/\/ commutative and should be fixed.\n\tcopy := a.clone()\n\tfor _, f := range features {\n\t\tif err := f.ConfigureAttributes(env, ing, copy); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !a.equal(copy) {\n\t\t\tklog.Errorf(\"Feature %q is unstable generating attributes, %+v becomes %+v\", f.Name(), *a, *copy)\n\t\t\treturn fmt.Errorf(\"feature %q is unstable generating attributes, %+v becomes %+v\", f.Name(), *a, *copy)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ IngressResult is the result of an Ingress validation.\ntype IngressResult struct {\n\tErr   error\n\tPaths []*PathResult\n}\n\n\/\/ PathResult is the result of validating a path.\ntype PathResult struct {\n\tScheme string\n\tHost   string\n\tPath   string\n\tErr    error\n}\n\n\/\/ defaultAttributes are the base attributes for validation.\nfunc defaultAttributes() *IngressValidatorAttributes {\n\treturn &IngressValidatorAttributes{\n\t\tCheckHTTP:      true,\n\t\tCheckHTTPS:     false,\n\t\tHTTPPort:       80,\n\t\tHTTPSPort:      443,\n\t\tRequestTimeout: 1 * time.Second,\n\t}\n}\n\n\/\/ NewIngressValidator returns a new validator for checking the correctness of\n\/\/ an Ingress spec against the behavior of the instantiated load balancer.\n\/\/ If attribs is nil, then the default set of attributes will be used.\nfunc NewIngressValidator(env ValidatorEnv, ing *v1beta1.Ingress, features []Feature, attribs *IngressValidatorAttributes) (*IngressValidator, error) {\n\tvar fvs []FeatureValidator\n\tfor _, f := range features {\n\t\tfvs = append(fvs, f.NewValidator())\n\t}\n\n\tif attribs == nil {\n\t\tattribs = defaultAttributes()\n\t}\n\tattribs.baseAttributes(ing)\n\tif err := attribs.applyFeatures(env, ing, fvs); err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n\treturn &IngressValidator{\n\t\ting:      ing,\n\t\tfeatures: fvs,\n\t\tattribs:  attribs,\n\t\tclient:   client,\n\t}, nil\n}\n\n\/\/ IngressValidator encapsulates the logic required to validate a given configuration\n\/\/ is behaving correctly.\ntype IngressValidator struct {\n\ting      *v1beta1.Ingress\n\tfeatures []FeatureValidator\n\n\tattribs *IngressValidatorAttributes\n\tclient  *http.Client\n}\n\n\/\/ the right SSL certificate is presented\n\/\/ each path, each host returns the right contents\n\n\/\/ vip for the load balancer. This currently uses the first entry, returns nil\n\/\/ if the VIP is not available.\nfunc (v *IngressValidator) vip() *string {\n\tstatuses := v.ing.Status.LoadBalancer.Ingress\n\tif len(statuses) == 0 {\n\t\treturn nil\n\t}\n\tret := statuses[0].IP\n\treturn &ret\n}\n\n\/\/ Check runs all of the checks against the instantiated load balancer.\nfunc (v *IngressValidator) Check(ctx context.Context) *IngressResult {\n\tklog.V(3).Infof(\"Check Ingress %s\/%s attribs=%+v\", v.ing.Namespace, v.ing.Name, v.attribs)\n\tret := &IngressResult{}\n\tret.Err = v.CheckPaths(ctx, ret)\n\treturn ret\n}\n\n\/\/ CheckPaths checks the host, paths that have been configured. Checks are\n\/\/ run in parallel.\nfunc (v *IngressValidator) CheckPaths(ctx context.Context, vr *IngressResult) error {\n\tvar (\n\t\tthunks []func()\n\t\twg     sync.WaitGroup\n\t)\n\tfor _, scheme := range v.attribs.schemes() {\n\t\tif v.ing.Spec.Backend != nil {\n\t\t\tklog.V(2).Infof(\"Checking default backend for Ingress %s\/%s\", v.ing.Namespace, v.ing.Name)\n\t\t\t\/\/ Capture variables for the thunk.\n\t\t\tresult := &PathResult{Scheme: scheme}\n\t\t\tvr.Paths = append(vr.Paths, result)\n\t\t\tscheme := scheme\n\t\t\tctx, cancelFunc := context.WithTimeout(ctx, v.attribs.RequestTimeout)\n\t\t\tdefer cancelFunc()\n\t\t\tf := func() {\n\t\t\t\tresult.Err = v.checkPath(ctx, scheme, \"\", pathForDefaultBackend)\n\t\t\t\twg.Done()\n\t\t\t}\n\t\t\tthunks = append(thunks, f)\n\t\t\twg.Add(1)\n\t\t}\n\n\t\tfor _, rule := range v.ing.Spec.Rules {\n\t\t\tif rule.HTTP == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, path := range rule.HTTP.Paths {\n\t\t\t\t\/\/ Capture variables for the thunk.\n\t\t\t\tresult := &PathResult{Scheme: scheme, Host: rule.Host, Path: path.Path}\n\t\t\t\tvr.Paths = append(vr.Paths, result)\n\t\t\t\tscheme, host, path := scheme, rule.Host, path.Path\n\t\t\t\tctx, cancelFunc := context.WithTimeout(ctx, v.attribs.RequestTimeout)\n\t\t\t\tdefer cancelFunc()\n\t\t\t\tf := func() {\n\t\t\t\t\tresult.Err = v.checkPath(ctx, scheme, host, path)\n\t\t\t\t\twg.Done()\n\t\t\t\t}\n\t\t\t\tthunks = append(thunks, f)\n\t\t\t\twg.Add(1)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, f := range thunks {\n\t\tgo f()\n\t}\n\tklog.V(2).Infof(\"Waiting for path checks for Ingress %s\/%s to finish\", v.ing.Namespace, v.ing.Name)\n\twg.Wait()\n\n\tfor _, r := range vr.Paths {\n\t\tif r.Err != nil {\n\t\t\tklog.V(2).Infof(\"Got an error checking paths for Ingress %s\/%s: %v\", v.ing.Namespace, v.ing.Name, r.Err)\n\t\t\treturn r.Err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ checkPath performs a check for scheme:\/\/host\/path.\nfunc (v *IngressValidator) checkPath(ctx context.Context, scheme, host, path string) error {\n\tif v.vip() == nil {\n\t\treturn fmt.Errorf(\"ingress %s\/%s does not have a VIP\", v.ing.Namespace, v.ing.Name)\n\t}\n\tvip := *v.vip()\n\n\turl := fmt.Sprintf(\"%s:\/\/%s%s%s\", scheme, vip, portStr(v.attribs, scheme), path)\n\tklog.V(3).Infof(\"Checking Ingress %s\/%s url=%q\", v.ing.Namespace, v.ing.Name, url)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif host != \"\" {\n\t\treq.Host = host\n\t}\n\treq = req.WithContext(ctx)\n\n\t\/\/ Apply modifications for the features.\n\tfor _, f := range v.features {\n\t\tf.ModifyRequest(host, path, req)\n\t}\n\n\tklog.V(3).Infof(\"Request is %+v\", *req)\n\n\tresp, err := v.client.Do(req)\n\tif err != nil && err != http.ErrUseLastResponse {\n\t\tklog.Infof(\"Ingress %s\/%s: %v\", v.ing.Namespace, v.ing.Name, err)\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tklog.Infof(\"Ingress %s\/%s reading body: %v\", v.ing.Namespace, v.ing.Name, err)\n\t\treturn err\n\t}\n\n\tklog.V(2).Infof(\"Ingress %s\/%s GET %q: %d (%d bytes)\", v.ing.Namespace, v.ing.Name, url, resp.StatusCode, len(body))\n\n\tdoStandardCheck := true\n\t\/\/ Perform the checks for each of the features.\n\tfor _, f := range v.features {\n\t\taction, err := f.CheckResponse(host, path, resp, body)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error from %s validator: %v\", f.Name(), err)\n\t\t}\n\t\tswitch action {\n\t\tcase CheckResponseContinue:\n\t\tcase CheckResponseSkip:\n\t\t\tdoStandardCheck = false\n\t\t}\n\t}\n\n\tif doStandardCheck && resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"ingress %s\/%s: GET %q: %d, want 200\", v.ing.Namespace, v.ing.Name, url, resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n\/\/ portStr returns the \":<port>\" for the given scheme. If the port is default\n\/\/ or scheme is unknown then \"\" will be returned.\nfunc portStr(a *IngressValidatorAttributes, scheme string) string {\n\tswitch scheme {\n\tcase \"http\":\n\t\tif a.HTTPPort == 80 {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\":%d\", a.HTTPPort)\n\tcase \"https\":\n\t\tif a.HTTPSPort == 443 {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn fmt.Sprintf(\":%d\", a.HTTPSPort)\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 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 metrics\n\nimport (\n\t\"time\"\n\n\tclientPkg \"github.com\/cilium\/cilium\/pkg\/client\"\n\thealthClientPkg \"github.com\/cilium\/cilium\/pkg\/health\/client\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tupdateLatencyMetricsInterval = 30 * time.Second\n)\n\ntype statusCollector struct {\n\tciliumClient *clientPkg.Client\n\thealthClient *healthClientPkg.Client\n\n\tcontrollersFailingDesc         *prometheus.Desc\n\tipAddressesDesc                *prometheus.Desc\n\tunreachableNodesDesc           *prometheus.Desc\n\tunreachableHealthEndpointsDesc *prometheus.Desc\n}\n\nfunc newStatusCollector() *statusCollector {\n\tciliumClient, err := clientPkg.NewClient(\"\")\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Error while creating Cilium API client\")\n\t}\n\n\thealthClient, err := healthClientPkg.NewClient(\"\")\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Error while creating cilium-health API client\")\n\t}\n\n\treturn &statusCollector{\n\t\tciliumClient: ciliumClient,\n\t\thealthClient: healthClient,\n\t\tcontrollersFailingDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"controllers_failing\"),\n\t\t\t\"Number of failing controllers\",\n\t\t\tnil, nil,\n\t\t),\n\t\tipAddressesDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"ip_addresses\"),\n\t\t\t\"Number of allocated IP addresses\",\n\t\t\t[]string{\"family\"}, nil,\n\t\t),\n\t\tunreachableNodesDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"unreachable_nodes\"),\n\t\t\t\"Number of nodes that cannot be reached\",\n\t\t\tnil, nil,\n\t\t),\n\t\tunreachableHealthEndpointsDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"unreachable_health_endpoints\"),\n\t\t\t\"Number of health endpoints that cannot be reached\",\n\t\t\tnil, nil,\n\t\t),\n\t}\n}\n\nfunc (s *statusCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- s.controllersFailingDesc\n\tch <- s.ipAddressesDesc\n\tch <- s.unreachableNodesDesc\n\tch <- s.unreachableHealthEndpointsDesc\n}\n\nfunc (s *statusCollector) Collect(ch chan<- prometheus.Metric) {\n\tstatusResponse, err := s.ciliumClient.Daemon.GetHealthz(nil)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error while getting Cilium status\")\n\t\treturn\n\t}\n\n\tif statusResponse.Payload == nil {\n\t\treturn\n\t}\n\n\t\/\/ Controllers failing\n\tcontrollersFailing := 0\n\n\tfor _, ctrl := range statusResponse.Payload.Controllers {\n\t\tif ctrl.Status == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ctrl.Status.ConsecutiveFailureCount > 0 {\n\t\t\tcontrollersFailing++\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.controllersFailingDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(controllersFailing),\n\t)\n\n\t\/\/ Address count\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.ipAddressesDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(len(statusResponse.Payload.IPAM.IPV4)),\n\t\t\"ipv4\",\n\t)\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.ipAddressesDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(len(statusResponse.Payload.IPAM.IPV6)),\n\t\t\"ipv6\",\n\t)\n\n\thealthStatusResponse, err := s.healthClient.Connectivity.GetStatus(nil)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error while getting cilium-health status\")\n\t\treturn\n\t}\n\n\tif healthStatusResponse.Payload == nil {\n\t\treturn\n\t}\n\n\t\/\/ Nodes and endpoints healthStatusResponse\n\tvar (\n\t\tunreachableNodes     int\n\t\tunreachableEndpoints int\n\t)\n\n\tfor _, nodeStatus := range healthStatusResponse.Payload.Nodes {\n\t\tif !healthClientPkg.PathIsHealthy(nodeStatus.Host.PrimaryAddress) {\n\t\t\tunreachableNodes++\n\t\t}\n\t\tif nodeStatus.Endpoint != nil && !healthClientPkg.PathIsHealthy(nodeStatus.Endpoint) {\n\t\t\tunreachableEndpoints++\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.unreachableNodesDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(unreachableNodes),\n\t)\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.unreachableHealthEndpointsDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(unreachableEndpoints),\n\t)\n}\n<commit_msg>metrics: Check IPAM field for nil<commit_after>\/\/ Copyright 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 metrics\n\nimport (\n\t\"time\"\n\n\tclientPkg \"github.com\/cilium\/cilium\/pkg\/client\"\n\thealthClientPkg \"github.com\/cilium\/cilium\/pkg\/health\/client\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tupdateLatencyMetricsInterval = 30 * time.Second\n)\n\ntype statusCollector struct {\n\tciliumClient *clientPkg.Client\n\thealthClient *healthClientPkg.Client\n\n\tcontrollersFailingDesc         *prometheus.Desc\n\tipAddressesDesc                *prometheus.Desc\n\tunreachableNodesDesc           *prometheus.Desc\n\tunreachableHealthEndpointsDesc *prometheus.Desc\n}\n\nfunc newStatusCollector() *statusCollector {\n\tciliumClient, err := clientPkg.NewClient(\"\")\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Error while creating Cilium API client\")\n\t}\n\n\thealthClient, err := healthClientPkg.NewClient(\"\")\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Error while creating cilium-health API client\")\n\t}\n\n\treturn &statusCollector{\n\t\tciliumClient: ciliumClient,\n\t\thealthClient: healthClient,\n\t\tcontrollersFailingDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"controllers_failing\"),\n\t\t\t\"Number of failing controllers\",\n\t\t\tnil, nil,\n\t\t),\n\t\tipAddressesDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"ip_addresses\"),\n\t\t\t\"Number of allocated IP addresses\",\n\t\t\t[]string{\"family\"}, nil,\n\t\t),\n\t\tunreachableNodesDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"unreachable_nodes\"),\n\t\t\t\"Number of nodes that cannot be reached\",\n\t\t\tnil, nil,\n\t\t),\n\t\tunreachableHealthEndpointsDesc: prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(Namespace, \"\", \"unreachable_health_endpoints\"),\n\t\t\t\"Number of health endpoints that cannot be reached\",\n\t\t\tnil, nil,\n\t\t),\n\t}\n}\n\nfunc (s *statusCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- s.controllersFailingDesc\n\tch <- s.ipAddressesDesc\n\tch <- s.unreachableNodesDesc\n\tch <- s.unreachableHealthEndpointsDesc\n}\n\nfunc (s *statusCollector) Collect(ch chan<- prometheus.Metric) {\n\tstatusResponse, err := s.ciliumClient.Daemon.GetHealthz(nil)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error while getting Cilium status\")\n\t\treturn\n\t}\n\n\tif statusResponse.Payload == nil {\n\t\treturn\n\t}\n\n\t\/\/ Controllers failing\n\tcontrollersFailing := 0\n\n\tfor _, ctrl := range statusResponse.Payload.Controllers {\n\t\tif ctrl.Status == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ctrl.Status.ConsecutiveFailureCount > 0 {\n\t\t\tcontrollersFailing++\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.controllersFailingDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(controllersFailing),\n\t)\n\n\tif statusResponse.Payload.IPAM != nil {\n\t\t\/\/ Address count\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ts.ipAddressesDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(len(statusResponse.Payload.IPAM.IPV4)),\n\t\t\t\"ipv4\",\n\t\t)\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\ts.ipAddressesDesc,\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(len(statusResponse.Payload.IPAM.IPV6)),\n\t\t\t\"ipv6\",\n\t\t)\n\t}\n\n\thealthStatusResponse, err := s.healthClient.Connectivity.GetStatus(nil)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error while getting cilium-health status\")\n\t\treturn\n\t}\n\n\tif healthStatusResponse.Payload == nil {\n\t\treturn\n\t}\n\n\t\/\/ Nodes and endpoints healthStatusResponse\n\tvar (\n\t\tunreachableNodes     int\n\t\tunreachableEndpoints int\n\t)\n\n\tfor _, nodeStatus := range healthStatusResponse.Payload.Nodes {\n\t\tif !healthClientPkg.PathIsHealthy(nodeStatus.Host.PrimaryAddress) {\n\t\t\tunreachableNodes++\n\t\t}\n\t\tif nodeStatus.Endpoint != nil && !healthClientPkg.PathIsHealthy(nodeStatus.Endpoint) {\n\t\t\tunreachableEndpoints++\n\t\t}\n\t}\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.unreachableNodesDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(unreachableNodes),\n\t)\n\n\tch <- prometheus.MustNewConstMetric(\n\t\ts.unreachableHealthEndpointsDesc,\n\t\tprometheus.GaugeValue,\n\t\tfloat64(unreachableEndpoints),\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package multiverse\n\nimport (\n\t\"time\"\n)\n\n\/\/ block, classic, commander ?\n\nfunc init() {\n\tFormats.List = []*Format{\n\t\tFormats.Standard,\n\t\tFormats.Extended,\n\t\tFormats.Modern,\n\t\tFormats.Vintage,\n\t\tFormats.Legacy,\n\t}\n}\n\ntype Format struct {\n\tSetOk func(*Set) bool\n\tName  string\n}\n\n\/\/ The deck formats we know about. (Standard, Extended, Modern, etc.)\nvar Formats = struct {\n\tStandard, Extended, Modern, Vintage, Legacy, Un *Format\n\n\tList []*Format\n}{\n\t&Format{standardSetLegal, \"standard\"},\n\t&Format{extendedSetLegal, \"extended\"},\n\t&Format{modernSetLegal, \"modern\"},\n\t&Format{vintageSetLegal, \"vintage\"},\n\t&Format{legacySetLegal, \"legacy\"},\n\t&Format{unSet, \"un\"},\n\n\tnil,\n}\n\nfunc unSet(s *Set) bool {\n\treturn s.Type == SetTypes.Un\n}\n\nfunc vintageSetLegal(s *Set) bool {\n\treturn !unSet(s)\n}\n\nfunc legacySetLegal(s *Set) bool {\n\treturn !unSet(s)\n}\n\nvar firstModernSet = time.Date(2003, time.July, 28, 0, 0, 0, 0, time.UTC)\n\nfunc modernSetLegal(s *Set) bool {\n\treturn !unSet(s) && !s.Released.Before(firstModernSet) &&\n\t\t(s.Type == SetTypes.Core || s.Type == SetTypes.Expansion)\n}\n\nfunc extendedSetLegal(s *Set) bool {\n\treturn true\n}\n\nfunc standardSetLegal(s *Set) bool {\n\treturn true\n}\n\nfunc (f *Format) Ok(c *Card) (bool, error) {\n\tfor _, format := range c.Restricted {\n\t\tif format == f {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tfor _, format := range c.Banned {\n\t\tif format == f {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tfor _, printing := range c.Printings {\n\t\tif f.SetOk(printing.Set) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}\n<commit_msg>Made Formats gob-able.<commit_after>package multiverse\n\nimport (\n\t\"time\"\n)\n\n\/\/ block, classic, commander ?\n\nfunc init() {\n\tFormats.List = []*Format{\n\t\tFormats.Standard,\n\t\tFormats.Extended,\n\t\tFormats.Modern,\n\t\tFormats.Vintage,\n\t\tFormats.Legacy,\n\t}\n}\n\ntype Format struct {\n\tSetOk func(*Set) bool\n\tName  string\n}\n\ntype unrecognizedFormatErr string\n\nfunc (err unrecognizedFormatErr) Error() string {\n\treturn \"unrecognized format: \" + string(err)\n}\n\nfunc (f *Format) GobDecode(name []byte) error {\n\tfor _, format := range Formats.List {\n\t\tif format.Name == string(name) {\n\t\t\t*f = *format\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn unrecognizedFormatErr(string(name))\n}\n\nfunc (f *Format) GobEncode() ([]byte, error) {\n\treturn []byte(f.Name), nil\n}\n\n\/\/ The deck formats we know about. (Standard, Extended, Modern, etc.)\nvar Formats = struct {\n\tStandard, Extended, Modern, Vintage, Legacy, Un *Format\n\n\tList []*Format\n}{\n\t&Format{standardSetLegal, \"standard\"},\n\t&Format{extendedSetLegal, \"extended\"},\n\t&Format{modernSetLegal, \"modern\"},\n\t&Format{vintageSetLegal, \"vintage\"},\n\t&Format{legacySetLegal, \"legacy\"},\n\t&Format{unSet, \"un\"},\n\n\tnil,\n}\n\nfunc unSet(s *Set) bool {\n\treturn s.Type == SetTypes.Un\n}\n\nfunc vintageSetLegal(s *Set) bool {\n\treturn !unSet(s)\n}\n\nfunc legacySetLegal(s *Set) bool {\n\treturn !unSet(s)\n}\n\nvar firstModernSet = time.Date(2003, time.July, 28, 0, 0, 0, 0, time.UTC)\n\nfunc modernSetLegal(s *Set) bool {\n\treturn !unSet(s) && !s.Released.Before(firstModernSet) &&\n\t\t(s.Type == SetTypes.Core || s.Type == SetTypes.Expansion)\n}\n\nfunc extendedSetLegal(s *Set) bool {\n\treturn true\n}\n\nfunc standardSetLegal(s *Set) bool {\n\treturn true\n}\n\nfunc (f *Format) Ok(c *Card) (bool, error) {\n\tfor _, format := range c.Restricted {\n\t\tif format == f {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tfor _, format := range c.Banned {\n\t\tif format == f {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tfor _, printing := range c.Printings {\n\t\tif f.SetOk(printing.Set) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, 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 types\n\nimport (\n\t\"context\"\n\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/filter\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/meta\"\n\t\"google.golang.org\/api\/compute\/v1\"\n\t\"google.golang.org\/api\/googleapi\"\n\t\"k8s.io\/legacy-cloud-providers\/gce\"\n)\n\ntype NetworkEndpointEntry struct {\n\tNetworkEndpoint *compute.NetworkEndpoint\n\tHealths         []*compute.HealthStatusForNetworkEndpoint\n}\n\ntype NetworkEndpointStore map[meta.Key][]NetworkEndpointEntry\n\nfunc (s NetworkEndpointStore) AddNetworkEndpointHealthStatus(key meta.Key, entries []NetworkEndpointEntry) {\n\ts[key] = entries\n}\n\n\/\/ GetNetworkEndpointStore is a helper function to access the NetworkEndpointStore of the mock NEG cloud\nfunc GetNetworkEndpointStore(negCloud NetworkEndpointGroupCloud) NetworkEndpointStore {\n\tadapter := negCloud.(*cloudProviderAdapter)\n\tmockedCloud := adapter.c.Compute().(*cloud.MockGCE)\n\tret := mockedCloud.MockNetworkEndpointGroups.X.(NetworkEndpointStore)\n\treturn ret\n}\n\nfunc MockNetworkEndpointAPIs(fakeGCE *gce.Cloud) {\n\tm := (fakeGCE.Compute().(*cloud.MockGCE))\n\tm.MockNetworkEndpointGroups.X = NetworkEndpointStore{}\n\tm.MockNetworkEndpointGroups.AttachNetworkEndpointsHook = MockAttachNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.DetachNetworkEndpointsHook = MockDetachNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.ListNetworkEndpointsHook = MockListNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.AggregatedListHook = MockAggregatedListNetworkEndpointGroupHook\n}\n\n\/\/ TODO: move this logic into code gen\n\/\/ TODO: make AggregateList return map[meta.Key]Object\nfunc MockAggregatedListNetworkEndpointGroupHook(ctx context.Context, fl *filter.F, m *cloud.MockNetworkEndpointGroups) (bool, map[string][]*compute.NetworkEndpointGroup, error) {\n\tobjs := map[string][]*compute.NetworkEndpointGroup{}\n\tfor _, obj := range m.Objects {\n\t\tres, err := cloud.ParseResourceURL(obj.ToGA().SelfLink)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\tif !fl.Match(obj.ToGA()) {\n\t\t\tcontinue\n\t\t}\n\t\tvar location string\n\t\tswitch res.Key.Type() {\n\t\tcase meta.Regional:\n\t\t\tlocation = fmt.Sprintf(\"regions\/%s\", res.Key.Region)\n\t\t\tbreak\n\t\tcase meta.Zonal:\n\t\t\tlocation = fmt.Sprintf(\"zones\/%s\", res.Key.Zone)\n\t\t\tbreak\n\t\tcase meta.Global:\n\t\t\tlocation = string(meta.Global)\n\t\t}\n\t\tobjs[location] = append(objs[location], obj.ToGA())\n\t}\n\t\/\/ Always return global\n\tif _, ok := objs[meta.Global]; !ok {\n\t\tobjs[meta.Global] = []*compute.NetworkEndpointGroup{}\n\t}\n\treturn true, objs, nil\n}\n\nfunc MockListNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsListEndpointsRequest, filter *filter.F, m *cloud.MockNetworkEndpointGroups) ([]*compute.NetworkEndpointWithHealthStatus, error) {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\treturn generateNetworkEndpointWithHealthStatusList(m.X.(NetworkEndpointStore)[*key]), nil\n}\n\nfunc MockAttachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsAttachEndpointsRequest, m *cloud.MockNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tnewList := m.X.(NetworkEndpointStore)[*key]\n\tfor _, newEp := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, oldEp := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(oldEp.NetworkEndpoint, newEp) {\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\tnewList = append(newList, generateNetworkEndpointEntry(newEp))\n\t\t}\n\t}\n\tm.X.(NetworkEndpointStore)[*key] = newList\n\treturn nil\n}\n\nfunc MockDetachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsDetachEndpointsRequest, m *cloud.MockNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tfor _, left := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, right := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(left, right.NetworkEndpoint) {\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\treturn &googleapi.Error{\n\t\t\t\tCode:    http.StatusNotFound,\n\t\t\t\tMessage: fmt.Sprintf(\"Endpoint %v was not found in NetworkEndpointGroup %q\", left, key.String()),\n\t\t\t}\n\t\t}\n\t}\n\n\tnewList := []*compute.NetworkEndpoint{}\n\tfor _, ep := range m.X.(NetworkEndpointStore)[*key] {\n\t\tfound := false\n\t\tfor _, del := range obj.NetworkEndpoints {\n\t\t\tif isNetworkEndpointsEqual(ep.NetworkEndpoint, del) {\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\tnewList = append(newList, ep.NetworkEndpoint)\n\t\t}\n\t}\n\n\tm.X.(NetworkEndpointStore)[*key] = generateNetworkEndpointEntryList(newList)\n\treturn nil\n}\n\nfunc isNetworkEndpointsEqual(left, right *compute.NetworkEndpoint) bool {\n\tif left.IpAddress == right.IpAddress && left.Port == right.Port && left.Instance == right.Instance {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc generateNetworkEndpointEntry(networkEndpoint *compute.NetworkEndpoint) NetworkEndpointEntry {\n\treturn NetworkEndpointEntry{\n\t\tNetworkEndpoint: networkEndpoint,\n\t\tHealths:         []*compute.HealthStatusForNetworkEndpoint{},\n\t}\n}\n\nfunc generateNetworkEndpointEntryList(networkEndpoints []*compute.NetworkEndpoint) []NetworkEndpointEntry {\n\tret := []NetworkEndpointEntry{}\n\tfor _, ne := range networkEndpoints {\n\t\tret = append(ret, generateNetworkEndpointEntry(ne))\n\t}\n\treturn ret\n}\n\nfunc generateNetworkEndpointWithHealthStatus(networkEndpointEntry NetworkEndpointEntry) *compute.NetworkEndpointWithHealthStatus {\n\treturn &compute.NetworkEndpointWithHealthStatus{\n\t\tNetworkEndpoint: networkEndpointEntry.NetworkEndpoint,\n\t\tHealths:         networkEndpointEntry.Healths,\n\t}\n}\n\nfunc generateNetworkEndpointWithHealthStatusList(networkEndpointEntryList []NetworkEndpointEntry) []*compute.NetworkEndpointWithHealthStatus {\n\tret := []*compute.NetworkEndpointWithHealthStatus{}\n\tfor _, ne := range networkEndpointEntryList {\n\t\tret = append(ret, generateNetworkEndpointWithHealthStatus(ne))\n\t}\n\treturn ret\n}\n<commit_msg>Added Mock NEG hooks for alpha APIs.<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 types\n\nimport (\n\t\"context\"\n\t\"k8s.io\/ingress-gce\/pkg\/composite\"\n\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/filter\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/meta\"\n\tcomputealpha \"google.golang.org\/api\/compute\/v0.alpha\"\n\t\"google.golang.org\/api\/compute\/v1\"\n\t\"google.golang.org\/api\/googleapi\"\n\t\"k8s.io\/legacy-cloud-providers\/gce\"\n)\n\ntype NetworkEndpointEntry struct {\n\tNetworkEndpoint *composite.NetworkEndpoint\n\tHealths         []*composite.HealthStatusForNetworkEndpoint\n}\n\ntype NetworkEndpointStore map[meta.Key][]NetworkEndpointEntry\n\nfunc (s NetworkEndpointStore) AddNetworkEndpointHealthStatus(key meta.Key, entries []NetworkEndpointEntry) {\n\ts[key] = entries\n}\n\n\/\/ GetNetworkEndpointStore is a helper function to access the NetworkEndpointStore of the mock NEG cloud\nfunc GetNetworkEndpointStore(negCloud NetworkEndpointGroupCloud) NetworkEndpointStore {\n\tadapter := negCloud.(*cloudProviderAdapter)\n\tmockedCloud := adapter.c.Compute().(*cloud.MockGCE)\n\tret := mockedCloud.MockNetworkEndpointGroups.X.(NetworkEndpointStore)\n\treturn ret\n}\n\nfunc MockNetworkEndpointAPIs(fakeGCE *gce.Cloud) {\n\tm := (fakeGCE.Compute().(*cloud.MockGCE))\n\tm.MockNetworkEndpointGroups.X = NetworkEndpointStore{}\n\tm.MockNetworkEndpointGroups.AttachNetworkEndpointsHook = MockAttachNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.DetachNetworkEndpointsHook = MockDetachNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.ListNetworkEndpointsHook = MockListNetworkEndpointsHook\n\tm.MockNetworkEndpointGroups.AggregatedListHook = MockAggregatedListNetworkEndpointGroupHook\n\n\tm.MockAlphaNetworkEndpointGroups.X = NetworkEndpointStore{}\n\tm.MockAlphaNetworkEndpointGroups.AttachNetworkEndpointsHook = MockAlphaAttachNetworkEndpointsHook\n\tm.MockAlphaNetworkEndpointGroups.DetachNetworkEndpointsHook = MockAlphaDetachNetworkEndpointsHook\n\tm.MockAlphaNetworkEndpointGroups.ListNetworkEndpointsHook = MockAlphaListNetworkEndpointsHook\n\tm.MockAlphaNetworkEndpointGroups.AggregatedListHook = MockAlphaAggregatedListNetworkEndpointGroupHook\n}\n\n\/\/ TODO: move this logic into code gen\n\/\/ TODO: make AggregateList return map[meta.Key]Object\nfunc MockAggregatedListNetworkEndpointGroupHook(ctx context.Context, fl *filter.F, m *cloud.MockNetworkEndpointGroups) (bool, map[string][]*compute.NetworkEndpointGroup, error) {\n\tobjs := map[string][]*compute.NetworkEndpointGroup{}\n\tfor _, obj := range m.Objects {\n\t\tres, err := cloud.ParseResourceURL(obj.ToGA().SelfLink)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\tif !fl.Match(obj.ToGA()) {\n\t\t\tcontinue\n\t\t}\n\t\tvar location string\n\t\tswitch res.Key.Type() {\n\t\tcase meta.Regional:\n\t\t\tlocation = fmt.Sprintf(\"regions\/%s\", res.Key.Region)\n\t\t\tbreak\n\t\tcase meta.Zonal:\n\t\t\tlocation = fmt.Sprintf(\"zones\/%s\", res.Key.Zone)\n\t\t\tbreak\n\t\tcase meta.Global:\n\t\t\tlocation = string(meta.Global)\n\t\t}\n\t\tobjs[location] = append(objs[location], obj.ToGA())\n\t}\n\t\/\/ Always return global\n\tif _, ok := objs[meta.Global]; !ok {\n\t\tobjs[meta.Global] = []*compute.NetworkEndpointGroup{}\n\t}\n\treturn true, objs, nil\n}\n\nfunc MockListNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsListEndpointsRequest, filter *filter.F, m *cloud.MockNetworkEndpointGroups) ([]*compute.NetworkEndpointWithHealthStatus, error) {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\treturn generateNetworkEndpointWithHealthStatusList(m.X.(NetworkEndpointStore)[*key]), nil\n}\n\nfunc MockAttachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsAttachEndpointsRequest, m *cloud.MockNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tnewList := m.X.(NetworkEndpointStore)[*key]\n\tfor _, newEp := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, oldEp := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(oldEp.NetworkEndpoint, toComposite(newEp)) {\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\tnewList = append(newList, generateNetworkEndpointEntry(toComposite(newEp)))\n\t\t}\n\t}\n\tm.X.(NetworkEndpointStore)[*key] = newList\n\treturn nil\n}\n\nfunc MockDetachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *compute.NetworkEndpointGroupsDetachEndpointsRequest, m *cloud.MockNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tfor _, left := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, right := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(toComposite(left), right.NetworkEndpoint) {\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\treturn &googleapi.Error{\n\t\t\t\tCode:    http.StatusNotFound,\n\t\t\t\tMessage: fmt.Sprintf(\"Endpoint %v was not found in NetworkEndpointGroup %q\", left, key.String()),\n\t\t\t}\n\t\t}\n\t}\n\n\tnewList := []*composite.NetworkEndpoint{}\n\tfor _, ep := range m.X.(NetworkEndpointStore)[*key] {\n\t\tfound := false\n\t\tfor _, del := range obj.NetworkEndpoints {\n\t\t\tif isNetworkEndpointsEqual(ep.NetworkEndpoint, toComposite(del)) {\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\tnewList = append(newList, ep.NetworkEndpoint)\n\t\t}\n\t}\n\n\tm.X.(NetworkEndpointStore)[*key] = generateNetworkEndpointEntryList(newList)\n\treturn nil\n}\n\nfunc MockAlphaAggregatedListNetworkEndpointGroupHook(ctx context.Context, fl *filter.F, m *cloud.MockAlphaNetworkEndpointGroups) (bool, map[string][]*computealpha.NetworkEndpointGroup, error) {\n\tobjs := map[string][]*computealpha.NetworkEndpointGroup{}\n\tfor _, obj := range m.Objects {\n\t\tres, err := cloud.ParseResourceURL(obj.ToAlpha().SelfLink)\n\t\tif err != nil {\n\t\t\treturn false, nil, err\n\t\t}\n\t\tif !fl.Match(obj.ToAlpha()) {\n\t\t\tcontinue\n\t\t}\n\t\tvar location string\n\t\tswitch res.Key.Type() {\n\t\tcase meta.Regional:\n\t\t\tlocation = fmt.Sprintf(\"regions\/%s\", res.Key.Region)\n\t\t\tbreak\n\t\tcase meta.Zonal:\n\t\t\tlocation = fmt.Sprintf(\"zones\/%s\", res.Key.Zone)\n\t\t\tbreak\n\t\tcase meta.Global:\n\t\t\tlocation = string(meta.Global)\n\t\t}\n\t\tobjs[location] = append(objs[location], obj.ToAlpha())\n\t}\n\t\/\/ Always return global\n\tif _, ok := objs[meta.Global]; !ok {\n\t\tobjs[meta.Global] = []*computealpha.NetworkEndpointGroup{}\n\t}\n\treturn true, objs, nil\n}\n\nfunc MockAlphaListNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *computealpha.NetworkEndpointGroupsListEndpointsRequest, filter *filter.F, m *cloud.MockAlphaNetworkEndpointGroups) ([]*computealpha.NetworkEndpointWithHealthStatus, error) {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn nil, &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\treturn generateAlphaNetworkEndpointWithHealthStatusList(m.X.(NetworkEndpointStore)[*key]), nil\n}\n\nfunc MockAlphaAttachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *computealpha.NetworkEndpointGroupsAttachEndpointsRequest, m *cloud.MockAlphaNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tnewList := m.X.(NetworkEndpointStore)[*key]\n\tfor _, newEp := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, oldEp := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(oldEp.NetworkEndpoint, toComposite(newEp)) {\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\tnewList = append(newList, generateNetworkEndpointEntry(toComposite(newEp)))\n\t\t}\n\t}\n\tm.X.(NetworkEndpointStore)[*key] = newList\n\treturn nil\n}\n\nfunc MockAlphaDetachNetworkEndpointsHook(ctx context.Context, key *meta.Key, obj *computealpha.NetworkEndpointGroupsDetachEndpointsRequest, m *cloud.MockAlphaNetworkEndpointGroups) error {\n\t_, err := m.Get(ctx, key)\n\tif err != nil {\n\t\treturn &googleapi.Error{\n\t\t\tCode:    http.StatusNotFound,\n\t\t\tMessage: fmt.Sprintf(\"Key: %s was not found in NetworkEndpointGroup\", key.String()),\n\t\t}\n\t}\n\n\tm.Lock.Lock()\n\tdefer m.Lock.Unlock()\n\n\tif _, ok := m.X.(NetworkEndpointStore)[*key]; !ok {\n\t\tm.X.(NetworkEndpointStore)[*key] = []NetworkEndpointEntry{}\n\t}\n\n\tfor _, left := range obj.NetworkEndpoints {\n\t\tfound := false\n\t\tfor _, right := range m.X.(NetworkEndpointStore)[*key] {\n\t\t\tif isNetworkEndpointsEqual(toComposite(left), right.NetworkEndpoint) {\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\treturn &googleapi.Error{\n\t\t\t\tCode:    http.StatusNotFound,\n\t\t\t\tMessage: fmt.Sprintf(\"Endpoint %v was not found in NetworkEndpointGroup %q\", left, key.String()),\n\t\t\t}\n\t\t}\n\t}\n\n\tnewList := []*composite.NetworkEndpoint{}\n\tfor _, ep := range m.X.(NetworkEndpointStore)[*key] {\n\t\tfound := false\n\t\tfor _, del := range obj.NetworkEndpoints {\n\t\t\tif isNetworkEndpointsEqual(ep.NetworkEndpoint, toComposite(del)) {\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\tnewList = append(newList, ep.NetworkEndpoint)\n\t\t}\n\t}\n\n\tm.X.(NetworkEndpointStore)[*key] = generateNetworkEndpointEntryList(newList)\n\treturn nil\n}\n\nfunc toComposite(input interface{}) *composite.NetworkEndpoint {\n\tout, _ := composite.ToNetworkEndpoint(input)\n\treturn out\n}\n\nfunc isNetworkEndpointsEqual(left, right *composite.NetworkEndpoint) bool {\n\tif left.IpAddress == right.IpAddress && left.Port == right.Port && left.Instance == right.Instance {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc generateNetworkEndpointEntry(networkEndpoint *composite.NetworkEndpoint) NetworkEndpointEntry {\n\treturn NetworkEndpointEntry{\n\t\tNetworkEndpoint: networkEndpoint,\n\t\tHealths:         []*composite.HealthStatusForNetworkEndpoint{},\n\t}\n}\n\nfunc generateNetworkEndpointEntryList(networkEndpoints []*composite.NetworkEndpoint) []NetworkEndpointEntry {\n\tret := []NetworkEndpointEntry{}\n\tfor _, ne := range networkEndpoints {\n\t\tret = append(ret, generateNetworkEndpointEntry(ne))\n\t}\n\treturn ret\n}\n\nfunc generateNetworkEndpointWithHealthStatus(networkEndpointEntry NetworkEndpointEntry) *compute.NetworkEndpointWithHealthStatus {\n\tret := &compute.NetworkEndpointWithHealthStatus{}\n\tret.NetworkEndpoint, _ = networkEndpointEntry.NetworkEndpoint.ToGA()\n\n\tfor _, health := range networkEndpointEntry.Healths {\n\t\th, _ := health.ToGA()\n\t\tret.Healths = append(ret.Healths, h)\n\t}\n\treturn ret\n}\n\nfunc generateAlphaNetworkEndpointWithHealthStatus(networkEndpointEntry NetworkEndpointEntry) *computealpha.NetworkEndpointWithHealthStatus {\n\tret := &computealpha.NetworkEndpointWithHealthStatus{}\n\tret.NetworkEndpoint, _ = networkEndpointEntry.NetworkEndpoint.ToAlpha()\n\n\tfor _, health := range networkEndpointEntry.Healths {\n\t\th, _ := health.ToAlpha()\n\t\tret.Healths = append(ret.Healths, h)\n\t}\n\treturn ret\n}\n\nfunc generateNetworkEndpointWithHealthStatusList(networkEndpointEntryList []NetworkEndpointEntry) []*compute.NetworkEndpointWithHealthStatus {\n\tret := []*compute.NetworkEndpointWithHealthStatus{}\n\tfor _, ne := range networkEndpointEntryList {\n\t\tret = append(ret, generateNetworkEndpointWithHealthStatus(ne))\n\t}\n\treturn ret\n}\n\nfunc generateAlphaNetworkEndpointWithHealthStatusList(networkEndpointEntryList []NetworkEndpointEntry) []*computealpha.NetworkEndpointWithHealthStatus {\n\tret := []*computealpha.NetworkEndpointWithHealthStatus{}\n\tfor _, ne := range networkEndpointEntryList {\n\t\tret = append(ret, generateAlphaNetworkEndpointWithHealthStatus(ne))\n\t}\n\treturn ret\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\n*\n* Copyright 2017 SAP SE\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You should have received a copy of the License along with this\n* program. If not, you may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS 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 plugins\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/gophercloud\/gophercloud\"\n\t\"github.com\/gophercloud\/gophercloud\/openstack\"\n\t\"github.com\/gophercloud\/gophercloud\/openstack\/sharedfilesystems\/v2\/sharenetworks\"\n\t\"github.com\/gophercloud\/gophercloud\/pagination\"\n\t\"github.com\/sapcc\/limes\/pkg\/limes\"\n\t\"github.com\/sapcc\/limes\/pkg\/util\"\n)\n\ntype manilaPlugin struct {\n\tcfg limes.ServiceConfiguration\n}\n\nvar manilaResources = []limes.ResourceInfo{\n\t{\n\t\tName: \"share_networks\",\n\t\tUnit: limes.UnitNone,\n\t},\n\t{\n\t\tName: \"share_capacity\",\n\t\tUnit: limes.UnitGibibytes,\n\t},\n\t{\n\t\tName: \"shares\",\n\t\tUnit: limes.UnitNone,\n\t},\n\t{\n\t\tName: \"snapshot_capacity\",\n\t\tUnit: limes.UnitGibibytes,\n\t},\n\t{\n\t\tName: \"share_snapshots\",\n\t\tUnit: limes.UnitNone,\n\t},\n}\n\nfunc init() {\n\tlimes.RegisterQuotaPlugin(func(c limes.ServiceConfiguration) limes.QuotaPlugin {\n\t\treturn &manilaPlugin{c}\n\t})\n}\n\n\/\/ServiceType implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) ServiceType() string {\n\treturn \"sharev2\"\n}\n\n\/\/Resources implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) Resources() []limes.ResourceInfo {\n\treturn manilaResources\n}\n\nfunc (p *manilaPlugin) Client(driver limes.Driver) (*gophercloud.ServiceClient, error) {\n\treturn openstack.NewSharedFileSystemV2(driver.Client(),\n\t\tgophercloud.EndpointOpts{Availability: gophercloud.AvailabilityPublic},\n\t)\n}\n\n\/\/Scrape implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) Scrape(driver limes.Driver, domainUUID, projectUUID string) (map[string]limes.ResourceData, error) {\n\tclient, err := p.Client(driver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result gophercloud.Result\n\tvar totalShareUsage, totalSnapshotUsage, totalShareNetworksUsage = int64(0), 0, 0\n\n\t\/\/Get absolute quota limits per project\n\turl := client.ServiceURL(\"os-quota-sets\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar manilaQuotaData struct {\n\t\tQuotaSet struct {\n\t\t\tGigabytes         int64 `json:\"gigabytes\"`\n\t\t\tShares            int64 `json:\"shares\"`\n\t\t\tSnapshotGigabytes int64 `json:\"snapshot_gigabytes\"`\n\t\t\tSnapshots         int64 `json:\"snapshots\"`\n\t\t\tShareNetworks     int64 `json:\"share_networks\"`\n\t\t} `json:\"quota_set\"`\n\t}\n\terr = result.ExtractInto(&manilaQuotaData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/Get usage of shares per project\n\turl = client.ServiceURL(\"shares\", \"detail\") + fmt.Sprintf(\"?project_id=%s&all_tenants=1\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar manilaShareUsageData struct {\n\t\tShares []struct {\n\t\t\tSize int64 `json:\"size\"`\n\t\t} `json:\"shares\"`\n\t}\n\terr = result.ExtractInto(&manilaShareUsageData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, element := range manilaShareUsageData.Shares {\n\t\ttotalShareUsage += element.Size\n\t}\n\n\t\/\/Get usage of snapshots per project\n\turl = client.ServiceURL(\"snapshots\", \"detail\") + fmt.Sprintf(\"?project_id=%s&all_tenants=1\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar manilaSnapshotUsageData struct {\n\t\tSnapshots []struct {\n\t\t\tShareSize int `json:\"share_size\"`\n\t\t} `json:\"snapshots\"`\n\t}\n\terr = result.ExtractInto(&manilaSnapshotUsageData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, element := range manilaSnapshotUsageData.Snapshots {\n\t\ttotalSnapshotUsage += element.ShareSize\n\t}\n\n\t\/\/Get usage of shared networks\n\tpages := 0\n\tsharenetworks.ListDetail(client, sharenetworks.ListOpts{ProjectID: projectUUID}).EachPage(func(page pagination.Page) (bool, error) {\n\t\tpages++\n\t\tsn, err := sharenetworks.ExtractShareNetworks(page)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\ttotalShareNetworksUsage = len(sn)\n\t\treturn true, nil\n\t})\n\n\tutil.LogDebug(\"Scraped quota and usage for service: sharev2.\")\n\n\treturn map[string]limes.ResourceData{\n\t\t\"shares\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Shares,\n\t\t\tUsage: uint64(len(manilaShareUsageData.Shares)),\n\t\t},\n\t\t\"share_snapshots\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Snapshots,\n\t\t\tUsage: uint64(len(manilaSnapshotUsageData.Snapshots)),\n\t\t},\n\t\t\"share_networks\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.ShareNetworks,\n\t\t\tUsage: uint64(totalShareNetworksUsage),\n\t\t},\n\t\t\"share_capacity\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Gigabytes,\n\t\t\tUsage: uint64(totalShareUsage),\n\t\t},\n\t\t\"snapshot_capacity\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.SnapshotGigabytes,\n\t\t\tUsage: uint64(totalSnapshotUsage),\n\t\t},\n\t}, err\n}\n\n\/\/SetQuota implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) SetQuota(driver limes.Driver, domainUUID, projectUUID string, quotas map[string]uint64) error {\n\tclient, err := p.Client(driver)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestData := map[string]map[string]uint64{\n\t\t\"quota_set\": {\n\t\t\t\"gigabytes\":          quotas[\"share_capacity\"],\n\t\t\t\"snapshots\":          quotas[\"share_snapshots\"],\n\t\t\t\"snapshot_gigabytes\": quotas[\"snapshot_capacity\"],\n\t\t\t\"shares\":             quotas[\"shares\"],\n\t\t\t\"share_networks\":     quotas[\"share_networks\"],\n\t\t},\n\t}\n\n\turl := client.ServiceURL(\"os-quota-sets\", projectUUID)\n\t_, err = client.Put(url, requestData, nil, &gophercloud.RequestOpts{OkCodes: []int{200}})\n\n\treturn nil\n}\n<commit_msg>use uint64 for sizes<commit_after>\/*******************************************************************************\n*\n* Copyright 2017 SAP SE\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You should have received a copy of the License along with this\n* program. If not, you may obtain a copy of the License at\n*\n*     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS 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 plugins\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/gophercloud\/gophercloud\"\n\t\"github.com\/gophercloud\/gophercloud\/openstack\"\n\t\"github.com\/gophercloud\/gophercloud\/openstack\/sharedfilesystems\/v2\/sharenetworks\"\n\t\"github.com\/gophercloud\/gophercloud\/pagination\"\n\t\"github.com\/sapcc\/limes\/pkg\/limes\"\n\t\"github.com\/sapcc\/limes\/pkg\/util\"\n)\n\ntype manilaPlugin struct {\n\tcfg limes.ServiceConfiguration\n}\n\nvar manilaResources = []limes.ResourceInfo{\n\t{\n\t\tName: \"share_networks\",\n\t\tUnit: limes.UnitNone,\n\t},\n\t{\n\t\tName: \"share_capacity\",\n\t\tUnit: limes.UnitGibibytes,\n\t},\n\t{\n\t\tName: \"shares\",\n\t\tUnit: limes.UnitNone,\n\t},\n\t{\n\t\tName: \"snapshot_capacity\",\n\t\tUnit: limes.UnitGibibytes,\n\t},\n\t{\n\t\tName: \"share_snapshots\",\n\t\tUnit: limes.UnitNone,\n\t},\n}\n\nfunc init() {\n\tlimes.RegisterQuotaPlugin(func(c limes.ServiceConfiguration) limes.QuotaPlugin {\n\t\treturn &manilaPlugin{c}\n\t})\n}\n\n\/\/ServiceType implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) ServiceType() string {\n\treturn \"sharev2\"\n}\n\n\/\/Resources implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) Resources() []limes.ResourceInfo {\n\treturn manilaResources\n}\n\nfunc (p *manilaPlugin) Client(driver limes.Driver) (*gophercloud.ServiceClient, error) {\n\treturn openstack.NewSharedFileSystemV2(driver.Client(),\n\t\tgophercloud.EndpointOpts{Availability: gophercloud.AvailabilityPublic},\n\t)\n}\n\n\/\/Scrape implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) Scrape(driver limes.Driver, domainUUID, projectUUID string) (map[string]limes.ResourceData, error) {\n\tclient, err := p.Client(driver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result gophercloud.Result\n\tvar totalShareUsage, totalSnapshotUsage, totalShareNetworksUsage = uint64(0), uint64(0), uint64(0)\n\n\t\/\/Get absolute quota limits per project\n\turl := client.ServiceURL(\"os-quota-sets\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar manilaQuotaData struct {\n\t\tQuotaSet struct {\n\t\t\tGigabytes         int64 `json:\"gigabytes\"`\n\t\t\tShares            int64 `json:\"shares\"`\n\t\t\tSnapshotGigabytes int64 `json:\"snapshot_gigabytes\"`\n\t\t\tSnapshots         int64 `json:\"snapshots\"`\n\t\t\tShareNetworks     int64 `json:\"share_networks\"`\n\t\t} `json:\"quota_set\"`\n\t}\n\terr = result.ExtractInto(&manilaQuotaData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/Get usage of shares per project\n\turl = client.ServiceURL(\"shares\", \"detail\") + fmt.Sprintf(\"?project_id=%s&all_tenants=1\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar manilaShareUsageData struct {\n\t\tShares []struct {\n\t\t\tSize uint64 `json:\"size\"`\n\t\t} `json:\"shares\"`\n\t}\n\terr = result.ExtractInto(&manilaShareUsageData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, element := range manilaShareUsageData.Shares {\n\t\ttotalShareUsage += element.Size\n\t}\n\n\t\/\/Get usage of snapshots per project\n\turl = client.ServiceURL(\"snapshots\", \"detail\") + fmt.Sprintf(\"?project_id=%s&all_tenants=1\", projectUUID)\n\t_, err = client.Get(url, &result.Body, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar manilaSnapshotUsageData struct {\n\t\tSnapshots []struct {\n\t\t\tShareSize uint64 `json:\"share_size\"`\n\t\t} `json:\"snapshots\"`\n\t}\n\terr = result.ExtractInto(&manilaSnapshotUsageData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, element := range manilaSnapshotUsageData.Snapshots {\n\t\ttotalSnapshotUsage += element.ShareSize\n\t}\n\n\t\/\/Get usage of shared networks\n\tpages := 0\n\tsharenetworks.ListDetail(client, sharenetworks.ListOpts{ProjectID: projectUUID}).EachPage(func(page pagination.Page) (bool, error) {\n\t\tpages++\n\t\tsn, err := sharenetworks.ExtractShareNetworks(page)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\ttotalShareNetworksUsage = uint64(len(sn))\n\t\treturn true, nil\n\t})\n\n\tutil.LogDebug(\"Scraped quota and usage for service: sharev2.\")\n\n\treturn map[string]limes.ResourceData{\n\t\t\"shares\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Shares,\n\t\t\tUsage: uint64(len(manilaShareUsageData.Shares)),\n\t\t},\n\t\t\"share_snapshots\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Snapshots,\n\t\t\tUsage: uint64(len(manilaSnapshotUsageData.Snapshots)),\n\t\t},\n\t\t\"share_networks\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.ShareNetworks,\n\t\t\tUsage: uint64(totalShareNetworksUsage),\n\t\t},\n\t\t\"share_capacity\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.Gigabytes,\n\t\t\tUsage: uint64(totalShareUsage),\n\t\t},\n\t\t\"snapshot_capacity\": {\n\t\t\tQuota: manilaQuotaData.QuotaSet.SnapshotGigabytes,\n\t\t\tUsage: uint64(totalSnapshotUsage),\n\t\t},\n\t}, err\n}\n\n\/\/SetQuota implements the limes.QuotaPlugin interface.\nfunc (p *manilaPlugin) SetQuota(driver limes.Driver, domainUUID, projectUUID string, quotas map[string]uint64) error {\n\tclient, err := p.Client(driver)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestData := map[string]map[string]uint64{\n\t\t\"quota_set\": {\n\t\t\t\"gigabytes\":          quotas[\"share_capacity\"],\n\t\t\t\"snapshots\":          quotas[\"share_snapshots\"],\n\t\t\t\"snapshot_gigabytes\": quotas[\"snapshot_capacity\"],\n\t\t\t\"shares\":             quotas[\"shares\"],\n\t\t\t\"share_networks\":     quotas[\"share_networks\"],\n\t\t},\n\t}\n\n\turl := client.ServiceURL(\"os-quota-sets\", projectUUID)\n\t_, err = client.Put(url, requestData, nil, &gophercloud.RequestOpts{OkCodes: []int{200}})\n\n\treturn nil\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 queue\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/cenkalti\/backoff\/v4\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/rand\"\n\n\t\"istio.io\/pkg\/log\"\n)\n\n\/\/ Task to be performed.\ntype Task func() error\n\ntype BackoffTask struct {\n\ttask    Task\n\tbackoff *backoff.ExponentialBackOff\n}\n\n\/\/ Instance of work tickets processed using a rate-limiting loop\ntype Instance interface {\n\t\/\/ Push a task.\n\tPush(task Task)\n\t\/\/ Run the loop until a signal on the channel\n\tRun(<-chan struct{})\n\n\t\/\/ Closed returns a chan that will be signaled when the Instance has stopped processing tasks.\n\tClosed() <-chan struct{}\n}\n\ntype queueImpl struct {\n\tdelay        time.Duration\n\tretryBackoff *backoff.ExponentialBackOff\n\ttasks        []*BackoffTask\n\tcond         *sync.Cond\n\tclosing      bool\n\tclosed       chan struct{}\n\tcloseOnce    *sync.Once\n\tid           string\n}\n\nfunc newExponentialBackOff(eb *backoff.ExponentialBackOff) *backoff.ExponentialBackOff {\n\tif eb == nil {\n\t\treturn nil\n\t}\n\tteb := backoff.NewExponentialBackOff()\n\tteb.InitialInterval = eb.InitialInterval\n\tteb.MaxElapsedTime = eb.MaxElapsedTime\n\tteb.MaxInterval = eb.MaxInterval\n\tteb.Multiplier = eb.Multiplier\n\tteb.RandomizationFactor = eb.RandomizationFactor\n\treturn teb\n}\n\n\/\/ NewQueue instantiates a queue with a processing function\nfunc NewQueue(errorDelay time.Duration) Instance {\n\treturn NewQueueWithID(errorDelay, rand.String(10))\n}\n\nfunc NewQueueWithID(errorDelay time.Duration, name string) Instance {\n\treturn &queueImpl{\n\t\tdelay:     errorDelay,\n\t\ttasks:     make([]*BackoffTask, 0),\n\t\tclosing:   false,\n\t\tclosed:    make(chan struct{}),\n\t\tcloseOnce: &sync.Once{},\n\t\tcond:      sync.NewCond(&sync.Mutex{}),\n\t\tid:        name,\n\t}\n}\n\nfunc NewBackOffQueue(backoff *backoff.ExponentialBackOff) Instance {\n\treturn &queueImpl{\n\t\tretryBackoff: backoff,\n\t\ttasks:        make([]*BackoffTask, 0),\n\t\tclosing:      false,\n\t\tclosed:       make(chan struct{}),\n\t\tcloseOnce:    &sync.Once{},\n\t\tcond:         sync.NewCond(&sync.Mutex{}),\n\t}\n}\n\nfunc (q *queueImpl) Push(item Task) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.closing {\n\t\tq.tasks = append(q.tasks, &BackoffTask{item, newExponentialBackOff(q.retryBackoff)})\n\t}\n\tq.cond.Signal()\n}\n\nfunc (q *queueImpl) pushRetryTask(item *BackoffTask) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.closing {\n\t\tq.tasks = append(q.tasks, item)\n\t}\n\tq.cond.Signal()\n}\n\nfunc (q *queueImpl) Closed() <-chan struct{} {\n\treturn q.closed\n}\n\nfunc (q *queueImpl) Run(stop <-chan struct{}) {\n\tlog.Debugf(\"started queue %s\", q.id)\n\tdefer func() {\n\t\tq.closeOnce.Do(func() {\n\t\t\tlog.Debugf(\"closed queue %s\", q.id)\n\t\t\tclose(q.closed)\n\t\t})\n\t}()\n\tgo func() {\n\t\t<-stop\n\t\tq.cond.L.Lock()\n\t\tq.cond.Signal()\n\t\tq.closing = true\n\t\tq.cond.L.Unlock()\n\t}()\n\n\tfor {\n\t\tq.cond.L.Lock()\n\n\t\t\/\/ wait for closing to be set, or a task to be pushed\n\t\tfor !q.closing && len(q.tasks) == 0 {\n\t\t\tq.cond.Wait()\n\t\t}\n\n\t\tif q.closing {\n\t\t\tq.cond.L.Unlock()\n\t\t\t\/\/ We must be shutting down.\n\t\t\treturn\n\t\t}\n\n\t\tbackoffTask := q.tasks[0]\n\t\t\/\/ Slicing will not free the underlying elements of the array, so explicitly clear them out here\n\t\tq.tasks[0] = nil\n\t\tq.tasks = q.tasks[1:]\n\n\t\tq.cond.L.Unlock()\n\n\t\tif err := backoffTask.task(); err != nil {\n\t\t\tdelay := q.delay\n\t\t\tif q.retryBackoff != nil {\n\t\t\t\tdelay = backoffTask.backoff.NextBackOff()\n\t\t\t}\n\t\t\tlog.Infof(\"Work item handle failed (%v), retry after delay %v\", err, delay)\n\t\t\ttime.AfterFunc(delay, func() {\n\t\t\t\tq.pushRetryTask(backoffTask)\n\t\t\t})\n\t\t}\n\t}\n}\n<commit_msg>refactor get and process functionality of queue (#40441)<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 queue\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/cenkalti\/backoff\/v4\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/rand\"\n\n\t\"istio.io\/pkg\/log\"\n)\n\n\/\/ Task to be performed.\ntype Task func() error\n\ntype BackoffTask struct {\n\ttask    Task\n\tbackoff *backoff.ExponentialBackOff\n}\n\n\/\/ Instance of work tickets processed using a rate-limiting loop\ntype Instance interface {\n\t\/\/ Push a task.\n\tPush(task Task)\n\t\/\/ Run the loop until a signal on the channel\n\tRun(<-chan struct{})\n\n\t\/\/ Closed returns a chan that will be signaled when the Instance has stopped processing tasks.\n\tClosed() <-chan struct{}\n}\n\ntype queueImpl struct {\n\tdelay        time.Duration\n\tretryBackoff *backoff.ExponentialBackOff\n\ttasks        []*BackoffTask\n\tcond         *sync.Cond\n\tclosing      bool\n\tclosed       chan struct{}\n\tcloseOnce    *sync.Once\n\tid           string\n}\n\nfunc newExponentialBackOff(eb *backoff.ExponentialBackOff) *backoff.ExponentialBackOff {\n\tif eb == nil {\n\t\treturn nil\n\t}\n\tteb := backoff.NewExponentialBackOff()\n\tteb.InitialInterval = eb.InitialInterval\n\tteb.MaxElapsedTime = eb.MaxElapsedTime\n\tteb.MaxInterval = eb.MaxInterval\n\tteb.Multiplier = eb.Multiplier\n\tteb.RandomizationFactor = eb.RandomizationFactor\n\treturn teb\n}\n\n\/\/ NewQueue instantiates a queue with a processing function\nfunc NewQueue(errorDelay time.Duration) Instance {\n\treturn NewQueueWithID(errorDelay, rand.String(10))\n}\n\nfunc NewQueueWithID(errorDelay time.Duration, name string) Instance {\n\treturn &queueImpl{\n\t\tdelay:     errorDelay,\n\t\ttasks:     make([]*BackoffTask, 0),\n\t\tclosing:   false,\n\t\tclosed:    make(chan struct{}),\n\t\tcloseOnce: &sync.Once{},\n\t\tcond:      sync.NewCond(&sync.Mutex{}),\n\t\tid:        name,\n\t}\n}\n\nfunc NewBackOffQueue(backoff *backoff.ExponentialBackOff) Instance {\n\treturn &queueImpl{\n\t\tretryBackoff: backoff,\n\t\ttasks:        make([]*BackoffTask, 0),\n\t\tclosing:      false,\n\t\tclosed:       make(chan struct{}),\n\t\tcloseOnce:    &sync.Once{},\n\t\tcond:         sync.NewCond(&sync.Mutex{}),\n\t}\n}\n\nfunc (q *queueImpl) Push(item Task) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.closing {\n\t\tq.tasks = append(q.tasks, &BackoffTask{item, newExponentialBackOff(q.retryBackoff)})\n\t}\n\tq.cond.Signal()\n}\n\nfunc (q *queueImpl) pushRetryTask(item *BackoffTask) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.closing {\n\t\tq.tasks = append(q.tasks, item)\n\t}\n\tq.cond.Signal()\n}\n\nfunc (q *queueImpl) Closed() <-chan struct{} {\n\treturn q.closed\n}\n\n\/\/ get blocks until it can return a task to be processed. If shutdown = true,\n\/\/ the processing go routine should stop.\nfunc (q *queueImpl) get() (task *BackoffTask, shutdown bool) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\t\/\/ wait for closing to be set, or a task to be pushed\n\tfor !q.closing && len(q.tasks) == 0 {\n\t\tq.cond.Wait()\n\t}\n\n\tif q.closing {\n\t\t\/\/ We must be shutting down.\n\t\treturn nil, true\n\t}\n\ttask = q.tasks[0]\n\t\/\/ Slicing will not free the underlying elements of the array, so explicitly clear them out here\n\tq.tasks[0] = nil\n\tq.tasks = q.tasks[1:]\n\treturn task, false\n}\n\nfunc (q *queueImpl) processNextItem() bool {\n\t\/\/ Wait until there is a new item in the queue\n\ttask, shuttingdown := q.get()\n\tif shuttingdown {\n\t\treturn false\n\t}\n\n\t\/\/ Run the task.\n\tif err := task.task(); err != nil {\n\t\tdelay := q.delay\n\t\tif q.retryBackoff != nil {\n\t\t\tdelay = task.backoff.NextBackOff()\n\t\t}\n\t\tlog.Infof(\"Work item handle failed (%v), retry after delay %v\", err, delay)\n\t\ttime.AfterFunc(delay, func() {\n\t\t\tq.pushRetryTask(task)\n\t\t})\n\t}\n\treturn true\n}\n\nfunc (q *queueImpl) Run(stop <-chan struct{}) {\n\tlog.Debugf(\"started queue %s\", q.id)\n\tdefer func() {\n\t\tq.closeOnce.Do(func() {\n\t\t\tlog.Debugf(\"closed queue %s\", q.id)\n\t\t\tclose(q.closed)\n\t\t})\n\t}()\n\tgo func() {\n\t\t<-stop\n\t\tq.cond.L.Lock()\n\t\tq.cond.Signal()\n\t\tq.closing = true\n\t\tq.cond.L.Unlock()\n\t}()\n\n\tfor q.processNextItem() {\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package network\n\nimport (\n\t\"io\"\n\t\"fmt\"\n\t\"errors\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"bytes\"\n)\n\n\/\/ A NODE is either a NEURON or a SENSOR.\n\/\/   - If it's a sensor, it can be loaded with a value for output\n\/\/   - If it's a neuron, it has a list of its incoming input signals ([]*Link is used)\n\/\/ Use an activation count to avoid flushing\ntype NNode struct {\n\t\/\/ The ID of the node\n\tId                int\n\n\t\/\/ If true the node is active\n\tIsActive          bool\n\n\t\/\/ The type of node activation function (SIGMOID, ...)\n\tActivationType    NodeActivationType\n\t\/\/ The neuron type for this node (HIDDEN, INPUT, OUTPUT, BIAS)\n\tNeuronType        NodeNeuronType\n\n\t\/\/ The activation for current step\n\tActiveOut         float64\n\t\/\/ The activation from PREVIOUS (time-delayed) time step, if there is one\n\tActiveOutTd       float64\n\t\/\/ The node's activation value\n\tActivation        float64\n\t\/\/ The number of activations for current node\n\tActivationsCount  int32\n\t\/\/ The activation sum\n\tActivationSum     float64\n\n\t\/\/ The list of all incoming connections\n\tIncoming          []*Link\n\t\/\/ The list of all outgoing connections\n\tOutgoing          []*Link\n\t\/\/ The trait linked to the node\n\tTrait             *neat.Trait\n\n\t\/\/ Used for Gene decoding by referencing analogue to this node in organism phenotype\n\tPhenotypeAnalogue *NNode\n\n\t\/* ************ LEARNING PARAMETERS *********** *\/\n\t\/\/ The following parameters are for use in neurons that learn through habituation,\n\t\/\/ sensitization, or Hebbian-type processes  *\/\n\tParams            []float64\n\n\t\/\/ Activation value of node at time t-1; Holds the previous step's activation for recurrency\n\tlastActivation    float64\n\t\/\/ Activation value of node at time t-2 Holds the activation before  the previous step's\n\t\/\/ This is necessary for a special recurrent case when the innode of a recurrent link is one time step ahead of the outnode.\n\t\/\/ The innode then needs to send from TWO time steps ago\n\tlastActivation2   float64\n}\n\n\/\/ Creates new node with specified ID and neuron type associated (INPUT, HIDDEN, OUTPUT, BIAS)\nfunc NewNNode(nodeid int, neuronType NodeNeuronType) *NNode {\n\tn := newNode()\n\tn.Id = nodeid\n\tn.NeuronType = neuronType\n\treturn n\n}\n\n\/\/ Construct a NNode off another NNode with given trait for genome purposes\nfunc NewNNodeCopy(n *NNode, t *neat.Trait) *NNode {\n\tnode := newNode()\n\tnode.Id = n.Id\n\tnode.NeuronType = n.NeuronType\n\tnode.Trait = t\n\tnode.deriveTrait(t)\n\treturn node\n}\n\n\/\/ Read a NNode from specified Reader and applies corresponding trait to it from a list of traits provided\nfunc ReadNNode(r io.Reader, traits []*neat.Trait) *NNode {\n\tn := newNode()\n\tvar trait_id, node_type int\n\tfmt.Fscanf(r, \"%d %d %d %d \", &n.Id, &trait_id, &node_type, &n.NeuronType)\n\tif trait_id != 0 && traits != nil {\n\t\t\/\/ find corresponding node trait from list\n\t\tfor _, t := range traits {\n\t\t\tif trait_id == t.Id {\n\t\t\t\tn.Trait = t\n\t\t\t\tn.deriveTrait(t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ just create empty params\n\t\tn.deriveTrait(nil)\n\t}\n\treturn n\n}\n\n\/\/ The private default constructor\nfunc newNode() *NNode {\n\treturn &NNode{\n\t\tNeuronType:HiddenNeuron,\n\t\tActivationType:SigmoidSteepenedActivation,\n\t\tIncoming:make([]*Link, 0),\n\t\tOutgoing:make([]*Link, 0),\n\t}\n}\n\n\/\/ Copy trait parameters into this node's parameters\nfunc (n *NNode) deriveTrait(t *neat.Trait) {\n\tn.Params = make([]float64, neat.Num_trait_params)\n\tif t != nil {\n\t\tfor i, p := range t.Params {\n\t\t\tn.Params[i] = p\n\t\t}\n\t}\n}\n\n\/\/ Set new activation value to this node\nfunc (n *NNode) setActivation(input float64) {\n\t\/\/ Keep a memory of activations for potential time delayed connections\n\tn.saveActivations()\n\t\/\/ Set new activation value\n\tn.Activation = input\n\t\/\/ Increment the activation_count\n\tn.ActivationsCount++\n}\n\n\/\/ Saves current node's activations for potential time delayed connections\nfunc (n *NNode) saveActivations() {\n\tn.lastActivation2 = n.lastActivation\n\tn.lastActivation = n.Activation\n}\n\n\/\/ Returns activation for a current step\nfunc (n *NNode) GetActiveOut() float64 {\n\tif n.ActivationsCount > 0 {\n\t\treturn n.Activation\n\t} else {\n\t\treturn 0.0\n\t}\n}\n\n\/\/ Returns activation from PREVIOUS time step\nfunc (n *NNode) GetActiveOutTd() float64 {\n\tif n.ActivationsCount > 1 {\n\t\treturn n.lastActivation\n\t} else {\n\t\treturn 0.0\n\t}\n}\n\n\/\/ Returns true if this node is SENSOR\nfunc (n *NNode) IsSensor() bool {\n\treturn n.NeuronType == InputNeuron || n.NeuronType == BiasNeuron\n}\n\n\/\/ returns true if this node is NEURON\nfunc (n *NNode) IsNeuron() bool {\n\treturn n.NeuronType == HiddenNeuron || n.NeuronType == OutputNeuron\n}\n\n\/\/ If the node is a SENSOR, returns TRUE and loads the value\nfunc (n *NNode) SensorLoad(load float64) bool {\n\tif n.IsSensor() {\n\t\t\/\/ Keep a memory of activations for potential time delayed connections\n\t\tn.saveActivations()\n\t\t\/\/ Puts sensor into next time-step\n\t\tn.ActivationsCount++\n\t\tn.Activation = load\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\n\/\/ Adds a NONRECURRENT Link to an incoming NNode in the incoming List\nfunc (n *NNode) AddIncoming(in *NNode, weight float64) {\n\tnewLink := NewLink(weight, in, n, false)\n\tn.Incoming = append(n.Incoming, newLink)\n}\n\n\/\/ Adds a Link to a new NNode in the incoming List\nfunc (n *NNode) AddIncomingRecurrent(in *NNode, weight float64, recur bool) {\n\tnewLink := NewLink(weight, in, n, recur)\n\tn.Incoming = append(n.Incoming, newLink)\n}\n\n\/\/ Recursively deactivate backwards through the network\nfunc (n *NNode) Flushback() {\n\tn.ActivationsCount = 0\n\tn.Activation = 0\n\tn.lastActivation = 0\n\tn.lastActivation2 = 0\n}\n\n\/\/ Verify flushing for debuging\nfunc (n *NNode) FlushbackCheck() error {\n\tif n.ActivationsCount > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has activation count %d\", n, n.ActivationsCount))\n\t}\n\tif n.Activation > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has activation %f\", n, n.Activation))\n\t}\n\tif n.lastActivation > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has last_activation %f\", n, n.lastActivation))\n\t}\n\tif n.lastActivation2 > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has last_activation2 %f\", n, n.lastActivation2))\n\t}\n\treturn nil\n}\n\n\/\/ Dump node to a writer\nfunc (n *NNode) Write(w io.Writer) {\n\ttrait_id := 0\n\tif n.Trait != nil {\n\t\ttrait_id = n.Trait.Id\n\t}\n\tfmt.Fprintf(w, \"%d %d %d %d\", n.Id, trait_id, n.NodeType(), n.NeuronType)\n}\n\n\/\/ Find the greatest depth starting from this neuron at depth d\nfunc (n *NNode) Depth(d int) (int, error) {\n\tif d > 100 {\n\t\treturn 10, errors.New(\"NNode: Depth can not be determined for network with loop\");\n\t}\n\t\/\/ Base Case\n\tif n.IsSensor() {\n\t\treturn d, nil\n\t} else {\n\t\t\/\/ recursion\n\t\tmax := d \/\/ The max depth\n\t\tfor _, l := range n.Incoming {\n\t\t\tcur_depth, err := l.InNode.Depth(d + 1)\n\t\t\tif err != nil {\n\t\t\t\treturn cur_depth, err\n\t\t\t}\n\t\t\tif cur_depth > max {\n\t\t\t\tmax = cur_depth\n\t\t\t}\n\t\t}\n\t\treturn max, nil\n\t}\n\n}\n\n\/\/ Convenient method to check network's node type (SENSOR, NEURON)\nfunc (n *NNode) NodeType() NodeType {\n\tif n.IsSensor() {\n\t\treturn SensorNode\n\t}\n\treturn NeuronNode\n}\n\nfunc (n *NNode) String() string {\n\treturn fmt.Sprintf(\"(%s id:%03d, %s, %s -> step: %d = %.3f %.3f)\",\n\t\tNodeTypeName(n.NodeType()), n.Id, NeuronTypeName(n.NeuronType), NodeActivators.ActivationNameFromType(n.ActivationType),\n\t\tn.ActivationsCount, n.Activation, n.Params)\n}\n\n\/\/ Prints all node's fields to the string\nfunc (n *NNode) Print() string {\n\tstr := \"NNode fields\\n\"\n\tb := bytes.NewBufferString(str)\n\tfmt.Fprintf(b, \"\\tId: %d\\n\", n.Id)\n\tfmt.Fprintf(b, \"\\tIsActive: %t\\n\", n.IsActive)\n\tfmt.Fprintf(b, \"\\tActivation: %f\\n\", n.Activation)\n\tfmt.Fprintf(b, \"\\tActivation Type: %s\\n\", NodeActivators.ActivationNameFromType(n.ActivationType))\n\tfmt.Fprintf(b, \"\\tNeuronType: %d\\n\", n.NeuronType)\n\tfmt.Fprintf(b, \"\\tActiveOut: %f\\n\", n.ActiveOut)\n\tfmt.Fprintf(b, \"\\tActiveOutTd: %f\\n\", n.ActiveOutTd)\n\tfmt.Fprintf(b, \"\\tActivationsCount: %d\\n\", n.ActivationsCount)\n\tfmt.Fprintf(b, \"\\tActivationSum: %f\\n\", n.ActivationSum)\n\tfmt.Fprintf(b, \"\\tIncoming: %s\\n\", n.Incoming)\n\tfmt.Fprintf(b, \"\\tOutgoing: %s\\n\", n.Outgoing)\n\tfmt.Fprintf(b, \"\\tTrait: %s\\n\", n.Trait)\n\tfmt.Fprintf(b, \"\\tPhenotypeAnalogue: %s\\n\", n.PhenotypeAnalogue)\n\tfmt.Fprintf(b, \"\\tParams: %f\\n\", n.Params)\n\tfmt.Fprintf(b, \"\\tlastActivation: %f\\n\", n.lastActivation)\n\tfmt.Fprintf(b, \"\\tlastActivation2: %f\\n\", n.lastActivation2)\n\n\treturn b.String()\n}\n\n\n<commit_msg>Changed access visibility for default constructor and trait duplication methods<commit_after>package network\n\nimport (\n\t\"io\"\n\t\"fmt\"\n\t\"errors\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"bytes\"\n)\n\n\/\/ A NODE is either a NEURON or a SENSOR.\n\/\/   - If it's a sensor, it can be loaded with a value for output\n\/\/   - If it's a neuron, it has a list of its incoming input signals ([]*Link is used)\n\/\/ Use an activation count to avoid flushing\ntype NNode struct {\n\t\/\/ The ID of the node\n\tId                int\n\n\t\/\/ If true the node is active\n\tIsActive          bool\n\n\t\/\/ The type of node activation function (SIGMOID, ...)\n\tActivationType    NodeActivationType\n\t\/\/ The neuron type for this node (HIDDEN, INPUT, OUTPUT, BIAS)\n\tNeuronType        NodeNeuronType\n\n\t\/\/ The activation for current step\n\tActiveOut         float64\n\t\/\/ The activation from PREVIOUS (time-delayed) time step, if there is one\n\tActiveOutTd       float64\n\t\/\/ The node's activation value\n\tActivation        float64\n\t\/\/ The number of activations for current node\n\tActivationsCount  int32\n\t\/\/ The activation sum\n\tActivationSum     float64\n\n\t\/\/ The list of all incoming connections\n\tIncoming          []*Link\n\t\/\/ The list of all outgoing connections\n\tOutgoing          []*Link\n\t\/\/ The trait linked to the node\n\tTrait             *neat.Trait\n\n\t\/\/ Used for Gene decoding by referencing analogue to this node in organism phenotype\n\tPhenotypeAnalogue *NNode\n\n\t\/* ************ LEARNING PARAMETERS *********** *\/\n\t\/\/ The following parameters are for use in neurons that learn through habituation,\n\t\/\/ sensitization, or Hebbian-type processes  *\/\n\tParams            []float64\n\n\t\/\/ Activation value of node at time t-1; Holds the previous step's activation for recurrency\n\tlastActivation    float64\n\t\/\/ Activation value of node at time t-2 Holds the activation before  the previous step's\n\t\/\/ This is necessary for a special recurrent case when the innode of a recurrent link is one time step ahead of the outnode.\n\t\/\/ The innode then needs to send from TWO time steps ago\n\tlastActivation2   float64\n}\n\n\/\/ Creates new node with specified ID and neuron type associated (INPUT, HIDDEN, OUTPUT, BIAS)\nfunc NewNNode(nodeid int, neuronType NodeNeuronType) *NNode {\n\tn := NewNetworkNode()\n\tn.Id = nodeid\n\tn.NeuronType = neuronType\n\treturn n\n}\n\n\/\/ Construct a NNode off another NNode with given trait for genome purposes\nfunc NewNNodeCopy(n *NNode, t *neat.Trait) *NNode {\n\tnode := NewNetworkNode()\n\tnode.Id = n.Id\n\tnode.NeuronType = n.NeuronType\n\tnode.Trait = t\n\tnode.DeriveTrait(t)\n\treturn node\n}\n\n\/\/ Read a NNode from specified Reader and applies corresponding trait to it from a list of traits provided\nfunc ReadNNode(r io.Reader, traits []*neat.Trait) *NNode {\n\tn := NewNetworkNode()\n\tvar trait_id, node_type int\n\tfmt.Fscanf(r, \"%d %d %d %d \", &n.Id, &trait_id, &node_type, &n.NeuronType)\n\tif trait_id != 0 && traits != nil {\n\t\t\/\/ find corresponding node trait from list\n\t\tfor _, t := range traits {\n\t\t\tif trait_id == t.Id {\n\t\t\t\tn.Trait = t\n\t\t\t\tn.DeriveTrait(t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ just create empty params\n\t\tn.DeriveTrait(nil)\n\t}\n\treturn n\n}\n\n\/\/ The default constructor\nfunc NewNetworkNode() *NNode {\n\treturn &NNode{\n\t\tNeuronType:HiddenNeuron,\n\t\tActivationType:SigmoidSteepenedActivation,\n\t\tIncoming:make([]*Link, 0),\n\t\tOutgoing:make([]*Link, 0),\n\t}\n}\n\n\/\/ Copy trait parameters into this node's parameters\nfunc (n *NNode) DeriveTrait(t *neat.Trait) {\n\tn.Params = make([]float64, neat.Num_trait_params)\n\tif t != nil {\n\t\tfor i, p := range t.Params {\n\t\t\tn.Params[i] = p\n\t\t}\n\t}\n}\n\n\/\/ Set new activation value to this node\nfunc (n *NNode) setActivation(input float64) {\n\t\/\/ Keep a memory of activations for potential time delayed connections\n\tn.saveActivations()\n\t\/\/ Set new activation value\n\tn.Activation = input\n\t\/\/ Increment the activation_count\n\tn.ActivationsCount++\n}\n\n\/\/ Saves current node's activations for potential time delayed connections\nfunc (n *NNode) saveActivations() {\n\tn.lastActivation2 = n.lastActivation\n\tn.lastActivation = n.Activation\n}\n\n\/\/ Returns activation for a current step\nfunc (n *NNode) GetActiveOut() float64 {\n\tif n.ActivationsCount > 0 {\n\t\treturn n.Activation\n\t} else {\n\t\treturn 0.0\n\t}\n}\n\n\/\/ Returns activation from PREVIOUS time step\nfunc (n *NNode) GetActiveOutTd() float64 {\n\tif n.ActivationsCount > 1 {\n\t\treturn n.lastActivation\n\t} else {\n\t\treturn 0.0\n\t}\n}\n\n\/\/ Returns true if this node is SENSOR\nfunc (n *NNode) IsSensor() bool {\n\treturn n.NeuronType == InputNeuron || n.NeuronType == BiasNeuron\n}\n\n\/\/ returns true if this node is NEURON\nfunc (n *NNode) IsNeuron() bool {\n\treturn n.NeuronType == HiddenNeuron || n.NeuronType == OutputNeuron\n}\n\n\/\/ If the node is a SENSOR, returns TRUE and loads the value\nfunc (n *NNode) SensorLoad(load float64) bool {\n\tif n.IsSensor() {\n\t\t\/\/ Keep a memory of activations for potential time delayed connections\n\t\tn.saveActivations()\n\t\t\/\/ Puts sensor into next time-step\n\t\tn.ActivationsCount++\n\t\tn.Activation = load\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\n\/\/ Adds a NONRECURRENT Link to an incoming NNode in the incoming List\nfunc (n *NNode) AddIncoming(in *NNode, weight float64) {\n\tnewLink := NewLink(weight, in, n, false)\n\tn.Incoming = append(n.Incoming, newLink)\n}\n\n\/\/ Adds a Link to a new NNode in the incoming List\nfunc (n *NNode) AddIncomingRecurrent(in *NNode, weight float64, recur bool) {\n\tnewLink := NewLink(weight, in, n, recur)\n\tn.Incoming = append(n.Incoming, newLink)\n}\n\n\/\/ Recursively deactivate backwards through the network\nfunc (n *NNode) Flushback() {\n\tn.ActivationsCount = 0\n\tn.Activation = 0\n\tn.lastActivation = 0\n\tn.lastActivation2 = 0\n}\n\n\/\/ Verify flushing for debuging\nfunc (n *NNode) FlushbackCheck() error {\n\tif n.ActivationsCount > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has activation count %d\", n, n.ActivationsCount))\n\t}\n\tif n.Activation > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has activation %f\", n, n.Activation))\n\t}\n\tif n.lastActivation > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has last_activation %f\", n, n.lastActivation))\n\t}\n\tif n.lastActivation2 > 0 {\n\t\treturn errors.New(fmt.Sprintf(\"NNODE: %s has last_activation2 %f\", n, n.lastActivation2))\n\t}\n\treturn nil\n}\n\n\/\/ Dump node to a writer\nfunc (n *NNode) Write(w io.Writer) {\n\ttrait_id := 0\n\tif n.Trait != nil {\n\t\ttrait_id = n.Trait.Id\n\t}\n\tfmt.Fprintf(w, \"%d %d %d %d\", n.Id, trait_id, n.NodeType(), n.NeuronType)\n}\n\n\/\/ Find the greatest depth starting from this neuron at depth d\nfunc (n *NNode) Depth(d int) (int, error) {\n\tif d > 100 {\n\t\treturn 10, errors.New(\"NNode: Depth can not be determined for network with loop\");\n\t}\n\t\/\/ Base Case\n\tif n.IsSensor() {\n\t\treturn d, nil\n\t} else {\n\t\t\/\/ recursion\n\t\tmax := d \/\/ The max depth\n\t\tfor _, l := range n.Incoming {\n\t\t\tcur_depth, err := l.InNode.Depth(d + 1)\n\t\t\tif err != nil {\n\t\t\t\treturn cur_depth, err\n\t\t\t}\n\t\t\tif cur_depth > max {\n\t\t\t\tmax = cur_depth\n\t\t\t}\n\t\t}\n\t\treturn max, nil\n\t}\n\n}\n\n\/\/ Convenient method to check network's node type (SENSOR, NEURON)\nfunc (n *NNode) NodeType() NodeType {\n\tif n.IsSensor() {\n\t\treturn SensorNode\n\t}\n\treturn NeuronNode\n}\n\nfunc (n *NNode) String() string {\n\treturn fmt.Sprintf(\"(%s id:%03d, %s, %s -> step: %d = %.3f %.3f)\",\n\t\tNodeTypeName(n.NodeType()), n.Id, NeuronTypeName(n.NeuronType), NodeActivators.ActivationNameFromType(n.ActivationType),\n\t\tn.ActivationsCount, n.Activation, n.Params)\n}\n\n\/\/ Prints all node's fields to the string\nfunc (n *NNode) Print() string {\n\tstr := \"NNode fields\\n\"\n\tb := bytes.NewBufferString(str)\n\tfmt.Fprintf(b, \"\\tId: %d\\n\", n.Id)\n\tfmt.Fprintf(b, \"\\tIsActive: %t\\n\", n.IsActive)\n\tfmt.Fprintf(b, \"\\tActivation: %f\\n\", n.Activation)\n\tfmt.Fprintf(b, \"\\tActivation Type: %s\\n\", NodeActivators.ActivationNameFromType(n.ActivationType))\n\tfmt.Fprintf(b, \"\\tNeuronType: %d\\n\", n.NeuronType)\n\tfmt.Fprintf(b, \"\\tActiveOut: %f\\n\", n.ActiveOut)\n\tfmt.Fprintf(b, \"\\tActiveOutTd: %f\\n\", n.ActiveOutTd)\n\tfmt.Fprintf(b, \"\\tActivationsCount: %d\\n\", n.ActivationsCount)\n\tfmt.Fprintf(b, \"\\tActivationSum: %f\\n\", n.ActivationSum)\n\tfmt.Fprintf(b, \"\\tIncoming: %s\\n\", n.Incoming)\n\tfmt.Fprintf(b, \"\\tOutgoing: %s\\n\", n.Outgoing)\n\tfmt.Fprintf(b, \"\\tTrait: %s\\n\", n.Trait)\n\tfmt.Fprintf(b, \"\\tPhenotypeAnalogue: %s\\n\", n.PhenotypeAnalogue)\n\tfmt.Fprintf(b, \"\\tParams: %f\\n\", n.Params)\n\tfmt.Fprintf(b, \"\\tlastActivation: %f\\n\", n.lastActivation)\n\tfmt.Fprintf(b, \"\\tlastActivation2: %f\\n\", n.lastActivation2)\n\n\treturn b.String()\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>package router\n\nimport \"github.com\/andrepereira\/kobayashi-maru\/net\/controls\"\n\ntype Id struct {\n\tIP            string \/\/IP address\n\tVendor        string \/\/Vendor of emulated hardware\n\tModel         string \/\/Model of emulated hardware\n\tOS            string \/\/Operating systemof emulated hardware\n\tTX            int64  \/\/Actual uplink speed in kbps\n\tRX            int64  \/\/Actual downlink speed in kbps\n\tTXPPS         int64  \/\/Actual uplink speed in pps\n\tRXPPS         int64  \/\/Actual downlink speed in pps\n\tTXM           int64  \/\/Maximum uplink in kbps\n\tRXM           int64  \/\/Maximum downlink in kbps\n\tTXPPSM        int64  \/\/Maximum uplink in pps\n\tRXPPSM        int64  \/\/Maximum downlink in pps\n\tRoorPassword  string \/\/Password of administrative user\n\tUSER          string \/\/Username of a non privileged user at active\n\tUserPassword  string \/\/Password of a non privileged user at system\n\tProcessRuning [20]string\n}\n\n\/\/Authorize the route to a destiny \"to\"\n\/\/This make the function of a router device\n\/\/Uses a to string with a IP address\n\/\/Return a boolean with authorization or not to routing (if the route\n\/\/exists at routing table\nfunc Routing(to string) bool {\n\n\tif routertbl.GetRoute(to) {\n\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n\n}\n<commit_msg>Improvement at Id struct<commit_after>package router\n\nimport \"github.com\/andrepereira\/kobayashi-maru\/net\/controls\"\n\ntype Id struct {\n\tIP            string        \/\/IP address\n\tVendor        string        \/\/Vendor of emulated hardware\n\tModel         string        \/\/Model of emulated hardware\n\tOS            string        \/\/Operating systemof emulated hardware\n\tTX            int64         \/\/Actual uplink speed in kbps\n\tRX            int64         \/\/Actual downlink speed in kbps\n\tTXPPS         int64         \/\/Actual uplink speed in pps\n\tRXPPS         int64         \/\/Actual downlink speed in pps\n\tTXM           int64         \/\/Maximum uplink in kbps\n\tRXM           int64         \/\/Maximum downlink in kbps\n\tTXPPSM        int64         \/\/Maximum uplink in pps\n\tRXPPSM        int64         \/\/Maximum downlink in pps\n\tRoorPassword  string        \/\/Password of administrative user\n\tUSER          string        \/\/Username of a non privileged user at active\n\tUserPassword  string        \/\/Password of a non privileged user at system\n\tProcessRuning [20][2]string \/\/Table 20x2 of runing process with process name and your version\n}\n\n\/\/Authorize the route to a destiny \"to\"\n\/\/This make the function of a router device\n\/\/Uses a to string with a IP address\n\/\/Return a boolean with authorization or not to routing (if the route\n\/\/exists at routing table\nfunc Routing(to string) bool {\n\n\tif routertbl.GetRoute(to) {\n\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package plugin\n\n\/* Explanation about this directory. (Don't overwrite this file) *\/\n\/\/\n\/\/ - This is a directory where plugins are placed.\n\/\/ - You can add a GO file as a new plugins.\n\/\/   - File name should be same as the name of plugin.\n\/\/ - Note: This function is still in experimental state.\n<commit_msg>fix indent<commit_after>package plugin\n\n\/* Explanation about this directory. (Don't overwrite this file) *\/\n\/\/\n\/\/ - This is a directory where plugins are placed.\n\/\/ - You can add a GO file as a new plugins.\n\/\/ - File name should be same as the name of plugin.\n\/\/ - Note: This function is still in experimental state.\n<|endoftext|>"}
{"text":"<commit_before>package ipamplugin\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/docker\/libnetwork\/ipamapi\"\n\t\"github.com\/docker\/libnetwork\/netlabel\"\n\tgodocker \"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/weaveworks\/weave\/api\"\n\t. \"github.com\/weaveworks\/weave\/common\"\n\t\"github.com\/weaveworks\/weave\/common\/docker\"\n)\n\nconst (\n\tWeaveContainer = \"weave\"\n)\n\ntype ipam struct {\n\tclient *docker.Client\n\tweave  *api.Client\n}\n\nfunc NewIpam(client *docker.Client, version string) (ipamapi.Ipam, error) {\n\tresolver := func() (string, error) {\n\t\taddr, err := client.GetContainerIP(WeaveContainer)\n\t\tif _, ok := err.(*godocker.NoSuchContainer); ok {\n\t\t\treturn \"\", fmt.Errorf(\"%s container is not present. Have you launched it?\", WeaveContainer)\n\t\t}\n\t\treturn addr, err\n\t}\n\treturn &ipam{client: client, weave: api.NewClientWithResolver(resolver)}, nil\n}\n\nfunc (i *ipam) GetDefaultAddressSpaces() (string, string, error) {\n\tLog.Debugln(\"GetDefaultAddressSpaces\")\n\treturn \"weavelocal\", \"weaveglobal\", nil\n}\n\nfunc (i *ipam) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {\n\tLog.Debugln(\"RequestPool\", addressSpace, pool, subPool, options)\n\tcidr, err := i.weave.DefaultSubnet()\n\tLog.Debugln(\"RequestPool returning \", cidr, err)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\t\/\/ Pass back a fake \"gateway address\"; we don't actually use it,\n\t\/\/ so just give the network address.\n\tdata := map[string]string{netlabel.Gateway: cidr.String()}\n\treturn \"weavepool\", cidr, data, err\n}\n\nfunc (i *ipam) ReleasePool(poolID string) error {\n\tLog.Debugln(\"ReleasePool\", poolID)\n\treturn nil\n}\n\nfunc (i *ipam) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) {\n\tLog.Debugln(\"RequestAddress\", poolID, address, options)\n\t\/\/ Pass magic string to weave IPAM, which then stores the address under its own string\n\tip, err := i.weave.AllocateIP(\"_\")\n\tLog.Debugln(\"allocateIP returned\", ip, err)\n\treturn ip, nil, err\n}\n\nfunc (i *ipam) ReleaseAddress(poolID string, address net.IP) error {\n\tLog.Debugln(\"ReleaseAddress\", poolID, address)\n\treturn i.weave.ReleaseIP(address.String())\n}\n<commit_msg>Add two functions required by ipamapi \"contract\" but not actually used<commit_after>package ipamplugin\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/docker\/libnetwork\/discoverapi\"\n\t\"github.com\/docker\/libnetwork\/ipamapi\"\n\t\"github.com\/docker\/libnetwork\/netlabel\"\n\tgodocker \"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/weaveworks\/weave\/api\"\n\t. \"github.com\/weaveworks\/weave\/common\"\n\t\"github.com\/weaveworks\/weave\/common\/docker\"\n)\n\nconst (\n\tWeaveContainer = \"weave\"\n)\n\ntype ipam struct {\n\tclient *docker.Client\n\tweave  *api.Client\n}\n\nfunc NewIpam(client *docker.Client, version string) (ipamapi.Ipam, error) {\n\tresolver := func() (string, error) {\n\t\taddr, err := client.GetContainerIP(WeaveContainer)\n\t\tif _, ok := err.(*godocker.NoSuchContainer); ok {\n\t\t\treturn \"\", fmt.Errorf(\"%s container is not present. Have you launched it?\", WeaveContainer)\n\t\t}\n\t\treturn addr, err\n\t}\n\treturn &ipam{client: client, weave: api.NewClientWithResolver(resolver)}, nil\n}\n\nfunc (i *ipam) GetDefaultAddressSpaces() (string, string, error) {\n\tLog.Debugln(\"GetDefaultAddressSpaces\")\n\treturn \"weavelocal\", \"weaveglobal\", nil\n}\n\nfunc (i *ipam) RequestPool(addressSpace, pool, subPool string, options map[string]string, v6 bool) (string, *net.IPNet, map[string]string, error) {\n\tLog.Debugln(\"RequestPool\", addressSpace, pool, subPool, options)\n\tcidr, err := i.weave.DefaultSubnet()\n\tLog.Debugln(\"RequestPool returning \", cidr, err)\n\tif err != nil {\n\t\treturn \"\", nil, nil, err\n\t}\n\t\/\/ Pass back a fake \"gateway address\"; we don't actually use it,\n\t\/\/ so just give the network address.\n\tdata := map[string]string{netlabel.Gateway: cidr.String()}\n\treturn \"weavepool\", cidr, data, err\n}\n\nfunc (i *ipam) ReleasePool(poolID string) error {\n\tLog.Debugln(\"ReleasePool\", poolID)\n\treturn nil\n}\n\nfunc (i *ipam) RequestAddress(poolID string, address net.IP, options map[string]string) (*net.IPNet, map[string]string, error) {\n\tLog.Debugln(\"RequestAddress\", poolID, address, options)\n\t\/\/ Pass magic string to weave IPAM, which then stores the address under its own string\n\tip, err := i.weave.AllocateIP(\"_\")\n\tLog.Debugln(\"allocateIP returned\", ip, err)\n\treturn ip, nil, err\n}\n\nfunc (i *ipam) ReleaseAddress(poolID string, address net.IP) error {\n\tLog.Debugln(\"ReleaseAddress\", poolID, address)\n\treturn i.weave.ReleaseIP(address.String())\n}\n\n\/\/ Functions required by ipamapi \"contract\" but not actually used.\n\nfunc (i *ipam) DiscoverNew(discoverapi.DiscoveryType, interface{}) error {\n\treturn nil\n}\n\nfunc (i *ipam) DiscoverDelete(discoverapi.DiscoveryType, interface{}) error {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* post-anything allows you to send HTTP POST\/GET to anything, anywhere.\nsupports CORS, and can be used as a static file server*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nfunc main() {\n\tlisten := flag.String(\"listen\", \"\", \"interface to listen on e.g. 0.0.0.0:8000\")\n\tdir := flag.String(\"dir\", \"\", \"serve static files from here, will use url of \/static\/*\")\n\tflag.Parse()\n\tif *listen == \"\" {\n\t\tlog.Fatal(\"listen is required\")\n\t}\n\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.ParseForm()\n\t\tswitch req.Method {\n\t\tcase \"GET\":\n\t\t\tlogMap(req.Form)\n\t\tcase \"POST\":\n\t\t\tlogMap(req.Form)\n\t\tcase \"OPTIONS\":\n\t\t\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\t}\n\t\tw.WriteHeader(200)\n\t})\n\tif *dir != \"\" {\n\t\thttp.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(*dir))))\n\t}\n\tlog.Fatal(http.ListenAndServe(*listen, nil))\n}\n\nfunc logMap(m url.Values) {\n\tfmt.Println(\"Request Values\")\n\tfor k, v := range m {\n\t\tfmt.Println(k, v)\n\t}\n}\n<commit_msg>Adds file upload route<commit_after>\/* post-anything allows you to send HTTP POST\/GET to anything, anywhere.\nsupports CORS, and can be used as a static file server*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\n\t\"github.com\/mholt\/binding\"\n)\n\ntype fileRequest struct {\n\tFile *multipart.FileHeader\n}\n\nfunc (f *fileRequest) FieldMap(req *http.Request) binding.FieldMap {\n\treturn binding.FieldMap{\n\t\t&f.File: \"file\",\n\t}\n}\n\nfunc main() {\n\tlisten := flag.String(\"listen\", \"\", \"interface to listen on e.g. 0.0.0.0:8000\")\n\tdir := flag.String(\"dir\", \"\", \"serve static files from here, will use url of \/static\/*\")\n\tflag.Parse()\n\tif *listen == \"\" {\n\t\tlog.Fatal(\"listen is required\")\n\t}\n\n\thttp.HandleFunc(\"\/sendfile\", func(w http.ResponseWriter, req *http.Request) {\n\t\tfReq := &fileRequest{}\n\t\tbinding.MaxMemory = 104857600000\n\t\tif errs := binding.Bind(req, fReq); errs.Len() != 0 {\n\t\t\tw.WriteHeader(500)\n\t\t\treturn\n\t\t}\n\t\tif fReq.File == nil {\n\t\t\tw.WriteHeader(400)\n\t\t\treturn\n\t\t}\n\t\tfh, err := fReq.File.Open()\n\t\tif err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\treturn\n\t\t}\n\t\tdefer fh.Close()\n\t\tfh2, err := os.Create(fReq.File.Filename)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\treturn\n\t\t}\n\t\tdefer fh2.Close()\n\n\t\tif _, err := io.Copy(fh2, fh); err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(200)\n\t})\n\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.ParseForm()\n\t\tswitch req.Method {\n\t\tcase \"GET\":\n\t\t\tlogMap(req.Form)\n\t\tcase \"POST\":\n\t\t\tlogMap(req.Form)\n\t\tcase \"OPTIONS\":\n\t\t\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\t\t}\n\t\tw.WriteHeader(200)\n\t})\n\n\tif *dir != \"\" {\n\t\thttp.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(*dir))))\n\t}\n\n\tlog.Fatal(http.ListenAndServe(*listen, nil))\n}\n\nfunc logMap(m url.Values) {\n\tfmt.Println(\"Request Values\")\n\tfor k, v := range m {\n\t\tfmt.Println(k, v)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\tmkr \"github.com\/mackerelio\/mackerel-client-go\"\n\t\"github.com\/mackerelio\/mkr\/logger\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar commandAlerts = cli.Command{\n\tName:      \"alerts\",\n\tUsage:     \"Retrieve\/Close alerts\",\n\tArgsUsage: \"[--with-closed | -w] [--limit | -l]\",\n\tDescription: `\n    Retrieve\/Close alerts. With no subcommand specified, this will show all alerts.\n    Requests APIs under \"\/api\/v0\/alerts\". See https:\/\/mackerel.io\/api-docs\/entry\/alerts .\n`,\n\tAction: doAlertsRetrieve,\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{Name: \"with-closed, w\", Usage: \"Display open alert including close alert. default: false\"},\n\t\tcli.IntFlag{Name: \"limit, l\", Value: 100, Usage: \"Set the number of alerts to display at once when withClosed is active. default: 100\"},\n\t},\n\tSubcommands: []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tUsage:     \"list alerts\",\n\t\t\tArgsUsage: \"[--service | -s <service>] [--host-status | -S <file>] [--color | -c] [--with-closed | -w] [--limit | -l]\",\n\t\t\tDescription: `\n    Shows alerts in human-readable format.\n`,\n\t\t\tAction: doAlertsList,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"service, s\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by service. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"host-status, S\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by status of each host. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.BoolTFlag{Name: \"color, c\", Usage: \"Colorize output. default: true\"},\n\t\t\t\tcli.BoolFlag{Name: \"with-closed, w\", Usage: \"Display open alert including close alert. default: false\"},\n\t\t\t\tcli.IntFlag{Name: \"limit, l\", Value: 100, Usage: \"Set the number of alerts to display at once when withClosed is active. default: 100\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"close\",\n\t\t\tUsage:     \"close alerts\",\n\t\t\tArgsUsage: \"<alertIds....>\",\n\t\t\tDescription: `\n    Closes alerts. Multiple alert IDs can be specified.\n`,\n\t\t\tAction: doAlertsClose,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{Name: \"reason, r\", Value: \"\", Usage: \"Reason of closing alert.\"},\n\t\t\t\tcli.BoolFlag{Name: \"verbose, v\", Usage: \"Verbose output mode\"},\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype alertSet struct {\n\tAlert   *mkr.Alert\n\tHost    *mkr.Host\n\tMonitor mkr.Monitor\n}\n\nfunc joinMonitorsAndHosts(client *mkr.Client, alerts []*mkr.Alert) []*alertSet {\n\thostsJSON, err := client.FindHosts(&mkr.FindHostsParam{\n\t\tStatuses: []string{\"working\", \"standby\", \"poweroff\", \"maintenance\"},\n\t})\n\tlogger.DieIf(err)\n\n\thosts := map[string]*mkr.Host{}\n\tfor _, host := range hostsJSON {\n\t\thosts[host.ID] = host\n\t}\n\n\tmonitorsJSON, err := client.FindMonitors()\n\tlogger.DieIf(err)\n\n\tmonitors := map[string]mkr.Monitor{}\n\tfor _, monitor := range monitorsJSON {\n\t\tmonitors[monitor.MonitorID()] = monitor\n\t}\n\n\talertSets := []*alertSet{}\n\tfor _, alert := range alerts {\n\t\talertSets = append(\n\t\t\talertSets,\n\t\t\t&alertSet{Alert: alert, Host: hosts[alert.HostID], Monitor: monitors[alert.MonitorID]},\n\t\t)\n\t}\n\treturn alertSets\n}\n\nfunc formatJoinedAlert(alertSet *alertSet, colorize bool) string {\n\tconst layout = \"2006-01-02 15:04:05\"\n\n\thost := alertSet.Host\n\tmonitor := alertSet.Monitor\n\talert := alertSet.Alert\n\n\thostMsg := \"\"\n\tif host != nil {\n\t\tstatusMsg := host.Status\n\t\tif host.IsRetired == true {\n\t\t\tstatusMsg = \"retired\"\n\t\t}\n\t\tif colorize {\n\t\t\tswitch statusMsg {\n\t\t\tcase \"working\":\n\t\t\t\tstatusMsg = color.BlueString(\"working\")\n\t\t\tcase \"standby\":\n\t\t\t\tstatusMsg = color.GreenString(\"standby\")\n\t\t\tcase \"poweroff\":\n\t\t\t\tstatusMsg = \"poweroff\"\n\t\t\tcase \"maintenance\":\n\t\t\t\tstatusMsg = color.YellowString(\"maintenance\")\n\t\t\t}\n\t\t}\n\t\thostMsg = fmt.Sprintf(\" %s %s\", host.Name, statusMsg)\n\t\troleMsgs := []string{}\n\t\tfor service, roles := range host.Roles {\n\t\t\troleMsgs = append(roleMsgs, fmt.Sprintf(\"%s:%s\", service, strings.Join(roles, \",\")))\n\t\t}\n\t\thostMsg += \" [\" + strings.Join(roleMsgs, \", \") + \"]\"\n\t}\n\n\tmonitorMsg := \"\"\n\tif monitor != nil {\n\t\tswitch m := monitor.(type) {\n\t\tcase *mkr.MonitorConnectivity:\n\t\t\tmonitorMsg = \"\"\n\t\tcase *mkr.MonitorHostMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorServiceMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f\", m.Service, m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorExternalHTTP:\n\t\t\tstatusRegexp, _ := regexp.Compile(\"^[2345][0-9][0-9]$\")\n\t\t\tswitch alert.Status {\n\t\t\tcase \"CRITICAL\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeCritical != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f > %.2f msec, status:%s\", m.URL, alert.Value, *m.ResponseTimeCritical, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f msec, %s\", m.URL, alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tcase \"WARNING\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeWarning != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f > %.2f msec, status:%s\", alert.Value, *m.ResponseTimeWarning, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, %s\", alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, status:%s\", alert.Value, alert.Message)\n\t\t\t}\n\t\tcase *mkr.MonitorExpression:\n\t\t\texpression := formatExpressionOneline(m.Expression)\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else if alert.Status == \"UNKNOWN\" {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", expression)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", expression, alert.Value)\n\t\t\t}\n\t\tdefault:\n\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", monitor.MonitorType())\n\t\t}\n\t\tif monitorMsg == \"\" {\n\t\t\tmonitorMsg = monitor.MonitorName()\n\t\t} else {\n\t\t\tmonitorMsg = monitor.MonitorName() + \" \" + monitorMsg\n\t\t}\n\t}\n\t\/\/ If alert is caused by check monitoring, take monitorMsg from alert.message\n\tif alert.Type == \"check\" {\n\t\tmonitorMsg = formatCheckMessage(alert.Message)\n\t}\n\n\tstatusMsg := alert.Status\n\tif colorize {\n\t\tswitch alert.Status {\n\t\tcase \"CRITICAL\":\n\t\t\tstatusMsg = color.RedString(\"CRITICAL \")\n\t\tcase \"WARNING\":\n\t\t\tstatusMsg = color.YellowString(\"WARNING \")\n\t\tcase \"OK\":\n\t\t\tstatusMsg = color.GreenString(\"OK \")\n\t\tcase \"UNKNOWN\":\n\t\t\tstatusMsg = \"UNKNOWN \"\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s %s %s %s%s\", alert.ID, time.Unix(alert.OpenedAt, 0).Format(layout), statusMsg, monitorMsg, hostMsg)\n}\n\nvar expressionNewlinePattern = regexp.MustCompile(`\\s*[\\r\\n]+\\s*`)\n\nfunc formatExpressionOneline(expr string) string {\n\texpr = strings.Trim(expressionNewlinePattern.ReplaceAllString(expr, \" \"), \" \")\n\treturn strings.Replace(strings.Replace(expr, \"( \", \"(\", -1), \" )\", \")\", -1)\n}\n\nfunc formatCheckMessage(msg string) string {\n\ttruncated := false\n\tif index := strings.IndexAny(msg, \"\\n\\r\"); index != -1 {\n\t\tmsg = msg[0:index]\n\t\ttruncated = true\n\t}\n\tif runes := []rune(msg); len(runes) > 100 {\n\t\tmsg = string(runes[0:100])\n\t\ttruncated = true\n\t}\n\tif truncated {\n\t\tmsg = msg + \"...\"\n\t}\n\treturn msg\n}\n\nfunc doAlertsRetrieve(c *cli.Context) error {\n\tclient := newMackerelFromContext(c)\n\twithClosed := c.Bool(\"with-closed\")\n\tlimit := c.Int(\"limit\")\n\n\tif withClosed {\n\t\talerts, err := client.FindWithClosedAlerts()\n\t\tlogger.DieIf(err)\n\t\tif alerts.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tif limit > len(alerts.Alerts) {\n\t\t\t\t\tnextAlerts, err := client.FindWithClosedAlertsByNextID(alerts.NextID)\n\t\t\t\t\tlogger.DieIf(err)\n\t\t\t\t\talerts.Alerts = append(alerts.Alerts, nextAlerts.Alerts...)\n\t\t\t\t\talerts.NextID = nextAlerts.NextID\n\t\t\t\t\tif alerts.NextID == \"\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(alerts.Alerts) > limit {\n\t\t\talerts.Alerts = alerts.Alerts[:limit]\n\t\t}\n\t\tPrettyPrintJSON(alerts.Alerts)\n\t} else {\n\t\talerts, err := client.FindAlerts()\n\t\tlogger.DieIf(err)\n\t\tif alerts.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tnextAlerts, err := client.FindAlertsByNextID(alerts.NextID)\n\t\t\t\tlogger.DieIf(err)\n\t\t\t\talerts.Alerts = append(alerts.Alerts, nextAlerts.Alerts...)\n\t\t\t\talerts.NextID = nextAlerts.NextID\n\t\t\t\tif alerts.NextID == \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t}\n\n\t\tif len(alerts.Alerts) > limit {\n\t\t\talerts.Alerts = alerts.Alerts[:limit]\n\t\t}\n\t\tPrettyPrintJSON(alerts.Alerts)\n\t}\n\treturn nil\n}\n\nfunc doAlertsList(c *cli.Context) error {\n\tfilterServices := c.StringSlice(\"service\")\n\tfilterStatuses := c.StringSlice(\"host-status\")\n\tclient := newMackerelFromContext(c)\n\twithClosed := c.Bool(\"with-closed\")\n\tlimit := c.Int(\"limit\")\n\tvar alert []*mkr.Alert\n\n\tif withClosed {\n\t\talerts, err := client.FindWithClosedAlerts()\n\t\tlogger.DieIf(err)\n\t\tif alerts.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tif limit > len(alerts.Alerts) {\n\t\t\t\t\tnextAlerts, err := client.FindWithClosedAlertsByNextID(alerts.NextID)\n\t\t\t\t\tlogger.DieIf(err)\n\t\t\t\t\talerts.Alerts = append(alerts.Alerts, nextAlerts.Alerts...)\n\t\t\t\t\talerts.NextID = nextAlerts.NextID\n\t\t\t\t\tif alerts.NextID == \"\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\talert = alerts.Alerts\n\t\tif len(alert) > limit {\n\t\t\talert = alert[:limit]\n\t\t}\n\t} else {\n\t\talerts, err := client.FindAlerts()\n\t\tlogger.DieIf(err)\n\t\tif alerts.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tnextAlerts, err := client.FindAlertsByNextID(alerts.NextID)\n\t\t\t\tlogger.DieIf(err)\n\t\t\t\talerts.Alerts = append(alerts.Alerts, nextAlerts.Alerts...)\n\t\t\t\talerts.NextID = nextAlerts.NextID\n\t\t\t\tif alerts.NextID == \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t}\n\t\talert = alerts.Alerts\n\t\tif len(alert) > limit {\n\t\t\talert = alert[:limit]\n\t\t}\n\t}\n\tjoinedAlerts := joinMonitorsAndHosts(client, alert)\n\tfor _, joinAlert := range joinedAlerts {\n\t\tif len(filterServices) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterService := range filterServices {\n\t\t\t\tif joinAlert.Host != nil {\n\t\t\t\t\tif _, ok := joinAlert.Host.Roles[filterService]; ok {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar service string\n\t\t\t\t\tif m, ok := joinAlert.Monitor.(*mkr.MonitorServiceMetric); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t} else if m, ok := joinAlert.Monitor.(*mkr.MonitorExternalHTTP); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t}\n\t\t\t\t\tfound = service == filterService\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\t\tif len(filterStatuses) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterStatus := range filterStatuses {\n\t\t\t\tif joinAlert.Host != nil && joinAlert.Host.Status == filterStatus {\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\tcontinue\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(color.Output, formatJoinedAlert(joinAlert, c.BoolT(\"color\")))\n\t}\n\treturn nil\n}\n\nfunc doAlertsClose(c *cli.Context) error {\n\tisVerbose := c.Bool(\"verbose\")\n\targAlertIDs := c.Args()\n\treason := c.String(\"reason\")\n\n\tif len(argAlertIDs) < 1 {\n\t\tcli.ShowCommandHelp(c, \"alerts\")\n\t\tos.Exit(1)\n\t}\n\n\tclient := newMackerelFromContext(c)\n\tfor _, alertID := range argAlertIDs {\n\t\talert, err := client.CloseAlert(alertID, reason)\n\t\tlogger.DieIf(err)\n\n\t\tlogger.Log(\"Alert closed\", alertID)\n\t\tif isVerbose == true {\n\t\t\tPrettyPrintJSON(alert)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>refactor alerts commands<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\tmkr \"github.com\/mackerelio\/mackerel-client-go\"\n\t\"github.com\/mackerelio\/mkr\/logger\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar commandAlerts = cli.Command{\n\tName:      \"alerts\",\n\tUsage:     \"Retrieve\/Close alerts\",\n\tArgsUsage: \"[--with-closed | -w] [--limit | -l]\",\n\tDescription: `\n    Retrieve\/Close alerts. With no subcommand specified, this will show all alerts.\n    Requests APIs under \"\/api\/v0\/alerts\". See https:\/\/mackerel.io\/api-docs\/entry\/alerts .\n`,\n\tAction: doAlertsRetrieve,\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{Name: \"with-closed, w\", Usage: \"Display open alert including close alert. default: false\"},\n\t\tcli.IntFlag{Name: \"limit, l\", Value: 100, Usage: \"Set the number of alerts to display at once when withClosed is active. default: 100\"},\n\t},\n\tSubcommands: []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tUsage:     \"list alerts\",\n\t\t\tArgsUsage: \"[--service | -s <service>] [--host-status | -S <file>] [--color | -c] [--with-closed | -w] [--limit | -l]\",\n\t\t\tDescription: `\n    Shows alerts in human-readable format.\n`,\n\t\t\tAction: doAlertsList,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"service, s\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by service. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"host-status, S\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by status of each host. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.BoolTFlag{Name: \"color, c\", Usage: \"Colorize output. default: true\"},\n\t\t\t\tcli.BoolFlag{Name: \"with-closed, w\", Usage: \"Display open alert including close alert. default: false\"},\n\t\t\t\tcli.IntFlag{Name: \"limit, l\", Value: 100, Usage: \"Set the number of alerts to display at once when withClosed is active. default: 100\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"close\",\n\t\t\tUsage:     \"close alerts\",\n\t\t\tArgsUsage: \"<alertIds....>\",\n\t\t\tDescription: `\n    Closes alerts. Multiple alert IDs can be specified.\n`,\n\t\t\tAction: doAlertsClose,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{Name: \"reason, r\", Value: \"\", Usage: \"Reason of closing alert.\"},\n\t\t\t\tcli.BoolFlag{Name: \"verbose, v\", Usage: \"Verbose output mode\"},\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype alertSet struct {\n\tAlert   *mkr.Alert\n\tHost    *mkr.Host\n\tMonitor mkr.Monitor\n}\n\nfunc joinMonitorsAndHosts(client *mkr.Client, alerts []*mkr.Alert) []*alertSet {\n\thostsJSON, err := client.FindHosts(&mkr.FindHostsParam{\n\t\tStatuses: []string{\"working\", \"standby\", \"poweroff\", \"maintenance\"},\n\t})\n\tlogger.DieIf(err)\n\n\thosts := map[string]*mkr.Host{}\n\tfor _, host := range hostsJSON {\n\t\thosts[host.ID] = host\n\t}\n\n\tmonitorsJSON, err := client.FindMonitors()\n\tlogger.DieIf(err)\n\n\tmonitors := map[string]mkr.Monitor{}\n\tfor _, monitor := range monitorsJSON {\n\t\tmonitors[monitor.MonitorID()] = monitor\n\t}\n\n\talertSets := []*alertSet{}\n\tfor _, alert := range alerts {\n\t\talertSets = append(\n\t\t\talertSets,\n\t\t\t&alertSet{Alert: alert, Host: hosts[alert.HostID], Monitor: monitors[alert.MonitorID]},\n\t\t)\n\t}\n\treturn alertSets\n}\n\nfunc formatJoinedAlert(alertSet *alertSet, colorize bool) string {\n\tconst layout = \"2006-01-02 15:04:05\"\n\n\thost := alertSet.Host\n\tmonitor := alertSet.Monitor\n\talert := alertSet.Alert\n\n\thostMsg := \"\"\n\tif host != nil {\n\t\tstatusMsg := host.Status\n\t\tif host.IsRetired == true {\n\t\t\tstatusMsg = \"retired\"\n\t\t}\n\t\tif colorize {\n\t\t\tswitch statusMsg {\n\t\t\tcase \"working\":\n\t\t\t\tstatusMsg = color.BlueString(\"working\")\n\t\t\tcase \"standby\":\n\t\t\t\tstatusMsg = color.GreenString(\"standby\")\n\t\t\tcase \"poweroff\":\n\t\t\t\tstatusMsg = \"poweroff\"\n\t\t\tcase \"maintenance\":\n\t\t\t\tstatusMsg = color.YellowString(\"maintenance\")\n\t\t\t}\n\t\t}\n\t\thostMsg = fmt.Sprintf(\" %s %s\", host.Name, statusMsg)\n\t\troleMsgs := []string{}\n\t\tfor service, roles := range host.Roles {\n\t\t\troleMsgs = append(roleMsgs, fmt.Sprintf(\"%s:%s\", service, strings.Join(roles, \",\")))\n\t\t}\n\t\thostMsg += \" [\" + strings.Join(roleMsgs, \", \") + \"]\"\n\t}\n\n\tmonitorMsg := \"\"\n\tif monitor != nil {\n\t\tswitch m := monitor.(type) {\n\t\tcase *mkr.MonitorConnectivity:\n\t\t\tmonitorMsg = \"\"\n\t\tcase *mkr.MonitorHostMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorServiceMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f\", m.Service, m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorExternalHTTP:\n\t\t\tstatusRegexp, _ := regexp.Compile(\"^[2345][0-9][0-9]$\")\n\t\t\tswitch alert.Status {\n\t\t\tcase \"CRITICAL\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeCritical != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f > %.2f msec, status:%s\", m.URL, alert.Value, *m.ResponseTimeCritical, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f msec, %s\", m.URL, alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tcase \"WARNING\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeWarning != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f > %.2f msec, status:%s\", alert.Value, *m.ResponseTimeWarning, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, %s\", alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, status:%s\", alert.Value, alert.Message)\n\t\t\t}\n\t\tcase *mkr.MonitorExpression:\n\t\t\texpression := formatExpressionOneline(m.Expression)\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else if alert.Status == \"UNKNOWN\" {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", expression)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", expression, alert.Value)\n\t\t\t}\n\t\tdefault:\n\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", monitor.MonitorType())\n\t\t}\n\t\tif monitorMsg == \"\" {\n\t\t\tmonitorMsg = monitor.MonitorName()\n\t\t} else {\n\t\t\tmonitorMsg = monitor.MonitorName() + \" \" + monitorMsg\n\t\t}\n\t}\n\t\/\/ If alert is caused by check monitoring, take monitorMsg from alert.message\n\tif alert.Type == \"check\" {\n\t\tmonitorMsg = formatCheckMessage(alert.Message)\n\t}\n\n\tstatusMsg := alert.Status\n\tif colorize {\n\t\tswitch alert.Status {\n\t\tcase \"CRITICAL\":\n\t\t\tstatusMsg = color.RedString(\"CRITICAL \")\n\t\tcase \"WARNING\":\n\t\t\tstatusMsg = color.YellowString(\"WARNING \")\n\t\tcase \"OK\":\n\t\t\tstatusMsg = color.GreenString(\"OK \")\n\t\tcase \"UNKNOWN\":\n\t\t\tstatusMsg = \"UNKNOWN \"\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s %s %s %s%s\", alert.ID, time.Unix(alert.OpenedAt, 0).Format(layout), statusMsg, monitorMsg, hostMsg)\n}\n\nvar expressionNewlinePattern = regexp.MustCompile(`\\s*[\\r\\n]+\\s*`)\n\nfunc formatExpressionOneline(expr string) string {\n\texpr = strings.Trim(expressionNewlinePattern.ReplaceAllString(expr, \" \"), \" \")\n\treturn strings.Replace(strings.Replace(expr, \"( \", \"(\", -1), \" )\", \")\", -1)\n}\n\nfunc formatCheckMessage(msg string) string {\n\ttruncated := false\n\tif index := strings.IndexAny(msg, \"\\n\\r\"); index != -1 {\n\t\tmsg = msg[0:index]\n\t\ttruncated = true\n\t}\n\tif runes := []rune(msg); len(runes) > 100 {\n\t\tmsg = string(runes[0:100])\n\t\ttruncated = true\n\t}\n\tif truncated {\n\t\tmsg = msg + \"...\"\n\t}\n\treturn msg\n}\n\nfunc doAlertsRetrieve(c *cli.Context) error {\n\tclient := newMackerelFromContext(c)\n\twithClosed := c.Bool(\"with-closed\")\n\tlimit := c.Int(\"limit\")\n\talerts, err := fetchAlerts(client, withClosed, limit)\n\tlogger.DieIf(err)\n\tPrettyPrintJSON(alerts)\n\treturn nil\n}\n\nfunc doAlertsList(c *cli.Context) error {\n\tfilterServices := c.StringSlice(\"service\")\n\tfilterStatuses := c.StringSlice(\"host-status\")\n\tclient := newMackerelFromContext(c)\n\twithClosed := c.Bool(\"with-closed\")\n\tlimit := c.Int(\"limit\")\n\talerts, err := fetchAlerts(client, withClosed, limit)\n\tlogger.DieIf(err)\n\n\tjoinedAlerts := joinMonitorsAndHosts(client, alerts)\n\tfor _, joinAlert := range joinedAlerts {\n\t\tif len(filterServices) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterService := range filterServices {\n\t\t\t\tif joinAlert.Host != nil {\n\t\t\t\t\tif _, ok := joinAlert.Host.Roles[filterService]; ok {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar service string\n\t\t\t\t\tif m, ok := joinAlert.Monitor.(*mkr.MonitorServiceMetric); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t} else if m, ok := joinAlert.Monitor.(*mkr.MonitorExternalHTTP); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t}\n\t\t\t\t\tfound = service == filterService\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\t\tif len(filterStatuses) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterStatus := range filterStatuses {\n\t\t\t\tif joinAlert.Host != nil && joinAlert.Host.Status == filterStatus {\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\tcontinue\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(color.Output, formatJoinedAlert(joinAlert, c.BoolT(\"color\")))\n\t}\n\treturn nil\n}\n\nfunc fetchAlerts(client *mkr.Client, withClosed bool, limit int) ([]*mkr.Alert, error) {\n\tvar resp *mkr.AlertsResp\n\tvar err error\n\tif withClosed {\n\t\tif resp, err = client.FindWithClosedAlerts(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif resp.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tif limit <= len(resp.Alerts) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tnextResp, err := client.FindWithClosedAlertsByNextID(resp.NextID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tresp.Alerts = append(resp.Alerts, nextResp.Alerts...)\n\t\t\t\tresp.NextID = nextResp.NextID\n\t\t\t\tif resp.NextID == \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif resp, err = client.FindAlerts(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif resp.NextID != \"\" {\n\t\t\tfor {\n\t\t\t\tnextResp, err := client.FindAlertsByNextID(resp.NextID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tresp.Alerts = append(resp.Alerts, nextResp.Alerts...)\n\t\t\t\tresp.NextID = nextResp.NextID\n\t\t\t\tif resp.NextID == \"\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t}\n\t\t}\n\t}\n\tif len(resp.Alerts) > limit {\n\t\tresp.Alerts = resp.Alerts[:limit]\n\t}\n\treturn resp.Alerts, nil\n}\n\nfunc doAlertsClose(c *cli.Context) error {\n\tisVerbose := c.Bool(\"verbose\")\n\targAlertIDs := c.Args()\n\treason := c.String(\"reason\")\n\n\tif len(argAlertIDs) < 1 {\n\t\tcli.ShowCommandHelp(c, \"alerts\")\n\t\tos.Exit(1)\n\t}\n\n\tclient := newMackerelFromContext(c)\n\tfor _, alertID := range argAlertIDs {\n\t\talert, err := client.CloseAlert(alertID, reason)\n\t\tlogger.DieIf(err)\n\n\t\tlogger.Log(\"Alert closed\", alertID)\n\t\tif isVerbose == true {\n\t\t\tPrettyPrintJSON(alert)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\tmkr \"github.com\/mackerelio\/mackerel-client-go\"\n\t\"github.com\/mackerelio\/mkr\/logger\"\n\t\"golang.org\/x\/exp\/utf8string\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar commandAlerts = cli.Command{\n\tName:  \"alerts\",\n\tUsage: \"Retrieve\/Close alerts\",\n\tDescription: `\n    Retrieve\/Close alerts. With no subcommand specified, this will show all alerts.\n    Requests APIs under \"\/api\/v0\/alerts\". See https:\/\/mackerel.io\/api-docs\/entry\/alerts .\n`,\n\tAction: doAlertsRetrieve,\n\tSubcommands: []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tUsage:     \"list alerts\",\n\t\t\tArgsUsage: \"[--service | -s <service>] [--host-status | -S <file>] [--color | -c]\",\n\t\t\tDescription: `\n    Shows alerts in human-readable format.\n`,\n\t\t\tAction: doAlertsList,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"service, s\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by service. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"host-status, S\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by status of each host. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.BoolTFlag{Name: \"color, c\", Usage: \"Colorize output. default: true\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"close\",\n\t\t\tUsage:     \"close alerts\",\n\t\t\tArgsUsage: \"<alertIds....>\",\n\t\t\tDescription: `\n    Closes alerts. Multiple alert IDs can be specified.\n`,\n\t\t\tAction: doAlertsClose,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{Name: \"reason, r\", Value: \"\", Usage: \"Reason of closing alert.\"},\n\t\t\t\tcli.BoolFlag{Name: \"verbose, v\", Usage: \"Verbose output mode\"},\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype alertSet struct {\n\tAlert   *mkr.Alert\n\tHost    *mkr.Host\n\tMonitor mkr.Monitor\n}\n\nfunc joinMonitorsAndHosts(client *mkr.Client, alerts []*mkr.Alert) []*alertSet {\n\thostsJSON, err := client.FindHosts(&mkr.FindHostsParam{\n\t\tStatuses: []string{\"working\", \"standby\", \"poweroff\", \"maintenance\"},\n\t})\n\tlogger.DieIf(err)\n\n\thosts := map[string]*mkr.Host{}\n\tfor _, host := range hostsJSON {\n\t\thosts[host.ID] = host\n\t}\n\n\tmonitorsJSON, err := client.FindMonitors()\n\tlogger.DieIf(err)\n\n\tmonitors := map[string]mkr.Monitor{}\n\tfor _, monitor := range monitorsJSON {\n\t\tmonitors[monitor.MonitorID()] = monitor\n\t}\n\n\talertSets := []*alertSet{}\n\tfor _, alert := range alerts {\n\t\talertSets = append(\n\t\t\talertSets,\n\t\t\t&alertSet{Alert: alert, Host: hosts[alert.HostID], Monitor: monitors[alert.MonitorID]},\n\t\t)\n\t}\n\treturn alertSets\n}\n\nfunc formatJoinedAlert(alertSet *alertSet, colorize bool) string {\n\tconst layout = \"2006-01-02 15:04:05\"\n\n\thost := alertSet.Host\n\tmonitor := alertSet.Monitor\n\talert := alertSet.Alert\n\n\thostMsg := \"\"\n\tif host != nil {\n\t\tstatusMsg := host.Status\n\t\tif host.IsRetired == true {\n\t\t\tstatusMsg = \"retired\"\n\t\t}\n\t\tif colorize {\n\t\t\tswitch statusMsg {\n\t\t\tcase \"working\":\n\t\t\t\tstatusMsg = color.BlueString(\"working\")\n\t\t\tcase \"standby\":\n\t\t\t\tstatusMsg = color.GreenString(\"standby\")\n\t\t\tcase \"poweroff\":\n\t\t\t\tstatusMsg = \"poweroff\"\n\t\t\tcase \"maintenance\":\n\t\t\t\tstatusMsg = color.YellowString(\"maintenance\")\n\t\t\t}\n\t\t}\n\t\thostMsg = fmt.Sprintf(\" %s %s\", host.Name, statusMsg)\n\t\troleMsgs := []string{}\n\t\tfor service, roles := range host.Roles {\n\t\t\troleMsgs = append(roleMsgs, fmt.Sprintf(\"%s:%s\", service, strings.Join(roles, \",\")))\n\t\t}\n\t\thostMsg += \" [\" + strings.Join(roleMsgs, \", \") + \"]\"\n\t}\n\n\tmonitorMsg := \"\"\n\tif monitor != nil {\n\t\tswitch m := monitor.(type) {\n\t\tcase *mkr.MonitorConnectivity:\n\t\t\tmonitorMsg = \"\"\n\t\tcase *mkr.MonitorHostMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorServiceMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f\", m.Service, m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorExternalHTTP:\n\t\t\tstatusRegexp, _ := regexp.Compile(\"^[2345][0-9][0-9]$\")\n\t\t\tswitch alert.Status {\n\t\t\tcase \"CRITICAL\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeCritical != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f > %.2f msec, status:%s\", m.URL, alert.Value, *m.ResponseTimeCritical, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f msec, %s\", m.URL, alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tcase \"WARNING\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeWarning != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f > %.2f msec, status:%s\", alert.Value, *m.ResponseTimeWarning, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, %s\", alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, status:%s\", alert.Value, alert.Message)\n\t\t\t}\n\t\tcase *mkr.MonitorExpression:\n\t\t\texpression := formatExpressionOneline(m.Expression)\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else if alert.Status == \"UNKNOWN\" {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", expression)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", expression, alert.Value)\n\t\t\t}\n\t\tdefault:\n\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", monitor.MonitorType())\n\t\t}\n\t\tif monitorMsg == \"\" {\n\t\t\tmonitorMsg = monitor.MonitorName()\n\t\t} else {\n\t\t\tmonitorMsg = monitor.MonitorName() + \" \" + monitorMsg\n\t\t}\n\t}\n\t\/\/ If alert is caused by check monitoring, take monitorMsg from alert.message\n\tif alert.Type == \"check\" {\n\t\tmonitorMsg = formatCheckMessage(alert.Message)\n\t}\n\n\tstatusMsg := alert.Status\n\tif colorize {\n\t\tswitch alert.Status {\n\t\tcase \"CRITICAL\":\n\t\t\tstatusMsg = color.RedString(\"CRITICAL\")\n\t\tcase \"WARNING\":\n\t\t\tstatusMsg = color.YellowString(\"WARNING \")\n\t\tcase \"UNKNOWN\":\n\t\t\tstatusMsg = \"UNKNOWN \"\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s %s %s %s%s\", alert.ID, time.Unix(alert.OpenedAt, 0).Format(layout), statusMsg, monitorMsg, hostMsg)\n}\n\nvar expressionNewlinePattern = regexp.MustCompile(`\\s*[\\r\\n]+\\s*`)\n\nfunc formatExpressionOneline(expr string) string {\n\texpr = strings.Trim(expressionNewlinePattern.ReplaceAllString(expr, \" \"), \" \")\n\treturn strings.Replace(strings.Replace(expr, \"( \", \"(\", -1), \" )\", \")\", -1)\n}\n\nfunc formatCheckMessage(msg string) string {\n\ttruncated := false\n\tif index := strings.IndexAny(msg, \"\\n\\r\"); index != -1 {\n\t\tmsg = msg[0:index]\n\t\ttruncated = true\n\t}\n\tif msgU := utf8string.NewString(msg); msgU.RuneCount() > 100 {\n\t\tmsg = msgU.Slice(0, 100)\n\t\ttruncated = true\n\t}\n\tif truncated {\n\t\tmsg = msg + \"...\"\n\t}\n\treturn msg\n}\n\nfunc doAlertsRetrieve(c *cli.Context) error {\n\tclient := newMackerelFromContext(c)\n\n\talerts, err := client.FindAlerts()\n\tlogger.DieIf(err)\n\tPrettyPrintJSON(alerts)\n\treturn nil\n}\n\nfunc doAlertsList(c *cli.Context) error {\n\tfilterServices := c.StringSlice(\"service\")\n\tfilterStatuses := c.StringSlice(\"host-status\")\n\tclient := newMackerelFromContext(c)\n\n\talerts, err := client.FindAlerts()\n\tlogger.DieIf(err)\n\tjoinedAlerts := joinMonitorsAndHosts(client, alerts)\n\n\tfor _, joinAlert := range joinedAlerts {\n\t\tif len(filterServices) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterService := range filterServices {\n\t\t\t\tif joinAlert.Host != nil {\n\t\t\t\t\tif _, ok := joinAlert.Host.Roles[filterService]; ok {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar service string\n\t\t\t\t\tif m, ok := joinAlert.Monitor.(*mkr.MonitorServiceMetric); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t} else if m, ok := joinAlert.Monitor.(*mkr.MonitorExternalHTTP); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t}\n\t\t\t\t\tfound = service == filterService\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\t\tif len(filterStatuses) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterStatus := range filterStatuses {\n\t\t\t\tif joinAlert.Host != nil && joinAlert.Host.Status == filterStatus {\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\tcontinue\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(color.Output, formatJoinedAlert(joinAlert, c.BoolT(\"color\")))\n\t}\n\treturn nil\n}\n\nfunc doAlertsClose(c *cli.Context) error {\n\tisVerbose := c.Bool(\"verbose\")\n\targAlertIDs := c.Args()\n\treason := c.String(\"reason\")\n\n\tif len(argAlertIDs) < 1 {\n\t\tcli.ShowCommandHelp(c, \"alerts\")\n\t\tos.Exit(1)\n\t}\n\n\tclient := newMackerelFromContext(c)\n\tfor _, alertID := range argAlertIDs {\n\t\talert, err := client.CloseAlert(alertID, reason)\n\t\tlogger.DieIf(err)\n\n\t\tlogger.Log(\"Alert closed\", alertID)\n\t\tif isVerbose == true {\n\t\t\tPrettyPrintJSON(alert)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>use []rune<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\tmkr \"github.com\/mackerelio\/mackerel-client-go\"\n\t\"github.com\/mackerelio\/mkr\/logger\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar commandAlerts = cli.Command{\n\tName:  \"alerts\",\n\tUsage: \"Retrieve\/Close alerts\",\n\tDescription: `\n    Retrieve\/Close alerts. With no subcommand specified, this will show all alerts.\n    Requests APIs under \"\/api\/v0\/alerts\". See https:\/\/mackerel.io\/api-docs\/entry\/alerts .\n`,\n\tAction: doAlertsRetrieve,\n\tSubcommands: []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tUsage:     \"list alerts\",\n\t\t\tArgsUsage: \"[--service | -s <service>] [--host-status | -S <file>] [--color | -c]\",\n\t\t\tDescription: `\n    Shows alerts in human-readable format.\n`,\n\t\t\tAction: doAlertsList,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"service, s\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by service. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"host-status, S\",\n\t\t\t\t\tValue: &cli.StringSlice{},\n\t\t\t\t\tUsage: \"Filters alerts by status of each host. Multiple choices are allowed.\",\n\t\t\t\t},\n\t\t\t\tcli.BoolTFlag{Name: \"color, c\", Usage: \"Colorize output. default: true\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"close\",\n\t\t\tUsage:     \"close alerts\",\n\t\t\tArgsUsage: \"<alertIds....>\",\n\t\t\tDescription: `\n    Closes alerts. Multiple alert IDs can be specified.\n`,\n\t\t\tAction: doAlertsClose,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{Name: \"reason, r\", Value: \"\", Usage: \"Reason of closing alert.\"},\n\t\t\t\tcli.BoolFlag{Name: \"verbose, v\", Usage: \"Verbose output mode\"},\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype alertSet struct {\n\tAlert   *mkr.Alert\n\tHost    *mkr.Host\n\tMonitor mkr.Monitor\n}\n\nfunc joinMonitorsAndHosts(client *mkr.Client, alerts []*mkr.Alert) []*alertSet {\n\thostsJSON, err := client.FindHosts(&mkr.FindHostsParam{\n\t\tStatuses: []string{\"working\", \"standby\", \"poweroff\", \"maintenance\"},\n\t})\n\tlogger.DieIf(err)\n\n\thosts := map[string]*mkr.Host{}\n\tfor _, host := range hostsJSON {\n\t\thosts[host.ID] = host\n\t}\n\n\tmonitorsJSON, err := client.FindMonitors()\n\tlogger.DieIf(err)\n\n\tmonitors := map[string]mkr.Monitor{}\n\tfor _, monitor := range monitorsJSON {\n\t\tmonitors[monitor.MonitorID()] = monitor\n\t}\n\n\talertSets := []*alertSet{}\n\tfor _, alert := range alerts {\n\t\talertSets = append(\n\t\t\talertSets,\n\t\t\t&alertSet{Alert: alert, Host: hosts[alert.HostID], Monitor: monitors[alert.MonitorID]},\n\t\t)\n\t}\n\treturn alertSets\n}\n\nfunc formatJoinedAlert(alertSet *alertSet, colorize bool) string {\n\tconst layout = \"2006-01-02 15:04:05\"\n\n\thost := alertSet.Host\n\tmonitor := alertSet.Monitor\n\talert := alertSet.Alert\n\n\thostMsg := \"\"\n\tif host != nil {\n\t\tstatusMsg := host.Status\n\t\tif host.IsRetired == true {\n\t\t\tstatusMsg = \"retired\"\n\t\t}\n\t\tif colorize {\n\t\t\tswitch statusMsg {\n\t\t\tcase \"working\":\n\t\t\t\tstatusMsg = color.BlueString(\"working\")\n\t\t\tcase \"standby\":\n\t\t\t\tstatusMsg = color.GreenString(\"standby\")\n\t\t\tcase \"poweroff\":\n\t\t\t\tstatusMsg = \"poweroff\"\n\t\t\tcase \"maintenance\":\n\t\t\t\tstatusMsg = color.YellowString(\"maintenance\")\n\t\t\t}\n\t\t}\n\t\thostMsg = fmt.Sprintf(\" %s %s\", host.Name, statusMsg)\n\t\troleMsgs := []string{}\n\t\tfor service, roles := range host.Roles {\n\t\t\troleMsgs = append(roleMsgs, fmt.Sprintf(\"%s:%s\", service, strings.Join(roles, \",\")))\n\t\t}\n\t\thostMsg += \" [\" + strings.Join(roleMsgs, \", \") + \"]\"\n\t}\n\n\tmonitorMsg := \"\"\n\tif monitor != nil {\n\t\tswitch m := monitor.(type) {\n\t\tcase *mkr.MonitorConnectivity:\n\t\t\tmonitorMsg = \"\"\n\t\tcase *mkr.MonitorHostMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorServiceMetric:\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f %s %.2f\", m.Service, m.Metric, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %s %.2f\", m.Service, m.Metric, alert.Value)\n\t\t\t}\n\t\tcase *mkr.MonitorExternalHTTP:\n\t\t\tstatusRegexp, _ := regexp.Compile(\"^[2345][0-9][0-9]$\")\n\t\t\tswitch alert.Status {\n\t\t\tcase \"CRITICAL\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeCritical != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f > %.2f msec, status:%s\", m.URL, alert.Value, *m.ResponseTimeCritical, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f msec, %s\", m.URL, alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tcase \"WARNING\":\n\t\t\t\tif statusRegexp.MatchString(alert.Message) && m.ResponseTimeWarning != nil {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f > %.2f msec, status:%s\", alert.Value, *m.ResponseTimeWarning, alert.Message)\n\t\t\t\t} else {\n\t\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, %s\", alert.Value, alert.Message)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%.2f msec, status:%s\", alert.Value, alert.Message)\n\t\t\t}\n\t\tcase *mkr.MonitorExpression:\n\t\t\texpression := formatExpressionOneline(m.Expression)\n\t\t\tif alert.Status == \"CRITICAL\" && m.Critical != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Critical)\n\t\t\t} else if alert.Status == \"WARNING\" && m.Warning != nil {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f %s %.2f\", expression, alert.Value, m.Operator, *m.Warning)\n\t\t\t} else if alert.Status == \"UNKNOWN\" {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", expression)\n\t\t\t} else {\n\t\t\t\tmonitorMsg = fmt.Sprintf(\"%s %.2f\", expression, alert.Value)\n\t\t\t}\n\t\tdefault:\n\t\t\tmonitorMsg = fmt.Sprintf(\"%s\", monitor.MonitorType())\n\t\t}\n\t\tif monitorMsg == \"\" {\n\t\t\tmonitorMsg = monitor.MonitorName()\n\t\t} else {\n\t\t\tmonitorMsg = monitor.MonitorName() + \" \" + monitorMsg\n\t\t}\n\t}\n\t\/\/ If alert is caused by check monitoring, take monitorMsg from alert.message\n\tif alert.Type == \"check\" {\n\t\tmonitorMsg = formatCheckMessage(alert.Message)\n\t}\n\n\tstatusMsg := alert.Status\n\tif colorize {\n\t\tswitch alert.Status {\n\t\tcase \"CRITICAL\":\n\t\t\tstatusMsg = color.RedString(\"CRITICAL\")\n\t\tcase \"WARNING\":\n\t\t\tstatusMsg = color.YellowString(\"WARNING \")\n\t\tcase \"UNKNOWN\":\n\t\t\tstatusMsg = \"UNKNOWN \"\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s %s %s %s%s\", alert.ID, time.Unix(alert.OpenedAt, 0).Format(layout), statusMsg, monitorMsg, hostMsg)\n}\n\nvar expressionNewlinePattern = regexp.MustCompile(`\\s*[\\r\\n]+\\s*`)\n\nfunc formatExpressionOneline(expr string) string {\n\texpr = strings.Trim(expressionNewlinePattern.ReplaceAllString(expr, \" \"), \" \")\n\treturn strings.Replace(strings.Replace(expr, \"( \", \"(\", -1), \" )\", \")\", -1)\n}\n\nfunc formatCheckMessage(msg string) string {\n\ttruncated := false\n\tif index := strings.IndexAny(msg, \"\\n\\r\"); index != -1 {\n\t\tmsg = msg[0:index]\n\t\ttruncated = true\n\t}\n\tif runes := []rune(msg); len(runes) > 100 {\n\t\tmsg = string(runes[0:100])\n\t\ttruncated = true\n\t}\n\tif truncated {\n\t\tmsg = msg + \"...\"\n\t}\n\treturn msg\n}\n\nfunc doAlertsRetrieve(c *cli.Context) error {\n\tclient := newMackerelFromContext(c)\n\n\talerts, err := client.FindAlerts()\n\tlogger.DieIf(err)\n\tPrettyPrintJSON(alerts)\n\treturn nil\n}\n\nfunc doAlertsList(c *cli.Context) error {\n\tfilterServices := c.StringSlice(\"service\")\n\tfilterStatuses := c.StringSlice(\"host-status\")\n\tclient := newMackerelFromContext(c)\n\n\talerts, err := client.FindAlerts()\n\tlogger.DieIf(err)\n\tjoinedAlerts := joinMonitorsAndHosts(client, alerts)\n\n\tfor _, joinAlert := range joinedAlerts {\n\t\tif len(filterServices) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterService := range filterServices {\n\t\t\t\tif joinAlert.Host != nil {\n\t\t\t\t\tif _, ok := joinAlert.Host.Roles[filterService]; ok {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar service string\n\t\t\t\t\tif m, ok := joinAlert.Monitor.(*mkr.MonitorServiceMetric); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t} else if m, ok := joinAlert.Monitor.(*mkr.MonitorExternalHTTP); ok {\n\t\t\t\t\t\tservice = m.Service\n\t\t\t\t\t}\n\t\t\t\t\tfound = service == filterService\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\t\tif len(filterStatuses) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, filterStatus := range filterStatuses {\n\t\t\t\tif joinAlert.Host != nil && joinAlert.Host.Status == filterStatus {\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\tcontinue\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(color.Output, formatJoinedAlert(joinAlert, c.BoolT(\"color\")))\n\t}\n\treturn nil\n}\n\nfunc doAlertsClose(c *cli.Context) error {\n\tisVerbose := c.Bool(\"verbose\")\n\targAlertIDs := c.Args()\n\treason := c.String(\"reason\")\n\n\tif len(argAlertIDs) < 1 {\n\t\tcli.ShowCommandHelp(c, \"alerts\")\n\t\tos.Exit(1)\n\t}\n\n\tclient := newMackerelFromContext(c)\n\tfor _, alertID := range argAlertIDs {\n\t\talert, err := client.CloseAlert(alertID, reason)\n\t\tlogger.DieIf(err)\n\n\t\tlogger.Log(\"Alert closed\", alertID)\n\t\tif isVerbose == true {\n\t\t\tPrettyPrintJSON(alert)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tpath \"path\/filepath\"\n\t\"strings\"\n)\n\nvar cmdApiapp = &Command{\n\t\/\/ CustomFlags: true,\n\tUsageLine: \"api [appname]\",\n\tShort:     \"create an api application base on beego framework\",\n\tLong: `\ncreate an api application base on beego framework\n\nIn the current path, will create a folder named [appname]\n\nIn the appname folder has the follow struct:\n\n\t├── conf\n\t│   └── app.conf\n\t├── controllers\n\t│   └── default.go\n\t├── main.go\n\t└── models\n\t    └── default.go             \n\n`,\n}\n\nvar apiconf = `\nappname = {{.Appname}}\nhttpport = 8080\nrunmode = dev\nautorender = false\n`\nvar apiMaingo = `package main\n\nimport (\n\t\"{{.Appname}}\/controllers\"\n\t\"github.com\/astaxie\/beego\"\n)\n\nfunc main() {\n\tbeego.Router(\"\/{{.Version}}\/users\/:objectId\", &controllers.UserController{})\n\tbeego.Router(\"\/{{.Version}}\/users\", &controllers.UserController{})\n\tbeego.Run()\n}\n`\nvar apiModels = `package models\n\ntype User struct {\n\tId    interface{}\n\tName  string\n\tEmail string\n}\n\nfunc (this *User) One(id interface{}) (user User, err error) {\n\t\/\/ get user from DB\n\t\/\/ user, err = query(id)\n\tuser = User{id, \"astaxie\", \"astaxie@gmail.com\"}\n\treturn\n}\n\nfunc (this *User) All() (users []User, err error) {\n\t\/\/ get all users from DB\n\t\/\/ users, err = queryAll()\n\tusers = append([]User{}, User{1, \"astaxie\", \"astaxie@gmail.com\"})\n\tusers = append(users, User{2, \"someone\", \"someone@gmail.com\"})\n\treturn\n}\n\nfunc (this *User) Update(id interface{}) (err error) {\n\t\/\/ user, err = update(id, this)\n\treturn\n}\n\n`\n\nvar apiControllers = `package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"{{.Appname}}\/models\"\n\t\"github.com\/astaxie\/beego\"\n\t\"io\/ioutil\"\n)\n\ntype UserController struct {\n\tbeego.Controller\n}\n\nfunc (this *UserController) Get() {\n\tvar user models.User\n\tobjectId := this.Ctx.Params[\":objectId\"]\n\tif objectId != \"\" {\n\t\tuser, err := user.One(objectId)\n\t\tif err != nil {\n\t\t\tthis.Data[\"json\"] = err\n\t\t} else {\n\t\t\tthis.Data[\"json\"] = user\n\t\t}\n\t} else {\n\t\tusers, err := user.All()\n\t\tif err != nil {\n\t\t\tthis.Data[\"json\"] = err\n\t\t} else {\n\t\t\tthis.Data[\"json\"] = users\n\t\t}\n\t}\n\tthis.ServeJson()\n}\n\nfunc (this *UserController) Put() {\n\tdefer this.ServeJson()\n\tvar user models.User\n\tobjectId := this.Ctx.Params[\":objectId\"]\n\n\tbody, err := ioutil.ReadAll(this.Ctx.Request.Body)\n\tif err != nil {\n\t\tthis.Data[\"json\"] = err\n\t\treturn\n\t}\n\tthis.Ctx.Request.Body.Close()\n\n\tif err = json.Unmarshal(body, &user); err != nil {\n\t\tthis.Data[\"json\"] = err\n\t\treturn\n\t}\n\n\terr = user.Update(objectId)\n\tif err != nil {\n\t\tthis.Data[\"json\"] = err\n\t} else {\n\t\tthis.Data[\"json\"] = \"update success!\"\n\t}\n}\n\n`\n\nfunc init() {\n\tcmdApiapp.Run = createapi\n}\n\nfunc createapi(cmd *Command, args []string) {\n\tversion := \"1\"\n\tif len(args) == 2 {\n\t\tversion = args[1]\n\t} else if len(args) != 1 {\n\t\tfmt.Println(\"error args\")\n\t\tos.Exit(2)\n\t}\n\tapppath, packpath, err := checkEnv(args[0])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n\tos.MkdirAll(apppath, 0755)\n\tfmt.Println(\"create app folder:\", apppath)\n\tos.Mkdir(path.Join(apppath, \"conf\"), 0755)\n\tfmt.Println(\"create conf:\", path.Join(apppath, \"conf\"))\n\tos.Mkdir(path.Join(apppath, \"controllers\"), 0755)\n\tfmt.Println(\"create controllers:\", path.Join(apppath, \"controllers\"))\n\tos.Mkdir(path.Join(apppath, \"models\"), 0755)\n\tfmt.Println(\"create models:\", path.Join(apppath, \"models\"))\n\n\tfmt.Println(\"create conf app.conf:\", path.Join(apppath, \"conf\", \"app.conf\"))\n\twritetofile(path.Join(apppath, \"conf\", \"app.conf\"),\n\t\tstrings.Replace(apiconf, \"{{.Appname}}\", args[0], -1))\n\n\tfmt.Println(\"create controllers default.go:\", path.Join(apppath, \"controllers\", \"default.go\"))\n\twritetofile(path.Join(apppath, \"controllers\", \"default.go\"),\n\t\tstrings.Replace(apiControllers, \"{{.Appname}}\", packpath, -1))\n\n\tfmt.Println(\"create models default.go:\", path.Join(apppath, \"models\", \"default.go\"))\n\twritetofile(path.Join(apppath, \"models\", \"default.go\"), apiModels)\n\n\tfmt.Println(\"create main.go:\", path.Join(apppath, \"main.go\"))\n\tapiMaingo = strings.Replace(apiMaingo, \"{{.Version}}\", version, -1)\n\twritetofile(path.Join(apppath, \"main.go\"),\n\t\tstrings.Replace(apiMaingo, \"{{.Appname}}\", packpath, -1))\n}\n\nfunc checkEnv(appname string) (apppath, packpath string, err error) {\n\tcurpath, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgopath := os.Getenv(\"GOPATH\")\n\tDebugf(\"gopath:%s\", gopath)\n\tif gopath == \"\" {\n\t\terr = fmt.Errorf(\"you should set GOPATH in the env\")\n\t\treturn\n\t}\n\n\tappsrcpath := \"\"\n\thaspath := false\n\twgopath := path.SplitList(gopath)\n\tfor _, wg := range wgopath {\n\t\twg = path.Join(wg, \"src\")\n\n\t\tif path.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {\n\t\t\thaspath = true\n\t\t\tappsrcpath = wg\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !haspath {\n\t\terr = fmt.Errorf(\"can't create application outside of GOPATH `%s`\\n\"+\n\t\t\t\"you first should `cd $GOPATH%ssrc` then use create\\n\", gopath, string(path.Separator))\n\t\treturn\n\t}\n\tapppath = path.Join(curpath, appname)\n\n\tif _, e := os.Stat(apppath); os.IsNotExist(e) == false {\n\t\terr = fmt.Errorf(\"path `%s` exists, can not create app without remove it\\n\", apppath)\n\t\treturn\n\t}\n\tpackpath = strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), \"\/\")\n\treturn\n}\n<commit_msg>an example for api application<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\tpath \"path\/filepath\"\n\t\"strings\"\n)\n\nvar cmdApiapp = &Command{\n\t\/\/ CustomFlags: true,\n\tUsageLine: \"api [appname]\",\n\tShort:     \"create an api application base on beego framework\",\n\tLong: `\ncreate an api application base on beego framework\n\nIn the current path, will create a folder named [appname]\n\nIn the appname folder has the follow struct:\n\n\t├── conf\n\t│   └── app.conf\n\t├── controllers\n\t│   └── default.go\n\t├── main.go\n\t└── models\n\t    └── object.go             \n\n`,\n}\n\nvar apiconf = `\nappname = {{.Appname}}\nhttpport = 8080\nrunmode = dev\nautorender = false\ncopyrequestbody = true\n`\nvar apiMaingo = `package main\n\nimport (\n\t\"github.com\/astaxie\/beego\"\n\t\"{{.Appname}}\/controllers\"\n)\n\n\/\/\t\tObjects\n\n\/\/\tURL\t\t\t\t\tHTTP Verb\t\t\t\tFunctionality\n\/\/\t\/object\t\t\t\tPOST\t\t\t\t\tCreating Objects\n\/\/\t\/object\/<objectId>\tGET\t\t\t\t\t\tRetrieving Objects\n\/\/\t\/object\/<objectId>\tPUT\t\t\t\t\t\tUpdating Objects\n\/\/\t\/object\t\t\t\tGET\t\t\t\t\t\tQueries\n\/\/\t\/object\/<objectId>\tDELETE\t\t\t\t\tDeleting Objects\n\nfunc main() {\n\tbeego.RESTRouter(\"\/object\", &controllers.ObejctController{})\n\tbeego.Run()\n}\n`\nvar apiModels = `package models\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tObjects map[string]*Object\n)\n\ntype Object struct {\n\tObjectId   string\n\tScore      int64\n\tPlayerName string\n}\n\nfunc init() {\n\tObjects = make(map[string]*Object)\n\tObjects[\"hjkhsbnmn123\"] = &Object{\"hjkhsbnmn123\", 100, \"astaxie\"}\n\tObjects[\"mjjkxsxsaa23\"] = &Object{\"mjjkxsxsaa23\", 101, \"someone\"}\n}\n\nfunc AddOne(object Object) (ObjectId string) {\n\tobject.ObjectId = \"astaxie\" + strconv.FormatInt(time.Now().UnixNano(), 10)\n\tObjects[object.ObjectId] = &object\n\treturn object.ObjectId\n}\n\nfunc GetOne(ObjectId string) (object *Object, err error) {\n\tif v, ok := Objects[ObjectId]; ok {\n\t\treturn v, nil\n\t}\n\treturn nil, errors.New(\"ObjectId Not Exist\")\n}\n\nfunc GetAll() map[string]*Object {\n\treturn Objects\n}\n\nfunc Update(ObjectId string, Score int64) (err error) {\n\tif v, ok := Objects[ObjectId]; ok {\n\t\tv.Score = Score\n\t\treturn nil\n\t}\n\treturn errors.New(\"ObjectId Not Exist\")\n}\n\nfunc Delete(ObjectId string) {\n\tdelete(Objects, ObjectId)\n}\n`\n\nvar apiControllers = `package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/astaxie\/beego\"\n\t\"{{.Appname}}\/models\"\n)\n\ntype ResponseInfo struct {\n}\n\ntype ObejctController struct {\n\tbeego.Controller\n}\n\nfunc (this *ObejctController) Post() {\n\tvar ob models.Object\n\tjson.Unmarshal(this.Ctx.RequestBody, &ob)\n\tobjectid := models.AddOne(ob)\n\tthis.Data[\"json\"] = \"{\\\"ObjectId\\\":\\\"\" + objectid + \"\\\"}\"\n\tthis.ServeJson()\n}\n\nfunc (this *ObejctController) Get() {\n\tobjectId := this.Ctx.Params[\":objectId\"]\n\tif objectId != \"\" {\n\t\tob, err := models.GetOne(objectId)\n\t\tif err != nil {\n\t\t\tthis.Data[\"json\"] = err\n\t\t} else {\n\t\t\tthis.Data[\"json\"] = ob\n\t\t}\n\t} else {\n\t\tobs := models.GetAll()\n\t\tthis.Data[\"json\"] = obs\n\t}\n\tthis.ServeJson()\n}\n\nfunc (this *ObejctController) Put() {\n\tobjectId := this.Ctx.Params[\":objectId\"]\n\tvar ob models.Object\n\tjson.Unmarshal(this.Ctx.RequestBody, &ob)\n\n\terr := models.Update(objectId, ob.Score)\n\tif err != nil {\n\t\tthis.Data[\"json\"] = err\n\t} else {\n\t\tthis.Data[\"json\"] = \"update success!\"\n\t}\n\tthis.ServeJson()\n}\n\nfunc (this *ObejctController) Delete() {\n\tobjectId := this.Ctx.Params[\":objectId\"]\n\tmodels.Delete(objectId)\n\tthis.Data[\"json\"] = \"delete success!\"\n\tthis.ServeJson()\n}\n`\n\nfunc init() {\n\tcmdApiapp.Run = createapi\n}\n\nfunc createapi(cmd *Command, args []string) {\n\tif len(args) != 1 {\n\t\tfmt.Println(\"error args\")\n\t\tos.Exit(2)\n\t}\n\tapppath, packpath, err := checkEnv(args[0])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n\tos.MkdirAll(apppath, 0755)\n\tfmt.Println(\"create app folder:\", apppath)\n\tos.Mkdir(path.Join(apppath, \"conf\"), 0755)\n\tfmt.Println(\"create conf:\", path.Join(apppath, \"conf\"))\n\tos.Mkdir(path.Join(apppath, \"controllers\"), 0755)\n\tfmt.Println(\"create controllers:\", path.Join(apppath, \"controllers\"))\n\tos.Mkdir(path.Join(apppath, \"models\"), 0755)\n\tfmt.Println(\"create models:\", path.Join(apppath, \"models\"))\n\n\tfmt.Println(\"create conf app.conf:\", path.Join(apppath, \"conf\", \"app.conf\"))\n\twritetofile(path.Join(apppath, \"conf\", \"app.conf\"),\n\t\tstrings.Replace(apiconf, \"{{.Appname}}\", args[0], -1))\n\n\tfmt.Println(\"create controllers default.go:\", path.Join(apppath, \"controllers\", \"default.go\"))\n\twritetofile(path.Join(apppath, \"controllers\", \"default.go\"),\n\t\tstrings.Replace(apiControllers, \"{{.Appname}}\", packpath, -1))\n\n\tfmt.Println(\"create models object.go:\", path.Join(apppath, \"models\", \"object.go\"))\n\twritetofile(path.Join(apppath, \"models\", \"object.go\"), apiModels)\n\n\tfmt.Println(\"create main.go:\", path.Join(apppath, \"main.go\"))\n\twritetofile(path.Join(apppath, \"main.go\"),\n\t\tstrings.Replace(apiMaingo, \"{{.Appname}}\", packpath, -1))\n}\n\nfunc checkEnv(appname string) (apppath, packpath string, err error) {\n\tcurpath, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgopath := os.Getenv(\"GOPATH\")\n\tDebugf(\"gopath:%s\", gopath)\n\tif gopath == \"\" {\n\t\terr = fmt.Errorf(\"you should set GOPATH in the env\")\n\t\treturn\n\t}\n\n\tappsrcpath := \"\"\n\thaspath := false\n\twgopath := path.SplitList(gopath)\n\tfor _, wg := range wgopath {\n\t\twg = path.Join(wg, \"src\")\n\n\t\tif path.HasPrefix(strings.ToLower(curpath), strings.ToLower(wg)) {\n\t\t\thaspath = true\n\t\t\tappsrcpath = wg\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !haspath {\n\t\terr = fmt.Errorf(\"can't create application outside of GOPATH `%s`\\n\"+\n\t\t\t\"you first should `cd $GOPATH%ssrc` then use create\\n\", gopath, string(path.Separator))\n\t\treturn\n\t}\n\tapppath = path.Join(curpath, appname)\n\n\tif _, e := os.Stat(apppath); os.IsNotExist(e) == false {\n\t\terr = fmt.Errorf(\"path `%s` exists, can not create app without remove it\\n\", apppath)\n\t\treturn\n\t}\n\tpackpath = strings.Join(strings.Split(apppath[len(appsrcpath)+1:], string(path.Separator)), \"\/\")\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package spotify\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ SimpleArtist contains basic info about an artist.\ntype SimpleArtist struct {\n\tName string `json:\"name\"`\n\tID   ID     `json:\"id\"`\n\t\/\/ The Spotify URI for the artist.\n\tURI URI `json:\"uri\"`\n\t\/\/ A link to the Web API enpoint providing full details of the artist.\n\tEndpoint     string            `json:\"href\"`\n\tExternalURLs map[string]string `json:\"external_urls\"`\n}\n\n\/\/ FullArtist provides extra artist data in addition to what is provided by SimpleArtist.\ntype FullArtist struct {\n\tSimpleArtist\n\t\/\/ The popularity of the artist, expressed as an integer between 0 and 100.\n\t\/\/ The artist's popularity is calculated from the popularity of the artist's tracks.\n\tPopularity int `json:\"popularity\"`\n\t\/\/ A list of genres the artist is associated with.  For example, \"Prog Rock\"\n\t\/\/ or \"Post-Grunge\".  If not yet classified, the slice is empty.\n\tGenres    []string  `json:\"genres\"`\n\tFollowers Followers `json:\"followers\"`\n\t\/\/ Images of the artist in various sizes, widest first.\n\tImages []Image `json:\"images\"`\n}\n\n\/\/ GetArtist gets Spotify catalog information for a single artist, given its Spotify ID.\nfunc (c *Client) GetArtist(id ID) (*FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\", c.baseURL, id)\n\n\tvar a FullArtist\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &a, nil\n}\n\n\/\/ GetArtists gets spotify catalog information for several artists based on their\n\/\/ Spotify IDs.  It supports up to 50 artists in a single call.  Artists are\n\/\/ returned in the order requested.  If an artist is not found, that position\n\/\/ in the result will be nil.  Duplicate IDs will result in duplicate artists\n\/\/ in the result.\nfunc (c *Client) GetArtists(ids ...ID) ([]*FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists?ids=%s\", c.baseURL, strings.Join(toStringSlice(ids), \",\"))\n\n\tvar a struct {\n\t\tArtists []*FullArtist\n\t}\n\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.Artists, nil\n}\n\n\/\/ GetArtistsTopTracks gets Spotify catalog information about an artist's top\n\/\/ tracks in a particular country.  It returns a maximum of 10 tracks.  The\n\/\/ country is specified as an ISO 3166-1 alpha-2 country code.\nfunc (c *Client) GetArtistsTopTracks(artistID ID, country string) ([]FullTrack, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/top-tracks?country=%s\", c.baseURL, artistID, country)\n\n\tvar t struct {\n\t\tTracks []FullTrack `json:\"tracks\"`\n\t}\n\n\terr := c.get(spotifyURL, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t.Tracks, nil\n}\n\n\/\/ GetRelatedArtists gets Spotify catalog information about artists similar to a\n\/\/ given artist.  Similarity is based on analysis of the Spotify community's\n\/\/ listening history.  This function returns up to 20 artists that are considered\n\/\/ related to the specified artist.\nfunc (c *Client) GetRelatedArtists(id ID) ([]FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/related-artists\", c.baseURL, id)\n\n\tvar a struct {\n\t\tArtists []FullArtist `json:\"artists\"`\n\t}\n\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.Artists, nil\n}\n\n\/\/ GetArtistAlbums gets Spotify catalog information about an artist's albums.\n\/\/ It is equivalent to GetArtistAlbumsOpt(artistID, nil).\nfunc (c *Client) GetArtistAlbums(artistID ID) (*SimpleAlbumPage, error) {\n\treturn c.GetArtistAlbumsOpt(artistID, nil, nil)\n}\n\n\/\/ GetArtistAlbumsOpt is just like GetArtistAlbums, but it accepts optional\n\/\/ parameters used to filter and sort the result.\n\/\/\n\/\/ The AlbumType argument can be used to find a particular type of album.  Search\n\/\/ for multiple types by OR-ing the types together.\nfunc (c *Client) GetArtistAlbumsOpt(artistID ID, options *Options, t *AlbumType) (*SimpleAlbumPage, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/albums\", c.baseURL, artistID)\n\t\/\/ add optional query string if options were specified\n\tvalues := url.Values{}\n\tif t != nil {\n\t\tvalues.Set(\"album_type\", t.encode())\n\t}\n\tif options != nil {\n\t\tif options.Country != nil {\n\t\t\tvalues.Set(\"market\", *options.Country)\n\t\t} else {\n\t\t\t\/\/ if the market is not specified, Spotify will likely return a lot\n\t\t\t\/\/ of duplicates (one for each market in which the album is available)\n\t\t\t\/\/ - prevent this behavior by falling back to the US by default\n\t\t\t\/\/ TODO: would this ever be the desired behavior?\n\t\t\tvalues.Set(\"market\", CountryUSA)\n\t\t}\n\t\tif options.Limit != nil {\n\t\t\tvalues.Set(\"limit\", strconv.Itoa(*options.Limit))\n\t\t}\n\t\tif options.Offset != nil {\n\t\t\tvalues.Set(\"offset\", strconv.Itoa(*options.Offset))\n\t\t}\n\t}\n\tif query := values.Encode(); query != \"\" {\n\t\tspotifyURL += \"?\" + query\n\t}\n\n\tvar p SimpleAlbumPage\n\n\terr := c.get(spotifyURL, &p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}\n<commit_msg>feat: Enable option to not sent market using GetArtistAlbumsOpt<commit_after>package spotify\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ SimpleArtist contains basic info about an artist.\ntype SimpleArtist struct {\n\tName string `json:\"name\"`\n\tID   ID     `json:\"id\"`\n\t\/\/ The Spotify URI for the artist.\n\tURI URI `json:\"uri\"`\n\t\/\/ A link to the Web API enpoint providing full details of the artist.\n\tEndpoint     string            `json:\"href\"`\n\tExternalURLs map[string]string `json:\"external_urls\"`\n}\n\n\/\/ FullArtist provides extra artist data in addition to what is provided by SimpleArtist.\ntype FullArtist struct {\n\tSimpleArtist\n\t\/\/ The popularity of the artist, expressed as an integer between 0 and 100.\n\t\/\/ The artist's popularity is calculated from the popularity of the artist's tracks.\n\tPopularity int `json:\"popularity\"`\n\t\/\/ A list of genres the artist is associated with.  For example, \"Prog Rock\"\n\t\/\/ or \"Post-Grunge\".  If not yet classified, the slice is empty.\n\tGenres    []string  `json:\"genres\"`\n\tFollowers Followers `json:\"followers\"`\n\t\/\/ Images of the artist in various sizes, widest first.\n\tImages []Image `json:\"images\"`\n}\n\n\/\/ GetArtist gets Spotify catalog information for a single artist, given its Spotify ID.\nfunc (c *Client) GetArtist(id ID) (*FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\", c.baseURL, id)\n\n\tvar a FullArtist\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &a, nil\n}\n\n\/\/ GetArtists gets spotify catalog information for several artists based on their\n\/\/ Spotify IDs.  It supports up to 50 artists in a single call.  Artists are\n\/\/ returned in the order requested.  If an artist is not found, that position\n\/\/ in the result will be nil.  Duplicate IDs will result in duplicate artists\n\/\/ in the result.\nfunc (c *Client) GetArtists(ids ...ID) ([]*FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists?ids=%s\", c.baseURL, strings.Join(toStringSlice(ids), \",\"))\n\n\tvar a struct {\n\t\tArtists []*FullArtist\n\t}\n\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.Artists, nil\n}\n\n\/\/ GetArtistsTopTracks gets Spotify catalog information about an artist's top\n\/\/ tracks in a particular country.  It returns a maximum of 10 tracks.  The\n\/\/ country is specified as an ISO 3166-1 alpha-2 country code.\nfunc (c *Client) GetArtistsTopTracks(artistID ID, country string) ([]FullTrack, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/top-tracks?country=%s\", c.baseURL, artistID, country)\n\n\tvar t struct {\n\t\tTracks []FullTrack `json:\"tracks\"`\n\t}\n\n\terr := c.get(spotifyURL, &t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t.Tracks, nil\n}\n\n\/\/ GetRelatedArtists gets Spotify catalog information about artists similar to a\n\/\/ given artist.  Similarity is based on analysis of the Spotify community's\n\/\/ listening history.  This function returns up to 20 artists that are considered\n\/\/ related to the specified artist.\nfunc (c *Client) GetRelatedArtists(id ID) ([]FullArtist, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/related-artists\", c.baseURL, id)\n\n\tvar a struct {\n\t\tArtists []FullArtist `json:\"artists\"`\n\t}\n\n\terr := c.get(spotifyURL, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn a.Artists, nil\n}\n\n\/\/ GetArtistAlbums gets Spotify catalog information about an artist's albums.\n\/\/ It is equivalent to GetArtistAlbumsOpt(artistID, nil).\nfunc (c *Client) GetArtistAlbums(artistID ID) (*SimpleAlbumPage, error) {\n\treturn c.GetArtistAlbumsOpt(artistID, nil, nil)\n}\n\n\/\/ GetArtistAlbumsOpt is just like GetArtistAlbums, but it accepts optional\n\/\/ parameters used to filter and sort the result.\n\/\/\n\/\/ The AlbumType argument can be used to find a particular type of album.  Search\n\/\/ for multiple types by OR-ing the types together. If the market (Options) is\n\/\/ not specified, Spotify will likely return a lot of duplicates (one for each\n\/\/ market in which the album is available)\nfunc (c *Client) GetArtistAlbumsOpt(artistID ID, options *Options, t *AlbumType) (*SimpleAlbumPage, error) {\n\tspotifyURL := fmt.Sprintf(\"%sartists\/%s\/albums\", c.baseURL, artistID)\n\t\/\/ add optional query string if options were specified\n\tvalues := url.Values{}\n\tif t != nil {\n\t\tvalues.Set(\"album_type\", t.encode())\n\t}\n\tif options != nil {\n\t\tif options.Country != nil {\n\t\t\tvalues.Set(\"market\", *options.Country)\n\t\t}\n\t\tif options.Limit != nil {\n\t\t\tvalues.Set(\"limit\", strconv.Itoa(*options.Limit))\n\t\t}\n\t\tif options.Offset != nil {\n\t\t\tvalues.Set(\"offset\", strconv.Itoa(*options.Offset))\n\t\t}\n\t}\n\tif query := values.Encode(); query != \"\" {\n\t\tspotifyURL += \"?\" + query\n\t}\n\n\tvar p SimpleAlbumPage\n\n\terr := c.get(spotifyURL, &p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &p, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"errors\"\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\/dustin\/go-hashset\"\n\t\"github.com\/dustin\/gomemcached\"\n\n\t\"encoding\/hex\"\n\t\"github.com\/couchbaselabs\/cbfs\/config\"\n\t\"sync\"\n)\n\nconst backupKey = \"\/@backup\"\n\ntype backupItem struct {\n\tFn   string                `json:\"filename\"`\n\tOid  string                `json:\"oid\"`\n\tWhen time.Time             `json:\"when\"`\n\tConf cbfsconfig.CBFSConfig `json:\"conf\"`\n}\n\ntype backups struct {\n\tLatest  backupItem   `json:\"latest\"`\n\tBackups []backupItem `json:\"backups\"`\n}\n\nfunc logDuration(m string, startTime time.Time) {\n\tlog.Printf(\"Completed %v in %v\", m, time.Since(startTime))\n}\n\nfunc streamFileMeta(w io.Writer,\n\tfch chan *namedFile,\n\tech chan error) error {\n\n\tenc := json.NewEncoder(w)\n\tfor {\n\t\tselect {\n\t\tcase f, ok := <-fch:\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terr := enc.Encode(map[string]interface{}{\n\t\t\t\t\"path\": f.name,\n\t\t\t\t\"meta\": f.meta,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase e, ok := <-ech:\n\t\t\tif ok {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tech = nil\n\t\t}\n\t}\n}\n\nfunc backupTo(w io.Writer) (err error) {\n\tfch := make(chan *namedFile)\n\tech := make(chan error)\n\tqch := make(chan bool)\n\n\tdefer close(qch)\n\n\tdefer logDuration(\"backup\", time.Now())\n\n\tgo pathGenerator(\"\", fch, ech, qch)\n\n\tgz := gzip.NewWriter(w)\n\tdefer func() {\n\t\te := gz.Close()\n\t\tif err != nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\treturn streamFileMeta(gz, fch, ech)\n}\n\nfunc recordBackupObject() error {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tf, err := os.Create(filepath.Join(*root, \".backup.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\te := json.NewEncoder(f)\n\treturn e.Encode(&b)\n}\n\nfunc recordRemoteBackupObjects() {\n\trn, err := findRemoteNodes()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting remote nodes for recording backup: %v\",\n\t\t\terr)\n\t\treturn\n\t}\n\tfor _, n := range rn {\n\t\tu := fmt.Sprintf(\"http:\/\/%s%s\",\n\t\t\tn.Address(), markBackupPrefix)\n\t\tc := n.Client()\n\t\tres, err := c.Post(u, \"application\/octet-stream\", nil)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error posting to %v: %v\", u, err)\n\t\t\tcontinue\n\t\t}\n\t\tres.Body.Close()\n\t\tif res.StatusCode != 204 {\n\t\t\tlog.Printf(\"HTTP Error posting to %v: %v\", u, res.Status)\n\t\t}\n\t}\n}\n\nfunc removeDeadBackups(b *backups) {\n\t\/\/ Keep only backups we're pretty sure still exist.\n\tobn := b.Backups\n\tb.Backups = nil\n\tfor _, bi := range obn {\n\t\tfm := fileMeta{}\n\t\terr := couchbase.Get(shortName(bi.Fn), &fm)\n\t\tif gomemcached.IsNotFound(err) {\n\t\t\tlog.Printf(\"Dropping previous (deleted) backup: %v\",\n\t\t\t\tbi.Fn)\n\t\t} else {\n\t\t\tb.Backups = append(b.Backups, bi)\n\t\t}\n\t}\n\n}\n\nfunc storeBackupObject(fn, h string) error {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil && !gomemcached.IsNotFound(err) {\n\t\tlog.Printf(\"Weird: %v\", err)\n\t\t\/\/ return err\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tob := backupItem{fn, h, time.Now().UTC(), *globalConfig}\n\n\tb.Latest = ob\n\tb.Backups = append(b.Backups, ob)\n\n\treturn couchbase.Set(backupKey, 0, &b)\n}\n\nfunc backupToCBFS(fn string) error {\n\tf, err := NewHashRecord(*root, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tpr, pw := io.Pipe()\n\n\tgo func() { pw.CloseWithError(backupTo(pw)) }()\n\n\th, length, err := f.Process(pr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = recordBlobOwnership(h, length, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfm := fileMeta{\n\t\tOID:      h,\n\t\tLength:   length,\n\t\tModified: time.Now().UTC(),\n\t}\n\n\terr = storeMeta(fn, 0, fm, 1, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = storeBackupObject(fn, h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = recordBackupObject()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to record backup OID: %v\", err)\n\t}\n\n\tgo recordRemoteBackupObjects()\n\n\tlog.Printf(\"Replicating backup %v.\", h)\n\tgo increaseReplicaCount(h, length, globalConfig.MinReplicas-1)\n\n\treturn nil\n}\n\nfunc doMarkBackup(w http.ResponseWriter, req *http.Request) {\n\tif req.FormValue(\"all\") == \"true\" {\n\t\tgo recordRemoteBackupObjects()\n\t}\n\terr := recordBackupObject()\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error marking backup; %v\", err), 500)\n\t\treturn\n\t}\n\tw.WriteHeader(204)\n}\n\nfunc doBackupDocs(w http.ResponseWriter, req *http.Request) {\n\tfn := req.FormValue(\"fn\")\n\tif fn == \"\" {\n\t\thttp.Error(w, \"Missing fn parameter\", 400)\n\t\treturn\n\t}\n\n\tif bg, _ := strconv.ParseBool(req.FormValue(\"bg\")); bg {\n\t\tgo func() {\n\t\t\terr := backupToCBFS(fn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error performing bg backup: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tw.WriteHeader(202)\n\t\treturn\n\t}\n\n\terr := backupToCBFS(fn)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error performing backup: %v\", err), 500)\n\t\treturn\n\t}\n\n\tw.WriteHeader(201)\n}\n\nfunc doGetBackupInfo(w http.ResponseWriter, req *http.Request) {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil {\n\t\tcode := 500\n\t\tif gomemcached.IsNotFound(err) {\n\t\t\tcode = 404\n\t\t}\n\t\thttp.Error(w, err.Error(), code)\n\t\treturn\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tsendJson(w, req, &b)\n}\n\nvar errExists = errors.New(\"item exists\")\n\nfunc maybeStoreMeta(k string, fm fileMeta, exp int, force bool) error {\n\tif force {\n\t\treturn couchbase.Set(k, exp, fm)\n\t}\n\tadded, err := couchbase.Add(k, exp, fm)\n\tif err == nil && !added {\n\t\terr = errExists\n\t}\n\treturn err\n}\n\nfunc doRestoreDocument(w http.ResponseWriter, req *http.Request, fn string) {\n\td := json.NewDecoder(req.Body)\n\tfm := fileMeta{}\n\terr := d.Decode(&fm)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfor len(fn) > 0 && fn[0] == '\/' {\n\t\tfn = fn[1:]\n\t}\n\n\tif fn == \"\" {\n\t\thttp.Error(w, \"No filename\", 400)\n\t\treturn\n\t}\n\n\tif strings.Contains(fn, \"\/\/\") {\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Too many slashes in the path name: %v\", fn), 400)\n\t\treturn\n\t}\n\n\t_, err = referenceBlob(fm.OID)\n\tif err != nil {\n\t\tlog.Printf(\"Missing blob %v while restoring %v - restoring anyway\",\n\t\t\tfm.OID, fn)\n\t}\n\n\texp := getExpiration(req.Header)\n\tif exp == -1 {\n\t\texp = getExpiration(fm.Headers)\n\t\tif exp > 0 && exp < 60*60*24*30 {\n\t\t\texp = int(fm.Modified.Add(time.Second * time.Duration(exp)).Unix())\n\t\t}\n\t}\n\n\tif exp < 0 {\n\t\tlog.Printf(\"Attempt to restore expired file: %v\", fn)\n\t\tw.WriteHeader(201)\n\t\treturn\n\t}\n\n\tforce := false\n\terr = maybeStoreMeta(fn, fm, exp, force)\n\tswitch err {\n\tcase errExists:\n\t\thttp.Error(w, err.Error(), 409)\n\t\treturn\n\tcase nil:\n\tdefault:\n\t\tlog.Printf(\"Error storing file meta of %v -> %v: %v\",\n\t\t\tfn, fm.OID, err)\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Error recording file meta: %v\", err), 500)\n\t\treturn\n\t}\n\n\tlog.Printf(\"Restored %v -> %v (exp=%v)\", fn, fm.OID, exp)\n\n\tw.WriteHeader(201)\n}\n\nfunc loadBackupHashes(oid string) (*hashset.Hashset, int, error) {\n\trv := &hashset.Hashset{}\n\n\tr := blobReader(oid)\n\tdefer r.Close()\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer gz.Close()\n\n\td := json.NewDecoder(gz)\n\n\thashlen := getHash().Size()\n\n\tvisited := 0\n\tfor {\n\t\tob := struct {\n\t\t\tMeta struct {\n\t\t\t\tOID   string\n\t\t\t\tOlder []struct {\n\t\t\t\t\tOID string\n\t\t\t\t}\n\t\t\t}\n\t\t}{}\n\n\t\terr := d.Decode(&ob)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\toid, err := hex.DecodeString(ob.Meta.OID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, visited, err\n\t\t\t}\n\t\t\tif len(oid) != hashlen {\n\t\t\t\tlog.Printf(\"Invalid hash from %#v\", ob)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trv.Add(oid)\n\t\t\tvisited++\n\t\t\tfor _, obs := range ob.Meta.Older {\n\t\t\t\toid, err = hex.DecodeString(obs.OID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, visited, err\n\t\t\t\t}\n\t\t\t\trv.Add(oid)\n\t\t\t\tvisited++\n\t\t\t}\n\t\tcase io.EOF:\n\t\t\treturn rv, visited, nil\n\t\tdefault:\n\t\t\treturn nil, visited, err\n\t\t}\n\t}\n}\n\nfunc loadExistingHashes() (*hashset.Hashset, error) {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil && !gomemcached.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\toids := make(chan string)\n\thsch := make(chan *hashset.Hashset)\n\tvisitch := make(chan int)\n\terrch := make(chan error)\n\n\twg := sync.WaitGroup{}\n\n\tfor i := 0; i < 4; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor o := range oids {\n\t\t\t\th, v, e := loadBackupHashes(o)\n\t\t\t\tif e == nil {\n\t\t\t\t\thsch <- h\n\t\t\t\t} else {\n\t\t\t\t\terrch <- e\n\t\t\t\t}\n\t\t\t\tvisitch <- v\n\t\t\t}\n\t\t}()\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(hsch)\n\t\tclose(visitch)\n\t\tclose(errch)\n\t}()\n\n\tgo func() {\n\t\tfor _, i := range b.Backups {\n\t\t\tlog.Printf(\"Loading backups from %v \/ %v\", i.Oid, i.Fn)\n\t\t\toids <- i.Oid\n\t\t}\n\t\tclose(oids)\n\t}()\n\n\tvisited := 0\n\ths := &hashset.Hashset{}\n\tfor {\n\t\t\/\/ Done getting all the things\n\t\tif hsch == nil && visitch == nil && errch == nil {\n\t\t\tbreak\n\t\t}\n\t\tselect {\n\t\tcase v, ok := <-visitch:\n\t\t\tvisited += v\n\t\t\tif !ok {\n\t\t\t\tvisitch = nil\n\t\t\t}\n\t\tcase e, ok := <-errch:\n\t\t\terr = e\n\t\t\tif !ok {\n\t\t\t\terrch = nil\n\t\t\t}\n\t\tcase h, ok := <-hsch:\n\t\t\tif ok {\n\t\t\t\tlog.Printf(\"Got %v hashes from a backup\",\n\t\t\t\t\th.Len())\n\t\t\t\ths.AddAll(h)\n\t\t\t} else {\n\t\t\t\thsch = nil\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"Visited %v obs, kept %v\", visited, hs.Len())\n\n\treturn hs, err\n}\n<commit_msg>Something weirded up my imports<commit_after>package main\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\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\"sync\"\n\t\"time\"\n\n\t\"github.com\/dustin\/go-hashset\"\n\t\"github.com\/dustin\/gomemcached\"\n\n\t\"github.com\/couchbaselabs\/cbfs\/config\"\n)\n\nconst backupKey = \"\/@backup\"\n\ntype backupItem struct {\n\tFn   string                `json:\"filename\"`\n\tOid  string                `json:\"oid\"`\n\tWhen time.Time             `json:\"when\"`\n\tConf cbfsconfig.CBFSConfig `json:\"conf\"`\n}\n\ntype backups struct {\n\tLatest  backupItem   `json:\"latest\"`\n\tBackups []backupItem `json:\"backups\"`\n}\n\nfunc logDuration(m string, startTime time.Time) {\n\tlog.Printf(\"Completed %v in %v\", m, time.Since(startTime))\n}\n\nfunc streamFileMeta(w io.Writer,\n\tfch chan *namedFile,\n\tech chan error) error {\n\n\tenc := json.NewEncoder(w)\n\tfor {\n\t\tselect {\n\t\tcase f, ok := <-fch:\n\t\t\tif !ok {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terr := enc.Encode(map[string]interface{}{\n\t\t\t\t\"path\": f.name,\n\t\t\t\t\"meta\": f.meta,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase e, ok := <-ech:\n\t\t\tif ok {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tech = nil\n\t\t}\n\t}\n}\n\nfunc backupTo(w io.Writer) (err error) {\n\tfch := make(chan *namedFile)\n\tech := make(chan error)\n\tqch := make(chan bool)\n\n\tdefer close(qch)\n\n\tdefer logDuration(\"backup\", time.Now())\n\n\tgo pathGenerator(\"\", fch, ech, qch)\n\n\tgz := gzip.NewWriter(w)\n\tdefer func() {\n\t\te := gz.Close()\n\t\tif err != nil {\n\t\t\terr = e\n\t\t}\n\t}()\n\n\treturn streamFileMeta(gz, fch, ech)\n}\n\nfunc recordBackupObject() error {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tf, err := os.Create(filepath.Join(*root, \".backup.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\te := json.NewEncoder(f)\n\treturn e.Encode(&b)\n}\n\nfunc recordRemoteBackupObjects() {\n\trn, err := findRemoteNodes()\n\tif err != nil {\n\t\tlog.Printf(\"Error getting remote nodes for recording backup: %v\",\n\t\t\terr)\n\t\treturn\n\t}\n\tfor _, n := range rn {\n\t\tu := fmt.Sprintf(\"http:\/\/%s%s\",\n\t\t\tn.Address(), markBackupPrefix)\n\t\tc := n.Client()\n\t\tres, err := c.Post(u, \"application\/octet-stream\", nil)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error posting to %v: %v\", u, err)\n\t\t\tcontinue\n\t\t}\n\t\tres.Body.Close()\n\t\tif res.StatusCode != 204 {\n\t\t\tlog.Printf(\"HTTP Error posting to %v: %v\", u, res.Status)\n\t\t}\n\t}\n}\n\nfunc removeDeadBackups(b *backups) {\n\t\/\/ Keep only backups we're pretty sure still exist.\n\tobn := b.Backups\n\tb.Backups = nil\n\tfor _, bi := range obn {\n\t\tfm := fileMeta{}\n\t\terr := couchbase.Get(shortName(bi.Fn), &fm)\n\t\tif gomemcached.IsNotFound(err) {\n\t\t\tlog.Printf(\"Dropping previous (deleted) backup: %v\",\n\t\t\t\tbi.Fn)\n\t\t} else {\n\t\t\tb.Backups = append(b.Backups, bi)\n\t\t}\n\t}\n\n}\n\nfunc storeBackupObject(fn, h string) error {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil && !gomemcached.IsNotFound(err) {\n\t\tlog.Printf(\"Weird: %v\", err)\n\t\t\/\/ return err\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tob := backupItem{fn, h, time.Now().UTC(), *globalConfig}\n\n\tb.Latest = ob\n\tb.Backups = append(b.Backups, ob)\n\n\treturn couchbase.Set(backupKey, 0, &b)\n}\n\nfunc backupToCBFS(fn string) error {\n\tf, err := NewHashRecord(*root, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tpr, pw := io.Pipe()\n\n\tgo func() { pw.CloseWithError(backupTo(pw)) }()\n\n\th, length, err := f.Process(pr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = recordBlobOwnership(h, length, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfm := fileMeta{\n\t\tOID:      h,\n\t\tLength:   length,\n\t\tModified: time.Now().UTC(),\n\t}\n\n\terr = storeMeta(fn, 0, fm, 1, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = storeBackupObject(fn, h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = recordBackupObject()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to record backup OID: %v\", err)\n\t}\n\n\tgo recordRemoteBackupObjects()\n\n\tlog.Printf(\"Replicating backup %v.\", h)\n\tgo increaseReplicaCount(h, length, globalConfig.MinReplicas-1)\n\n\treturn nil\n}\n\nfunc doMarkBackup(w http.ResponseWriter, req *http.Request) {\n\tif req.FormValue(\"all\") == \"true\" {\n\t\tgo recordRemoteBackupObjects()\n\t}\n\terr := recordBackupObject()\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error marking backup; %v\", err), 500)\n\t\treturn\n\t}\n\tw.WriteHeader(204)\n}\n\nfunc doBackupDocs(w http.ResponseWriter, req *http.Request) {\n\tfn := req.FormValue(\"fn\")\n\tif fn == \"\" {\n\t\thttp.Error(w, \"Missing fn parameter\", 400)\n\t\treturn\n\t}\n\n\tif bg, _ := strconv.ParseBool(req.FormValue(\"bg\")); bg {\n\t\tgo func() {\n\t\t\terr := backupToCBFS(fn)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error performing bg backup: %v\", err)\n\t\t\t}\n\t\t}()\n\t\tw.WriteHeader(202)\n\t\treturn\n\t}\n\n\terr := backupToCBFS(fn)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error performing backup: %v\", err), 500)\n\t\treturn\n\t}\n\n\tw.WriteHeader(201)\n}\n\nfunc doGetBackupInfo(w http.ResponseWriter, req *http.Request) {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil {\n\t\tcode := 500\n\t\tif gomemcached.IsNotFound(err) {\n\t\t\tcode = 404\n\t\t}\n\t\thttp.Error(w, err.Error(), code)\n\t\treturn\n\t}\n\n\tremoveDeadBackups(&b)\n\n\tsendJson(w, req, &b)\n}\n\nvar errExists = errors.New(\"item exists\")\n\nfunc maybeStoreMeta(k string, fm fileMeta, exp int, force bool) error {\n\tif force {\n\t\treturn couchbase.Set(k, exp, fm)\n\t}\n\tadded, err := couchbase.Add(k, exp, fm)\n\tif err == nil && !added {\n\t\terr = errExists\n\t}\n\treturn err\n}\n\nfunc doRestoreDocument(w http.ResponseWriter, req *http.Request, fn string) {\n\td := json.NewDecoder(req.Body)\n\tfm := fileMeta{}\n\terr := d.Decode(&fm)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfor len(fn) > 0 && fn[0] == '\/' {\n\t\tfn = fn[1:]\n\t}\n\n\tif fn == \"\" {\n\t\thttp.Error(w, \"No filename\", 400)\n\t\treturn\n\t}\n\n\tif strings.Contains(fn, \"\/\/\") {\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Too many slashes in the path name: %v\", fn), 400)\n\t\treturn\n\t}\n\n\t_, err = referenceBlob(fm.OID)\n\tif err != nil {\n\t\tlog.Printf(\"Missing blob %v while restoring %v - restoring anyway\",\n\t\t\tfm.OID, fn)\n\t}\n\n\texp := getExpiration(req.Header)\n\tif exp == -1 {\n\t\texp = getExpiration(fm.Headers)\n\t\tif exp > 0 && exp < 60*60*24*30 {\n\t\t\texp = int(fm.Modified.Add(time.Second * time.Duration(exp)).Unix())\n\t\t}\n\t}\n\n\tif exp < 0 {\n\t\tlog.Printf(\"Attempt to restore expired file: %v\", fn)\n\t\tw.WriteHeader(201)\n\t\treturn\n\t}\n\n\tforce := false\n\terr = maybeStoreMeta(fn, fm, exp, force)\n\tswitch err {\n\tcase errExists:\n\t\thttp.Error(w, err.Error(), 409)\n\t\treturn\n\tcase nil:\n\tdefault:\n\t\tlog.Printf(\"Error storing file meta of %v -> %v: %v\",\n\t\t\tfn, fm.OID, err)\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Error recording file meta: %v\", err), 500)\n\t\treturn\n\t}\n\n\tlog.Printf(\"Restored %v -> %v (exp=%v)\", fn, fm.OID, exp)\n\n\tw.WriteHeader(201)\n}\n\nfunc loadBackupHashes(oid string) (*hashset.Hashset, int, error) {\n\trv := &hashset.Hashset{}\n\n\tr := blobReader(oid)\n\tdefer r.Close()\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer gz.Close()\n\n\td := json.NewDecoder(gz)\n\n\thashlen := getHash().Size()\n\n\tvisited := 0\n\tfor {\n\t\tob := struct {\n\t\t\tMeta struct {\n\t\t\t\tOID   string\n\t\t\t\tOlder []struct {\n\t\t\t\t\tOID string\n\t\t\t\t}\n\t\t\t}\n\t\t}{}\n\n\t\terr := d.Decode(&ob)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\toid, err := hex.DecodeString(ob.Meta.OID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, visited, err\n\t\t\t}\n\t\t\tif len(oid) != hashlen {\n\t\t\t\tlog.Printf(\"Invalid hash from %#v\", ob)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trv.Add(oid)\n\t\t\tvisited++\n\t\t\tfor _, obs := range ob.Meta.Older {\n\t\t\t\toid, err = hex.DecodeString(obs.OID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, visited, err\n\t\t\t\t}\n\t\t\t\trv.Add(oid)\n\t\t\t\tvisited++\n\t\t\t}\n\t\tcase io.EOF:\n\t\t\treturn rv, visited, nil\n\t\tdefault:\n\t\t\treturn nil, visited, err\n\t\t}\n\t}\n}\n\nfunc loadExistingHashes() (*hashset.Hashset, error) {\n\tb := backups{}\n\terr := couchbase.Get(backupKey, &b)\n\tif err != nil && !gomemcached.IsNotFound(err) {\n\t\treturn nil, err\n\t}\n\n\toids := make(chan string)\n\thsch := make(chan *hashset.Hashset)\n\tvisitch := make(chan int)\n\terrch := make(chan error)\n\n\twg := sync.WaitGroup{}\n\n\tfor i := 0; i < 4; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor o := range oids {\n\t\t\t\th, v, e := loadBackupHashes(o)\n\t\t\t\tif e == nil {\n\t\t\t\t\thsch <- h\n\t\t\t\t} else {\n\t\t\t\t\terrch <- e\n\t\t\t\t}\n\t\t\t\tvisitch <- v\n\t\t\t}\n\t\t}()\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(hsch)\n\t\tclose(visitch)\n\t\tclose(errch)\n\t}()\n\n\tgo func() {\n\t\tfor _, i := range b.Backups {\n\t\t\tlog.Printf(\"Loading backups from %v \/ %v\", i.Oid, i.Fn)\n\t\t\toids <- i.Oid\n\t\t}\n\t\tclose(oids)\n\t}()\n\n\tvisited := 0\n\ths := &hashset.Hashset{}\n\tfor {\n\t\t\/\/ Done getting all the things\n\t\tif hsch == nil && visitch == nil && errch == nil {\n\t\t\tbreak\n\t\t}\n\t\tselect {\n\t\tcase v, ok := <-visitch:\n\t\t\tvisited += v\n\t\t\tif !ok {\n\t\t\t\tvisitch = nil\n\t\t\t}\n\t\tcase e, ok := <-errch:\n\t\t\terr = e\n\t\t\tif !ok {\n\t\t\t\terrch = nil\n\t\t\t}\n\t\tcase h, ok := <-hsch:\n\t\t\tif ok {\n\t\t\t\tlog.Printf(\"Got %v hashes from a backup\",\n\t\t\t\t\th.Len())\n\t\t\t\ths.AddAll(h)\n\t\t\t} else {\n\t\t\t\thsch = nil\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"Visited %v obs, kept %v\", visited, hs.Len())\n\n\treturn hs, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/unixvoid\/glogger\"\n\t\"golang.org\/x\/crypto\/sha3\"\n\t\"gopkg.in\/gcfg.v1\"\n\t\"gopkg.in\/redis.v3\"\n)\n\ntype Config struct {\n\tBeacon struct {\n\t\tPort            int\n\t\tTokenSize       int\n\t\tTokenDictionary string\n\t\tLoglevel        string\n\t}\n\tSSL struct {\n\t\tUseTLS     bool\n\t\tServerCert string\n\t\tServerKey  string\n\t}\n\tRedis struct {\n\t\tHost string\n\t\tPort int\n\t}\n}\n\nvar (\n\tconfig = Config{}\n)\n\nfunc main() {\n\terr := gcfg.ReadFileInto(&config, \"config.gcfg\")\n\tif err != nil {\n\t\tfmt.Printf(\"Could not load config.gcfg, error: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ init logger\n\tif config.Beacon.Loglevel == \"debug\" {\n\t\tglogger.LogInit(os.Stdout, os.Stdout, os.Stdout, os.Stderr)\n\t} else if config.Beacon.Loglevel == \"cluster\" {\n\t\tglogger.LogInit(os.Stdout, os.Stdout, ioutil.Discard, os.Stderr)\n\t} else if config.Beacon.Loglevel == \"info\" {\n\t\tglogger.LogInit(os.Stdout, ioutil.Discard, ioutil.Discard, os.Stderr)\n\t} else {\n\t\tglogger.LogInit(ioutil.Discard, ioutil.Discard, ioutil.Discard, os.Stderr)\n\t}\n\n\tredisaddr := fmt.Sprint(config.Redis.Host, \":\", config.Redis.Port)\n\tbitport := fmt.Sprint(\":\", config.Beacon.Port)\n\tglogger.Info.Println(\"beacon running on\", config.Beacon.Port)\n\tglogger.Info.Println(\"link to redis on\", redisaddr)\n\t\/\/ initialize redis connection\n\tclient := redis.NewClient(&redis.Options{\n\t\tAddr:     redisaddr,\n\t\tPassword: \"\",\n\t\tDB:       0,\n\t})\n\n\t\/\/ all handlers. lookin funcy casue i have to pass redis handler\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"\/provision\", func(w http.ResponseWriter, r *http.Request) {\n\t\tprovision(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/update\", func(w http.ResponseWriter, r *http.Request) {\n\t\tupdate(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/remove\", func(w http.ResponseWriter, r *http.Request) {\n\t\tremove(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/{fdata}\", func(w http.ResponseWriter, r *http.Request) {\n\t\thandlerdynamic(w, r, client)\n\t}).Methods(\"GET\")\n\tif config.SSL.UseTLS {\n\t\tlog.Fatal(http.ListenAndServeTLS(bitport, config.SSL.ServerCert, config.SSL.ServerKey, router))\n\t} else {\n\t\tlog.Fatal(http.ListenAndServe(bitport, router))\n\t}\n}\n\nfunc handlerdynamic(w http.ResponseWriter, r *http.Request, client *redis.Client) {\n\tvars := mux.Vars(r)\n\tfdata := vars[\"fdata\"]\n\n\t\/\/ hash the token that is passed\n\tclientIdHash := sha3.Sum512([]byte(fdata))\n\n\tval, err := client.Get(fmt.Sprintf(\"ip:%x\", clientIdHash)).Result()\n\tif err != nil {\n\t\tlog.Printf(\"data does not exist\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(w, \"token not found\")\n\t} else {\n\t\t\/\/log.Printf(\"data exists\")\n\t\tfmt.Fprintf(w, \"%s\", val)\n\t}\n}\n\nfunc provision(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\n\t\/\/ sha3:512 hash the id\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\n\t\/\/ check if the id exists (sec:<clientId>)\n\t_, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\tfmt.Println(\"DEBUG :: COLLISION\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t} else {\n\t\t\/\/ generate token, store hashed token in db\n\t\ttoken := randStr(config.Beacon.TokenSize)\n\t\ttokenHash := sha3.Sum512([]byte(token))\n\n\t\t\/\/ return token to client\n\t\tw.Header().Set(\"token\", token)\n\t\tfmt.Fprintf(w, \"%s\", token)\n\n\t\t\/\/ done with client, rest is server side\n\t\t\/\/ sec:<hashed clientId> : hashed password\n\t\tclient.Set(fmt.Sprintf(\"sec:%x\", clientIdHash), fmt.Sprintf(\"%x\", tokenHash), 0).Err()\n\n\t\t\/\/ if temp objects, set an expire link on them\n\t\tif strings.EqualFold(state, \"tmp\") {\n\t\t}\n\t}\n}\n\nfunc update(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\tclientSec := strings.TrimSpace(r.FormValue(\"sec\"))\n\tclientAddress := strings.TrimSpace(r.FormValue(\"address\"))\n\n\t\/\/ sha3:512 hash the id and sec\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\tclientSecHash := sha3.Sum512([]byte(clientSec))\n\n\t\/\/ check if id exists\n\tstoredSecHash, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\t\/\/ id exists, make sure clientSecHash is the same as the stored version\n\t\tif fmt.Sprintf(\"%x\", clientSecHash) == storedSecHash {\n\t\t\t\/\/ client is authed, update clientAddress\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tclient.Set(fmt.Sprintf(\"ip:%x\", clientIdHash), clientAddress, 0).Err()\n\t\t} else {\n\t\t\t\/\/ client auth failed\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\/\/ id does not exist\n\t}\n}\n\nfunc remove(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\tclientSec := strings.TrimSpace(r.FormValue(\"sec\"))\n\n\t\/\/ sha3:512 hash the id and sec\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\tclientSecHash := sha3.Sum512([]byte(clientSec))\n\n\t\/\/ check if id exists\n\tstoredSecHash, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\t\/\/ id exists, make sure clientSecHash is the same as the stored version\n\t\tif fmt.Sprintf(\"%x\", clientSecHash) == storedSecHash {\n\t\t\t\/\/ client is authed\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tclient.Del(fmt.Sprintf(\"ip:%x\", clientIdHash))\n\t\t\tclient.Del(fmt.Sprintf(\"sec:%x\", clientIdHash))\n\t\t} else {\n\t\t\t\/\/ client auth failed\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\/\/ id does not exist\n\t}\n}\n\nfunc randStr(strSize int) string {\n\tdictionary := config.Beacon.TokenDictionary\n\n\tvar bytes = make([]byte, strSize)\n\trand.Read(bytes)\n\tfor k, v := range bytes {\n\t\tbytes[k] = dictionary[v%byte(len(dictionary))]\n\t}\n\n\treturn string(bytes)\n}\n<commit_msg>Add SSL settings<commit_after>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/unixvoid\/glogger\"\n\t\"golang.org\/x\/crypto\/sha3\"\n\t\"gopkg.in\/gcfg.v1\"\n\t\"gopkg.in\/redis.v3\"\n)\n\ntype Config struct {\n\tBeacon struct {\n\t\tPort            int\n\t\tTokenSize       int\n\t\tTokenDictionary string\n\t\tLoglevel        string\n\t}\n\tSSL struct {\n\t\tUseTLS     bool\n\t\tServerCert string\n\t\tServerKey  string\n\t}\n\tRedis struct {\n\t\tHost string\n\t\tPort int\n\t}\n}\n\nvar (\n\tconfig = Config{}\n)\n\nfunc main() {\n\terr := gcfg.ReadFileInto(&config, \"config.gcfg\")\n\tif err != nil {\n\t\tfmt.Printf(\"Could not load config.gcfg, error: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ init logger\n\tif config.Beacon.Loglevel == \"debug\" {\n\t\tglogger.LogInit(os.Stdout, os.Stdout, os.Stdout, os.Stderr)\n\t} else if config.Beacon.Loglevel == \"cluster\" {\n\t\tglogger.LogInit(os.Stdout, os.Stdout, ioutil.Discard, os.Stderr)\n\t} else if config.Beacon.Loglevel == \"info\" {\n\t\tglogger.LogInit(os.Stdout, ioutil.Discard, ioutil.Discard, os.Stderr)\n\t} else {\n\t\tglogger.LogInit(ioutil.Discard, ioutil.Discard, ioutil.Discard, os.Stderr)\n\t}\n\n\t\/\/ TODO error checking on redis instance (ping)\n\tredisaddr := fmt.Sprint(config.Redis.Host, \":\", config.Redis.Port)\n\tbitport := fmt.Sprint(\":\", config.Beacon.Port)\n\tglogger.Info.Println(\"link to redis on\", redisaddr)\n\t\/\/ initialize redis connection\n\tclient := redis.NewClient(&redis.Options{\n\t\tAddr:     redisaddr,\n\t\tPassword: \"\",\n\t\tDB:       0,\n\t})\n\n\t\/\/ router routes\/handlers\n\trouter := mux.NewRouter().StrictSlash(true)\n\trouter.HandleFunc(\"\/provision\", func(w http.ResponseWriter, r *http.Request) {\n\t\tprovision(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/update\", func(w http.ResponseWriter, r *http.Request) {\n\t\tupdate(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/remove\", func(w http.ResponseWriter, r *http.Request) {\n\t\tremove(w, r, client, \"tmp\")\n\t}).Methods(\"POST\")\n\trouter.HandleFunc(\"\/{fdata}\", func(w http.ResponseWriter, r *http.Request) {\n\t\thandlerdynamic(w, r, client)\n\t}).Methods(\"GET\")\n\n\tif config.SSL.UseTLS {\n\t\ttlsConfig := &tls.Config{\n\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\tMaxVersion: tls.VersionTLS12,\n\t\t\tCipherSuites: []uint16{\n\t\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n\t\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\t\ttls.TLS_RSA_WITH_AES_128_CBC_SHA,\n\t\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t\t\ttls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\t\ttls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,\n\t\t\t},\n\t\t\tPreferServerCipherSuites: true,\n\t\t\tClientSessionCache:       tls.NewLRUClientSessionCache(128),\n\t\t}\n\t\tglogger.Info.Println(\"beacon running https on\", config.Beacon.Port)\n\t\ttlsServer := &http.Server{Addr: fmt.Sprintf(\":%d\", config.Beacon.Port), Handler: router, TLSConfig: tlsConfig}\n\t\tlog.Fatal(tlsServer.ListenAndServeTLS(config.SSL.ServerCert, config.SSL.ServerKey))\n\t} else {\n\t\tglogger.Info.Println(\"beacon running http on\", config.Beacon.Port)\n\t\tlog.Fatal(http.ListenAndServe(bitport, router))\n\t}\n}\n\nfunc handlerdynamic(w http.ResponseWriter, r *http.Request, client *redis.Client) {\n\tvars := mux.Vars(r)\n\tfdata := vars[\"fdata\"]\n\n\t\/\/ hash the token that is passed\n\tclientIdHash := sha3.Sum512([]byte(fdata))\n\n\tval, err := client.Get(fmt.Sprintf(\"ip:%x\", clientIdHash)).Result()\n\tif err != nil {\n\t\tglogger.Debug.Printf(\"data does not exist\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tfmt.Fprintf(w, \"token not found\")\n\t} else {\n\t\t\/\/log.Printf(\"data exists\")\n\t\tfmt.Fprintf(w, \"%s\", val)\n\t}\n}\n\nfunc provision(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\n\t\/\/ sha3:512 hash the id\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\n\t\/\/ check if the id exists (sec:<clientId>)\n\t_, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\tfmt.Println(\"DEBUG :: COLLISION\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t} else {\n\t\t\/\/ generate token, store hashed token in db\n\t\ttoken := randStr(config.Beacon.TokenSize)\n\t\ttokenHash := sha3.Sum512([]byte(token))\n\n\t\t\/\/ return token to client\n\t\tw.Header().Set(\"token\", token)\n\t\tfmt.Fprintf(w, \"%s\", token)\n\n\t\t\/\/ done with client, rest is server side\n\t\t\/\/ sec:<hashed clientId> : hashed password\n\t\tclient.Set(fmt.Sprintf(\"sec:%x\", clientIdHash), fmt.Sprintf(\"%x\", tokenHash), 0).Err()\n\n\t\t\/\/ if temp objects, set an expire link on them\n\t\tif strings.EqualFold(state, \"tmp\") {\n\t\t}\n\t}\n}\n\nfunc update(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\tclientSec := strings.TrimSpace(r.FormValue(\"sec\"))\n\tclientAddress := strings.TrimSpace(r.FormValue(\"address\"))\n\n\t\/\/ sha3:512 hash the id and sec\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\tclientSecHash := sha3.Sum512([]byte(clientSec))\n\n\t\/\/ check if id exists\n\tstoredSecHash, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\t\/\/ id exists, make sure clientSecHash is the same as the stored version\n\t\tif fmt.Sprintf(\"%x\", clientSecHash) == storedSecHash {\n\t\t\t\/\/ client is authed, update clientAddress\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tclient.Set(fmt.Sprintf(\"ip:%x\", clientIdHash), clientAddress, 0).Err()\n\t\t} else {\n\t\t\t\/\/ client auth failed\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\/\/ id does not exist\n\t}\n}\n\nfunc remove(w http.ResponseWriter, r *http.Request, client *redis.Client, state string) {\n\t\/\/ get file POST from index\n\tr.ParseForm()\n\tclientId := strings.TrimSpace(r.FormValue(\"id\"))\n\tclientSec := strings.TrimSpace(r.FormValue(\"sec\"))\n\n\t\/\/ sha3:512 hash the id and sec\n\tclientIdHash := sha3.Sum512([]byte(clientId))\n\tclientSecHash := sha3.Sum512([]byte(clientSec))\n\n\t\/\/ check if id exists\n\tstoredSecHash, err := client.Get(fmt.Sprintf(\"sec:%x\", clientIdHash)).Result()\n\tif err != redis.Nil {\n\t\t\/\/ id exists, make sure clientSecHash is the same as the stored version\n\t\tif fmt.Sprintf(\"%x\", clientSecHash) == storedSecHash {\n\t\t\t\/\/ client is authed\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\tclient.Del(fmt.Sprintf(\"ip:%x\", clientIdHash))\n\t\t\tclient.Del(fmt.Sprintf(\"sec:%x\", clientIdHash))\n\t\t} else {\n\t\t\t\/\/ client auth failed\n\t\t\tw.WriteHeader(http.StatusForbidden)\n\t\t}\n\t} else {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\/\/ id does not exist\n\t}\n}\n\nfunc randStr(strSize int) string {\n\tdictionary := config.Beacon.TokenDictionary\n\n\tvar bytes = make([]byte, strSize)\n\trand.Read(bytes)\n\tfor k, v := range bytes {\n\t\tbytes[k] = dictionary[v%byte(len(dictionary))]\n\t}\n\n\treturn string(bytes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package bloomd\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"fmt\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"io\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Filter string\n\ntype Client interface {\n\tBulkSet(context.Context, Filter, ...string) ([]bool, error)\n\tCheck(context.Context, Filter, string) (bool, error)\n\tClear(context.Context, Filter) error\n\tClose(context.Context, Filter) error\n\tCreate(context.Context, Filter) error\n\tDrop(context.Context, Filter) error\n\tFlush(context.Context) error\n\tList(context.Context) (map[string]string, error)\n\tMultiCheck(context.Context, Filter, ...string) ([]bool, error)\n\tSet(context.Context, Filter, string) (bool, error)\n\tInfo(context.Context, Filter) (map[string]string, error)\n\tPing() error\n}\n\nconst (\n\tFLUSH           = \"flush\"\n\tLIST            = \"list\"\n\tCREATE          = \"create %s\"\n\tCREATE_CAPACITY = \"%s capacity=%d\"\n\tCREATE_PROB     = \"%s prob=%f\"\n\tCREATE_INMEM    = \"%s in_memory=1\"\n\tDROP            = \"drop %s\"\n\tCLOSE           = \"close %s\"\n\tCLEAR           = \"clear %s\"\n\tMULTI           = \"m\"\n\tBULK            = \"b\"\n\tSET             = \"s %s %s\"\n\tINFO            = \"info %s\"\n\n\tRESPONSE_DONE   = \"Done\"\n\tRESPONSE_EXISTS = \"Exists\"\n\tRESPONSE_YES    = \"Yes\"\n\tRESPONSE_NO     = \"No\"\n\tRESPONSE_START  = \"START\"\n\tRESPONSE_END    = \"END\"\n)\n\ntype client struct {\n\thostname string\n\ttimeout  time.Duration\n\taddr     *net.TCPAddr\n\tattempts int\n\thashKeys bool\n}\n\nfunc NewClient(hostname string, hashKeys bool, timeout time.Duration) (Client, error) {\n\t\/\/ TODO probably need to have a go routine call addr to resolve DNS periodically\n\taddr, err := net.ResolveTCPAddr(\"tcp\", hostname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &client{\n\t\thostname: hostname,\n\t\ttimeout:  timeout,\n\t\taddr:     addr,\n\t\thashKeys: hashKeys,\n\t}, nil\n}\n\n\/\/ Add multi keys to the filter\nfunc (t client) BulkSet(ctx context.Context, name Filter, keys ...string) ([]bool, error) {\n\treturn t.sendMultiCommand(BULK, name, keys...)\n}\n\n\/\/ Check if key exists in filter\nfunc (t client) Check(ctx context.Context, name Filter, key string) (bool, error) {\n\treturn false, errors.New(\"not implemented\")\n}\n\n\/\/ Clears the filter\nfunc (t client) Clear(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(CLEAR, name))\n}\n\n\/\/ Closes the filter\nfunc (t client) Close(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(CLOSE, name))\n}\n\n\/\/ Creates new fiter\nfunc (t client) Create(ctx context.Context, name Filter) error {\n\treturn t.CreateWithParams(ctx, name, 0, 0, false)\n}\n\n\/\/ Creates new fiter with additional params\nfunc (t client) CreateWithParams(ctx context.Context, name Filter, capacity int, probability float64, inMemory bool) error {\n\tif probability > 0 && capacity < 1 {\n\t\treturn errors.New(\"invalid capacity\/probability\")\n\t}\n\n\tcmd := fmt.Sprintf(CREATE, name)\n\tif capacity > 0 {\n\t\tcmd = fmt.Sprintf(CREATE_CAPACITY, cmd, capacity)\n\t}\n\tif probability > 0 {\n\t\tcmd = fmt.Sprintf(CREATE_PROB, cmd, probability)\n\t}\n\tif inMemory {\n\t\tcmd = fmt.Sprintf(CREATE_INMEM, cmd)\n\t}\n\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch resp {\n\tcase RESPONSE_DONE:\n\t\treturn nil\n\n\tcase RESPONSE_EXISTS:\n\t\treturn nil\n\n\tdefault:\n\t\treturn errors.Errorf(\"Invalid create resp '%s'\", resp)\n\t}\n}\n\n\/\/ Permanently deletes filter\nfunc (t client) Drop(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(DROP, name))\n}\n\n\/\/ Flush to disk\nfunc (t client) Flush(ctx context.Context) error {\n\treturn t.sendCommandDone(FLUSH)\n}\n\nfunc (t client) Info(ctx context.Context, name Filter) (map[string]string, error) {\n\treturn t.sendBlockCommand(fmt.Sprintf(INFO, name))\n}\n\n\/\/ List filters\nfunc (t client) List(ctx context.Context) (map[string]string, error) {\n\treturn t.sendBlockCommand(LIST)\n}\n\n\/\/ Checks whether multiple keys exist in the filter\nfunc (t client) MultiCheck(ctx context.Context, name Filter, keys ...string) ([]bool, error) {\n\treturn t.sendMultiCommand(MULTI, name, keys...)\n}\n\n\/\/ Add new key to filter\nfunc (t client) Set(ctx context.Context, name Filter, key string) (bool, error) {\n\tcmd := fmt.Sprintf(SET, name, t.hashKey(key))\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tswitch resp {\n\tcase RESPONSE_YES:\n\t\treturn true, nil\n\tcase RESPONSE_NO:\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, errors.Errorf(\"Invalid response '%s'\", resp)\n\t}\n}\n\nfunc (t client) Ping() error {\n\treturn errors.New(\"not implemented\")\n}\n\n\/\/ Returns the key we should send to the server\nfunc (t client) hashKey(key string) string {\n\tif t.hashKeys {\n\t\th := sha1.New()\n\t\ts := h.Sum([]byte(key))\n\t\treturn fmt.Sprintf(\"%x\", s)\n\t}\n\treturn key\n}\n\nfunc (t client) sendCommandDone(cmd string) error {\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"bloomd: error with command '%s'\", cmd)\n\t}\n\n\tif resp != RESPONSE_DONE {\n\t\treturn errors.Errorf(\"bloomd: error with resp '%s' command '%s'\", resp, cmd)\n\t}\n\n\treturn nil\n}\n\nfunc (t client) sendMultiCommand(c string, name Filter, keys ...string) ([]bool, error) {\n\tcmd := t.multiCommand(c, name, keys...)\n\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"bloomd: error with multi command '%s'\", cmd)\n\t}\n\n\tif !strings.HasPrefix(resp, RESPONSE_YES) && !strings.HasPrefix(resp, RESPONSE_NO) {\n\t\treturn nil, errors.Errorf(\"bloomd: error with multi response '%s' command '%s'\", resp, cmd)\n\t}\n\n\tresults := make([]bool, 0, len(keys))\n\tresponses := strings.Split(resp, \" \")\n\tfor _, r := range responses {\n\t\tresults = append(results, r == RESPONSE_YES)\n\t}\n\n\treturn results, nil\n}\n\nfunc (t client) multiCommand(cmd string, name Filter, keys ...string) string {\n\tbuf := &bytes.Buffer{}\n\tbuf.WriteString(cmd)\n\tbuf.WriteRune(' ')\n\tbuf.WriteString(string(name))\n\tfor _, key := range keys {\n\t\tbuf.WriteRune(' ')\n\t\tbuf.WriteString(t.hashKey(key))\n\t}\n\treturn buf.String()\n}\n\nfunc (t client) sendBlockCommand(cmd string) (map[string]string, error) {\n\tresp, err := t.sendCommand(LIST)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.HasPrefix(resp, RESPONSE_START) {\n\t\treturn nil, errors.Errorf(\"bloomd: invalid list start '%s' command '%s'\", resp, cmd)\n\t}\n\n\tresponses := make(map[string]string)\n\n\tsplit := strings.Split(resp, \"\\n\")\n\tfor _, line := range split {\n\t\tline := strings.TrimSpace(line)\n\n\t\tswitch line {\n\t\tcase RESPONSE_START:\n\t\tcase RESPONSE_END:\n\t\tcase \"\":\n\t\tdefault:\n\t\t\tsplit := strings.SplitN(line, \" \", 2)\n\t\t\tresponses[split[0]] = split[1]\n\t\t}\n\t}\n\treturn responses, nil\n}\n\nfunc (t client) sendCommand(cmd string) (string, error) {\n\n\tconn, err := newConnection(t.addr, t.attempts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer conn.Close()\n\n\tif err := send(conn, cmd, t.attempts); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tline, err := recv(conn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn line, nil\n}\n\nfunc newConnection(addr *net.TCPAddr, attempts int) (io.ReadWriteCloser, error) {\n\tattempted := 0\n\n\tvar conn net.Conn\n\tvar err error\n\tfor {\n\t\tconn, err = net.DialTCP(\"tcp\", nil, addr)\n\t\tif err != nil && attempted > attempts {\n\t\t\treturn nil, errors.Wrap(err, \"bloomd: unable to establish a connection\")\n\t\t}\n\t\tattempted++\n\t}\n\n\treturn conn, nil\n}\n\nfunc send(w io.Writer, cmd string, attempts int) error {\n\tattempted := 0\n\n\tfor {\n\t\t_, err := w.Write([]byte(cmd + \"\\n\"))\n\t\tif err != nil && attempted > attempts {\n\t\t\treturn errors.Wrap(err, \"bloomd: unable to write to connection\")\n\t\t}\n\t\tattempted++\n\t}\n\n\treturn nil\n}\n\nfunc recv(r io.Reader) (string, error) {\n\t\/\/TODO read block\n\tline, err := bufio.NewReader(r).ReadString('\\n')\n\tif err != nil && err != io.EOF {\n\t\treturn line, errors.Wrap(err, \"bloomd: unable to read connection\")\n\t}\n\treturn strings.TrimRight(line, \"\\r\\n\"), nil\n}\n<commit_msg>fixing read block<commit_after>package bloomd\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"fmt\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Filter string\n\ntype Client interface {\n\tBulkSet(context.Context, Filter, ...string) ([]bool, error)\n\tCheck(context.Context, Filter, string) (bool, error)\n\tClear(context.Context, Filter) error\n\tClose(context.Context, Filter) error\n\tCreate(context.Context, Filter) error\n\tDrop(context.Context, Filter) error\n\tFlush(context.Context) error\n\tList(context.Context) (map[string]string, error)\n\tMultiCheck(context.Context, Filter, ...string) ([]bool, error)\n\tSet(context.Context, Filter, string) (bool, error)\n\tInfo(context.Context, Filter) (map[string]string, error)\n\tPing() error\n}\n\nconst (\n\tFLUSH           = \"flush\"\n\tLIST            = \"list\"\n\tCREATE          = \"create %s\"\n\tCREATE_CAPACITY = \"%s capacity=%d\"\n\tCREATE_PROB     = \"%s prob=%f\"\n\tCREATE_INMEM    = \"%s in_memory=1\"\n\tDROP            = \"drop %s\"\n\tCLOSE           = \"close %s\"\n\tCLEAR           = \"clear %s\"\n\tMULTI           = \"m\"\n\tBULK            = \"b\"\n\tSET             = \"s %s %s\"\n\tINFO            = \"info %s\"\n\n\tRESPONSE_DONE   = \"Done\"\n\tRESPONSE_EXISTS = \"Exists\"\n\tRESPONSE_YES    = \"Yes\"\n\tRESPONSE_NO     = \"No\"\n\tRESPONSE_START  = \"START\"\n\tRESPONSE_END    = \"END\"\n)\n\ntype client struct {\n\thostname string\n\ttimeout  time.Duration\n\taddr     *net.TCPAddr\n\tattempts int\n\thashKeys bool\n}\n\nfunc NewClient(hostname string, hashKeys bool, timeout time.Duration) (Client, error) {\n\t\/\/ TODO probably need to have a go routine call addr to resolve DNS periodically\n\taddr, err := net.ResolveTCPAddr(\"tcp\", hostname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &client{\n\t\thostname: hostname,\n\t\ttimeout:  timeout,\n\t\taddr:     addr,\n\t\thashKeys: hashKeys,\n\t}, nil\n}\n\n\/\/ Add multi keys to the filter\nfunc (t client) BulkSet(ctx context.Context, name Filter, keys ...string) ([]bool, error) {\n\treturn t.sendMultiCommand(BULK, name, keys...)\n}\n\n\/\/ Check if key exists in filter\nfunc (t client) Check(ctx context.Context, name Filter, key string) (bool, error) {\n\treturn false, errors.New(\"not implemented\")\n}\n\n\/\/ Clears the filter\nfunc (t client) Clear(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(CLEAR, name))\n}\n\n\/\/ Closes the filter\nfunc (t client) Close(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(CLOSE, name))\n}\n\n\/\/ Creates new fiter\nfunc (t client) Create(ctx context.Context, name Filter) error {\n\treturn t.CreateWithParams(ctx, name, 0, 0, false)\n}\n\n\/\/ Creates new fiter with additional params\nfunc (t client) CreateWithParams(ctx context.Context, name Filter, capacity int, probability float64, inMemory bool) error {\n\tif probability > 0 && capacity < 1 {\n\t\treturn errors.New(\"invalid capacity\/probability\")\n\t}\n\n\tcmd := fmt.Sprintf(CREATE, name)\n\tif capacity > 0 {\n\t\tcmd = fmt.Sprintf(CREATE_CAPACITY, cmd, capacity)\n\t}\n\tif probability > 0 {\n\t\tcmd = fmt.Sprintf(CREATE_PROB, cmd, probability)\n\t}\n\tif inMemory {\n\t\tcmd = fmt.Sprintf(CREATE_INMEM, cmd)\n\t}\n\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch resp {\n\tcase RESPONSE_DONE:\n\t\treturn nil\n\n\tcase RESPONSE_EXISTS:\n\t\treturn nil\n\n\tdefault:\n\t\treturn errors.Errorf(\"Invalid create resp '%s'\", resp)\n\t}\n}\n\n\/\/ Permanently deletes filter\nfunc (t client) Drop(ctx context.Context, name Filter) error {\n\treturn t.sendCommandDone(fmt.Sprintf(DROP, name))\n}\n\n\/\/ Flush to disk\nfunc (t client) Flush(ctx context.Context) error {\n\treturn t.sendCommandDone(FLUSH)\n}\n\nfunc (t client) Info(ctx context.Context, name Filter) (map[string]string, error) {\n\treturn t.sendBlockCommand(fmt.Sprintf(INFO, name))\n}\n\n\/\/ List filters\nfunc (t client) List(ctx context.Context) (map[string]string, error) {\n\treturn t.sendBlockCommand(LIST)\n}\n\n\/\/ Checks whether multiple keys exist in the filter\nfunc (t client) MultiCheck(ctx context.Context, name Filter, keys ...string) ([]bool, error) {\n\treturn t.sendMultiCommand(MULTI, name, keys...)\n}\n\n\/\/ Add new key to filter\nfunc (t client) Set(ctx context.Context, name Filter, key string) (bool, error) {\n\tcmd := fmt.Sprintf(SET, name, t.hashKey(key))\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tswitch resp {\n\tcase RESPONSE_YES:\n\t\treturn true, nil\n\tcase RESPONSE_NO:\n\t\treturn true, nil\n\tdefault:\n\t\treturn false, errors.Errorf(\"Invalid response '%s'\", resp)\n\t}\n}\n\nfunc (t client) Ping() error {\n\treturn errors.New(\"not implemented\")\n}\n\n\/\/ Returns the key we should send to the server\nfunc (t client) hashKey(key string) string {\n\tif t.hashKeys {\n\t\th := sha1.New()\n\t\ts := h.Sum([]byte(key))\n\t\treturn fmt.Sprintf(\"%x\", s)\n\t}\n\treturn key\n}\n\nfunc (t client) sendCommandDone(cmd string) error {\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"bloomd: error with command '%s'\", cmd)\n\t}\n\n\tif resp != RESPONSE_DONE {\n\t\treturn errors.Errorf(\"bloomd: error with resp '%s' command '%s'\", resp, cmd)\n\t}\n\n\treturn nil\n}\n\nfunc (t client) sendMultiCommand(c string, name Filter, keys ...string) ([]bool, error) {\n\tcmd := t.multiCommand(c, name, keys...)\n\n\tresp, err := t.sendCommand(cmd)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"bloomd: error with multi command '%s'\", cmd)\n\t}\n\n\tif !strings.HasPrefix(resp, RESPONSE_YES) && !strings.HasPrefix(resp, RESPONSE_NO) {\n\t\treturn nil, errors.Errorf(\"bloomd: error with multi response '%s' command '%s'\", resp, cmd)\n\t}\n\n\tresults := make([]bool, 0, len(keys))\n\tresponses := strings.Split(resp, \" \")\n\tfor _, r := range responses {\n\t\tresults = append(results, r == RESPONSE_YES)\n\t}\n\n\treturn results, nil\n}\n\nfunc (t client) multiCommand(cmd string, name Filter, keys ...string) string {\n\tbuf := &bytes.Buffer{}\n\tbuf.WriteString(cmd)\n\tbuf.WriteRune(' ')\n\tbuf.WriteString(string(name))\n\tfor _, key := range keys {\n\t\tbuf.WriteRune(' ')\n\t\tbuf.WriteString(t.hashKey(key))\n\t}\n\treturn buf.String()\n}\n\nfunc (t client) sendBlockCommand(cmd string) (map[string]string, error) {\n\tresp, err := t.sendCommand(LIST)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !strings.HasPrefix(resp, RESPONSE_START) {\n\t\treturn nil, errors.Errorf(\"bloomd: invalid list start '%s' command '%s'\", resp, cmd)\n\t}\n\n\tresponses := make(map[string]string)\n\n\tsplit := strings.Split(resp, \"\\n\")\n\tfor _, line := range split {\n\t\tline := strings.TrimSpace(line)\n\n\t\tswitch line {\n\t\tcase RESPONSE_START:\n\t\tcase RESPONSE_END:\n\t\tcase \"\":\n\t\tdefault:\n\t\t\tsplit := strings.SplitN(line, \" \", 2)\n\t\t\tresponses[split[0]] = split[1]\n\t\t}\n\t}\n\treturn responses, nil\n}\n\nfunc (t client) sendCommand(cmd string) (string, error) {\n\n\tconn, err := newConnection(t.addr, t.attempts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer conn.Close()\n\n\tif err := send(conn, cmd, t.attempts); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tline, err := recv(conn)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn line, nil\n}\n\nfunc newConnection(addr *net.TCPAddr, attempts int) (io.ReadWriteCloser, error) {\n\tattempted := 0\n\n\tvar conn net.Conn\n\tvar err error\n\tfor {\n\t\tconn, err = net.DialTCP(\"tcp\", nil, addr)\n\t\tif err != nil && attempted > attempts {\n\t\t\treturn nil, errors.Wrap(err, \"bloomd: unable to establish a connection\")\n\t\t}\n\t\tattempted++\n\t}\n\n\treturn conn, nil\n}\n\nfunc send(w io.Writer, cmd string, attempts int) error {\n\tattempted := 0\n\n\tfor {\n\t\t_, err := w.Write([]byte(cmd + \"\\n\"))\n\t\tif err != nil && attempted > attempts {\n\t\t\treturn errors.Wrap(err, \"bloomd: unable to write to connection\")\n\t\t}\n\t\tattempted++\n\t}\n\n\treturn nil\n}\n\nfunc recv(r io.Reader) (string, error) {\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn line, errors.Wrap(err, \"bloomd: unable to read connection\")\n\t}\n\treturn strings.TrimRight(string(buf), \"\\r\\n\"), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package weed_server\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\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\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/topology\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\nfunc (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {\n\tvar dn *topology.DataNode\n\tt := ms.Topo\n\n\tdefer func() {\n\t\tif dn != nil {\n\n\t\t\tglog.V(0).Infof(\"unregister disconnected volume server %s:%d\", dn.Ip, dn.Port)\n\t\t\tt.UnRegisterDataNode(dn)\n\n\t\t\tmessage := &master_pb.VolumeLocation{\n\t\t\t\tUrl:       dn.Url(),\n\t\t\t\tPublicUrl: dn.PublicUrl,\n\t\t\t}\n\t\t\tfor _, v := range dn.GetVolumes() {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\n\t\t\tif len(message.DeletedVids) > 0 {\n\t\t\t\tms.clientChansLock.RLock()\n\t\t\t\tfor _, ch := range ms.clientChans {\n\t\t\t\t\tch <- message\n\t\t\t\t}\n\t\t\t\tms.clientChansLock.RUnlock()\n\t\t\t}\n\n\t\t}\n\t}()\n\n\tfor {\n\t\theartbeat, err := stream.Recv()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif dn == nil {\n\t\t\tt.Sequence.SetMax(heartbeat.MaxFileKey)\n\t\t\tif heartbeat.Ip == \"\" {\n\t\t\t\tif pr, ok := peer.FromContext(stream.Context()); ok {\n\t\t\t\t\tif pr.Addr != net.Addr(nil) {\n\t\t\t\t\t\theartbeat.Ip = pr.Addr.String()[0:strings.LastIndex(pr.Addr.String(), \":\")]\n\t\t\t\t\t\tglog.V(0).Infof(\"remote IP address is detected as %v\", heartbeat.Ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)\n\t\t\tdc := t.GetOrCreateDataCenter(dcName)\n\t\t\track := dc.GetOrCreateRack(rackName)\n\t\t\tdn = rack.GetOrCreateDataNode(heartbeat.Ip,\n\t\t\t\tint(heartbeat.Port), heartbeat.PublicUrl,\n\t\t\t\tint64(heartbeat.MaxVolumeCount))\n\t\t\tglog.V(0).Infof(\"added volume server %v:%d\", heartbeat.GetIp(), heartbeat.GetPort())\n\t\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\t\tVolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tglog.V(4).Infof(\"master received heartbeat %s\", heartbeat.String())\n\t\tmessage := &master_pb.VolumeLocation{\n\t\t\tUrl:       dn.Url(),\n\t\t\tPublicUrl: dn.PublicUrl,\n\t\t}\n\t\tif len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {\n\t\t\t\/\/ process delta volume ids if exists for fast volume id updates\n\t\t\tfor _, volInfo := range heartbeat.NewVolumes {\n\t\t\t\tmessage.NewVids = append(message.NewVids, volInfo.Id)\n\t\t\t}\n\t\t\tfor _, volInfo := range heartbeat.DeletedVolumes {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, volInfo.Id)\n\t\t\t}\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)\n\t\t}\n\n\t\tif len(heartbeat.Volumes) > 0 {\n\t\t\t\/\/ process heartbeat.Volumes\n\t\t\tnewVolumes, deletedVolumes := t.SyncDataNodeRegistration(heartbeat.Volumes, dn)\n\n\t\t\tfor _, v := range newVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see new volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(v.Id))\n\t\t\t}\n\t\t\tfor _, v := range deletedVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see deleted volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\t\t}\n\n\t\tif len(heartbeat.NewEcShards) > 0 || len(heartbeat.DeletedEcShards) > 0 {\n\t\t\t\/\/ TODO send out the delta\n\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeEcShards(heartbeat.NewEcShards, heartbeat.DeletedEcShards, dn)\n\n\t\t\tfor _, s := range heartbeat.NewEcShards {\n\t\t\t\tmessage.NewVids = append(message.NewVids, s.Id)\n\t\t\t}\n\t\t\tfor _, s := range heartbeat.DeletedEcShards {\n\t\t\t\tif dn.HasVolumesById(needle.VolumeId(s.Id)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, s.Id)\n\t\t\t}\n\n\t\t}\n\n\t\tif len(heartbeat.EcShards) > 0 {\n\t\t\tglog.V(0).Infof(\"master recieved ec shards from %s: %+v\", dn.Url(), heartbeat.EcShards)\n\t\t\tnewShards, deletedShards := t.SyncDataNodeEcShards(heartbeat.EcShards, dn)\n\n\t\t\t\/\/ broadcast the ec vid changes to master clients\n\t\t\tfor _, s := range newShards {\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(s.VolumeId))\n\t\t\t}\n\t\t\tfor _, s := range deletedShards {\n\t\t\t\tif dn.HasVolumesById(s.VolumeId) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))\n\t\t\t}\n\n\t\t}\n\n\t\tif len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {\n\t\t\tms.clientChansLock.RLock()\n\t\t\tfor host, ch := range ms.clientChans {\n\t\t\t\tglog.V(0).Infof(\"master send to %s: %s\", host, message.String())\n\t\t\t\tch <- message\n\t\t\t}\n\t\t\tms.clientChansLock.RUnlock()\n\t\t}\n\n\t\t\/\/ tell the volume servers about the leader\n\t\tnewLeader, err := t.Leader()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\tLeader: newLeader,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.\n\/\/ And clients gets the up-to-date list of volume locations\nfunc (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {\n\n\treq, err := stream.Recv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ms.Topo.IsLeader() {\n\t\treturn raft.NotLeaderError\n\t}\n\n\t\/\/ remember client address\n\tctx := stream.Context()\n\t\/\/ fmt.Printf(\"FromContext %+v\\n\", ctx)\n\tpr, ok := peer.FromContext(ctx)\n\tif !ok {\n\t\tglog.Error(\"failed to get peer from ctx\")\n\t\treturn fmt.Errorf(\"failed to get peer from ctx\")\n\t}\n\tif pr.Addr == net.Addr(nil) {\n\t\tglog.Error(\"failed to get peer address\")\n\t\treturn fmt.Errorf(\"failed to get peer address\")\n\t}\n\n\tclientName := req.Name + pr.Addr.String()\n\tglog.V(0).Infof(\"+ client %v\", clientName)\n\n\tmessageChan := make(chan *master_pb.VolumeLocation)\n\tstopChan := make(chan bool)\n\n\tms.clientChansLock.Lock()\n\tms.clientChans[clientName] = messageChan\n\tms.clientChansLock.Unlock()\n\n\tdefer func() {\n\t\tglog.V(0).Infof(\"- client %v\", clientName)\n\t\tms.clientChansLock.Lock()\n\t\tdelete(ms.clientChans, clientName)\n\t\tms.clientChansLock.Unlock()\n\t}()\n\n\tfor _, message := range ms.Topo.ToVolumeLocations() {\n\t\tif err := stream.Send(message); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, err := stream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tglog.V(2).Infof(\"- client %v: %v\", clientName, err)\n\t\t\t\tstopChan <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase message := <-messageChan:\n\t\t\tif err := stream.Send(message); err != nil {\n\t\t\t\tglog.V(0).Infof(\"=> client %v: %+v\", clientName, message)\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif !ms.Topo.IsLeader() {\n\t\t\t\treturn raft.NotLeaderError\n\t\t\t}\n\t\tcase <-stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>adjust ec shard status on disconnect<commit_after>package weed_server\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\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\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/topology\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\nfunc (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {\n\tvar dn *topology.DataNode\n\tt := ms.Topo\n\n\tdefer func() {\n\t\tif dn != nil {\n\n\t\t\tglog.V(0).Infof(\"unregister disconnected volume server %s:%d\", dn.Ip, dn.Port)\n\t\t\tt.UnRegisterDataNode(dn)\n\n\t\t\tmessage := &master_pb.VolumeLocation{\n\t\t\t\tUrl:       dn.Url(),\n\t\t\t\tPublicUrl: dn.PublicUrl,\n\t\t\t}\n\t\t\tfor _, v := range dn.GetVolumes() {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\t\t\tfor _, s := range dn.GetEcShards() {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))\n\t\t\t}\n\n\t\t\tif len(message.DeletedVids) > 0 {\n\t\t\t\tms.clientChansLock.RLock()\n\t\t\t\tfor _, ch := range ms.clientChans {\n\t\t\t\t\tch <- message\n\t\t\t\t}\n\t\t\t\tms.clientChansLock.RUnlock()\n\t\t\t}\n\n\t\t}\n\t}()\n\n\tfor {\n\t\theartbeat, err := stream.Recv()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif dn == nil {\n\t\t\tt.Sequence.SetMax(heartbeat.MaxFileKey)\n\t\t\tif heartbeat.Ip == \"\" {\n\t\t\t\tif pr, ok := peer.FromContext(stream.Context()); ok {\n\t\t\t\t\tif pr.Addr != net.Addr(nil) {\n\t\t\t\t\t\theartbeat.Ip = pr.Addr.String()[0:strings.LastIndex(pr.Addr.String(), \":\")]\n\t\t\t\t\t\tglog.V(0).Infof(\"remote IP address is detected as %v\", heartbeat.Ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)\n\t\t\tdc := t.GetOrCreateDataCenter(dcName)\n\t\t\track := dc.GetOrCreateRack(rackName)\n\t\t\tdn = rack.GetOrCreateDataNode(heartbeat.Ip,\n\t\t\t\tint(heartbeat.Port), heartbeat.PublicUrl,\n\t\t\t\tint64(heartbeat.MaxVolumeCount))\n\t\t\tglog.V(0).Infof(\"added volume server %v:%d\", heartbeat.GetIp(), heartbeat.GetPort())\n\t\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\t\tVolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tglog.V(4).Infof(\"master received heartbeat %s\", heartbeat.String())\n\t\tmessage := &master_pb.VolumeLocation{\n\t\t\tUrl:       dn.Url(),\n\t\t\tPublicUrl: dn.PublicUrl,\n\t\t}\n\t\tif len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {\n\t\t\t\/\/ process delta volume ids if exists for fast volume id updates\n\t\t\tfor _, volInfo := range heartbeat.NewVolumes {\n\t\t\t\tmessage.NewVids = append(message.NewVids, volInfo.Id)\n\t\t\t}\n\t\t\tfor _, volInfo := range heartbeat.DeletedVolumes {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, volInfo.Id)\n\t\t\t}\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)\n\t\t}\n\n\t\tif len(heartbeat.Volumes) > 0 {\n\t\t\t\/\/ process heartbeat.Volumes\n\t\t\tnewVolumes, deletedVolumes := t.SyncDataNodeRegistration(heartbeat.Volumes, dn)\n\n\t\t\tfor _, v := range newVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see new volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(v.Id))\n\t\t\t}\n\t\t\tfor _, v := range deletedVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see deleted volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\t\t}\n\n\t\tif len(heartbeat.NewEcShards) > 0 || len(heartbeat.DeletedEcShards) > 0 {\n\t\t\t\/\/ TODO send out the delta\n\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeEcShards(heartbeat.NewEcShards, heartbeat.DeletedEcShards, dn)\n\n\t\t\tfor _, s := range heartbeat.NewEcShards {\n\t\t\t\tmessage.NewVids = append(message.NewVids, s.Id)\n\t\t\t}\n\t\t\tfor _, s := range heartbeat.DeletedEcShards {\n\t\t\t\tif dn.HasVolumesById(needle.VolumeId(s.Id)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, s.Id)\n\t\t\t}\n\n\t\t}\n\n\t\tif len(heartbeat.EcShards) > 0 {\n\t\t\tglog.V(0).Infof(\"master recieved ec shards from %s: %+v\", dn.Url(), heartbeat.EcShards)\n\t\t\tnewShards, deletedShards := t.SyncDataNodeEcShards(heartbeat.EcShards, dn)\n\n\t\t\t\/\/ broadcast the ec vid changes to master clients\n\t\t\tfor _, s := range newShards {\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(s.VolumeId))\n\t\t\t}\n\t\t\tfor _, s := range deletedShards {\n\t\t\t\tif dn.HasVolumesById(s.VolumeId) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(s.VolumeId))\n\t\t\t}\n\n\t\t}\n\n\t\tif len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {\n\t\t\tms.clientChansLock.RLock()\n\t\t\tfor host, ch := range ms.clientChans {\n\t\t\t\tglog.V(0).Infof(\"master send to %s: %s\", host, message.String())\n\t\t\t\tch <- message\n\t\t\t}\n\t\t\tms.clientChansLock.RUnlock()\n\t\t}\n\n\t\t\/\/ tell the volume servers about the leader\n\t\tnewLeader, err := t.Leader()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\tLeader: newLeader,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.\n\/\/ And clients gets the up-to-date list of volume locations\nfunc (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {\n\n\treq, err := stream.Recv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ms.Topo.IsLeader() {\n\t\treturn raft.NotLeaderError\n\t}\n\n\t\/\/ remember client address\n\tctx := stream.Context()\n\t\/\/ fmt.Printf(\"FromContext %+v\\n\", ctx)\n\tpr, ok := peer.FromContext(ctx)\n\tif !ok {\n\t\tglog.Error(\"failed to get peer from ctx\")\n\t\treturn fmt.Errorf(\"failed to get peer from ctx\")\n\t}\n\tif pr.Addr == net.Addr(nil) {\n\t\tglog.Error(\"failed to get peer address\")\n\t\treturn fmt.Errorf(\"failed to get peer address\")\n\t}\n\n\tclientName := req.Name + pr.Addr.String()\n\tglog.V(0).Infof(\"+ client %v\", clientName)\n\n\tmessageChan := make(chan *master_pb.VolumeLocation)\n\tstopChan := make(chan bool)\n\n\tms.clientChansLock.Lock()\n\tms.clientChans[clientName] = messageChan\n\tms.clientChansLock.Unlock()\n\n\tdefer func() {\n\t\tglog.V(0).Infof(\"- client %v\", clientName)\n\t\tms.clientChansLock.Lock()\n\t\tdelete(ms.clientChans, clientName)\n\t\tms.clientChansLock.Unlock()\n\t}()\n\n\tfor _, message := range ms.Topo.ToVolumeLocations() {\n\t\tif err := stream.Send(message); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, err := stream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tglog.V(2).Infof(\"- client %v: %v\", clientName, err)\n\t\t\t\tstopChan <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase message := <-messageChan:\n\t\t\tif err := stream.Send(message); err != nil {\n\t\t\t\tglog.V(0).Infof(\"=> client %v: %+v\", clientName, message)\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif !ms.Topo.IsLeader() {\n\t\t\t\treturn raft.NotLeaderError\n\t\t\t}\n\t\tcase <-stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package weed_server\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\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\/topology\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\nfunc (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {\n\tvar dn *topology.DataNode\n\tt := ms.Topo\n\n\tdefer func() {\n\t\tif dn != nil {\n\n\t\t\tglog.V(0).Infof(\"unregister disconnected volume server %s:%d\", dn.Ip, dn.Port)\n\t\t\tt.UnRegisterDataNode(dn)\n\n\t\t\tmessage := &master_pb.VolumeLocation{\n\t\t\t\tUrl:       dn.Url(),\n\t\t\t\tPublicUrl: dn.PublicUrl,\n\t\t\t}\n\t\t\tfor _, v := range dn.GetVolumes() {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\n\t\t\tif len(message.DeletedVids) > 0 {\n\t\t\t\tms.clientChansLock.RLock()\n\t\t\t\tfor _, ch := range ms.clientChans {\n\t\t\t\t\tch <- message\n\t\t\t\t}\n\t\t\t\tms.clientChansLock.RUnlock()\n\t\t\t}\n\n\t\t}\n\t}()\n\n\tfor {\n\t\theartbeat, err := stream.Recv()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif dn == nil {\n\t\t\tt.Sequence.SetMax(heartbeat.MaxFileKey)\n\t\t\tif heartbeat.Ip == \"\" {\n\t\t\t\tif pr, ok := peer.FromContext(stream.Context()); ok {\n\t\t\t\t\tif pr.Addr != net.Addr(nil) {\n\t\t\t\t\t\theartbeat.Ip = pr.Addr.String()[0:strings.LastIndex(pr.Addr.String(), \":\")]\n\t\t\t\t\t\tglog.V(0).Infof(\"remote IP address is detected as %v\", heartbeat.Ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)\n\t\t\tdc := t.GetOrCreateDataCenter(dcName)\n\t\t\track := dc.GetOrCreateRack(rackName)\n\t\t\tdn = rack.GetOrCreateDataNode(heartbeat.Ip,\n\t\t\t\tint(heartbeat.Port), heartbeat.PublicUrl,\n\t\t\t\tint64(heartbeat.MaxVolumeCount))\n\t\t\tglog.V(0).Infof(\"added volume server %v:%d\", heartbeat.GetIp(), heartbeat.GetPort())\n\t\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\t\tVolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tglog.V(4).Infof(\"master received heartbeat %s\", heartbeat.String())\n\t\tmessage := &master_pb.VolumeLocation{\n\t\t\tUrl:       dn.Url(),\n\t\t\tPublicUrl: dn.PublicUrl,\n\t\t}\n\t\tif len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {\n\t\t\t\/\/ process delta volume ids if exists for fast volume id updates\n\t\t\tfor _, volInfo := range heartbeat.NewVolumes {\n\t\t\t\tmessage.NewVids = append(message.NewVids, volInfo.Id)\n\t\t\t}\n\t\t\tfor _, volInfo := range heartbeat.DeletedVolumes {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, volInfo.Id)\n\t\t\t}\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)\n\t\t}\n\n\t\tif len(heartbeat.Volumes) > 0 {\n\t\t\t\/\/ process heartbeat.Volumes\n\t\t\tnewVolumes, deletedVolumes := t.SyncDataNodeRegistration(heartbeat.Volumes, dn)\n\n\t\t\tfor _, v := range newVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see new volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(v.Id))\n\t\t\t}\n\t\t\tfor _, v := range deletedVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see deleted volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\t\t}\n\n\t\tif len(heartbeat.EcShards) > 0 {\n\t\t\tglog.V(0).Infof(\"master recieved ec shards from %s: %+v\", dn.Url(), heartbeat.EcShards)\n\t\t}\n\n\t\tif len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {\n\t\t\tms.clientChansLock.RLock()\n\t\t\tfor host, ch := range ms.clientChans {\n\t\t\t\tglog.V(0).Infof(\"master send to %s: %s\", host, message.String())\n\t\t\t\tch <- message\n\t\t\t}\n\t\t\tms.clientChansLock.RUnlock()\n\t\t}\n\n\t\t\/\/ tell the volume servers about the leader\n\t\tnewLeader, err := t.Leader()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\tLeader: newLeader,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.\n\/\/ And clients gets the up-to-date list of volume locations\nfunc (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {\n\n\treq, err := stream.Recv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ms.Topo.IsLeader() {\n\t\treturn raft.NotLeaderError\n\t}\n\n\t\/\/ remember client address\n\tctx := stream.Context()\n\t\/\/ fmt.Printf(\"FromContext %+v\\n\", ctx)\n\tpr, ok := peer.FromContext(ctx)\n\tif !ok {\n\t\tglog.Error(\"failed to get peer from ctx\")\n\t\treturn fmt.Errorf(\"failed to get peer from ctx\")\n\t}\n\tif pr.Addr == net.Addr(nil) {\n\t\tglog.Error(\"failed to get peer address\")\n\t\treturn fmt.Errorf(\"failed to get peer address\")\n\t}\n\n\tclientName := req.Name + pr.Addr.String()\n\tglog.V(0).Infof(\"+ client %v\", clientName)\n\n\tmessageChan := make(chan *master_pb.VolumeLocation)\n\tstopChan := make(chan bool)\n\n\tms.clientChansLock.Lock()\n\tms.clientChans[clientName] = messageChan\n\tms.clientChansLock.Unlock()\n\n\tdefer func() {\n\t\tglog.V(0).Infof(\"- client %v\", clientName)\n\t\tms.clientChansLock.Lock()\n\t\tdelete(ms.clientChans, clientName)\n\t\tms.clientChansLock.Unlock()\n\t}()\n\n\tfor _, message := range ms.Topo.ToVolumeLocations() {\n\t\tif err := stream.Send(message); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, err := stream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tglog.V(2).Infof(\"- client %v: %v\", clientName, err)\n\t\t\t\tstopChan <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase message := <-messageChan:\n\t\t\tif err := stream.Send(message); err != nil {\n\t\t\t\tglog.V(0).Infof(\"=> client %v: %+v\", clientName, message)\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif !ms.Topo.IsLeader() {\n\t\t\t\treturn raft.NotLeaderError\n\t\t\t}\n\t\tcase <-stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>push the ec shard info to master<commit_after>package weed_server\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\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\/topology\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\nfunc (ms *MasterServer) SendHeartbeat(stream master_pb.Seaweed_SendHeartbeatServer) error {\n\tvar dn *topology.DataNode\n\tt := ms.Topo\n\n\tdefer func() {\n\t\tif dn != nil {\n\n\t\t\tglog.V(0).Infof(\"unregister disconnected volume server %s:%d\", dn.Ip, dn.Port)\n\t\t\tt.UnRegisterDataNode(dn)\n\n\t\t\tmessage := &master_pb.VolumeLocation{\n\t\t\t\tUrl:       dn.Url(),\n\t\t\t\tPublicUrl: dn.PublicUrl,\n\t\t\t}\n\t\t\tfor _, v := range dn.GetVolumes() {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\n\t\t\tif len(message.DeletedVids) > 0 {\n\t\t\t\tms.clientChansLock.RLock()\n\t\t\t\tfor _, ch := range ms.clientChans {\n\t\t\t\t\tch <- message\n\t\t\t\t}\n\t\t\t\tms.clientChansLock.RUnlock()\n\t\t\t}\n\n\t\t}\n\t}()\n\n\tfor {\n\t\theartbeat, err := stream.Recv()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif dn == nil {\n\t\t\tt.Sequence.SetMax(heartbeat.MaxFileKey)\n\t\t\tif heartbeat.Ip == \"\" {\n\t\t\t\tif pr, ok := peer.FromContext(stream.Context()); ok {\n\t\t\t\t\tif pr.Addr != net.Addr(nil) {\n\t\t\t\t\t\theartbeat.Ip = pr.Addr.String()[0:strings.LastIndex(pr.Addr.String(), \":\")]\n\t\t\t\t\t\tglog.V(0).Infof(\"remote IP address is detected as %v\", heartbeat.Ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tdcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)\n\t\t\tdc := t.GetOrCreateDataCenter(dcName)\n\t\t\track := dc.GetOrCreateRack(rackName)\n\t\t\tdn = rack.GetOrCreateDataNode(heartbeat.Ip,\n\t\t\t\tint(heartbeat.Port), heartbeat.PublicUrl,\n\t\t\t\tint64(heartbeat.MaxVolumeCount))\n\t\t\tglog.V(0).Infof(\"added volume server %v:%d\", heartbeat.GetIp(), heartbeat.GetPort())\n\t\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\t\tVolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,\n\t\t\t}); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tglog.V(4).Infof(\"master received heartbeat %s\", heartbeat.String())\n\t\tmessage := &master_pb.VolumeLocation{\n\t\t\tUrl:       dn.Url(),\n\t\t\tPublicUrl: dn.PublicUrl,\n\t\t}\n\t\tif len(heartbeat.NewVolumes) > 0 || len(heartbeat.DeletedVolumes) > 0 {\n\t\t\t\/\/ process delta volume ids if exists for fast volume id updates\n\t\t\tfor _, volInfo := range heartbeat.NewVolumes {\n\t\t\t\tmessage.NewVids = append(message.NewVids, volInfo.Id)\n\t\t\t}\n\t\t\tfor _, volInfo := range heartbeat.DeletedVolumes {\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, volInfo.Id)\n\t\t\t}\n\t\t\t\/\/ update master internal volume layouts\n\t\t\tt.IncrementalSyncDataNodeRegistration(heartbeat.NewVolumes, heartbeat.DeletedVolumes, dn)\n\t\t}\n\n\t\tif len(heartbeat.Volumes) > 0 {\n\t\t\t\/\/ process heartbeat.Volumes\n\t\t\tnewVolumes, deletedVolumes := t.SyncDataNodeRegistration(heartbeat.Volumes, dn)\n\n\t\t\tfor _, v := range newVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see new volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.NewVids = append(message.NewVids, uint32(v.Id))\n\t\t\t}\n\t\t\tfor _, v := range deletedVolumes {\n\t\t\t\tglog.V(0).Infof(\"master see deleted volume %d from %s\", uint32(v.Id), dn.Url())\n\t\t\t\tmessage.DeletedVids = append(message.DeletedVids, uint32(v.Id))\n\t\t\t}\n\t\t}\n\n\t\tif len(heartbeat.EcShards) > 0 {\n\t\t\tglog.V(0).Infof(\"master recieved ec shards from %s: %+v\", dn.Url(), heartbeat.EcShards)\n\t\t\tnewShards, deletedShards := t.SyncDataNodeEcShards(heartbeat.EcShards, dn)\n\n\t\t\t\/\/TODO broadcast the ec vid\n\t\t\tif len(newShards)>0{\n\n\t\t\t}\n\t\t\tif len(deletedShards)>0{\n\n\t\t\t}\n\n\t\t}\n\n\t\tif len(message.NewVids) > 0 || len(message.DeletedVids) > 0 {\n\t\t\tms.clientChansLock.RLock()\n\t\t\tfor host, ch := range ms.clientChans {\n\t\t\t\tglog.V(0).Infof(\"master send to %s: %s\", host, message.String())\n\t\t\t\tch <- message\n\t\t\t}\n\t\t\tms.clientChansLock.RUnlock()\n\t\t}\n\n\t\t\/\/ tell the volume servers about the leader\n\t\tnewLeader, err := t.Leader()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := stream.Send(&master_pb.HeartbeatResponse{\n\t\t\tLeader: newLeader,\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ KeepConnected keep a stream gRPC call to the master. Used by clients to know the master is up.\n\/\/ And clients gets the up-to-date list of volume locations\nfunc (ms *MasterServer) KeepConnected(stream master_pb.Seaweed_KeepConnectedServer) error {\n\n\treq, err := stream.Recv()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ms.Topo.IsLeader() {\n\t\treturn raft.NotLeaderError\n\t}\n\n\t\/\/ remember client address\n\tctx := stream.Context()\n\t\/\/ fmt.Printf(\"FromContext %+v\\n\", ctx)\n\tpr, ok := peer.FromContext(ctx)\n\tif !ok {\n\t\tglog.Error(\"failed to get peer from ctx\")\n\t\treturn fmt.Errorf(\"failed to get peer from ctx\")\n\t}\n\tif pr.Addr == net.Addr(nil) {\n\t\tglog.Error(\"failed to get peer address\")\n\t\treturn fmt.Errorf(\"failed to get peer address\")\n\t}\n\n\tclientName := req.Name + pr.Addr.String()\n\tglog.V(0).Infof(\"+ client %v\", clientName)\n\n\tmessageChan := make(chan *master_pb.VolumeLocation)\n\tstopChan := make(chan bool)\n\n\tms.clientChansLock.Lock()\n\tms.clientChans[clientName] = messageChan\n\tms.clientChansLock.Unlock()\n\n\tdefer func() {\n\t\tglog.V(0).Infof(\"- client %v\", clientName)\n\t\tms.clientChansLock.Lock()\n\t\tdelete(ms.clientChans, clientName)\n\t\tms.clientChansLock.Unlock()\n\t}()\n\n\tfor _, message := range ms.Topo.ToVolumeLocations() {\n\t\tif err := stream.Send(message); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\t_, err := stream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tglog.V(2).Infof(\"- client %v: %v\", clientName, err)\n\t\t\t\tstopChan <- true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tticker := time.NewTicker(5 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase message := <-messageChan:\n\t\t\tif err := stream.Send(message); err != nil {\n\t\t\t\tglog.V(0).Infof(\"=> client %v: %+v\", clientName, message)\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tif !ms.Topo.IsLeader() {\n\t\t\t\treturn raft.NotLeaderError\n\t\t\t}\n\t\tcase <-stopChan:\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Peter H. Froehlich. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license,\n\/\/ see the LICENSE.md file.\n\n\/\/ Dupes finds duplicate files in the given paths.\n\/\/\n\/\/ Run dupes as follows:\n\/\/\n\/\/\tdupes path1 path2 ...\n\/\/\n\/\/ Dupes will process each path. Directories will be walked\n\/\/ recursively, regular files will be checked against all\n\/\/ others. Dupes will print clusters of paths, separated\n\/\/ by an empty line, for each duplicate it finds. Dupes will\n\/\/ also print statistics about duplicates at the end.\n\/\/\n\/\/ The -p option uses a \"paranoid\" byte-by-byte file comparison\n\/\/ instead of SHA1 digests to identify duplicates.\n\/\/\n\/\/ The -s option sets the minimum file size you care about;\n\/\/ if defaults to 1 so empty files are ignored.\n\/\/\n\/\/ The -g option sets a globbing pattern for the file names\n\/\/ you care about; it defaults to * which matches all file\n\/\/ names.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\/pprof\"\n\t\"sort\"\n)\n\nconst (\n\tglobDefault = \"*\"\n)\n\nvar (\n\tparanoid    = flag.Bool(\"p\", false, \"paranoid byte-by-byte file comparison\")\n\tminimumSize = flag.Int64(\"s\", 1, \"minimum size (in bytes) of files to consider\")\n\tglobbing    = flag.String(\"g\", globDefault, \"glob expression for files to consider\")\n\tcpuprofile  = flag.String(\"cpuprofile\", \"\", \"write cpu profile to file (development only)\")\n)\n\nvar (\n\thashes = make(map[string]string)   \/\/ maps from digests to paths\n\tsizes  = make(map[int64]string)    \/\/ maps from sizes to paths\n\tfinal  = make(map[string][]string) \/\/ maps from paths to duplicate paths (collates all dupes)\n\n\tfiles  counter  \/\/ number of files examined\n\tdupes  counter  \/\/ number of duplicate files\n\twasted bytesize \/\/ space (in bytes) occupied by duplicates\n)\n\n\/\/ fileContentsMatch does a byte-by-byte comparison of the files with the\n\/\/ given paths\nfunc fileContentsMatch(pa, pb string) (bool, error) {\n\ta, err := os.Open(pa)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer a.Close()\n\tb, err := os.Open(pb)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer b.Close()\n\n\treturn fileContentsHelper(a, b)\n}\n\nfunc fileContentsHelper(a, b io.Reader) (bool, error) {\n\tbufferSize := os.Getpagesize()\n\n\tba := make([]byte, bufferSize)\n\tbb := make([]byte, bufferSize)\n\n\tfor {\n\t\tla, erra := a.Read(ba)\n\t\tlb, errb := b.Read(bb)\n\n\t\t\/\/ specification of Read() says to check returned size\n\t\t\/\/ before considering errors; who are we to disagree?\n\t\tif la > 0 || lb > 0 {\n\t\t\t\/\/ it's okay to use Equal here because whatever may\n\t\t\t\/\/ be left behind in the buffers after a short read\n\t\t\t\/\/ had to be Equal in the prior iteration; note that\n\t\t\t\/\/ we don't have to check la == lb either because if\n\t\t\t\/\/ they were not, Equal should fail\n\t\t\tif !bytes.Equal(ba, bb) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ specification of Read() says that sooner or later we'll\n\t\t\/\/ see io.EOF regardless of returned size; only if both\n\t\t\/\/ files end in the same iteration (and made it past Equal\n\t\t\/\/ above) do we have a duplicate\n\t\tswitch {\n\t\tcase erra == io.EOF && errb == io.EOF:\n\t\t\treturn true, nil\n\t\tcase erra != nil:\n\t\t\treturn false, erra\n\t\tcase errb != nil:\n\t\t\treturn false, errb\n\t\t}\n\t}\n}\n\n\/\/ checksum calculates a hash digest for the file with the given path\nfunc checksum(path string) (string, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\thasher := sha1.New()\n\t_, err = io.Copy(hasher, file)\n\tsum := fmt.Sprintf(\"%x\", hasher.Sum(nil))\n\n\treturn sum, err\n}\n\n\/\/ check is called for each path we walk. It only examines regular, non-empty\n\/\/ files. It first rules out duplicates by file size; for files that remain\n\/\/ it calculates a checksum; if it has seen the same checksum before, it\n\/\/ signals a duplicate; otherwise it remembers the checksum and the path of\n\/\/ the original file before moving on; in paranoid mode it follows up with a\n\/\/ byte-by-byte file comparison.\nfunc check(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsize := info.Size()\n\n\tif !info.Mode().IsRegular() || size < *minimumSize {\n\t\treturn nil\n\t}\n\n\tif *globbing != globDefault {\n\t\tmatched, err := filepath.Match(*globbing, info.Name())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfiles++\n\n\tvar dupe string\n\tvar ok bool\n\tif dupe, ok = sizes[size]; !ok {\n\t\tsizes[size] = path\n\t\treturn nil\n\t}\n\n\t\/\/ backpatch new file into hashes\n\tsum, err := checksum(dupe)\n\tif err != nil {\n\t\treturn err\n\t}\n\thashes[sum] = dupe\n\n\tsum, err = checksum(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dupe, ok = hashes[sum]; !ok {\n\t\thashes[sum] = path\n\t\treturn nil\n\t}\n\n\tif *paranoid {\n\t\tsame, err := fileContentsMatch(path, dupe)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !same {\n\t\t\tfmt.Printf(\"cool: %s sha1-collides with %s!\\n\", path, dupe)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tdupes++\n\twasted += bytesize(size)\n\n\tfinal[dupe] = append(final[dupe], path)\n\n\treturn nil\n}\n\nfunc sortedDupes() []string {\n\tvar sk []string\n\tfor k := range final {\n\t\tsk = append(sk, k)\n\t}\n\tsort.Strings(sk)\n\treturn sk\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tvar program = os.Args[0]\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [option...] directory...\\n\", program)\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tflag.Usage()\n\t}\n\n\t_, err := filepath.Match(*globbing, \"checking pattern syntax\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error: invalid pattern for -g (%v)\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif *cpuprofile != \"\" {\n\t\tf, err := os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: can't create profile (%v)\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\n\tfor _, root := range flag.Args() {\n\t\terr = filepath.Walk(root, check)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"warning: issue while walking %s (%v)\\n\", root, err)\n\t\t}\n\t}\n\n\tsk := sortedDupes()\n\tfor _, k := range sk {\n\t\tvs := final[k]\n\t\tfmt.Println(k)\n\t\tfor _, v := range vs {\n\t\t\tfmt.Println(v)\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tif len(sizes) > 0 || len(hashes) > 0 {\n\t\tfmt.Printf(\"%v files examined, %v duplicates found, %v wasted\\n\", files, dupes, wasted)\n\t}\n}\n<commit_msg>Always print the stats.<commit_after>\/\/ Copyright 2016 Peter H. Froehlich. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license,\n\/\/ see the LICENSE.md file.\n\n\/\/ Dupes finds duplicate files in the given paths.\n\/\/\n\/\/ Run dupes as follows:\n\/\/\n\/\/\tdupes path1 path2 ...\n\/\/\n\/\/ Dupes will process each path. Directories will be walked\n\/\/ recursively, regular files will be checked against all\n\/\/ others. Dupes will print clusters of paths, separated\n\/\/ by an empty line, for each duplicate it finds. Dupes will\n\/\/ also print statistics about duplicates at the end.\n\/\/\n\/\/ The -p option uses a \"paranoid\" byte-by-byte file comparison\n\/\/ instead of SHA1 digests to identify duplicates.\n\/\/\n\/\/ The -s option sets the minimum file size you care about;\n\/\/ if defaults to 1 so empty files are ignored.\n\/\/\n\/\/ The -g option sets a globbing pattern for the file names\n\/\/ you care about; it defaults to * which matches all file\n\/\/ names.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\/pprof\"\n\t\"sort\"\n)\n\nconst (\n\tglobDefault = \"*\"\n)\n\nvar (\n\tparanoid    = flag.Bool(\"p\", false, \"paranoid byte-by-byte file comparison\")\n\tminimumSize = flag.Int64(\"s\", 1, \"minimum size (in bytes) of files to consider\")\n\tglobbing    = flag.String(\"g\", globDefault, \"glob expression for files to consider\")\n\tcpuprofile  = flag.String(\"cpuprofile\", \"\", \"write cpu profile to file (development only)\")\n)\n\nvar (\n\thashes = make(map[string]string)   \/\/ maps from digests to paths\n\tsizes  = make(map[int64]string)    \/\/ maps from sizes to paths\n\tfinal  = make(map[string][]string) \/\/ maps from paths to duplicate paths (collates all dupes)\n\n\tfiles  counter  \/\/ number of files examined\n\tdupes  counter  \/\/ number of duplicate files\n\twasted bytesize \/\/ space (in bytes) occupied by duplicates\n)\n\n\/\/ fileContentsMatch does a byte-by-byte comparison of the files with the\n\/\/ given paths\nfunc fileContentsMatch(pa, pb string) (bool, error) {\n\ta, err := os.Open(pa)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer a.Close()\n\tb, err := os.Open(pb)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tdefer b.Close()\n\n\treturn fileContentsHelper(a, b)\n}\n\nfunc fileContentsHelper(a, b io.Reader) (bool, error) {\n\tbufferSize := os.Getpagesize()\n\n\tba := make([]byte, bufferSize)\n\tbb := make([]byte, bufferSize)\n\n\tfor {\n\t\tla, erra := a.Read(ba)\n\t\tlb, errb := b.Read(bb)\n\n\t\t\/\/ specification of Read() says to check returned size\n\t\t\/\/ before considering errors; who are we to disagree?\n\t\tif la > 0 || lb > 0 {\n\t\t\t\/\/ it's okay to use Equal here because whatever may\n\t\t\t\/\/ be left behind in the buffers after a short read\n\t\t\t\/\/ had to be Equal in the prior iteration; note that\n\t\t\t\/\/ we don't have to check la == lb either because if\n\t\t\t\/\/ they were not, Equal should fail\n\t\t\tif !bytes.Equal(ba, bb) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ specification of Read() says that sooner or later we'll\n\t\t\/\/ see io.EOF regardless of returned size; only if both\n\t\t\/\/ files end in the same iteration (and made it past Equal\n\t\t\/\/ above) do we have a duplicate\n\t\tswitch {\n\t\tcase erra == io.EOF && errb == io.EOF:\n\t\t\treturn true, nil\n\t\tcase erra != nil:\n\t\t\treturn false, erra\n\t\tcase errb != nil:\n\t\t\treturn false, errb\n\t\t}\n\t}\n}\n\n\/\/ checksum calculates a hash digest for the file with the given path\nfunc checksum(path string) (string, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\n\thasher := sha1.New()\n\t_, err = io.Copy(hasher, file)\n\tsum := fmt.Sprintf(\"%x\", hasher.Sum(nil))\n\n\treturn sum, err\n}\n\n\/\/ check is called for each path we walk. It only examines regular, non-empty\n\/\/ files. It first rules out duplicates by file size; for files that remain\n\/\/ it calculates a checksum; if it has seen the same checksum before, it\n\/\/ signals a duplicate; otherwise it remembers the checksum and the path of\n\/\/ the original file before moving on; in paranoid mode it follows up with a\n\/\/ byte-by-byte file comparison.\nfunc check(path string, info os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsize := info.Size()\n\n\tif !info.Mode().IsRegular() || size < *minimumSize {\n\t\treturn nil\n\t}\n\n\tif *globbing != globDefault {\n\t\tmatched, err := filepath.Match(*globbing, info.Name())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfiles++\n\n\tvar dupe string\n\tvar ok bool\n\tif dupe, ok = sizes[size]; !ok {\n\t\tsizes[size] = path\n\t\treturn nil\n\t}\n\n\t\/\/ backpatch new file into hashes\n\tsum, err := checksum(dupe)\n\tif err != nil {\n\t\treturn err\n\t}\n\thashes[sum] = dupe\n\n\tsum, err = checksum(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif dupe, ok = hashes[sum]; !ok {\n\t\thashes[sum] = path\n\t\treturn nil\n\t}\n\n\tif *paranoid {\n\t\tsame, err := fileContentsMatch(path, dupe)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !same {\n\t\t\tfmt.Printf(\"cool: %s sha1-collides with %s!\\n\", path, dupe)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tdupes++\n\twasted += bytesize(size)\n\n\tfinal[dupe] = append(final[dupe], path)\n\n\treturn nil\n}\n\nfunc sortedDupes() []string {\n\tvar sk []string\n\tfor k := range final {\n\t\tsk = append(sk, k)\n\t}\n\tsort.Strings(sk)\n\treturn sk\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tvar program = os.Args[0]\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [option...] directory...\\n\", program)\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tflag.Usage()\n\t}\n\n\t_, err := filepath.Match(*globbing, \"checking pattern syntax\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error: invalid pattern for -g (%v)\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif *cpuprofile != \"\" {\n\t\tf, err := os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error: can't create profile (%v)\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tpprof.StartCPUProfile(f)\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\n\tfor _, root := range flag.Args() {\n\t\terr = filepath.Walk(root, check)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"warning: issue while walking %s (%v)\\n\", root, err)\n\t\t}\n\t}\n\n\tsk := sortedDupes()\n\tfor _, k := range sk {\n\t\tvs := final[k]\n\t\tfmt.Println(k)\n\t\tfor _, v := range vs {\n\t\t\tfmt.Println(v)\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\tfmt.Printf(\"%v files examined, %v duplicates found, %v wasted\\n\", files, dupes, wasted)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\tsm \"github.com\/ifn\/go-statemachine\"\n)\n\ntype DeskMsg struct {\n\tDesk [][]string `json:\"desk\"`\n}\n\ntype PlayerMsg struct {\n\tCmd  sm.EventType `json:\"command\"`\n\tCard string       `json:\"card\"`\n}\n\n\/\/\n\nvar Suits []string = []string{\n\t\"S\",\n\t\"C\",\n\t\"H\",\n\t\"D\",\n}\n\nvar CardValues map[string]int = map[string]int{\n\t\"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"10\": 10,\n\t\"J\": 11,\n\t\"Q\": 12,\n\t\"K\": 13,\n\t\"A\": 14,\n}\n\nfunc higher(c0, c1, t string) int {\n\t\/\/ c0 and c1 have the same suit\n\tif c0[0] == c1[0] {\n\t\tif CardValues[c0[1:]] > CardValues[c1[1:]] {\n\t\t\treturn 1\n\t\t}\n\t\tif CardValues[c0[1:]] < CardValues[c1[1:]] {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t}\n\t\/\/ c0 is trump, c1 is not\n\tif c0[:1] == t {\n\t\treturn 1\n\t}\n\t\/\/ c1 is trump, c0 is not\n\tif c1[:1] == t {\n\t\treturn -1\n\t}\n\t\/\/ suits are different, both are not trump\n\treturn -2\n}\n\nvar CardRE *regexp.Regexp = regexp.MustCompile(`[SCHD]([6-9JQKA]|10)`)\n\nfunc isValid(c string) bool {\n\treturn CardRE.MatchString(c)\n}\n\n\/\/\n\nconst (\n\tcmdStart sm.EventType = iota\n\tcmdMove\n\n\tcmdCount\n)\n\nconst (\n\tstateCollection sm.State = iota\n\n\tstateAttack\n\tstateDefense\n\n\tstateCount\n)\n\ntype roundResult int\n\nconst (\n\tNone roundResult = iota\n\tBeat\n\tNotBeat\n)\n\nfunc stateToString(s sm.State) string {\n\treturn [...]string{\n\t\tstateCollection: \"COLLECTION\",\n\t\tstateDefense:    \"DEFENSE\",\n\t\tstateAttack:     \"ATTACK\",\n\t}[s]\n}\n\nfunc cmdToString(t sm.EventType) string {\n\treturn [...]string{\n\t\tcmdStart: \"START\",\n\t\tcmdMove:  \"MOVE\",\n\t}[t]\n}\n\n\/\/\n\ntype cmdArgs struct {\n\tconn *playerConn\n\tcard string\n}\n\n\/\/\n\nfunc logOutOfTurn(pconn *playerConn) {\n\tlog.Printf(\"out of turn: %v\", pconn.conn.RemoteAddr())\n}\n\nfunc logWontBeat(c1, c2, t string) {\n\tlog.Printf(\"%v won't bit %v, trump is \", c1, c2, t)\n}\n\nfunc logNoQuorum(n int) {\n\tlog.Printf(\"no quorum: %v player(s)\", n)\n}\n\n\/\/\n\ntype gameState struct {\n\t\/\/ 1. fields that don't change during a game\n\n\tsm  *sm.StateMachine\n\thub *hub\n\n\t\/\/ trump suit\n\ttrump string\n\n\t\/\/ 2. fields that don't change during a round\n\n\tdeck []string\n\n\t\/\/ attacker that started a round\n\taconnStart *playerConn\n\t\/\/ defender\n\tdconn *playerConn\n\n\t\/\/ 3. fields that change during a round\n\n\t\/\/ attacker\n\taconn *playerConn\n\t\/\/ card that should be beaten\n\tcardToBeat string\n}\n\nfunc (self *gameState) popCard() (card string) {\n\tif deck := self.deck; len(deck) > 0 {\n\t\tcard = deck[0]\n\t\tself.deck = deck[1:]\n\t}\n\treturn\n}\n\nfunc (self *gameState) initDeck() {\n\tnumCards := len(Suits) * len(CardValues)\n\tself.deck = make([]string, 0, numCards+ \/*for trump*\/ 1)\n\n\tdeck := make([]string, 0, numCards)\n\tfor i := range Suits {\n\t\tfor cv := range CardValues {\n\t\t\tdeck = append(deck, Suits[i]+cv)\n\t\t}\n\t}\n\n\torder := rand.Perm(numCards)\n\tfor i := range order {\n\t\tself.deck = append(self.deck, deck[order[i]])\n\t}\n}\n\nfunc (self *gameState) setTrump() {\n\tcard := self.popCard()\n\tself.trump = card[:1]\n\tself.deck = append(self.deck, card)\n}\n\nfunc (self *gameState) nextPlayer(c *playerConn) *playerConn {\n\treturn self.hub.conns.(*mapRing).Next(c).(*playerConn)\n}\n\nfunc (self *gameState) chooseStarting() *playerConn {\n\tconns := self.hub.conns.(*mapRing)\n\n\treturn conns.Nth(rand.Intn(conns.Len())).(*playerConn)\n}\n\nfunc (self *gameState) setRoles(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.aconn = self.chooseStarting()\n\tcase Beat:\n\t\tself.aconn = self.dconn\n\tcase NotBeat:\n\t\tself.aconn = self.nextPlayer(self.dconn)\n\t}\n\tself.dconn = self.nextPlayer(self.aconn)\n\tself.aconnStart = self.aconn\n}\n\nfunc (self *gameState) dealCards() {\n\tfor i := 0; i < 6; i++ {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tpc.(*playerConn).takeCard()\n\t\t}\n\t}\n}\n\nfunc (self *gameState) takeCards() {\n\tconns := self.hub.conns.(*mapRing)\n\n\ttakeCards := func(pc *playerConn) {\n\t\tfor len(self.deck) > 0 && len(pc.cards) < 6 {\n\t\t\tpc.takeCard()\n\t\t}\n\t}\n\n\tfor pc := range conns.EnumerateFrom(self.aconnStart) {\n\t\tif pc := pc.(*playerConn); pc != self.dconn {\n\t\t\ttakeCards(pc)\n\t\t}\n\t}\n\ttakeCards(self.dconn)\n}\n\nfunc (self *gameState) newRound(res roundResult) {\n\tif res == None {\n\t\tself.initDeck()\n\t\tself.dealCards()\n\t\tself.setTrump()\n\t} else {\n\t\tself.takeCards()\n\t}\n\tself.setRoles(res)\n}\n\n\/\/ event handlers\n\/\/ event handlers are actually transition functions.\n\/\/ in case error event handler should neither change the gameState,\n\/\/ nor return the state value different from passed to it as an argument.\n\nfunc (self *gameState) handleStartInCollection(s sm.State, e *sm.Event) sm.State {\n\tif n := self.hub.conns.(*mapRing).Len(); n < 2 {\n\t\tlogNoQuorum(n)\n\t\treturn s\n\t}\n\n\tself.newRound(None)\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInAttack(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.aconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ attacker sent the card\n\tif card != \"\" {\n\t\tself.cardToBeat = card\n\t\treturn stateDefense\n\t}\n\n\t\/\/ attacker sent no card\n\n\taconn := self.nextPlayer(self.aconn)\n\tif aconn == self.dconn {\n\t\taconn = self.nextPlayer(aconn)\n\t}\n\n\t\/\/ check if all attackers have been polled\n\tif aconn == self.aconnStart {\n\t\tself.newRound(Beat)\n\t\treturn stateAttack\n\t}\n\n\tself.aconn = aconn\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInDefense(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.dconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ defender takes the cards\n\tif card == \"\" {\n\t\tself.newRound(NotBeat)\n\t\treturn stateAttack\n\t}\n\n\t\/\/ check that the sent card is capable to beat\n\tif higher(card, self.cardToBeat, self.trump) != 1 {\n\t\tlogWontBeat(card, self.cardToBeat, self.trump)\n\t\treturn s\n\t}\n\n\treturn stateAttack\n}\n\nfunc (self *gameState) showDesk(s sm.State, e *sm.Event) sm.State {\n\tdesk, err := json.Marshal(DeskMsg{})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn s\n\t}\n\n\tself.hub.bcastChan <- desk\n\n\treturn s\n}\n\n\/\/\n\nfunc NewGameState() *gameState {\n\tgst := new(gameState)\n\n\tgst.sm = sm.New(stateCollection, uint(stateCount), uint(cmdCount))\n\n\tgst.sm.On(cmdStart,\n\t\t[]sm.State{stateCollection},\n\t\tgst.handleStartInCollection,\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack},\n\t\tgst.handleMoveInAttack,\n\t)\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateDefense},\n\t\tgst.handleMoveInDefense,\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack, stateDefense},\n\t\tgst.showDesk,\n\t)\n\n\tgst.hub = NewHub()\n\n\treturn gst\n}\n\n\/\/\n\ntype playerConn struct {\n\tgst *gameState\n\n\tcards map[string]bool\n\n\tconn      *websocket.Conn\n\thubToConn chan []byte\n}\n\nfunc (self *playerConn) takeCard() {\n\tif card := self.gst.popCard(); card != \"\" {\n\t\tself.cards[card] = true\n\t}\n}\n\nfunc (self *playerConn) write() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-self.hubToConn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/TODO: text or binary?\n\t\t\terr := self.conn.WriteMessage(websocket.TextMessage, m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *playerConn) read() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tvar m PlayerMsg\n\n\tfor {\n\t\terr := self.conn.ReadJSON(&m)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tvar event *sm.Event\n\t\tswitch m.Cmd {\n\t\tcase cmdStart:\n\t\t\tevent = &sm.Event{cmdStart, nil}\n\t\tcase cmdMove:\n\t\t\tevent = &sm.Event{cmdMove, cmdArgs{self, m.Card}}\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown command: %v\", m.Cmd)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = self.gst.sm.Emit(event)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\nfunc playerHandler(gst *gameState) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tp := &playerConn{gst, make(map[string]bool), conn, make(chan []byte)}\n\n\t\tgst.hub.regChan <- p\n\t\tdefer func() {\n\t\t\tgst.hub.unregChan <- p\n\t\t}()\n\n\t\tgo p.write()\n\t\tp.read()\n\t}\n}\n\n\/\/\n\nfunc startDurakSrv() error {\n\tgst := NewGameState()\n\n\thttp.HandleFunc(\"\/\", playerHandler(gst))\n\n\treturn http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n}\n\nfunc main() {\n\terr := startDurakSrv()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n<commit_msg>replaced bool by empty struct in set<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\tsm \"github.com\/ifn\/go-statemachine\"\n)\n\ntype DeskMsg struct {\n\tDesk [][]string `json:\"desk\"`\n}\n\ntype PlayerMsg struct {\n\tCmd  sm.EventType `json:\"command\"`\n\tCard string       `json:\"card\"`\n}\n\n\/\/\n\nvar Suits []string = []string{\n\t\"S\",\n\t\"C\",\n\t\"H\",\n\t\"D\",\n}\n\nvar CardValues map[string]int = map[string]int{\n\t\"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"10\": 10,\n\t\"J\": 11,\n\t\"Q\": 12,\n\t\"K\": 13,\n\t\"A\": 14,\n}\n\nfunc higher(c0, c1, t string) int {\n\t\/\/ c0 and c1 have the same suit\n\tif c0[0] == c1[0] {\n\t\tif CardValues[c0[1:]] > CardValues[c1[1:]] {\n\t\t\treturn 1\n\t\t}\n\t\tif CardValues[c0[1:]] < CardValues[c1[1:]] {\n\t\t\treturn -1\n\t\t}\n\t\treturn 0\n\t}\n\t\/\/ c0 is trump, c1 is not\n\tif c0[:1] == t {\n\t\treturn 1\n\t}\n\t\/\/ c1 is trump, c0 is not\n\tif c1[:1] == t {\n\t\treturn -1\n\t}\n\t\/\/ suits are different, both are not trump\n\treturn -2\n}\n\nvar CardRE *regexp.Regexp = regexp.MustCompile(`[SCHD]([6-9JQKA]|10)`)\n\nfunc isValid(c string) bool {\n\treturn CardRE.MatchString(c)\n}\n\n\/\/\n\nconst (\n\tcmdStart sm.EventType = iota\n\tcmdMove\n\n\tcmdCount\n)\n\nconst (\n\tstateCollection sm.State = iota\n\n\tstateAttack\n\tstateDefense\n\n\tstateCount\n)\n\ntype roundResult int\n\nconst (\n\tNone roundResult = iota\n\tBeat\n\tNotBeat\n)\n\nfunc stateToString(s sm.State) string {\n\treturn [...]string{\n\t\tstateCollection: \"COLLECTION\",\n\t\tstateDefense:    \"DEFENSE\",\n\t\tstateAttack:     \"ATTACK\",\n\t}[s]\n}\n\nfunc cmdToString(t sm.EventType) string {\n\treturn [...]string{\n\t\tcmdStart: \"START\",\n\t\tcmdMove:  \"MOVE\",\n\t}[t]\n}\n\n\/\/\n\ntype cmdArgs struct {\n\tconn *playerConn\n\tcard string\n}\n\n\/\/\n\nfunc logOutOfTurn(pconn *playerConn) {\n\tlog.Printf(\"out of turn: %v\", pconn.conn.RemoteAddr())\n}\n\nfunc logWontBeat(c1, c2, t string) {\n\tlog.Printf(\"%v won't bit %v, trump is \", c1, c2, t)\n}\n\nfunc logNoQuorum(n int) {\n\tlog.Printf(\"no quorum: %v player(s)\", n)\n}\n\n\/\/\n\ntype gameState struct {\n\t\/\/ 1. fields that don't change during a game\n\n\tsm  *sm.StateMachine\n\thub *hub\n\n\t\/\/ trump suit\n\ttrump string\n\n\t\/\/ 2. fields that don't change during a round\n\n\tdeck []string\n\n\t\/\/ attacker that started a round\n\taconnStart *playerConn\n\t\/\/ defender\n\tdconn *playerConn\n\n\t\/\/ 3. fields that change during a round\n\n\t\/\/ attacker\n\taconn *playerConn\n\t\/\/ card that should be beaten\n\tcardToBeat string\n}\n\nfunc (self *gameState) popCard() (card string) {\n\tif deck := self.deck; len(deck) > 0 {\n\t\tcard = deck[0]\n\t\tself.deck = deck[1:]\n\t}\n\treturn\n}\n\nfunc (self *gameState) initDeck() {\n\tnumCards := len(Suits) * len(CardValues)\n\tself.deck = make([]string, 0, numCards+ \/*for trump*\/ 1)\n\n\tdeck := make([]string, 0, numCards)\n\tfor i := range Suits {\n\t\tfor cv := range CardValues {\n\t\t\tdeck = append(deck, Suits[i]+cv)\n\t\t}\n\t}\n\n\torder := rand.Perm(numCards)\n\tfor i := range order {\n\t\tself.deck = append(self.deck, deck[order[i]])\n\t}\n}\n\nfunc (self *gameState) setTrump() {\n\tcard := self.popCard()\n\tself.trump = card[:1]\n\tself.deck = append(self.deck, card)\n}\n\nfunc (self *gameState) nextPlayer(c *playerConn) *playerConn {\n\treturn self.hub.conns.(*mapRing).Next(c).(*playerConn)\n}\n\nfunc (self *gameState) chooseStarting() *playerConn {\n\tconns := self.hub.conns.(*mapRing)\n\n\treturn conns.Nth(rand.Intn(conns.Len())).(*playerConn)\n}\n\nfunc (self *gameState) setRoles(res roundResult) {\n\tswitch res {\n\tcase None:\n\t\tself.aconn = self.chooseStarting()\n\tcase Beat:\n\t\tself.aconn = self.dconn\n\tcase NotBeat:\n\t\tself.aconn = self.nextPlayer(self.dconn)\n\t}\n\tself.dconn = self.nextPlayer(self.aconn)\n\tself.aconnStart = self.aconn\n}\n\nfunc (self *gameState) dealCards() {\n\tfor i := 0; i < 6; i++ {\n\t\tfor pc := range self.hub.conns.Enumerate() {\n\t\t\tpc.(*playerConn).takeCard()\n\t\t}\n\t}\n}\n\nfunc (self *gameState) takeCards() {\n\tconns := self.hub.conns.(*mapRing)\n\n\ttakeCards := func(pc *playerConn) {\n\t\tfor len(self.deck) > 0 && len(pc.cards) < 6 {\n\t\t\tpc.takeCard()\n\t\t}\n\t}\n\n\tfor pc := range conns.EnumerateFrom(self.aconnStart) {\n\t\tif pc := pc.(*playerConn); pc != self.dconn {\n\t\t\ttakeCards(pc)\n\t\t}\n\t}\n\ttakeCards(self.dconn)\n}\n\nfunc (self *gameState) newRound(res roundResult) {\n\tif res == None {\n\t\tself.initDeck()\n\t\tself.dealCards()\n\t\tself.setTrump()\n\t} else {\n\t\tself.takeCards()\n\t}\n\tself.setRoles(res)\n}\n\n\/\/ event handlers\n\/\/ event handlers are actually transition functions.\n\/\/ in case error event handler should neither change the gameState,\n\/\/ nor return the state value different from passed to it as an argument.\n\nfunc (self *gameState) handleStartInCollection(s sm.State, e *sm.Event) sm.State {\n\tif n := self.hub.conns.(*mapRing).Len(); n < 2 {\n\t\tlogNoQuorum(n)\n\t\treturn s\n\t}\n\n\tself.newRound(None)\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInAttack(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.aconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ attacker sent the card\n\tif card != \"\" {\n\t\tself.cardToBeat = card\n\t\treturn stateDefense\n\t}\n\n\t\/\/ attacker sent no card\n\n\taconn := self.nextPlayer(self.aconn)\n\tif aconn == self.dconn {\n\t\taconn = self.nextPlayer(aconn)\n\t}\n\n\t\/\/ check if all attackers have been polled\n\tif aconn == self.aconnStart {\n\t\tself.newRound(Beat)\n\t\treturn stateAttack\n\t}\n\n\tself.aconn = aconn\n\treturn stateAttack\n}\n\nfunc (self *gameState) handleMoveInDefense(s sm.State, e *sm.Event) sm.State {\n\tconn := e.Data.(cmdArgs).conn\n\tcard := e.Data.(cmdArgs).card\n\n\t\/\/ check that it's conn's turn to move\n\tif conn != self.dconn {\n\t\tlogOutOfTurn(conn)\n\t\treturn s\n\t}\n\n\t\/\/ defender takes the cards\n\tif card == \"\" {\n\t\tself.newRound(NotBeat)\n\t\treturn stateAttack\n\t}\n\n\t\/\/ check that the sent card is capable to beat\n\tif higher(card, self.cardToBeat, self.trump) != 1 {\n\t\tlogWontBeat(card, self.cardToBeat, self.trump)\n\t\treturn s\n\t}\n\n\treturn stateAttack\n}\n\nfunc (self *gameState) showDesk(s sm.State, e *sm.Event) sm.State {\n\tdesk, err := json.Marshal(DeskMsg{})\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn s\n\t}\n\n\tself.hub.bcastChan <- desk\n\n\treturn s\n}\n\n\/\/\n\nfunc NewGameState() *gameState {\n\tgst := new(gameState)\n\n\tgst.sm = sm.New(stateCollection, uint(stateCount), uint(cmdCount))\n\n\tgst.sm.On(cmdStart,\n\t\t[]sm.State{stateCollection},\n\t\tgst.handleStartInCollection,\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack},\n\t\tgst.handleMoveInAttack,\n\t)\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateDefense},\n\t\tgst.handleMoveInDefense,\n\t)\n\n\tgst.sm.On(cmdMove,\n\t\t[]sm.State{stateAttack, stateDefense},\n\t\tgst.showDesk,\n\t)\n\n\tgst.hub = NewHub()\n\n\treturn gst\n}\n\n\/\/\n\ntype playerConn struct {\n\tgst *gameState\n\n\tcards map[string]struct{}\n\n\tconn      *websocket.Conn\n\thubToConn chan []byte\n}\n\nfunc (self *playerConn) takeCard() {\n\tif card := self.gst.popCard(); card != \"\" {\n\t\tself.cards[card] = struct{}{}\n\t}\n}\n\nfunc (self *playerConn) write() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-self.hubToConn:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/TODO: text or binary?\n\t\t\terr := self.conn.WriteMessage(websocket.TextMessage, m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *playerConn) read() {\n\tdefer func() {\n\t\terr := self.conn.Close()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}()\n\n\tvar m PlayerMsg\n\n\tfor {\n\t\terr := self.conn.ReadJSON(&m)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tvar event *sm.Event\n\t\tswitch m.Cmd {\n\t\tcase cmdStart:\n\t\t\tevent = &sm.Event{cmdStart, nil}\n\t\tcase cmdMove:\n\t\t\tevent = &sm.Event{cmdMove, cmdArgs{self, m.Card}}\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown command: %v\", m.Cmd)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = self.gst.sm.Emit(event)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\nfunc playerHandler(gst *gameState) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\tp := &playerConn{gst, make(map[string]struct{}), conn, make(chan []byte)}\n\n\t\tgst.hub.regChan <- p\n\t\tdefer func() {\n\t\t\tgst.hub.unregChan <- p\n\t\t}()\n\n\t\tgo p.write()\n\t\tp.read()\n\t}\n}\n\n\/\/\n\nfunc startDurakSrv() error {\n\tgst := NewGameState()\n\n\thttp.HandleFunc(\"\/\", playerHandler(gst))\n\n\treturn http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n}\n\nfunc main() {\n\terr := startDurakSrv()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage embed allows for storing data resources in a virtual filesystem\nthat gets compiled directly into the output program, eliminating the need\nto distribute data files with the application. This is especially useful for small\nweb servers that need to deliver content files.\n\nThe data is gzipped to save space.\n\nAn external tool for generating output files can be found at http:\/\/github.com\/cratonica\/embedder\n\nAuthor: Clint Caywood\n\nhttp:\/\/github.com\/cratonica\/embed\n*\/\npackage embed\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ A mapping of resource identifiers to associated data\ntype ResourceMap map[string][]byte\n\n\/\/ A compressed resource map that can be used for serialization\ntype PackedResourceMap []byte\n\nvar byteOrder binary.ByteOrder = binary.LittleEndian\n\n\/\/ Packs the map of resource identifiers => []byte into\n\/\/ a buffer. This process is revered by calling Unpack.\nfunc Pack(data ResourceMap) (PackedResourceMap, error) {\n\tvar buf bytes.Buffer\n\twriter, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, v := range data {\n\t\tif err = binary.Write(writer, byteOrder, int32(len(i))); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err = writer.Write([]byte(i)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = binary.Write(writer, byteOrder, int32(len(v))); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err = writer.Write(v); err != nil {\n\t\t}\n\t}\n\tif err = writer.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := buf.Bytes()\n\treturn result, nil\n}\n\ntype DeserializationError struct {\n\twhat     string\n\texpected int\n\tactual   int\n}\n\nfunc (this *DeserializationError) Error() string {\n\treturn fmt.Sprintf(\"Failure deserializing resource: expected %v to be %v bytes, but only read %v bytes\", this.what, this.expected, this.actual)\n}\n\nfunc NewDeserializationError(what string, expected int, actual int) *DeserializationError {\n\treturn &DeserializationError{what, expected, actual}\n}\n\n\/\/ Reads a buffer generated by a call to Pack, returning the original map\nfunc Unpack(data PackedResourceMap) (ResourceMap, error) {\n\tresult := make(map[string][]byte)\n\tbuf := bytes.NewBuffer(data)\n\treader, err := gzip.NewReader(buf)\n\tdefer func() {\n\t\treader.Close()\n\t}()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tvar size int32\n\t\terr := binary.Read(reader, byteOrder, &size)\n\t\tif err != nil {\n\t\t\tbreak \/\/ EOF\n\t\t}\n\t\tkeyBuf, err := readAll(reader, int(size))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = binary.Read(reader, byteOrder, &size)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdataBuf, err := readAll(reader, int(size))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[string(keyBuf)] = dataBuf\n\t}\n\treturn result, nil\n}\n\n\/\/ Recursively packs all files in the given directory into\n\/\/ a resource map. Directory delimiters are converted to Unix-style \/\n\/\/ regardless of the host operating system.\nfunc CreateFromFiles(path string) (ResourceMap, error) {\n\tresult := make(map[string][]byte)\n\terr := crawl(filepath.Clean(path), filepath.Clean(path), result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Generates Go code containing the given data that can be included in the target project\nfunc GenerateGoCode(packageName string, varName string, data PackedResourceMap) string {\n\ttemplate := `\npackage %v\n\nimport \"github.com\/cratonica\/embed\"\n\nvar %v embed.PackedResourceMap = %#v\n`\n\treturn fmt.Sprintf(template, packageName, varName, data)\n}\n\nfunc readAll(reader io.Reader, size int) ([]byte, error) {\n\tresult := make([]byte, size)\n\ttotalBytes := 0\n\tfor totalBytes < size {\n\t\treadSize, err := reader.Read(result[totalBytes:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttotalBytes += readSize\n\t}\n\treturn result, nil\n}\n\nfunc crawl(rootPath string, currentPath string, dest map[string][]byte) error {\n\tfiles, err := ioutil.ReadDir(currentPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tfullPath := filepath.Join(currentPath, file.Name())\n\t\tif file.IsDir() {\n\t\t\terr := crawl(rootPath, fullPath, dest)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tbuf, err := ioutil.ReadFile(fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failure reading file %v: %v\", fullPath, err)\n\t\t\t} else {\n\t\t\t\tkey := strings.TrimLeft(fullPath, rootPath)\n\t\t\t\tif strings.HasPrefix(key, string(os.PathSeparator)) {\n\t\t\t\t\tkey = key[1:]\n\t\t\t\t}\n\t\t\t\t\/\/ Convert to unix style for internal use\n\t\t\t\tkey = strings.Replace(key, string(os.PathSeparator), \"\/\", -1)\n\t\t\t\tdest[key] = buf\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Fix typo<commit_after>\/*\nPackage embed allows for storing data resources in a virtual filesystem\nthat gets compiled directly into the output program, eliminating the need\nto distribute data files with the application. This is especially useful for small\nweb servers that need to deliver content files.\n\nThe data is gzipped to save space.\n\nAn external tool for generating output files can be found at http:\/\/github.com\/cratonica\/embedder\n\nAuthor: Clint Caywood\n\nhttp:\/\/github.com\/cratonica\/embed\n*\/\npackage embed\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ A mapping of resource identifiers to associated data\ntype ResourceMap map[string][]byte\n\n\/\/ A compressed resource map that can be used for serialization\ntype PackedResourceMap []byte\n\nvar byteOrder binary.ByteOrder = binary.LittleEndian\n\n\/\/ Packs the map of resource identifiers => []byte into\n\/\/ a buffer. This process is reversed by calling Unpack.\nfunc Pack(data ResourceMap) (PackedResourceMap, error) {\n\tvar buf bytes.Buffer\n\twriter, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, v := range data {\n\t\tif err = binary.Write(writer, byteOrder, int32(len(i))); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err = writer.Write([]byte(i)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err = binary.Write(writer, byteOrder, int32(len(v))); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, err = writer.Write(v); err != nil {\n\t\t}\n\t}\n\tif err = writer.Close(); err != nil {\n\t\treturn nil, err\n\t}\n\tresult := buf.Bytes()\n\treturn result, nil\n}\n\ntype DeserializationError struct {\n\twhat     string\n\texpected int\n\tactual   int\n}\n\nfunc (this *DeserializationError) Error() string {\n\treturn fmt.Sprintf(\"Failure deserializing resource: expected %v to be %v bytes, but only read %v bytes\", this.what, this.expected, this.actual)\n}\n\nfunc NewDeserializationError(what string, expected int, actual int) *DeserializationError {\n\treturn &DeserializationError{what, expected, actual}\n}\n\n\/\/ Reads a buffer generated by a call to Pack, returning the original map\nfunc Unpack(data PackedResourceMap) (ResourceMap, error) {\n\tresult := make(map[string][]byte)\n\tbuf := bytes.NewBuffer(data)\n\treader, err := gzip.NewReader(buf)\n\tdefer func() {\n\t\treader.Close()\n\t}()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tvar size int32\n\t\terr := binary.Read(reader, byteOrder, &size)\n\t\tif err != nil {\n\t\t\tbreak \/\/ EOF\n\t\t}\n\t\tkeyBuf, err := readAll(reader, int(size))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = binary.Read(reader, byteOrder, &size)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdataBuf, err := readAll(reader, int(size))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[string(keyBuf)] = dataBuf\n\t}\n\treturn result, nil\n}\n\n\/\/ Recursively packs all files in the given directory into\n\/\/ a resource map. Directory delimiters are converted to Unix-style \/\n\/\/ regardless of the host operating system.\nfunc CreateFromFiles(path string) (ResourceMap, error) {\n\tresult := make(map[string][]byte)\n\terr := crawl(filepath.Clean(path), filepath.Clean(path), result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Generates Go code containing the given data that can be included in the target project\nfunc GenerateGoCode(packageName string, varName string, data PackedResourceMap) string {\n\ttemplate := `\npackage %v\n\nimport \"github.com\/cratonica\/embed\"\n\nvar %v embed.PackedResourceMap = %#v\n`\n\treturn fmt.Sprintf(template, packageName, varName, data)\n}\n\nfunc readAll(reader io.Reader, size int) ([]byte, error) {\n\tresult := make([]byte, size)\n\ttotalBytes := 0\n\tfor totalBytes < size {\n\t\treadSize, err := reader.Read(result[totalBytes:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttotalBytes += readSize\n\t}\n\treturn result, nil\n}\n\nfunc crawl(rootPath string, currentPath string, dest map[string][]byte) error {\n\tfiles, err := ioutil.ReadDir(currentPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, file := range files {\n\t\tfullPath := filepath.Join(currentPath, file.Name())\n\t\tif file.IsDir() {\n\t\t\terr := crawl(rootPath, fullPath, dest)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tbuf, err := ioutil.ReadFile(fullPath)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failure reading file %v: %v\", fullPath, err)\n\t\t\t} else {\n\t\t\t\tkey := strings.TrimLeft(fullPath, rootPath)\n\t\t\t\tif strings.HasPrefix(key, string(os.PathSeparator)) {\n\t\t\t\t\tkey = key[1:]\n\t\t\t\t}\n\t\t\t\t\/\/ Convert to unix style for internal use\n\t\t\t\tkey = strings.Replace(key, string(os.PathSeparator), \"\/\", -1)\n\t\t\t\tdest[key] = buf\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe emogo package provides go bindings for emokit\n(https:\/\/github.com\/openyou\/emokit). \n*\/\npackage emogo\n\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\n\/\/ #include <emokit\/emokit.h>\n\/\/ #include <stdint.h>\n\/\/ #cgo LDFLAGS: -lemokit\nimport \"C\"\n\n\/\/ These are defined in emokit.h and reproduced here as cgo isn't\n\/\/ linking them in for some reason.\nconst (\n\tEMOKIT_VID int = 0x21a1\n\tEMOKIT_PID  = 0x0001\n\tEmokitPacketSize = 32\n)\n\ntype HeadsetType uint\n\nconst (\n\tDeveloperHeadset HeadsetType = 0\n\tConsumerHeadset HeadsetType = 1\n)\n\n\/\/ EmokitContext represents a connection to an EPOC device. \ntype EmokitContext struct {\n\teeg *C.struct_emokit_device\n}\n\nfunc NewEmokitContext(t HeadsetType) (*EmokitContext, error) {\n\te := new(EmokitContext)\n\te.eeg = C.emokit_create()\n\tret := C.emokit_open(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID), C.uint(t))\n\tif ret != 0 {\n\t\treturn nil, errors.New(\"Cannot access device.\")\n\t}\n\treturn e, nil\n}\n\ntype EmokitFrame struct {\n\traw []byte\n\trendered C.struct_emokit_frame\n}\n\nfunc NewEmokitFrame() *EmokitFrame {\n\tf := new(EmokitFrame)\n\tf.raw = make([]byte, EmokitPacketSize)\n\treturn f\n}\n\n\/\/ readData reads data from the EPOC dongle and returns 0 on success, <0\n\/\/ on error.\nfunc (e *EmokitContext) readData() error {\n\tn := C.emokit_read_data(e.eeg)\n\tif n >= 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(\"emokit_read_data failed\")\n}\n\nfunc (e *EmokitContext) getNextFrame() (*EmokitFrame, error) {\n\tf := NewEmokitFrame()\n\tf.rendered = C.emokit_get_next_frame(e.eeg)\n\tif f.rendered.counter == 0 {\n\t\treturn nil, errors.New(\"Could not read raw packet.\")\n\t}\n\tC.emokit_get_raw_frame(e.eeg, (*C.uchar)(unsafe.Pointer(&f.raw[0])))\n\treturn f, nil\n}\n\n\/\/ GetFrame returns the next available EPOC frame. If there is no frame\n\/\/ to be read, the error value will be EAGAIN.\nfunc (e *EmokitContext) GetFrame() (*EmokitFrame, error) {\n\terr := e.readData()\n\tif err == nil {\n\t\tf, err := e.getNextFrame()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn f, nil\n\t}\n\treturn nil, err\n}\n\nfunc (e *EmokitContext) Count() int {\n\tn := C.emokit_get_count(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID))\n\treturn int(n)\n}\n\n\/\/ Raw returns the (unencrypted) raw EPOC frame.\nfunc (f *EmokitFrame) Raw() []byte {\n\treturn f.raw\n}\n\n\/\/ Gyro returns the current (x,y) of the frame's Gyro value.\nfunc (f *EmokitFrame) Gyro() (int,int) {\n\treturn int(f.rendered.gyroX), int(f.rendered.gyroY)\n}\n<commit_msg>Add Shutdown function<commit_after>\/*\nThe emogo package provides go bindings for emokit\n(https:\/\/github.com\/openyou\/emokit). \n*\/\npackage emogo\n\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\n\/\/ #include <emokit\/emokit.h>\n\/\/ #include <stdint.h>\n\/\/ #cgo LDFLAGS: -lemokit\nimport \"C\"\n\n\/\/ These are defined in emokit.h and reproduced here as cgo isn't\n\/\/ linking them in for some reason.\nconst (\n\tEMOKIT_VID int = 0x21a1\n\tEMOKIT_PID  = 0x0001\n\tEmokitPacketSize = 32\n)\n\ntype HeadsetType uint\n\nconst (\n\tDeveloperHeadset HeadsetType = 0\n\tConsumerHeadset HeadsetType = 1\n)\n\n\/\/ EmokitContext represents a connection to an EPOC device. \ntype EmokitContext struct {\n\teeg *C.struct_emokit_device\n}\n\nfunc NewEmokitContext(t HeadsetType) (*EmokitContext, error) {\n\te := new(EmokitContext)\n\te.eeg = C.emokit_create()\n\tret := C.emokit_open(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID), C.uint(t))\n\tif ret != 0 {\n\t\treturn nil, errors.New(\"Cannot access device.\")\n\t}\n\treturn e, nil\n}\n\n\/\/ Shutdown closes the connection to the EPOC and frees associated \n\/\/ memory.\nfunc (c *EmokitContext) Shutdown() {\n\tC.emokit_close(c.eeg)\n\tC.emokit_delete(c.eeg)\n}\n\ntype EmokitFrame struct {\n\traw []byte\n\trendered C.struct_emokit_frame\n}\n\nfunc NewEmokitFrame() *EmokitFrame {\n\tf := new(EmokitFrame)\n\tf.raw = make([]byte, EmokitPacketSize)\n\treturn f\n}\n\n\/\/ readData reads data from the EPOC dongle and returns 0 on success, <0\n\/\/ on error.\nfunc (e *EmokitContext) readData() error {\n\tn := C.emokit_read_data(e.eeg)\n\tif n >= 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(\"emokit_read_data failed\")\n}\n\nfunc (e *EmokitContext) getNextFrame() (*EmokitFrame, error) {\n\tf := NewEmokitFrame()\n\tf.rendered = C.emokit_get_next_frame(e.eeg)\n\tif f.rendered.counter == 0 {\n\t\treturn nil, errors.New(\"Could not read raw packet.\")\n\t}\n\tC.emokit_get_raw_frame(e.eeg, (*C.uchar)(unsafe.Pointer(&f.raw[0])))\n\treturn f, nil\n}\n\n\/\/ GetFrame returns the next available EPOC frame. If there is no frame\n\/\/ to be read, the error value will be EAGAIN.\nfunc (e *EmokitContext) GetFrame() (*EmokitFrame, error) {\n\terr := e.readData()\n\tif err == nil {\n\t\tf, err := e.getNextFrame()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn f, nil\n\t}\n\treturn nil, err\n}\n\nfunc (e *EmokitContext) Count() int {\n\tn := C.emokit_get_count(e.eeg, C.int(EMOKIT_VID), C.int(EMOKIT_PID))\n\treturn int(n)\n}\n\n\/\/ Raw returns the (unencrypted) raw EPOC frame.\nfunc (f *EmokitFrame) Raw() []byte {\n\treturn f.raw\n}\n\n\/\/ Gyro returns the current (x,y) of the frame's Gyro value.\nfunc (f *EmokitFrame) Gyro() (int,int) {\n\treturn int(f.rendered.gyroX), int(f.rendered.gyroY)\n}\n<|endoftext|>"}
{"text":"<commit_before>package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Defines the key when adding errors using WithError.\nvar ErrorKey = \"error\"\n\n\/\/ An entry is the final or intermediate Logrus logging entry. It contains all\n\/\/ the fields passed with WithField{,s}. It's finally logged when Debug, Info,\n\/\/ Warn, Error, Fatal or Panic is called on it. These objects can be reused and\n\/\/ passed around as much as you wish to avoid field duplication.\ntype Entry struct {\n\tLogger *Logger\n\n\t\/\/ Contains all the fields set by the user.\n\tData Fields\n\n\t\/\/ Time at which the log entry was created\n\tTime time.Time\n\n\t\/\/ Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic\n\tLevel Level\n\n\t\/\/ Message passed to Debug, Info, Warn, Error, Fatal or Panic\n\tMessage string\n}\n\nfunc NewEntry(logger *Logger) *Entry {\n\treturn &Entry{\n\t\tLogger: logger,\n\t\t\/\/ Default is three fields, give a little extra room\n\t\tData: make(Fields, 5),\n\t}\n}\n\n\/\/ Returns a reader for the entry, which is a proxy to the formatter.\nfunc (entry *Entry) Reader() (*bytes.Buffer, error) {\n\tserialized, err := entry.Logger.Formatter.Format(entry)\n\treturn bytes.NewBuffer(serialized), err\n}\n\n\/\/ Returns the string representation from the reader and ultimately the\n\/\/ formatter.\nfunc (entry *Entry) String() (string, error) {\n\treader, err := entry.Reader()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn reader.String(), err\n}\n\n\/\/ Add an error as single field (using the key defined in ErrorKey) to the Entry.\nfunc (entry *Entry) WithError(err error) *Entry {\n\treturn entry.WithField(ErrorKey, err)\n}\n\n\/\/ Add a single field to the Entry.\nfunc (entry *Entry) WithField(key string, value interface{}) *Entry {\n\treturn entry.WithFields(Fields{key: value})\n}\n\n\/\/ Add a map of fields to the Entry.\nfunc (entry *Entry) WithFields(fields Fields) *Entry {\n\tdata := make(Fields, len(entry.Data)+len(fields))\n\tfor k, v := range entry.Data {\n\t\tdata[k] = v\n\t}\n\tfor k, v := range fields {\n\t\tdata[k] = v\n\t}\n\treturn &Entry{Logger: entry.Logger, Data: data}\n}\n\n\/\/ This function is not declared with a pointer value because otherwise\n\/\/ race conditions will occur when using multiple goroutines\nfunc (entry Entry) log(level Level, msg string) {\n\tentry.Time = time.Now()\n\tentry.Level = level\n\tentry.Message = msg\n\n\tif err := entry.Logger.Hooks.Fire(level, &entry); err != nil {\n\t\tentry.Logger.mu.Lock()\n\t\tfmt.Fprintf(os.Stderr, \"Failed to fire hook: %v\\n\", err)\n\t\tentry.Logger.mu.Unlock()\n\t}\n\n\treader, err := entry.Reader()\n\tif err != nil {\n\t\tentry.Logger.mu.Lock()\n\t\tfmt.Fprintf(os.Stderr, \"Failed to obtain reader, %v\\n\", err)\n\t\tentry.Logger.mu.Unlock()\n\t}\n\n\tentry.Logger.mu.Lock()\n\tdefer entry.Logger.mu.Unlock()\n\n\t_, err = io.Copy(entry.Logger.Out, reader)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to write to log, %v\\n\", err)\n\t}\n\n\t\/\/ To avoid Entry#log() returning a value that only would make sense for\n\t\/\/ panic() to use in Entry#Panic(), we avoid the allocation by checking\n\t\/\/ directly here.\n\tif level <= PanicLevel {\n\t\tpanic(&entry)\n\t}\n}\n\nfunc (entry *Entry) Debug(args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.log(DebugLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Print(args ...interface{}) {\n\tentry.Info(args...)\n}\n\nfunc (entry *Entry) Info(args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.log(InfoLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Warn(args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.log(WarnLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Warning(args ...interface{}) {\n\tentry.Warn(args...)\n}\n\nfunc (entry *Entry) Error(args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.log(ErrorLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Fatal(args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.log(FatalLevel, fmt.Sprint(args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panic(args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.log(PanicLevel, fmt.Sprint(args...))\n\t}\n\tpanic(fmt.Sprint(args...))\n}\n\n\/\/ Entry Printf family functions\n\nfunc (entry *Entry) Debugf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.Debug(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Infof(format string, args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.Info(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Printf(format string, args ...interface{}) {\n\tentry.Infof(format, args...)\n}\n\nfunc (entry *Entry) Warnf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.Warn(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Warningf(format string, args ...interface{}) {\n\tentry.Warnf(format, args...)\n}\n\nfunc (entry *Entry) Errorf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.Error(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Fatalf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.Fatal(fmt.Sprintf(format, args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panicf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.Panic(fmt.Sprintf(format, args...))\n\t}\n}\n\n\/\/ Entry Println family functions\n\nfunc (entry *Entry) Debugln(args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.Debug(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Infoln(args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.Info(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Println(args ...interface{}) {\n\tentry.Infoln(args...)\n}\n\nfunc (entry *Entry) Warnln(args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.Warn(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Warningln(args ...interface{}) {\n\tentry.Warnln(args...)\n}\n\nfunc (entry *Entry) Errorln(args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.Error(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Fatalln(args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.Fatal(entry.sprintlnn(args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panicln(args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.Panic(entry.sprintlnn(args...))\n\t}\n}\n\n\/\/ Sprintlnn => Sprint no newline. This is to get the behavior of how\n\/\/ fmt.Sprintln where spaces are always added between operands, regardless of\n\/\/ their type. Instead of vendoring the Sprintln implementation to spare a\n\/\/ string allocation, we do the simplest thing.\nfunc (entry *Entry) sprintlnn(args ...interface{}) string {\n\tmsg := fmt.Sprintln(args...)\n\treturn msg[:len(msg)-1]\n}\n<commit_msg>Add *Entry.Bytes() for using byte[] directly<commit_after>package logrus\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Defines the key when adding errors using WithError.\nvar ErrorKey = \"error\"\n\n\/\/ An entry is the final or intermediate Logrus logging entry. It contains all\n\/\/ the fields passed with WithField{,s}. It's finally logged when Debug, Info,\n\/\/ Warn, Error, Fatal or Panic is called on it. These objects can be reused and\n\/\/ passed around as much as you wish to avoid field duplication.\ntype Entry struct {\n\tLogger *Logger\n\n\t\/\/ Contains all the fields set by the user.\n\tData Fields\n\n\t\/\/ Time at which the log entry was created\n\tTime time.Time\n\n\t\/\/ Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic\n\tLevel Level\n\n\t\/\/ Message passed to Debug, Info, Warn, Error, Fatal or Panic\n\tMessage string\n}\n\nfunc NewEntry(logger *Logger) *Entry {\n\treturn &Entry{\n\t\tLogger: logger,\n\t\t\/\/ Default is three fields, give a little extra room\n\t\tData: make(Fields, 5),\n\t}\n}\n\n\/\/ Returns a reader for the entry, which is a proxy to the formatter.\nfunc (entry *Entry) Reader() (*bytes.Buffer, error) {\n\tserialized, err := entry.Logger.Formatter.Format(entry)\n\treturn bytes.NewBuffer(serialized), err\n}\n\n\/\/ Returns a byte[] for the entry, which is a proxy to the formatter.\nfunc (entry *Entry) Bytes() ([]byte, error) {\n\treturn entry.Logger.Formatter.Format(entry)\n}\n\n\/\/ Returns the string representation from the reader and ultimately the\n\/\/ formatter.\nfunc (entry *Entry) String() (string, error) {\n\treader, err := entry.Reader()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn reader.String(), err\n}\n\n\/\/ Add an error as single field (using the key defined in ErrorKey) to the Entry.\nfunc (entry *Entry) WithError(err error) *Entry {\n\treturn entry.WithField(ErrorKey, err)\n}\n\n\/\/ Add a single field to the Entry.\nfunc (entry *Entry) WithField(key string, value interface{}) *Entry {\n\treturn entry.WithFields(Fields{key: value})\n}\n\n\/\/ Add a map of fields to the Entry.\nfunc (entry *Entry) WithFields(fields Fields) *Entry {\n\tdata := make(Fields, len(entry.Data)+len(fields))\n\tfor k, v := range entry.Data {\n\t\tdata[k] = v\n\t}\n\tfor k, v := range fields {\n\t\tdata[k] = v\n\t}\n\treturn &Entry{Logger: entry.Logger, Data: data}\n}\n\n\/\/ This function is not declared with a pointer value because otherwise\n\/\/ race conditions will occur when using multiple goroutines\nfunc (entry Entry) log(level Level, msg string) {\n\tentry.Time = time.Now()\n\tentry.Level = level\n\tentry.Message = msg\n\n\tif err := entry.Logger.Hooks.Fire(level, &entry); err != nil {\n\t\tentry.Logger.mu.Lock()\n\t\tfmt.Fprintf(os.Stderr, \"Failed to fire hook: %v\\n\", err)\n\t\tentry.Logger.mu.Unlock()\n\t}\n\n\treader, err := entry.Reader()\n\tif err != nil {\n\t\tentry.Logger.mu.Lock()\n\t\tfmt.Fprintf(os.Stderr, \"Failed to obtain reader, %v\\n\", err)\n\t\tentry.Logger.mu.Unlock()\n\t}\n\n\tentry.Logger.mu.Lock()\n\tdefer entry.Logger.mu.Unlock()\n\n\t_, err = io.Copy(entry.Logger.Out, reader)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to write to log, %v\\n\", err)\n\t}\n\n\t\/\/ To avoid Entry#log() returning a value that only would make sense for\n\t\/\/ panic() to use in Entry#Panic(), we avoid the allocation by checking\n\t\/\/ directly here.\n\tif level <= PanicLevel {\n\t\tpanic(&entry)\n\t}\n}\n\nfunc (entry *Entry) Debug(args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.log(DebugLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Print(args ...interface{}) {\n\tentry.Info(args...)\n}\n\nfunc (entry *Entry) Info(args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.log(InfoLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Warn(args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.log(WarnLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Warning(args ...interface{}) {\n\tentry.Warn(args...)\n}\n\nfunc (entry *Entry) Error(args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.log(ErrorLevel, fmt.Sprint(args...))\n\t}\n}\n\nfunc (entry *Entry) Fatal(args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.log(FatalLevel, fmt.Sprint(args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panic(args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.log(PanicLevel, fmt.Sprint(args...))\n\t}\n\tpanic(fmt.Sprint(args...))\n}\n\n\/\/ Entry Printf family functions\n\nfunc (entry *Entry) Debugf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.Debug(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Infof(format string, args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.Info(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Printf(format string, args ...interface{}) {\n\tentry.Infof(format, args...)\n}\n\nfunc (entry *Entry) Warnf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.Warn(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Warningf(format string, args ...interface{}) {\n\tentry.Warnf(format, args...)\n}\n\nfunc (entry *Entry) Errorf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.Error(fmt.Sprintf(format, args...))\n\t}\n}\n\nfunc (entry *Entry) Fatalf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.Fatal(fmt.Sprintf(format, args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panicf(format string, args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.Panic(fmt.Sprintf(format, args...))\n\t}\n}\n\n\/\/ Entry Println family functions\n\nfunc (entry *Entry) Debugln(args ...interface{}) {\n\tif entry.Logger.Level >= DebugLevel {\n\t\tentry.Debug(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Infoln(args ...interface{}) {\n\tif entry.Logger.Level >= InfoLevel {\n\t\tentry.Info(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Println(args ...interface{}) {\n\tentry.Infoln(args...)\n}\n\nfunc (entry *Entry) Warnln(args ...interface{}) {\n\tif entry.Logger.Level >= WarnLevel {\n\t\tentry.Warn(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Warningln(args ...interface{}) {\n\tentry.Warnln(args...)\n}\n\nfunc (entry *Entry) Errorln(args ...interface{}) {\n\tif entry.Logger.Level >= ErrorLevel {\n\t\tentry.Error(entry.sprintlnn(args...))\n\t}\n}\n\nfunc (entry *Entry) Fatalln(args ...interface{}) {\n\tif entry.Logger.Level >= FatalLevel {\n\t\tentry.Fatal(entry.sprintlnn(args...))\n\t}\n\tExit(1)\n}\n\nfunc (entry *Entry) Panicln(args ...interface{}) {\n\tif entry.Logger.Level >= PanicLevel {\n\t\tentry.Panic(entry.sprintlnn(args...))\n\t}\n}\n\n\/\/ Sprintlnn => Sprint no newline. This is to get the behavior of how\n\/\/ fmt.Sprintln where spaces are always added between operands, regardless of\n\/\/ their type. Instead of vendoring the Sprintln implementation to spare a\n\/\/ string allocation, we do the simplest thing.\nfunc (entry *Entry) sprintlnn(args ...interface{}) string {\n\tmsg := fmt.Sprintln(args...)\n\treturn msg[:len(msg)-1]\n}\n<|endoftext|>"}
{"text":"<commit_before>package otto\n\nimport (\n\t\"fmt\"\n\t\"errors\"\n)\n\ntype _error struct {\n\tName string\n\tMessage string\n\n\tLine int \/\/ Hackish -- line where the error\/exception occurred\n}\n\nvar messageDetail map[string]string = map[string]string{\n\t\"notDefined\": \"%v is not defined\",\n}\n\nfunc messageFromDescription(description string, argumentList... interface{}) string {\n\tmessage := messageDetail[description]\n\tif message == \"\" {\n\t\tmessage = description\n\t}\n\tmessage = fmt.Sprintf(message, argumentList...)\n\treturn message\n}\n\nfunc (self _error) MessageValue() Value {\n\tif self.Message == \"\" {\n\t\treturn UndefinedValue()\n\t}\n\treturn toValue(self.Message)\n}\n\nfunc (self _error) String() string {\n\tif len(self.Name) == 0 {\n\t\treturn self.Message\n\t}\n\tif len(self.Message) == 0 {\n\t\treturn self.Name\n\t}\n\treturn fmt.Sprintf(\"%s: %s\", self.Name, self.Message)\n}\n\nfunc newError(name string, argumentList... interface{}) _error {\n\tdescription := \"\"\n\tvar node _node = nil\n\tlength := len(argumentList)\n\tif length > 0 {\n\t\tif node, _ = argumentList[length-1].(_node); node != nil  || argumentList[length-1] == nil {\n\t\t\targumentList = argumentList[0:length-1]\n\t\t\tlength -= 1\n\t\t}\n\t\tif length > 0 {\n\t\t\tdescription, argumentList = argumentList[0].(string), argumentList[1:]\n\t\t}\n\t}\n\terror := _error{\n\t\tName: name,\n\t\tMessage: messageFromDescription(description, argumentList...),\n\t\tLine: -1,\n\t}\n\tif node != nil {\n\t\terror.Line = node.position()\n\t}\n\treturn error\n}\n\nfunc newReferenceError(argumentList... interface{}) _error {\n\treturn newError(\"ReferenceError\", argumentList...)\n}\n\nfunc newTypeError(argumentList... interface{}) _error {\n\treturn newError(\"TypeError\", argumentList...)\n}\n\nfunc newRangeError(argumentList... interface{}) _error {\n\treturn newError(\"RangeError\", argumentList...)\n}\n\nfunc newSyntaxError(argumentList... interface{}) _error {\n\treturn newError(\"URIError\", argumentList...)\n}\n\nfunc newURIError(argumentList... interface{}) _error {\n\treturn newError(\"URIError\", argumentList...)\n}\n\nfunc typeErrorResult(throw bool) bool {\n\tif throw {\n\t\tpanic(newTypeError())\n\t}\n\treturn false\n}\n\nfunc catchPanic(function func()) (err error) {\n\tdefer func(){\n\t\tif caught := recover(); caught != nil {\n\t\t\tswitch caught := caught.(type) {\n\t\t\tcase _syntaxError:\n\t\t\t\terr = errors.New(caught.String())\n\t\t\t\treturn\n\t\t\tcase _error:\n\t\t\t\tif caught.Line == -1 {\n\t\t\t\t\terr = errors.New(caught.String())\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ We're 0-based (for now), hence the + 1\n\t\t\t\t\terr = errors.New(fmt.Sprintf(\"%s (line %d)\", caught.String(), caught.Line + 1))\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase _result:\n\t\t\t\tif caught.Kind == resultThrow {\n\t\t\t\t\terr = errors.New(toString(caught.Value))\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO Report this better\n\t\t\t\t\terr = errors.New(\"Here be dragons!\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(caught)\n\t\t}\n\t}()\n\tfunction()\n\treturn nil\n}\n\n\/\/ SyntaxError\n\ntype _syntaxError struct {\n\tMessage string\n\tLine int\n\tColumn int\n\tCharacter int\n}\n\nfunc (self _syntaxError) String() string {\n\tname := \"SyntaxError\"\n\tif len(self.Message) == 0 {\n\t\treturn name\n\t}\n\treturn fmt.Sprintf(\"%s: %s\", name, self.Message)\n}\n\nfunc (self _token) newSyntaxError(description string, argumentList... interface{}) *_syntaxError {\n\treturn &_syntaxError{\n\t\tMessage: messageFromDescription(description, argumentList...),\n\t\tLine: self.Line,\n\t\tColumn: self.Column,\n\t\tCharacter: self.Character,\n\t}\n}\n<commit_msg>Catch *_syntaxError<commit_after>package otto\n\nimport (\n\t\"fmt\"\n\t\"errors\"\n)\n\ntype _error struct {\n\tName string\n\tMessage string\n\n\tLine int \/\/ Hackish -- line where the error\/exception occurred\n}\n\nvar messageDetail map[string]string = map[string]string{\n\t\"notDefined\": \"%v is not defined\",\n}\n\nfunc messageFromDescription(description string, argumentList... interface{}) string {\n\tmessage := messageDetail[description]\n\tif message == \"\" {\n\t\tmessage = description\n\t}\n\tmessage = fmt.Sprintf(message, argumentList...)\n\treturn message\n}\n\nfunc (self _error) MessageValue() Value {\n\tif self.Message == \"\" {\n\t\treturn UndefinedValue()\n\t}\n\treturn toValue(self.Message)\n}\n\nfunc (self _error) String() string {\n\tif len(self.Name) == 0 {\n\t\treturn self.Message\n\t}\n\tif len(self.Message) == 0 {\n\t\treturn self.Name\n\t}\n\treturn fmt.Sprintf(\"%s: %s\", self.Name, self.Message)\n}\n\nfunc newError(name string, argumentList... interface{}) _error {\n\tdescription := \"\"\n\tvar node _node = nil\n\tlength := len(argumentList)\n\tif length > 0 {\n\t\tif node, _ = argumentList[length-1].(_node); node != nil  || argumentList[length-1] == nil {\n\t\t\targumentList = argumentList[0:length-1]\n\t\t\tlength -= 1\n\t\t}\n\t\tif length > 0 {\n\t\t\tdescription, argumentList = argumentList[0].(string), argumentList[1:]\n\t\t}\n\t}\n\terror := _error{\n\t\tName: name,\n\t\tMessage: messageFromDescription(description, argumentList...),\n\t\tLine: -1,\n\t}\n\tif node != nil {\n\t\terror.Line = node.position()\n\t}\n\treturn error\n}\n\nfunc newReferenceError(argumentList... interface{}) _error {\n\treturn newError(\"ReferenceError\", argumentList...)\n}\n\nfunc newTypeError(argumentList... interface{}) _error {\n\treturn newError(\"TypeError\", argumentList...)\n}\n\nfunc newRangeError(argumentList... interface{}) _error {\n\treturn newError(\"RangeError\", argumentList...)\n}\n\nfunc newSyntaxError(argumentList... interface{}) _error {\n\treturn newError(\"URIError\", argumentList...)\n}\n\nfunc newURIError(argumentList... interface{}) _error {\n\treturn newError(\"URIError\", argumentList...)\n}\n\nfunc typeErrorResult(throw bool) bool {\n\tif throw {\n\t\tpanic(newTypeError())\n\t}\n\treturn false\n}\n\nfunc catchPanic(function func()) (err error) {\n\tdefer func(){\n\t\tif caught := recover(); caught != nil {\n\t\t\tswitch caught := caught.(type) {\n\t\t\tcase *_syntaxError:\n\t\t\t\terr = errors.New(fmt.Sprintf(\"%s (line %d)\", caught.String(), caught.Line + 0))\n\t\t\t\treturn\n\t\t\tcase _error:\n\t\t\t\tif caught.Line == -1 {\n\t\t\t\t\terr = errors.New(caught.String())\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ We're 0-based (for now), hence the + 1\n\t\t\t\t\terr = errors.New(fmt.Sprintf(\"%s (line %d)\", caught.String(), caught.Line + 1))\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase _result:\n\t\t\t\tif caught.Kind == resultThrow {\n\t\t\t\t\terr = errors.New(toString(caught.Value))\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO Report this better\n\t\t\t\t\terr = errors.New(\"Here be dragons!\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(caught)\n\t\t}\n\t}()\n\tfunction()\n\treturn nil\n}\n\n\/\/ SyntaxError\n\ntype _syntaxError struct {\n\tMessage string\n\tLine int\n\tColumn int\n\tCharacter int\n}\n\nfunc (self _syntaxError) String() string {\n\tname := \"SyntaxError\"\n\tif len(self.Message) == 0 {\n\t\treturn name\n\t}\n\treturn fmt.Sprintf(\"%s: %s\", name, self.Message)\n}\n\nfunc (self _token) newSyntaxError(description string, argumentList... interface{}) *_syntaxError {\n\treturn &_syntaxError{\n\t\tMessage: messageFromDescription(description, argumentList...),\n\t\tLine: self.Line,\n\t\tColumn: self.Column,\n\t\tCharacter: self.Character,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package message\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/mitchellh\/mapstructure\"\n\t\"github.com\/trasa\/watchmud\/direction\"\n\t\"log\"\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ Turn a request of format type \"line\" into a Request message\n\/\/\n\/\/ have an input string like\n\/\/ tell bob hi there\n\/\/ turn into Request = message.TellRequest { \"bob\", \"hi there\" }\n\/\/ and so on.\n\/\/ note that not all commands can be parsed from line input\nfunc TranslateLineToRequest(line string) (request Request, err error) {\n\n\t\/\/ first parse into tokens\n\ttokens := strings.Fields(line)\n\tif len(tokens) == 0 {\n\t\trequest = NoOpRequest{\n\t\t\tRequest: RequestBase{MessageType: \"no_op\"},\n\t\t}\n\t\treturn\n\t}\n\tswitch tokens[0] {\n\tcase \"exits\", \"ex\":\n\t\trequest = ExitsRequest{\n\t\t\tRequest: RequestBase{MessageType: \"exits\"},\n\t\t}\n\tcase \"look\", \"l\":\n\t\trequest = LookRequest{\n\t\t\tRequest:   RequestBase{MessageType: \"look\"},\n\t\t\tValueList: tokens[1:],\n\t\t}\n\tcase \"n\", \"north\", \"s\", \"south\", \"e\", \"east\", \"w\", \"west\", \"u\", \"up\", \"d\", \"down\":\n\t\tvar d direction.Direction\n\t\tif d, err = direction.StringToDirection(tokens[0]); err == nil {\n\t\t\trequest = MoveRequest{\n\t\t\t\tRequest:   RequestBase{MessageType: \"move\"},\n\t\t\t\tDirection: d,\n\t\t\t}\n\t\t}\n\tcase \"'\", \"say\":\n\t\tif len(tokens) >= 2 {\n\t\t\trequest = SayRequest{\n\t\t\t\tRequest: RequestBase{MessageType: \"say\"},\n\t\t\t\tValue:   strings.Join(tokens[1:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"What do you want to say?\")\n\t\t}\n\tcase \"tell\", \"t\":\n\t\tif len(tokens) >= 3 {\n\t\t\trequest = TellRequest{\n\t\t\t\tRequest:            RequestBase{MessageType: \"tell\"},\n\t\t\t\tReceiverPlayerName: tokens[1],\n\t\t\t\tValue:              strings.Join(tokens[2:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ some sort of error about malformed tell request...\n\t\t\terr = errors.New(\"usage: tell [somebody] [something]\")\n\t\t}\n\tcase \"tellall\", \"ta\":\n\t\tif len(tokens) >= 2 {\n\t\t\trequest = TellAllRequest{\n\t\t\t\tRequest: RequestBase{MessageType: \"tell_all\"},\n\t\t\t\tValue:   strings.Join(tokens[1:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"usage: tellall [something]\")\n\t\t}\n\tcase \"who\":\n\t\trequest = WhoRequest{\n\t\t\tRequest: RequestBase{MessageType: \"who\"},\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"Unknown request: \" + tokens[0])\n\t}\n\treturn\n}\n\n\/\/ Turn a request of format type \"request\" into a Request object\nfunc TranslateToRequest(body map[string]interface{}) (request Request, err error) {\n\terr = nil\n\tmsgType := body[\"Request\"].(map[string]interface{})[\"msg_type\"].(string)\n\trequestBase := RequestBase{MessageType: msgType}\n\n\tswitch msgType {\n\tcase \"login\":\n\t\t\/\/{\n\t\t\/\/ \t\"Request\":{\n\t\t\/\/ \t\t\t\"msg_type\":\"login\"\n\t\t\/\/ \t\t},\n\t\t\/\/ \t\"player_name\":\"somedood\",\n\t\t\/\/ \t\"password\":\"NotImplemented\"\n\t\t\/\/ }\n\t\tvar lr LoginRequest\n\t\terr = mapstructure.Decode(body, &lr)\n\t\tlr.Request = requestBase\n\t\trequest = lr\n\n\tcase \"tell\":\n\t\tvar tr TellRequest\n\t\terr = mapstructure.Decode(body, &tr)\n\t\ttr.Request = requestBase\n\t\trequest = tr\n\n\tcase \"tell_all\":\n\t\tvar tar TellAllRequest\n\t\terr = mapstructure.Decode(body, &tar)\n\t\ttar.Request = requestBase\n\t\trequest = tar\n\n\tdefault:\n\t\terr = &UnknownMessageTypeError{MessageType: msgType}\n\t}\n\treturn\n}\n\nfunc TranslateToResponse(raw []byte) (response Response, err error) {\n\tvar rawMap map[string]interface{}\n\tif err = json.Unmarshal(raw, &rawMap); err != nil {\n\t\tlog.Println(\"Unmarshal error: \", err)\n\t\treturn\n\t}\n\tresponseMap := rawMap[\"Response\"].(map[string]interface{})\n\t\/\/noinspection GoNameStartsWithPackageName\n\tmessageType := responseMap[\"msg_type\"].(string)\n\n\tresponseRegistry := map[string]Response{\n\t\t\"say\": &SayResponse{},\n\t}\n\n\tswitch messageType {\n\tcase \"enter_room\":\n\t\tresponse = decodeResponse(&EnterRoomNotification{}, rawMap)\n\n\tcase \"error\":\n\t\tresponse = decodeResponse(&ErrorResponse{}, rawMap)\n\n\tcase \"exits\":\n\t\tresponse = decodeResponse(&ExitsResponse{}, rawMap)\n\n\tcase \"login_response\":\n\t\tresponse = decodeResponse(&LoginResponse{}, rawMap)\n\n\tcase \"look\":\n\t\tresponse = decodeResponse(&LookResponse{}, rawMap)\n\n\tcase \"move\":\n\t\tresponse = decodeResponse(&MoveResponse{}, rawMap)\n\n\tcase \"say\":\n\t\t\/\/ can we get this to work using the existing type from the map?\n\t\tt := responseRegistry[\"say\"]\n\t\tlog.Println(\"t is\", reflect.TypeOf(t))\n\t\t\/\/sr := reflect.ValueOf(t).Interface()\n\t\t\/\/log.Println(\"sr type that i have\", reflect.TypeOf(sr), reflect.TypeOf(&sr))\n\t\t\/\/log.Println(\"what im trying to get\", reflect.TypeOf(&SayResponse{}))\n\t\t\/\/log.Println(\"sr kind\", reflect.TypeOf(sr).Kind())\n\t\tresponse = decodeResponse(t, rawMap)\n\tdefault:\n\t\terr = &UnknownMessageTypeError{MessageType: messageType}\n\t\tlog.Println(\"unknown message type: \", err)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Println(\"Failed to decode rawMap:\", rawMap, err)\n\t\treturn\n\t}\n\tfillResponseBase(response, responseMap)\n\treturn\n}\n\n\/\/ take rawmap and use it to create a Response\nfunc decodeResponse(response interface{}, rawMap map[string]interface{}) Response {\n\t\/\/ decode the map into the response structure\n\tlog.Println(\"response kind\", reflect.TypeOf(response).Kind())\n\tmapstructure.Decode(rawMap, response)\n\treturn response.(Response)\n}\n\n\/\/ set the ResponseBase members (they aren't set through mapstructure.Decode)\nfunc fillResponseBase(response Response, responseMap map[string]interface{}) {\n\t\/\/noinspection GoNameStartsWithPackageName\n\tmessageType := responseMap[\"msg_type\"].(string)\n\treflect.ValueOf(response).Elem().FieldByName(\"Response\").Set(reflect.ValueOf(NewSuccessfulResponse(messageType)))\n\tresponse.SetResultCode(responseMap[\"result_code\"].(string))\n\tresponse.SetSuccessful(responseMap[\"success\"].(bool))\n\tresponse.SetMessageType(responseMap[\"msg_type\"].(string))\n}\n\nfunc TranslateToJson(obj interface{}) (result string, err error) {\n\traw, err := json.Marshal(obj)\n\tresult = string(raw)\n\treturn\n}\n<commit_msg>say decodeResponse works, attempting to fix for the rest now<commit_after>package message\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/mitchellh\/mapstructure\"\n\t\"github.com\/trasa\/watchmud\/direction\"\n\t\"log\"\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ Turn a request of format type \"line\" into a Request message\n\/\/\n\/\/ have an input string like\n\/\/ tell bob hi there\n\/\/ turn into Request = message.TellRequest { \"bob\", \"hi there\" }\n\/\/ and so on.\n\/\/ note that not all commands can be parsed from line input\nfunc TranslateLineToRequest(line string) (request Request, err error) {\n\n\t\/\/ first parse into tokens\n\ttokens := strings.Fields(line)\n\tif len(tokens) == 0 {\n\t\trequest = NoOpRequest{\n\t\t\tRequest: RequestBase{MessageType: \"no_op\"},\n\t\t}\n\t\treturn\n\t}\n\tswitch tokens[0] {\n\tcase \"exits\", \"ex\":\n\t\trequest = ExitsRequest{\n\t\t\tRequest: RequestBase{MessageType: \"exits\"},\n\t\t}\n\tcase \"look\", \"l\":\n\t\trequest = LookRequest{\n\t\t\tRequest:   RequestBase{MessageType: \"look\"},\n\t\t\tValueList: tokens[1:],\n\t\t}\n\tcase \"n\", \"north\", \"s\", \"south\", \"e\", \"east\", \"w\", \"west\", \"u\", \"up\", \"d\", \"down\":\n\t\tvar d direction.Direction\n\t\tif d, err = direction.StringToDirection(tokens[0]); err == nil {\n\t\t\trequest = MoveRequest{\n\t\t\t\tRequest:   RequestBase{MessageType: \"move\"},\n\t\t\t\tDirection: d,\n\t\t\t}\n\t\t}\n\tcase \"'\", \"say\":\n\t\tif len(tokens) >= 2 {\n\t\t\trequest = SayRequest{\n\t\t\t\tRequest: RequestBase{MessageType: \"say\"},\n\t\t\t\tValue:   strings.Join(tokens[1:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"What do you want to say?\")\n\t\t}\n\tcase \"tell\", \"t\":\n\t\tif len(tokens) >= 3 {\n\t\t\trequest = TellRequest{\n\t\t\t\tRequest:            RequestBase{MessageType: \"tell\"},\n\t\t\t\tReceiverPlayerName: tokens[1],\n\t\t\t\tValue:              strings.Join(tokens[2:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ some sort of error about malformed tell request...\n\t\t\terr = errors.New(\"usage: tell [somebody] [something]\")\n\t\t}\n\tcase \"tellall\", \"ta\":\n\t\tif len(tokens) >= 2 {\n\t\t\trequest = TellAllRequest{\n\t\t\t\tRequest: RequestBase{MessageType: \"tell_all\"},\n\t\t\t\tValue:   strings.Join(tokens[1:], \" \"),\n\t\t\t}\n\t\t} else {\n\t\t\terr = errors.New(\"usage: tellall [something]\")\n\t\t}\n\tcase \"who\":\n\t\trequest = WhoRequest{\n\t\t\tRequest: RequestBase{MessageType: \"who\"},\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"Unknown request: \" + tokens[0])\n\t}\n\treturn\n}\n\n\/\/ Turn a request of format type \"request\" into a Request object\nfunc TranslateToRequest(body map[string]interface{}) (request Request, err error) {\n\terr = nil\n\tmsgType := body[\"Request\"].(map[string]interface{})[\"msg_type\"].(string)\n\trequestBase := RequestBase{MessageType: msgType}\n\n\tswitch msgType {\n\tcase \"login\":\n\t\t\/\/{\n\t\t\/\/ \t\"Request\":{\n\t\t\/\/ \t\t\t\"msg_type\":\"login\"\n\t\t\/\/ \t\t},\n\t\t\/\/ \t\"player_name\":\"somedood\",\n\t\t\/\/ \t\"password\":\"NotImplemented\"\n\t\t\/\/ }\n\t\tvar lr LoginRequest\n\t\terr = mapstructure.Decode(body, &lr)\n\t\tlr.Request = requestBase\n\t\trequest = lr\n\n\tcase \"tell\":\n\t\tvar tr TellRequest\n\t\terr = mapstructure.Decode(body, &tr)\n\t\ttr.Request = requestBase\n\t\trequest = tr\n\n\tcase \"tell_all\":\n\t\tvar tar TellAllRequest\n\t\terr = mapstructure.Decode(body, &tar)\n\t\ttar.Request = requestBase\n\t\trequest = tar\n\n\tdefault:\n\t\terr = &UnknownMessageTypeError{MessageType: msgType}\n\t}\n\treturn\n}\n\n\/\/ map messageTypes to pointers to base Response objects\n\/\/ these pointers will be used to create new Responses\n\/\/ (don't use these directly!)\nvar responseRegistry = map[string]Response{\n\t\"say\": &SayResponse{},\n}\n\nfunc TranslateToResponse(raw []byte) (response Response, err error) {\n\tvar rawMap map[string]interface{}\n\tif err = json.Unmarshal(raw, &rawMap); err != nil {\n\t\tlog.Println(\"Unmarshal error: \", err)\n\t\treturn\n\t}\n\tresponseMap := rawMap[\"Response\"].(map[string]interface{})\n\t\/\/noinspection GoNameStartsWithPackageName\n\tmessageType := responseMap[\"msg_type\"].(string)\n\n\tswitch messageType {\n\tcase \"enter_room\":\n\t\tresponse = decodeResponse(&EnterRoomNotification{}, rawMap)\n\n\tcase \"error\":\n\t\tresponse = decodeResponse(&ErrorResponse{}, rawMap)\n\n\tcase \"exits\":\n\t\tresponse = decodeResponse(&ExitsResponse{}, rawMap)\n\n\tcase \"login_response\":\n\t\tresponse = decodeResponse(&LoginResponse{}, rawMap)\n\n\tcase \"look\":\n\t\tresponse = decodeResponse(&LookResponse{}, rawMap)\n\n\tcase \"move\":\n\t\tresponse = decodeResponse(&MoveResponse{}, rawMap)\n\n\tcase \"say\":\n\t\t\/\/ can we get this to work using the existing type from the map?\n\t\tt := responseRegistry[\"say\"]\n\t\tlog.Printf(\"t %s is at addr %p\", reflect.TypeOf(t), t)\n\t\tsr := reflect.New(reflect.TypeOf(t))\n\t\t\/\/sr := reflect.ValueOf(t).Interface()\n\t\tlog.Printf(\"sr type that i have %s - %s at addr %p\", reflect.TypeOf(sr), reflect.TypeOf(&sr), sr)\n\t\tlog.Println(\"what im trying to get\", reflect.TypeOf(&SayResponse{}))\n\t\tlog.Println(\"sr kind\", reflect.TypeOf(sr).Kind())\n\t\tresponse = decodeResponse(t, rawMap)\n\tdefault:\n\t\terr = &UnknownMessageTypeError{MessageType: messageType}\n\t\tlog.Println(\"unknown message type: \", err)\n\t\treturn\n\t}\n\n\tif err != nil {\n\t\tlog.Println(\"Failed to decode rawMap:\", rawMap, err)\n\t\treturn\n\t}\n\tfillResponseBase(response, responseMap)\n\treturn\n}\n\n\/\/ take rawmap and use it to create a Response\nfunc decodeResponse(response interface{}, rawMap map[string]interface{}) Response {\n\t\/\/ decode the map into the response structure\n\tlog.Println(\"response kind\", reflect.TypeOf(response).Kind())\n\tmapstructure.Decode(rawMap, response)\n\treturn response.(Response)\n}\n\n\/\/ set the ResponseBase members (they aren't set through mapstructure.Decode)\nfunc fillResponseBase(response Response, responseMap map[string]interface{}) {\n\t\/\/noinspection GoNameStartsWithPackageName\n\tmessageType := responseMap[\"msg_type\"].(string)\n\treflect.ValueOf(response).Elem().FieldByName(\"Response\").Set(reflect.ValueOf(NewSuccessfulResponse(messageType)))\n\tresponse.SetResultCode(responseMap[\"result_code\"].(string))\n\tresponse.SetSuccessful(responseMap[\"success\"].(bool))\n\tresponse.SetMessageType(responseMap[\"msg_type\"].(string))\n}\n\nfunc TranslateToJson(obj interface{}) (result string, err error) {\n\traw, err := json.Marshal(obj)\n\tresult = string(raw)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package meta\n\n\/\/ VorbisComment contains a list of name\/value-pairs.\n\/\/\n\/\/ ref: https:\/\/www.xiph.org\/flac\/format.html#metadata_block_vorbis_comment\ntype VorbisComment struct {\n\t\/\/ Vendor name.\n\tVendor string\n\t\/\/ Name-value pair tags.\n\tTags []VorbisTag\n}\n\n\/\/ A VorbisTag represents a name\/value-pair.\ntype VorbisTag struct {\n\t\/\/ Tag name.\n\tName string\n\t\/\/ Tag value.\n\tVal string\n}\n<commit_msg>meta: Simplify VorbisComment definition.<commit_after>package meta\n\n\/\/ VorbisComment contains a list of name-value pairs.\n\/\/\n\/\/ ref: https:\/\/www.xiph.org\/flac\/format.html#metadata_block_vorbis_comment\ntype VorbisComment struct {\n\t\/\/ Vendor name.\n\tVendor string\n\t\/\/ A list of tags, each represented by a name-value pair.\n\tTags [][2]string\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\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 AWAY events<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 == 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\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>package marshal\n\nimport (\n\t\/\/\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/xitongsys\/parquet-go\/common\"\n\t\"github.com\/xitongsys\/parquet-go\/layout\"\n\t\"github.com\/xitongsys\/parquet-go\/schema\"\n\t\"github.com\/xitongsys\/parquet-go\/types\"\n\t\"github.com\/xitongsys\/parquet-go\/parquet\"\n)\n\n\/\/Record Map KeyValue pair\ntype KeyValue struct {\n\tKey   reflect.Value\n\tValue reflect.Value\n}\n\ntype MapRecord struct {\n\tKeyValues []KeyValue\n\tIndex     int\n}\n\ntype SliceRecord struct {\n\tValues\t[]reflect.Value\n\tIndex\tint\n}\n\n\/\/Convert the table map to objects slice. desInterface is a slice of pointers of objects\nfunc Unmarshal(tableMap *map[string]*layout.Table, bgn int, end int, dstInterface interface{}, schemaHandler *schema.SchemaHandler, prefixPath string) (err error) {\n\t\/*\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch x := r.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(x)\n\t\t\tcase error:\n\t\t\t\terr = x\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"unknown error\")\n\t\t\t}\n\t\t}\n\t}()\n\t*\/\n\n\ttableNeeds := make(map[string]*layout.Table)\n\ttableBgn, tableEnd := make(map[string]int), make(map[string]int)\n\tfor name, table := range *tableMap {\n\t\tif !strings.HasPrefix(name, prefixPath) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttableNeeds[name] = table\n\n\t\tln := len(table.Values)\n\t\tnum := -1\n\t\ttableBgn[name], tableEnd[name] = -1, -1\n\t\tfor i := 0; i < ln; i++ {\n\t\t\tif table.RepetitionLevels[i] == 0 {\n\t\t\t\tnum++\n\t\t\t\tif num == bgn {\n\t\t\t\t\ttableBgn[name] = i\n\t\t\t\t}\n\t\t\t\tif num == end {\n\t\t\t\t\ttableEnd[name] = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif tableEnd[name] < 0 {\n\t\t\ttableEnd[name] = ln\n\t\t}\n\t\tif tableBgn[name] < 0 {\n\t\t\treturn\n\t\t}\n\t}\n\n\tmapRecords := make(map[reflect.Value]*MapRecord)\n\tmapRecordsStack := make([]reflect.Value, 0)\n\tsliceRecords := make(map[reflect.Value]*SliceRecord)\n\tsliceRecordsStack := make([]reflect.Value, 0)\n\troot := reflect.ValueOf(dstInterface).Elem()\n\n\tfor name, table := range tableNeeds {\n\t\tpath := table.Path\n\t\tbgn := tableBgn[name]\n\t\tend := tableEnd[name]\n\t\tschemaIndexs := make([]int, len(path))\n\t\tfor i := 0; i< len(path); i++ {\n\t\t\tcurPathStr := common.PathToStr(path[:i + 1])\n\t\t\tschemaIndexs[i] = int(schemaHandler.MapIndex[curPathStr])\n\t\t}\n\n\t\trepetitionLevels, definitionLevels := make([]int32, len(path)), make([]int32, len(path))\n\t\tfor i := 0; i<len(path); i++ {\n\t\t\trepetitionLevels[i], _ = schemaHandler.MaxRepetitionLevel(path[:i+1])\n\t\t\tdefinitionLevels[i], _ = schemaHandler.MaxDefinitionLevel(path[:i+1])\n\t\t}\n\n\t\tfor _, rc := range sliceRecords {\n\t\t\trc.Index = -1\n\t\t}\n\t\tfor _, rc := range mapRecords {\n\t\t\trc.Index = -1\n\t\t}\n\n\t\tfor i := bgn; i < end; i++ {\n\t\t\trl, dl, val := table.RepetitionLevels[i], table.DefinitionLevels[i], table.Values[i]\n\t\t\tpo, index := root, 0\n\t\t\tfor index < len(path) {\n\t\t\t\tschemaIndex := schemaIndexs[index]\n\t\t\t\tpT, cT := schemaHandler.SchemaElements[schemaIndex].Type, schemaHandler.SchemaElements[schemaIndex].ConvertedType\n\n\t\t\t\tif po.Type().Kind() == reflect.Slice && (cT == nil || *cT != parquet.ConvertedType_LIST){\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeSlice(po.Type(), 0, 0))\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := sliceRecords[po]; !ok {\n\t\t\t\t\t\tsliceRecords[po] = &SliceRecord{\n\t\t\t\t\t\t\tValues:\t[]reflect.Value{},\n\t\t\t\t\t\t\tIndex:\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsliceRecordsStack = append(sliceRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || sliceRecords[po].Index < 0 {\n\t\t\t\t\t\tsliceRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif sliceRecords[po].Index >= len(sliceRecords[po].Values) {\n\t\t\t\t\t\tsliceRecords[po].Values = append(sliceRecords[po].Values, reflect.New(po.Type().Elem()).Elem())\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = sliceRecords[po].Values[sliceRecords[po].Index]\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Slice && cT != nil && *cT == parquet.ConvertedType_LIST {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeSlice(po.Type(), 0, 0))\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := sliceRecords[po]; !ok {\n\t\t\t\t\t\tsliceRecords[po] = &SliceRecord{\n\t\t\t\t\t\t\tValues:\t[]reflect.Value{},\n\t\t\t\t\t\t\tIndex:\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsliceRecordsStack = append(sliceRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || sliceRecords[po].Index < 0 {\n\t\t\t\t\t\tsliceRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif sliceRecords[po].Index >= len(sliceRecords[po].Values) {\n\t\t\t\t\t\tsliceRecords[po].Values = append(sliceRecords[po].Values, reflect.New(po.Type().Elem()).Elem())\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = sliceRecords[po].Values[sliceRecords[po].Index]\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Map {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeMap(po.Type()))\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif _, ok := mapRecords[po]; !ok {\n\t\t\t\t\t\tmapRecords[po] = &MapRecord{\n\t\t\t\t\t\t\tKeyValues:\t[]KeyValue{},\n\t\t\t\t\t\t\tIndex:\t\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmapRecordsStack = append(mapRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || mapRecords[po].Index < 0 {\n\t\t\t\t\t\tmapRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif mapRecords[po].Index >= len(mapRecords[po].KeyValues) {\n\t\t\t\t\t\tmapRecords[po].KeyValues = append(mapRecords[po].KeyValues,\n\t\t\t\t\t\t\tKeyValue{\n\t\t\t\t\t\t\t\tKey: reflect.New(po.Type().Key()).Elem(),\n\t\t\t\t\t\t\t\tValue: reflect.New(po.Type().Elem()).Elem(),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif path[index + 1] == \"key\" {\n\t\t\t\t\t\tpo = mapRecords[po].KeyValues[mapRecords[po].Index].Key\n\n\t\t\t\t\t}else {\n\t\t\t\t\t\tpo = mapRecords[po].KeyValues[mapRecords[po].Index].Value\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Ptr {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.New(po.Type().Elem()))\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = po.Elem()\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Struct {\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpo = po.FieldByName(path[index])\n\n\t\t\t\t} else {\n\t\t\t\t\tpo.Set(reflect.ValueOf(types.ParquetTypeToGoType(val, pT, cT)))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := len(sliceRecordsStack) - 1; i >= 0; i-- {\n\t\tpo := sliceRecordsStack[i]\n\t\tvs := sliceRecords[po]\n\t\tpotmp := reflect.Append(po, vs.Values...)\n\t\tpo.Set(potmp)\n\t}\n\n\tfor i := len(mapRecordsStack) - 1; i >= 0; i-- {\n\t\tpo := mapRecordsStack[i]\n\t\tfor _, kv := range mapRecords[po].KeyValues {\n\t\t\tpo.SetMapIndex(kv.Key, kv.Value)\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>new unmarshal<commit_after>package marshal\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/xitongsys\/parquet-go\/common\"\n\t\"github.com\/xitongsys\/parquet-go\/layout\"\n\t\"github.com\/xitongsys\/parquet-go\/schema\"\n\t\"github.com\/xitongsys\/parquet-go\/types\"\n\t\"github.com\/xitongsys\/parquet-go\/parquet\"\n)\n\n\/\/Record Map KeyValue pair\ntype KeyValue struct {\n\tKey   reflect.Value\n\tValue reflect.Value\n}\n\ntype MapRecord struct {\n\tKeyValues []KeyValue\n\tIndex     int\n}\n\ntype SliceRecord struct {\n\tValues\t[]reflect.Value\n\tIndex\tint\n}\n\n\/\/Convert the table map to objects slice. desInterface is a slice of pointers of objects\nfunc Unmarshal(tableMap *map[string]*layout.Table, bgn int, end int, dstInterface interface{}, schemaHandler *schema.SchemaHandler, prefixPath string) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tswitch x := r.(type) {\n\t\t\tcase string:\n\t\t\t\terr = errors.New(x)\n\t\t\tcase error:\n\t\t\t\terr = x\n\t\t\tdefault:\n\t\t\t\terr = errors.New(\"unknown error\")\n\t\t\t}\n\t\t}\n\t}()\n\n\ttableNeeds := make(map[string]*layout.Table)\n\ttableBgn, tableEnd := make(map[string]int), make(map[string]int)\n\tfor name, table := range *tableMap {\n\t\tif !strings.HasPrefix(name, prefixPath) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttableNeeds[name] = table\n\n\t\tln := len(table.Values)\n\t\tnum := -1\n\t\ttableBgn[name], tableEnd[name] = -1, -1\n\t\tfor i := 0; i < ln; i++ {\n\t\t\tif table.RepetitionLevels[i] == 0 {\n\t\t\t\tnum++\n\t\t\t\tif num == bgn {\n\t\t\t\t\ttableBgn[name] = i\n\t\t\t\t}\n\t\t\t\tif num == end {\n\t\t\t\t\ttableEnd[name] = i\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif tableEnd[name] < 0 {\n\t\t\ttableEnd[name] = ln\n\t\t}\n\t\tif tableBgn[name] < 0 {\n\t\t\treturn\n\t\t}\n\t}\n\n\tmapRecords := make(map[reflect.Value]*MapRecord)\n\tmapRecordsStack := make([]reflect.Value, 0)\n\tsliceRecords := make(map[reflect.Value]*SliceRecord)\n\tsliceRecordsStack := make([]reflect.Value, 0)\n\troot := reflect.ValueOf(dstInterface).Elem()\n\n\tfor name, table := range tableNeeds {\n\t\tpath := table.Path\n\t\tbgn := tableBgn[name]\n\t\tend := tableEnd[name]\n\t\tschemaIndexs := make([]int, len(path))\n\t\tfor i := 0; i< len(path); i++ {\n\t\t\tcurPathStr := common.PathToStr(path[:i + 1])\n\t\t\tschemaIndexs[i] = int(schemaHandler.MapIndex[curPathStr])\n\t\t}\n\n\t\trepetitionLevels, definitionLevels := make([]int32, len(path)), make([]int32, len(path))\n\t\tfor i := 0; i<len(path); i++ {\n\t\t\trepetitionLevels[i], _ = schemaHandler.MaxRepetitionLevel(path[:i+1])\n\t\t\tdefinitionLevels[i], _ = schemaHandler.MaxDefinitionLevel(path[:i+1])\n\t\t}\n\n\t\tfor _, rc := range sliceRecords {\n\t\t\trc.Index = -1\n\t\t}\n\t\tfor _, rc := range mapRecords {\n\t\t\trc.Index = -1\n\t\t}\n\n\t\tfor i := bgn; i < end; i++ {\n\t\t\trl, dl, val := table.RepetitionLevels[i], table.DefinitionLevels[i], table.Values[i]\n\t\t\tpo, index := root, 0\n\t\t\tfor index < len(path) {\n\t\t\t\tschemaIndex := schemaIndexs[index]\n\t\t\t\tpT, cT := schemaHandler.SchemaElements[schemaIndex].Type, schemaHandler.SchemaElements[schemaIndex].ConvertedType\n\n\t\t\t\tif po.Type().Kind() == reflect.Slice && (cT == nil || *cT != parquet.ConvertedType_LIST){\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeSlice(po.Type(), 0, 0))\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := sliceRecords[po]; !ok {\n\t\t\t\t\t\tsliceRecords[po] = &SliceRecord{\n\t\t\t\t\t\t\tValues:\t[]reflect.Value{},\n\t\t\t\t\t\t\tIndex:\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsliceRecordsStack = append(sliceRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || sliceRecords[po].Index < 0 {\n\t\t\t\t\t\tsliceRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif sliceRecords[po].Index >= len(sliceRecords[po].Values) {\n\t\t\t\t\t\tsliceRecords[po].Values = append(sliceRecords[po].Values, reflect.New(po.Type().Elem()).Elem())\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = sliceRecords[po].Values[sliceRecords[po].Index]\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Slice && cT != nil && *cT == parquet.ConvertedType_LIST {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeSlice(po.Type(), 0, 0))\n\t\t\t\t\t}\n\n\t\t\t\t\tif _, ok := sliceRecords[po]; !ok {\n\t\t\t\t\t\tsliceRecords[po] = &SliceRecord{\n\t\t\t\t\t\t\tValues:\t[]reflect.Value{},\n\t\t\t\t\t\t\tIndex:\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsliceRecordsStack = append(sliceRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || sliceRecords[po].Index < 0 {\n\t\t\t\t\t\tsliceRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif sliceRecords[po].Index >= len(sliceRecords[po].Values) {\n\t\t\t\t\t\tsliceRecords[po].Values = append(sliceRecords[po].Values, reflect.New(po.Type().Elem()).Elem())\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = sliceRecords[po].Values[sliceRecords[po].Index]\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Map {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.MakeMap(po.Type()))\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif _, ok := mapRecords[po]; !ok {\n\t\t\t\t\t\tmapRecords[po] = &MapRecord{\n\t\t\t\t\t\t\tKeyValues:\t[]KeyValue{},\n\t\t\t\t\t\t\tIndex:\t\t-1,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmapRecordsStack = append(mapRecordsStack, po)\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif rl == repetitionLevels[index] || mapRecords[po].Index < 0 {\n\t\t\t\t\t\tmapRecords[po].Index++\n\t\t\t\t\t}\n\n\t\t\t\t\tif mapRecords[po].Index >= len(mapRecords[po].KeyValues) {\n\t\t\t\t\t\tmapRecords[po].KeyValues = append(mapRecords[po].KeyValues,\n\t\t\t\t\t\t\tKeyValue{\n\t\t\t\t\t\t\t\tKey: reflect.New(po.Type().Key()).Elem(),\n\t\t\t\t\t\t\t\tValue: reflect.New(po.Type().Elem()).Elem(),\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif path[index + 1] == \"key\" {\n\t\t\t\t\t\tpo = mapRecords[po].KeyValues[mapRecords[po].Index].Key\n\n\t\t\t\t\t}else {\n\t\t\t\t\t\tpo = mapRecords[po].KeyValues[mapRecords[po].Index].Value\n\t\t\t\t\t}\n\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Ptr {\n\t\t\t\t\tif po.IsNil() {\n\t\t\t\t\t\tpo.Set(reflect.New(po.Type().Elem()))\n\t\t\t\t\t}\n\n\t\t\t\t\tpo = po.Elem()\n\n\t\t\t\t} else if po.Type().Kind() == reflect.Struct {\n\t\t\t\t\tindex++\n\t\t\t\t\tif definitionLevels[index] > dl {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tpo = po.FieldByName(path[index])\n\n\t\t\t\t} else {\n\t\t\t\t\tpo.Set(reflect.ValueOf(types.ParquetTypeToGoType(val, pT, cT)))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := len(sliceRecordsStack) - 1; i >= 0; i-- {\n\t\tpo := sliceRecordsStack[i]\n\t\tvs := sliceRecords[po]\n\t\tpotmp := reflect.Append(po, vs.Values...)\n\t\tpo.Set(potmp)\n\t}\n\n\tfor i := len(mapRecordsStack) - 1; i >= 0; i-- {\n\t\tpo := mapRecordsStack[i]\n\t\tfor _, kv := range mapRecords[po].KeyValues {\n\t\t\tpo.SetMapIndex(kv.Key, kv.Value)\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 SteelSeries ApS.  All rights 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 package implements a basic LISP interpretor for embedding in a go program for scripting.\n\/\/ This file contains the built-in primitive functions.\n\npackage golisp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc RegisterSpecialFormPrimitives() {\n\tMakePrimitiveFunction(\"cond\", -1, CondImpl)\n\tMakePrimitiveFunction(\"case\", -1, CaseImpl)\n\tMakePrimitiveFunction(\"if\", -1, IfImpl)\n\tMakePrimitiveFunction(\"lambda\", -1, LambdaImpl)\n\tMakePrimitiveFunction(\"define\", -1, DefineImpl)\n\tMakePrimitiveFunction(\"defmacro\", -1, DefmacroImpl)\n\tMakePrimitiveFunction(\"let\", -1, LetImpl)\n\tMakePrimitiveFunction(\"begin\", -1, BeginImpl)\n\tMakePrimitiveFunction(\"do\", -1, DoImpl)\n\tMakePrimitiveFunction(\"apply\", -1, ApplyImpl)\n\tMakePrimitiveFunction(\"eval\", 1, EvalImpl)\n\tMakePrimitiveFunction(\"->\", -1, ChainImpl)\n\tMakePrimitiveFunction(\"=>\", -1, TapImpl)\n}\n\nfunc CondImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar condition *Data\n\tfor c := args; NotNilP(c); c = Cdr(c) {\n\t\tclause := Car(c)\n\t\tif !PairP(clause) {\n\t\t\terr = errors.New(\"Cond expect a sequence of clauses that are lists\")\n\t\t\treturn\n\t\t}\n\t\tcondition, err = Eval(Car(clause), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif BooleanValue(condition) || StringValue(Car(clause)) == \"else\" {\n\t\t\tfor e := Cdr(clause); NotNilP(e); e = Cdr(e) {\n\t\t\t\tresult, err = Eval(Car(e), env)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc evalList(l *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tfor sexpr := l; NotNilP(sexpr); sexpr = Cdr(sexpr) {\n\t\tresult, err = Eval(Car(sexpr), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc CaseImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar keyValue *Data\n\n\tkeyValue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor clauseCell := Cdr(args); NotNilP(clauseCell); clauseCell = Cdr(clauseCell) {\n\t\tclause := Car(clauseCell)\n\t\tif !PairP(clause) {\n\t\t\terr = errors.New(\"Case requires non-atomic clauses\")\n\t\t\treturn\n\t\t}\n\t\tif ListP(Car(clause)) {\n\t\t\tfor v := Car(clause); NotNilP(v); v = Cdr(v) {\n\t\t\t\tif IsEqual(Car(v), keyValue) {\n\t\t\t\t\treturn evalList(Cdr(clause), env)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if IsEqual(Car(clause), SymbolWithName(\"else\")) {\n\t\t\treturn evalList(Cdr(clause), env)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc IfImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 2 || Length(args) > 3 {\n\t\terr = errors.New(fmt.Sprintf(\"IF requires 2 or 3 arguments. Received %d.\", Length(args)))\n\t\treturn\n\t}\n\n\tc, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tcondition := BooleanValue(c)\n\tthenClause := Second(args)\n\telseClause := Third(args)\n\n\tif condition {\n\t\treturn Eval(thenClause, env)\n\t} else {\n\t\treturn Eval(elseClause, env)\n\t}\n}\n\nfunc LambdaImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tparams := Car(args)\n\tbody := Cdr(args)\n\treturn FunctionWithNameParamsBodyAndParent(\"anonymous\", params, body, env), nil\n}\n\nfunc DefineImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar value *Data\n\tthing := Car(args)\n\tif SymbolP(thing) {\n\t\tvalue, err = Eval(Cadr(args), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else if PairP(thing) {\n\t\tname := Car(thing)\n\t\tparams := Cdr(thing)\n\t\tthing = name\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"Function name has to be a symbol\")\n\t\t\treturn\n\t\t}\n\t\tbody := Cdr(args)\n\t\tvalue = FunctionWithNameParamsBodyAndParent(StringValue(name), params, body, env)\n\t} else {\n\t\terr = errors.New(\"Invalid definition\")\n\t\treturn\n\t}\n\tenv.BindLocallyTo(thing, value)\n\treturn value, nil\n}\n\nfunc DefmacroImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar value *Data\n\tthing := Car(args)\n\tif PairP(thing) {\n\t\tname := Car(thing)\n\t\tparams := Cdr(thing)\n\t\tthing = name\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"Macro name has to be a symbol\")\n\t\t\treturn\n\t\t}\n\t\tbody := Cadr(args)\n\t\tvalue = MacroWithNameParamsBodyAndParent(StringValue(name), params, body, env)\n\t} else {\n\t\terr = errors.New(\"Invalid macro definition\")\n\t\treturn\n\t}\n\tenv.BindLocallyTo(thing, value)\n\treturn value, nil\n}\n\nfunc bindLetLocals(bindingForms *Data, env *SymbolTableFrame) (err error) {\n\tvar name *Data\n\tvar value *Data\n\n\tfor cell := bindingForms; NotNilP(cell); cell = Cdr(cell) {\n\t\tbindingPair := Car(cell)\n\t\tif !PairP(bindingPair) {\n\t\t\terr = errors.New(\"Let requires a list of bindings (with are pairs) as it's first argument\")\n\t\t\treturn\n\t\t}\n\t\tname = Car(bindingPair)\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"First part of a let binding pair must be a symbol\")\n\t\t}\n\t\tvalue, err = Eval(Cadr(bindingPair), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tenv.BindLocallyTo(name, value)\n\t}\n\treturn\n}\n\nfunc LetImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 1 {\n\t\terr = errors.New(\"Let requires at least a list of bindings\")\n\t\treturn\n\t}\n\n\tif !PairP(Car(args)) {\n\t\terr = errors.New(\"Let requires a list of bindings as it's first argument\")\n\t\treturn\n\t}\n\n\tlocalFrame := NewSymbolTableFrameBelow(env)\n\tbindLetLocals(Car(args), localFrame)\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tresult, err = Eval(sexpr, localFrame)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc BeginImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tfor cell := args; NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tresult, err = Eval(sexpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc rebindDoLocals(bindingForms *Data, env *SymbolTableFrame) (err error) {\n\tvar name *Data\n\tvar value *Data\n\n\tfor cell := bindingForms; NotNilP(cell); cell = Cdr(cell) {\n\t\tbindingTuple := Car(cell)\n\t\tname = First(bindingTuple)\n\t\tif NotNilP(Third(bindingTuple)) {\n\t\t\tvalue, err = Eval(Third(bindingTuple), env)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tenv.BindLocallyTo(name, value)\n\t\t}\n\t}\n\treturn\n}\n\nfunc DoImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 2 {\n\t\terr = errors.New(\"Do requires at least a list of bindings and a test clause\")\n\t\treturn\n\t}\n\n\tbindings := Car(args)\n\tif !PairP(bindings) {\n\t\terr = errors.New(\"Do requires a list of bindings as it's first argument\")\n\t\treturn\n\t}\n\n\ttestClause := Cadr(args)\n\tif !PairP(testClause) {\n\t\terr = errors.New(\"Do requires a list as it's second argument\")\n\t\treturn\n\t}\n\n\tlocalFrame := NewSymbolTableFrameBelow(env)\n\tbindLetLocals(bindings, localFrame)\n\n\tbody := Cddr(args)\n\n\tvar shouldExit *Data\n\n\tfor true {\n\t\tshouldExit, err = Eval(Car(testClause), localFrame)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif BooleanValue(shouldExit) {\n\t\t\tfor cell := Cdr(testClause); NotNilP(cell); cell = Cdr(cell) {\n\t\t\t\tsexpr := Car(cell)\n\t\t\t\tresult, err = Eval(sexpr, localFrame)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tfor cell := body; NotNilP(cell); cell = Cdr(cell) {\n\t\t\tsexpr := Car(cell)\n\t\t\tresult, err = Eval(sexpr, localFrame)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\trebindDoLocals(bindings, localFrame)\n\t}\n\treturn\n}\n\nfunc ApplyImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 1 {\n\t\terr = errors.New(\"apply requires at least one argument\")\n\t\treturn\n\t}\n\n\tf, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !FunctionP(f) {\n\t\terr = errors.New(fmt.Sprintf(\"apply requires a function as it's first argument, but got %s.\", String(f)))\n\t}\n\n\tary := make([]*Data, 0, Length(args)-1)\n\n\tvar v *Data\n\tfor c := Cdr(args); NotNilP(c); c = Cdr(c) {\n\t\tv, err = Eval(Car(c), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tary = append(ary, v)\n\t}\n\n\tvar argList *Data\n\tif ListP(ary[len(ary)-1]) {\n\t\tif len(ary) > 1 {\n\t\t\targList = ArrayToListWithTail(ary[0:len(ary)-1], ary[len(ary)-1])\n\t\t} else {\n\t\t\targList = ary[0]\n\t\t}\n\t} else {\n\t\terr = errors.New(\"The last argument to apply must be a list\")\n\t\treturn\n\t}\n\n\treturn Apply(f, argList, env)\n}\n\nfunc EvalImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tsexpr, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tif !ListP(sexpr) {\n\t\terr = errors.New(fmt.Sprintf(\"eval expect a list argument, received a %s.\", TypeName(TypeOf(sexpr))))\n\t}\n\treturn Eval(sexpr, env)\n}\n\nfunc ChainImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) == 0 {\n\t\terr = errors.New(\"-> requires at least an initial value.\")\n\t\treturn\n\t}\n\n\tvar value *Data\n\n\tvalue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tvar newExpr *Data\n\t\tif ListP(sexpr) {\n\t\t\tnewExpr = Cons(Car(sexpr), Cons(value, Cdr(sexpr)))\n\t\t} else {\n\t\t\tnewExpr = Cons(sexpr, Cons(value, nil))\n\t\t}\n\t\tvalue, err = Eval(newExpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tresult = value\n\treturn\n}\n\nfunc TapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) == 0 {\n\t\terr = errors.New(\"tap requires at least an initial value.\")\n\t\treturn\n\t}\n\n\tvar value *Data\n\n\tvalue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = value\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tvar newExpr *Data\n\t\tif ListP(sexpr) {\n\t\t\tnewExpr = Cons(Car(sexpr), Cons(value, Cdr(sexpr)))\n\t\t} else {\n\t\t\tnewExpr = Cons(sexpr, Cons(value, nil))\n\t\t}\n\t\t_, err = Eval(newExpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Added prim 'code' to get back the code of a function.<commit_after>\/\/ Copyright 2014 SteelSeries ApS.  All rights 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 package implements a basic LISP interpretor for embedding in a go program for scripting.\n\/\/ This file contains the built-in primitive functions.\n\npackage golisp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc RegisterSpecialFormPrimitives() {\n\tMakePrimitiveFunction(\"cond\", -1, CondImpl)\n\tMakePrimitiveFunction(\"case\", -1, CaseImpl)\n\tMakePrimitiveFunction(\"if\", -1, IfImpl)\n\tMakePrimitiveFunction(\"lambda\", -1, LambdaImpl)\n\tMakePrimitiveFunction(\"define\", -1, DefineImpl)\n\tMakePrimitiveFunction(\"defmacro\", -1, DefmacroImpl)\n\tMakePrimitiveFunction(\"let\", -1, LetImpl)\n\tMakePrimitiveFunction(\"begin\", -1, BeginImpl)\n\tMakePrimitiveFunction(\"do\", -1, DoImpl)\n\tMakePrimitiveFunction(\"apply\", -1, ApplyImpl)\n\tMakePrimitiveFunction(\"eval\", 1, EvalImpl)\n\tMakePrimitiveFunction(\"->\", -1, ChainImpl)\n\tMakePrimitiveFunction(\"=>\", -1, TapImpl)\n\tMakePrimitiveFunction(\"code\", 1, CodeImpl)\n}\n\nfunc CondImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar condition *Data\n\tfor c := args; NotNilP(c); c = Cdr(c) {\n\t\tclause := Car(c)\n\t\tif !PairP(clause) {\n\t\t\terr = errors.New(\"Cond expect a sequence of clauses that are lists\")\n\t\t\treturn\n\t\t}\n\t\tcondition, err = Eval(Car(clause), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif BooleanValue(condition) || StringValue(Car(clause)) == \"else\" {\n\t\t\tfor e := Cdr(clause); NotNilP(e); e = Cdr(e) {\n\t\t\t\tresult, err = Eval(Car(e), env)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc evalList(l *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tfor sexpr := l; NotNilP(sexpr); sexpr = Cdr(sexpr) {\n\t\tresult, err = Eval(Car(sexpr), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc CaseImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar keyValue *Data\n\n\tkeyValue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor clauseCell := Cdr(args); NotNilP(clauseCell); clauseCell = Cdr(clauseCell) {\n\t\tclause := Car(clauseCell)\n\t\tif !PairP(clause) {\n\t\t\terr = errors.New(\"Case requires non-atomic clauses\")\n\t\t\treturn\n\t\t}\n\t\tif ListP(Car(clause)) {\n\t\t\tfor v := Car(clause); NotNilP(v); v = Cdr(v) {\n\t\t\t\tif IsEqual(Car(v), keyValue) {\n\t\t\t\t\treturn evalList(Cdr(clause), env)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if IsEqual(Car(clause), SymbolWithName(\"else\")) {\n\t\t\treturn evalList(Cdr(clause), env)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc IfImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 2 || Length(args) > 3 {\n\t\terr = errors.New(fmt.Sprintf(\"IF requires 2 or 3 arguments. Received %d.\", Length(args)))\n\t\treturn\n\t}\n\n\tc, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tcondition := BooleanValue(c)\n\tthenClause := Second(args)\n\telseClause := Third(args)\n\n\tif condition {\n\t\treturn Eval(thenClause, env)\n\t} else {\n\t\treturn Eval(elseClause, env)\n\t}\n}\n\nfunc LambdaImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tparams := Car(args)\n\tbody := Cdr(args)\n\treturn FunctionWithNameParamsBodyAndParent(\"anonymous\", params, body, env), nil\n}\n\nfunc DefineImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar value *Data\n\tthing := Car(args)\n\tif SymbolP(thing) {\n\t\tvalue, err = Eval(Cadr(args), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else if PairP(thing) {\n\t\tname := Car(thing)\n\t\tparams := Cdr(thing)\n\t\tthing = name\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"Function name has to be a symbol\")\n\t\t\treturn\n\t\t}\n\t\tbody := Cdr(args)\n\t\tvalue = FunctionWithNameParamsBodyAndParent(StringValue(name), params, body, env)\n\t} else {\n\t\terr = errors.New(\"Invalid definition\")\n\t\treturn\n\t}\n\tenv.BindLocallyTo(thing, value)\n\treturn value, nil\n}\n\nfunc DefmacroImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tvar value *Data\n\tthing := Car(args)\n\tif PairP(thing) {\n\t\tname := Car(thing)\n\t\tparams := Cdr(thing)\n\t\tthing = name\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"Macro name has to be a symbol\")\n\t\t\treturn\n\t\t}\n\t\tbody := Cadr(args)\n\t\tvalue = MacroWithNameParamsBodyAndParent(StringValue(name), params, body, env)\n\t} else {\n\t\terr = errors.New(\"Invalid macro definition\")\n\t\treturn\n\t}\n\tenv.BindLocallyTo(thing, value)\n\treturn value, nil\n}\n\nfunc bindLetLocals(bindingForms *Data, env *SymbolTableFrame) (err error) {\n\tvar name *Data\n\tvar value *Data\n\n\tfor cell := bindingForms; NotNilP(cell); cell = Cdr(cell) {\n\t\tbindingPair := Car(cell)\n\t\tif !PairP(bindingPair) {\n\t\t\terr = errors.New(\"Let requires a list of bindings (with are pairs) as it's first argument\")\n\t\t\treturn\n\t\t}\n\t\tname = Car(bindingPair)\n\t\tif !SymbolP(name) {\n\t\t\terr = errors.New(\"First part of a let binding pair must be a symbol\")\n\t\t}\n\t\tvalue, err = Eval(Cadr(bindingPair), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tenv.BindLocallyTo(name, value)\n\t}\n\treturn\n}\n\nfunc LetImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 1 {\n\t\terr = errors.New(\"Let requires at least a list of bindings\")\n\t\treturn\n\t}\n\n\tif !PairP(Car(args)) {\n\t\terr = errors.New(\"Let requires a list of bindings as it's first argument\")\n\t\treturn\n\t}\n\n\tlocalFrame := NewSymbolTableFrameBelow(env)\n\tbindLetLocals(Car(args), localFrame)\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tresult, err = Eval(sexpr, localFrame)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc BeginImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tfor cell := args; NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tresult, err = Eval(sexpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc rebindDoLocals(bindingForms *Data, env *SymbolTableFrame) (err error) {\n\tvar name *Data\n\tvar value *Data\n\n\tfor cell := bindingForms; NotNilP(cell); cell = Cdr(cell) {\n\t\tbindingTuple := Car(cell)\n\t\tname = First(bindingTuple)\n\t\tif NotNilP(Third(bindingTuple)) {\n\t\t\tvalue, err = Eval(Third(bindingTuple), env)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tenv.BindLocallyTo(name, value)\n\t\t}\n\t}\n\treturn\n}\n\nfunc DoImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 2 {\n\t\terr = errors.New(\"Do requires at least a list of bindings and a test clause\")\n\t\treturn\n\t}\n\n\tbindings := Car(args)\n\tif !PairP(bindings) {\n\t\terr = errors.New(\"Do requires a list of bindings as it's first argument\")\n\t\treturn\n\t}\n\n\ttestClause := Cadr(args)\n\tif !PairP(testClause) {\n\t\terr = errors.New(\"Do requires a list as it's second argument\")\n\t\treturn\n\t}\n\n\tlocalFrame := NewSymbolTableFrameBelow(env)\n\tbindLetLocals(bindings, localFrame)\n\n\tbody := Cddr(args)\n\n\tvar shouldExit *Data\n\n\tfor true {\n\t\tshouldExit, err = Eval(Car(testClause), localFrame)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif BooleanValue(shouldExit) {\n\t\t\tfor cell := Cdr(testClause); NotNilP(cell); cell = Cdr(cell) {\n\t\t\t\tsexpr := Car(cell)\n\t\t\t\tresult, err = Eval(sexpr, localFrame)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tfor cell := body; NotNilP(cell); cell = Cdr(cell) {\n\t\t\tsexpr := Car(cell)\n\t\t\tresult, err = Eval(sexpr, localFrame)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\trebindDoLocals(bindings, localFrame)\n\t}\n\treturn\n}\n\nfunc ApplyImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) < 1 {\n\t\terr = errors.New(\"apply requires at least one argument\")\n\t\treturn\n\t}\n\n\tf, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !FunctionP(f) {\n\t\terr = errors.New(fmt.Sprintf(\"apply requires a function as it's first argument, but got %s.\", String(f)))\n\t}\n\n\tary := make([]*Data, 0, Length(args)-1)\n\n\tvar v *Data\n\tfor c := Cdr(args); NotNilP(c); c = Cdr(c) {\n\t\tv, err = Eval(Car(c), env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tary = append(ary, v)\n\t}\n\n\tvar argList *Data\n\tif ListP(ary[len(ary)-1]) {\n\t\tif len(ary) > 1 {\n\t\t\targList = ArrayToListWithTail(ary[0:len(ary)-1], ary[len(ary)-1])\n\t\t} else {\n\t\t\targList = ary[0]\n\t\t}\n\t} else {\n\t\terr = errors.New(\"The last argument to apply must be a list\")\n\t\treturn\n\t}\n\n\treturn Apply(f, argList, env)\n}\n\nfunc EvalImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tsexpr, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tif !ListP(sexpr) {\n\t\terr = errors.New(fmt.Sprintf(\"eval expect a list argument, received a %s.\", TypeName(TypeOf(sexpr))))\n\t}\n\treturn Eval(sexpr, env)\n}\n\nfunc ChainImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) == 0 {\n\t\terr = errors.New(\"-> requires at least an initial value.\")\n\t\treturn\n\t}\n\n\tvar value *Data\n\n\tvalue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tvar newExpr *Data\n\t\tif ListP(sexpr) {\n\t\t\tnewExpr = Cons(Car(sexpr), Cons(value, Cdr(sexpr)))\n\t\t} else {\n\t\t\tnewExpr = Cons(sexpr, Cons(value, nil))\n\t\t}\n\t\tvalue, err = Eval(newExpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tresult = value\n\treturn\n}\n\nfunc TapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tif Length(args) == 0 {\n\t\terr = errors.New(\"tap requires at least an initial value.\")\n\t\treturn\n\t}\n\n\tvar value *Data\n\n\tvalue, err = Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = value\n\n\tfor cell := Cdr(args); NotNilP(cell); cell = Cdr(cell) {\n\t\tsexpr := Car(cell)\n\t\tvar newExpr *Data\n\t\tif ListP(sexpr) {\n\t\t\tnewExpr = Cons(Car(sexpr), Cons(value, Cdr(sexpr)))\n\t\t} else {\n\t\t\tnewExpr = Cons(sexpr, Cons(value, nil))\n\t\t}\n\t\t_, err = Eval(newExpr, env)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc CodeImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {\n\tf, err := Eval(Car(args), env)\n\tif err != nil {\n\t\treturn\n\t}\n\tif !FunctionP(f) {\n\t\terr = errors.New(fmt.Sprintf(\"code requires a function argument, but received a %s.\", TypeName(TypeOf(f))))\n\t\treturn\n\t}\n\n\tfunction := f.Func\n\treturn Cons(SymbolWithName(\"lambda\"), Cons(function.Params, function.Body)), nil\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 template\n\nimport (\n\t\"bytes\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\ttmplhtml \"html\/template\"\n\ttmpltext \"text\/template\"\n\n\t\"github.com\/prometheus\/common\/model\"\n\n\t\"github.com\/prometheus\/alertmanager\/template\/internal\/deftmpl\"\n\t\"github.com\/prometheus\/alertmanager\/types\"\n)\n\n\/\/ Template bundles a text and a html template instance.\ntype Template struct {\n\ttext *tmpltext.Template\n\thtml *tmplhtml.Template\n\n\tExternalURL *url.URL\n}\n\n\/\/ FromGlobs calls ParseGlob on all path globs provided and returns the\n\/\/ resulting Template.\nfunc FromGlobs(paths ...string) (*Template, error) {\n\tt := &Template{\n\t\ttext: tmpltext.New(\"\").Option(\"missingkey=zero\"),\n\t\thtml: tmplhtml.New(\"\").Option(\"missingkey=zero\"),\n\t}\n\tvar err error\n\n\tt.text = t.text.Funcs(tmpltext.FuncMap(DefaultFuncs))\n\tt.html = t.html.Funcs(tmplhtml.FuncMap(DefaultFuncs))\n\n\tb, err := deftmpl.Asset(\"template\/default.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif t.text, err = t.text.Parse(string(b)); err != nil {\n\t\treturn nil, err\n\t}\n\tif t.html, err = t.html.Parse(string(b)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, tp := range paths {\n\t\t\/\/ ParseGlob in the template packages errors if not at least one file is\n\t\t\/\/ matched. We want to allow empty matches that may be populated later on.\n\t\tp, err := filepath.Glob(tp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(p) > 0 {\n\t\t\tif t.text, err = t.text.ParseGlob(tp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif t.html, err = t.html.ParseGlob(tp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn t, nil\n}\n\n\/\/ ExecuteTextString needs a meaningful doc comment (TODO(fabxc)).\nfunc (t *Template) ExecuteTextString(text string, data interface{}) (string, error) {\n\ttmpl, err := t.text.Clone()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttmpl, err = tmpl.New(\"\").Option(\"missingkey=zero\").Parse(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf, data)\n\treturn buf.String(), err\n}\n\n\/\/ ExecuteHTMLString needs a meaningful doc comment (TODO(fabxc)).\nfunc (t *Template) ExecuteHTMLString(html string, data interface{}) (string, error) {\n\ttmpl, err := t.html.Clone()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttmpl, err = tmpl.New(\"\").Option(\"missingkey=zero\").Parse(html)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf, data)\n\treturn buf.String(), err\n}\n\ntype FuncMap map[string]interface{}\n\nvar DefaultFuncs = FuncMap{\n\t\"toUpper\": strings.ToUpper,\n\t\"toLower\": strings.ToLower,\n\t\"title\":   strings.Title,\n\t\/\/ join is equal to strings.Join but inverts the argument order\n\t\/\/ for easier pipelining in templates.\n\t\"join\": func(sep string, s []string) string {\n\t\treturn strings.Join(s, sep)\n\t},\n}\n\n\/\/ Pair is a key\/value string pair.\ntype Pair struct {\n\tName, Value string\n}\n\n\/\/ Pairs is a list of key\/value string pairs.\ntype Pairs []Pair\n\n\/\/ Names returns a list of names of the pairs.\nfunc (ps Pairs) Names() []string {\n\tns := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\tns = append(ns, p.Name)\n\t}\n\treturn ns\n}\n\n\/\/ Values returns a list of values of the pairs.\nfunc (ps Pairs) Values() []string {\n\tvs := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\tvs = append(vs, p.Value)\n\t}\n\treturn vs\n}\n\n\/\/ KV is a set of key\/value string pairs.\ntype KV map[string]string\n\n\/\/ SortedPairs returns a sorted list of key\/value pairs.\nfunc (kv KV) SortedPairs() Pairs {\n\tvar (\n\t\tpairs     = make([]Pair, 0, len(kv))\n\t\tkeys      = make([]string, 0, len(kv))\n\t\tsortStart = 0\n\t)\n\tfor k := range kv {\n\t\tif k == string(model.AlertNameLabel) {\n\t\t\tkeys = append([]string{k}, keys...)\n\t\t\tsortStart = 1\n\t\t} else {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t}\n\tsort.Strings(keys[sortStart:])\n\n\tfor _, k := range keys {\n\t\tpairs = append(pairs, Pair{k, kv[k]})\n\t}\n\treturn pairs\n}\n\n\/\/ Remove returns a copy of the key\/value set without the given keys.\nfunc (kv KV) Remove(keys []string) KV {\n\tkeySet := make(map[string]struct{}, len(keys))\n\tfor _, k := range keys {\n\t\tkeySet[k] = struct{}{}\n\t}\n\n\tres := KV{}\n\tfor k, v := range kv {\n\t\tif _, ok := keySet[k]; !ok {\n\t\t\tres[k] = v\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Names returns the names of the label names in the LabelSet.\nfunc (kv KV) Names() []string {\n\treturn kv.SortedPairs().Names()\n}\n\n\/\/ Values returns a list of the values in the LabelSet.\nfunc (kv KV) Values() []string {\n\treturn kv.SortedPairs().Values()\n}\n\n\/\/ Data is the data passed to notification templates and webhook pushes.\n\/\/\n\/\/ End-users should not be exposed to Go's type system, as this will confuse them and prevent\n\/\/ simple things like simple equality checks to fail. Map everything to float64\/string.\ntype Data struct {\n\tReceiver string `json:\"receiver\"`\n\tStatus   string `json:\"status\"`\n\tAlerts   Alerts `json:\"alerts\"`\n\n\tGroupLabels       KV `json:\"groupLabels\"`\n\tCommonLabels      KV `json:\"commonLabels\"`\n\tCommonAnnotations KV `json:\"commonAnnotations\"`\n\n\tExternalURL string `json:\"externalURL\"`\n}\n\n\/\/ Alert holds one alert for notification templates.\ntype Alert struct {\n\tStatus       string `json:\"status\"`\n\tLabels       KV     `json:\"labels\"`\n\tAnnotations  KV     `json:\"annotations\"`\n\tWasSilenced  bool   `json:\"-\"`\n\tWasInhibited bool   `json:\"-\"`\n\tGeneratorURL string `json:\"generatorURL\"`\n}\n\n\/\/ Alerts is a list of Alert objects.\ntype Alerts []Alert\n\n\/\/ Firing returns the subset of alerts that are firing.\nfunc (as Alerts) Firing() []Alert {\n\tres := []Alert{}\n\tfor _, a := range as {\n\t\tif a.Status == string(model.AlertFiring) {\n\t\t\tres = append(res, a)\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Resolved returns the subset of alerts that are resolved.\nfunc (as Alerts) Resolved() []Alert {\n\tres := []Alert{}\n\tfor _, a := range as {\n\t\tif a.Status == string(model.AlertResolved) {\n\t\t\tres = append(res, a)\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Data assembles data for template expansion.\nfunc (t *Template) Data(recv string, groupLabels model.LabelSet, alerts ...*types.Alert) *Data {\n\tdata := &Data{\n\t\tReceiver:          strings.SplitN(recv, \"\/\", 2)[0],\n\t\tStatus:            string(types.Alerts(alerts...).Status()),\n\t\tAlerts:            make(Alerts, 0, len(alerts)),\n\t\tGroupLabels:       KV{},\n\t\tCommonLabels:      KV{},\n\t\tCommonAnnotations: KV{},\n\t\tExternalURL:       t.ExternalURL.String(),\n\t}\n\n\tfor _, a := range alerts {\n\t\talert := Alert{\n\t\t\tStatus:       string(a.Status()),\n\t\t\tLabels:       make(KV, len(a.Labels)),\n\t\t\tAnnotations:  make(KV, len(a.Annotations)),\n\t\t\tWasSilenced:  a.WasSilenced,\n\t\t\tWasInhibited: a.WasInhibited,\n\t\t\tGeneratorURL: a.GeneratorURL,\n\t\t}\n\t\tfor k, v := range a.Labels {\n\t\t\talert.Labels[string(k)] = string(v)\n\t\t}\n\t\tfor k, v := range a.Annotations {\n\t\t\talert.Annotations[string(k)] = string(v)\n\t\t}\n\t\tdata.Alerts = append(data.Alerts, alert)\n\t}\n\n\tfor k, v := range groupLabels {\n\t\tdata.GroupLabels[string(k)] = string(v)\n\t}\n\n\tif len(alerts) >= 1 {\n\t\tvar (\n\t\t\tcommonLabels      = alerts[0].Labels.Clone()\n\t\t\tcommonAnnotations = alerts[0].Annotations.Clone()\n\t\t)\n\t\tfor _, a := range alerts[1:] {\n\t\t\tfor ln, lv := range commonLabels {\n\t\t\t\tif a.Labels[ln] != lv {\n\t\t\t\t\tdelete(commonLabels, ln)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor an, av := range commonAnnotations {\n\t\t\t\tif a.Annotations[an] != av {\n\t\t\t\t\tdelete(commonAnnotations, an)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, v := range commonLabels {\n\t\t\tdata.CommonLabels[string(k)] = string(v)\n\t\t}\n\t\tfor k, v := range commonAnnotations {\n\t\t\tdata.CommonAnnotations[string(k)] = string(v)\n\t\t}\n\t}\n\n\treturn data\n}\n<commit_msg>Expose alert interval in template data<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 template\n\nimport (\n\t\"bytes\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\ttmplhtml \"html\/template\"\n\ttmpltext \"text\/template\"\n\n\t\"github.com\/prometheus\/common\/model\"\n\n\t\"github.com\/prometheus\/alertmanager\/template\/internal\/deftmpl\"\n\t\"github.com\/prometheus\/alertmanager\/types\"\n)\n\n\/\/ Template bundles a text and a html template instance.\ntype Template struct {\n\ttext *tmpltext.Template\n\thtml *tmplhtml.Template\n\n\tExternalURL *url.URL\n}\n\n\/\/ FromGlobs calls ParseGlob on all path globs provided and returns the\n\/\/ resulting Template.\nfunc FromGlobs(paths ...string) (*Template, error) {\n\tt := &Template{\n\t\ttext: tmpltext.New(\"\").Option(\"missingkey=zero\"),\n\t\thtml: tmplhtml.New(\"\").Option(\"missingkey=zero\"),\n\t}\n\tvar err error\n\n\tt.text = t.text.Funcs(tmpltext.FuncMap(DefaultFuncs))\n\tt.html = t.html.Funcs(tmplhtml.FuncMap(DefaultFuncs))\n\n\tb, err := deftmpl.Asset(\"template\/default.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif t.text, err = t.text.Parse(string(b)); err != nil {\n\t\treturn nil, err\n\t}\n\tif t.html, err = t.html.Parse(string(b)); err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, tp := range paths {\n\t\t\/\/ ParseGlob in the template packages errors if not at least one file is\n\t\t\/\/ matched. We want to allow empty matches that may be populated later on.\n\t\tp, err := filepath.Glob(tp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(p) > 0 {\n\t\t\tif t.text, err = t.text.ParseGlob(tp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif t.html, err = t.html.ParseGlob(tp); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn t, nil\n}\n\n\/\/ ExecuteTextString needs a meaningful doc comment (TODO(fabxc)).\nfunc (t *Template) ExecuteTextString(text string, data interface{}) (string, error) {\n\ttmpl, err := t.text.Clone()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttmpl, err = tmpl.New(\"\").Option(\"missingkey=zero\").Parse(text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf, data)\n\treturn buf.String(), err\n}\n\n\/\/ ExecuteHTMLString needs a meaningful doc comment (TODO(fabxc)).\nfunc (t *Template) ExecuteHTMLString(html string, data interface{}) (string, error) {\n\ttmpl, err := t.html.Clone()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttmpl, err = tmpl.New(\"\").Option(\"missingkey=zero\").Parse(html)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = tmpl.Execute(&buf, data)\n\treturn buf.String(), err\n}\n\ntype FuncMap map[string]interface{}\n\nvar DefaultFuncs = FuncMap{\n\t\"toUpper\": strings.ToUpper,\n\t\"toLower\": strings.ToLower,\n\t\"title\":   strings.Title,\n\t\/\/ join is equal to strings.Join but inverts the argument order\n\t\/\/ for easier pipelining in templates.\n\t\"join\": func(sep string, s []string) string {\n\t\treturn strings.Join(s, sep)\n\t},\n}\n\n\/\/ Pair is a key\/value string pair.\ntype Pair struct {\n\tName, Value string\n}\n\n\/\/ Pairs is a list of key\/value string pairs.\ntype Pairs []Pair\n\n\/\/ Names returns a list of names of the pairs.\nfunc (ps Pairs) Names() []string {\n\tns := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\tns = append(ns, p.Name)\n\t}\n\treturn ns\n}\n\n\/\/ Values returns a list of values of the pairs.\nfunc (ps Pairs) Values() []string {\n\tvs := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\tvs = append(vs, p.Value)\n\t}\n\treturn vs\n}\n\n\/\/ KV is a set of key\/value string pairs.\ntype KV map[string]string\n\n\/\/ SortedPairs returns a sorted list of key\/value pairs.\nfunc (kv KV) SortedPairs() Pairs {\n\tvar (\n\t\tpairs     = make([]Pair, 0, len(kv))\n\t\tkeys      = make([]string, 0, len(kv))\n\t\tsortStart = 0\n\t)\n\tfor k := range kv {\n\t\tif k == string(model.AlertNameLabel) {\n\t\t\tkeys = append([]string{k}, keys...)\n\t\t\tsortStart = 1\n\t\t} else {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t}\n\tsort.Strings(keys[sortStart:])\n\n\tfor _, k := range keys {\n\t\tpairs = append(pairs, Pair{k, kv[k]})\n\t}\n\treturn pairs\n}\n\n\/\/ Remove returns a copy of the key\/value set without the given keys.\nfunc (kv KV) Remove(keys []string) KV {\n\tkeySet := make(map[string]struct{}, len(keys))\n\tfor _, k := range keys {\n\t\tkeySet[k] = struct{}{}\n\t}\n\n\tres := KV{}\n\tfor k, v := range kv {\n\t\tif _, ok := keySet[k]; !ok {\n\t\t\tres[k] = v\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Names returns the names of the label names in the LabelSet.\nfunc (kv KV) Names() []string {\n\treturn kv.SortedPairs().Names()\n}\n\n\/\/ Values returns a list of the values in the LabelSet.\nfunc (kv KV) Values() []string {\n\treturn kv.SortedPairs().Values()\n}\n\n\/\/ Data is the data passed to notification templates and webhook pushes.\n\/\/\n\/\/ End-users should not be exposed to Go's type system, as this will confuse them and prevent\n\/\/ simple things like simple equality checks to fail. Map everything to float64\/string.\ntype Data struct {\n\tReceiver string `json:\"receiver\"`\n\tStatus   string `json:\"status\"`\n\tAlerts   Alerts `json:\"alerts\"`\n\n\tGroupLabels       KV `json:\"groupLabels\"`\n\tCommonLabels      KV `json:\"commonLabels\"`\n\tCommonAnnotations KV `json:\"commonAnnotations\"`\n\n\tExternalURL string `json:\"externalURL\"`\n}\n\n\/\/ Alert holds one alert for notification templates.\ntype Alert struct {\n\tStatus       string    `json:\"status\"`\n\tLabels       KV        `json:\"labels\"`\n\tAnnotations  KV        `json:\"annotations\"`\n\tStartsAt     time.Time `json:\"startsAt\"`\n\tEndsAt       time.Time `json:\"endsAt\"`\n\tGeneratorURL string    `json:\"generatorURL\"`\n}\n\n\/\/ Alerts is a list of Alert objects.\ntype Alerts []Alert\n\n\/\/ Firing returns the subset of alerts that are firing.\nfunc (as Alerts) Firing() []Alert {\n\tres := []Alert{}\n\tfor _, a := range as {\n\t\tif a.Status == string(model.AlertFiring) {\n\t\t\tres = append(res, a)\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Resolved returns the subset of alerts that are resolved.\nfunc (as Alerts) Resolved() []Alert {\n\tres := []Alert{}\n\tfor _, a := range as {\n\t\tif a.Status == string(model.AlertResolved) {\n\t\t\tres = append(res, a)\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ Data assembles data for template expansion.\nfunc (t *Template) Data(recv string, groupLabels model.LabelSet, alerts ...*types.Alert) *Data {\n\tdata := &Data{\n\t\tReceiver:          strings.SplitN(recv, \"\/\", 2)[0],\n\t\tStatus:            string(types.Alerts(alerts...).Status()),\n\t\tAlerts:            make(Alerts, 0, len(alerts)),\n\t\tGroupLabels:       KV{},\n\t\tCommonLabels:      KV{},\n\t\tCommonAnnotations: KV{},\n\t\tExternalURL:       t.ExternalURL.String(),\n\t}\n\n\t\/\/ The call to types.Alert is necessary to correctly resolve the internal\n\t\/\/ representation to the user representation.\n\tfor _, a := range types.Alerts(alerts...) {\n\t\talert := Alert{\n\t\t\tStatus:       string(a.Status()),\n\t\t\tLabels:       make(KV, len(a.Labels)),\n\t\t\tAnnotations:  make(KV, len(a.Annotations)),\n\t\t\tStartsAt:     a.StartsAt,\n\t\t\tEndsAt:       a.EndsAt,\n\t\t\tGeneratorURL: a.GeneratorURL,\n\t\t}\n\t\tfor k, v := range a.Labels {\n\t\t\talert.Labels[string(k)] = string(v)\n\t\t}\n\t\tfor k, v := range a.Annotations {\n\t\t\talert.Annotations[string(k)] = string(v)\n\t\t}\n\t\tdata.Alerts = append(data.Alerts, alert)\n\t}\n\n\tfor k, v := range groupLabels {\n\t\tdata.GroupLabels[string(k)] = string(v)\n\t}\n\n\tif len(alerts) >= 1 {\n\t\tvar (\n\t\t\tcommonLabels      = alerts[0].Labels.Clone()\n\t\t\tcommonAnnotations = alerts[0].Annotations.Clone()\n\t\t)\n\t\tfor _, a := range alerts[1:] {\n\t\t\tfor ln, lv := range commonLabels {\n\t\t\t\tif a.Labels[ln] != lv {\n\t\t\t\t\tdelete(commonLabels, ln)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor an, av := range commonAnnotations {\n\t\t\t\tif a.Annotations[an] != av {\n\t\t\t\t\tdelete(commonAnnotations, an)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k, v := range commonLabels {\n\t\t\tdata.CommonLabels[string(k)] = string(v)\n\t\t}\n\t\tfor k, v := range commonAnnotations {\n\t\t\tdata.CommonAnnotations[string(k)] = string(v)\n\t\t}\n\t}\n\n\treturn data\n}\n<|endoftext|>"}
{"text":"<commit_before>package ipvs\n\nimport (\n\t\"net\"\n\t\"syscall\"\n\n\tgipvs \"github.com\/google\/seesaw\/ipvs\"\n\t\"github.com\/luizbafilho\/fusis\/api\/types\"\n)\n\nconst (\n\tNatMode    = gipvs.DFForwardMasq\n\tTunnelMode = gipvs.DFForwardTunnel\n\tRouteMode  = gipvs.DFForwardRoute\n)\n\nfunc stringToIPProto(s string) gipvs.IPProto {\n\tvar value gipvs.IPProto\n\tif s == \"udp\" {\n\t\tvalue = syscall.IPPROTO_UDP\n\t} else {\n\t\tvalue = syscall.IPPROTO_TCP\n\t}\n\n\treturn value\n}\n\nfunc stringToDestinationFlags(s string) gipvs.DestinationFlags {\n\tvar flag gipvs.DestinationFlags\n\n\tswitch s {\n\tcase \"nat\":\n\t\tflag = NatMode\n\tcase \"tunnel\":\n\t\tflag = TunnelMode\n\tdefault:\n\t\t\/\/ Default is Direct Routing\n\t\tflag = RouteMode\n\t}\n\n\treturn flag\n}\n\nfunc ToIpvsService(s *types.Service) *gipvs.Service {\n\tdestinations := []*gipvs.Destination{}\n\n\treturn &gipvs.Service{\n\t\tAddress:      net.ParseIP(s.Host),\n\t\tPort:         s.Port,\n\t\tProtocol:     stringToIPProto(s.Protocol),\n\t\tScheduler:    s.Scheduler,\n\t\tDestinations: destinations,\n\t}\n}\n\nfunc ToIpvsDestination(d *types.Destination) *gipvs.Destination {\n\treturn &gipvs.Destination{\n\t\tAddress: net.ParseIP(d.Host),\n\t\tPort:    d.Port,\n\t\tWeight:  d.Weight,\n\t\tFlags:   stringToDestinationFlags(d.Mode),\n\t}\n}\n<commit_msg>Revert \"ipvs: remove unreferenced code\"<commit_after>package ipvs\n\nimport (\n\t\"net\"\n\t\"syscall\"\n\n\tgipvs \"github.com\/google\/seesaw\/ipvs\"\n\t\"github.com\/luizbafilho\/fusis\/api\/types\"\n)\n\nconst (\n\tNatMode    = gipvs.DFForwardMasq\n\tTunnelMode = gipvs.DFForwardTunnel\n\tRouteMode  = gipvs.DFForwardRoute\n)\n\nfunc stringToIPProto(s string) gipvs.IPProto {\n\tvar value gipvs.IPProto\n\tif s == \"udp\" {\n\t\tvalue = syscall.IPPROTO_UDP\n\t} else {\n\t\tvalue = syscall.IPPROTO_TCP\n\t}\n\n\treturn value\n}\n\n\/\/MarshalJSON ...\nfunc ipProtoToString(proto gipvs.IPProto) string {\n\tvar value string\n\n\tif proto == syscall.IPPROTO_UDP {\n\t\tvalue = \"udp\"\n\t} else {\n\t\tvalue = \"tcp\"\n\t}\n\n\treturn value\n}\n\nfunc stringToDestinationFlags(s string) gipvs.DestinationFlags {\n\tvar flag gipvs.DestinationFlags\n\n\tswitch s {\n\tcase \"nat\":\n\t\tflag = NatMode\n\tcase \"tunnel\":\n\t\tflag = TunnelMode\n\tdefault:\n\t\t\/\/ Default is Direct Routing\n\t\tflag = RouteMode\n\t}\n\n\treturn flag\n}\n\n\/\/MarshalJSON ...\nfunc destinationFlagsToString(flags gipvs.DestinationFlags) string {\n\tvar value string\n\n\tswitch flags {\n\tcase NatMode:\n\t\tvalue = \"nat\"\n\t\t\/\/ *flags =\n\tcase TunnelMode:\n\t\tvalue = \"tunnel\"\n\tdefault:\n\t\t\/\/ Default is Direct Routing\n\t\tvalue = \"route\"\n\t}\n\n\treturn value\n}\n\nfunc ToIpvsService(s *types.Service) *gipvs.Service {\n\tdestinations := []*gipvs.Destination{}\n\n\treturn &gipvs.Service{\n\t\tAddress:      net.ParseIP(s.Host),\n\t\tPort:         s.Port,\n\t\tProtocol:     stringToIPProto(s.Protocol),\n\t\tScheduler:    s.Scheduler,\n\t\tDestinations: destinations,\n\t}\n}\n\nfunc ToIpvsDestination(d *types.Destination) *gipvs.Destination {\n\treturn &gipvs.Destination{\n\t\tAddress: net.ParseIP(d.Host),\n\t\tPort:    d.Port,\n\t\tWeight:  d.Weight,\n\t\tFlags:   stringToDestinationFlags(d.Mode),\n\t}\n}\n\nfunc NewService(s *gipvs.Service) types.Service {\n\tdestinations := []types.Destination{}\n\n\tfor _, dst := range s.Destinations {\n\t\tdestinations = append(destinations, newDestinationRequest(dst))\n\t}\n\n\treturn types.Service{\n\t\tHost:         s.Address.String(),\n\t\tPort:         s.Port,\n\t\tProtocol:     ipProtoToString(s.Protocol),\n\t\tScheduler:    s.Scheduler,\n\t\tDestinations: destinations,\n\t}\n}\n\nfunc newDestinationRequest(d *gipvs.Destination) types.Destination {\n\treturn types.Destination{\n\t\tHost:   d.Address.String(),\n\t\tPort:   d.Port,\n\t\tWeight: d.Weight,\n\t\tMode:   destinationFlagsToString(d.Flags),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package irc\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Register a callback to a connection and event code. A callback is a function\n\/\/ which takes only an Event pointer as parameter. Valid event codes are all\n\/\/ IRC\/CTCP commands and error\/response codes. This function returns the ID of\n\/\/ the registered callback for later management.\nfunc (irc *Connection) AddCallback(eventcode string, callback func(*Event)) int {\n\teventcode = strings.ToUpper(eventcode)\n\tid := 0\n\tif _, ok := irc.events[eventcode]; !ok {\n\t\tirc.events[eventcode] = make(map[int]func(*Event))\n\t\tid = 0\n\t} else {\n\t\tid = len(irc.events[eventcode])\n\t}\n\tirc.events[eventcode][id] = callback\n\treturn id\n}\n\n\/\/ Remove callback i (ID) from the given event code. This functions returns\n\/\/ true upon success, false if any error occurs.\nfunc (irc *Connection) RemoveCallback(eventcode string, i int) bool {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif event, ok := irc.events[eventcode]; ok {\n\t\tif _, ok := event[i]; ok {\n\t\t\tdelete(irc.events[eventcode], i)\n\t\t\treturn true\n\t\t}\n\t\tirc.Log.Printf(\"Event found, but no callback found at id %d\\n\", i)\n\t\treturn false\n\t}\n\n\tirc.Log.Println(\"Event not found\")\n\treturn false\n}\n\n\/\/ Remove all callbacks from a given event code. It returns true\n\/\/ if given event code is found and cleared.\nfunc (irc *Connection) ClearCallback(eventcode string) bool {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif _, ok := irc.events[eventcode]; ok {\n\t\tirc.events[eventcode] = make(map[int]func(*Event))\n\t\treturn true\n\t}\n\n\tirc.Log.Println(\"Event not found\")\n\treturn false\n}\n\n\/\/ Replace callback i (ID) associated with a given event code with a new callback function.\nfunc (irc *Connection) ReplaceCallback(eventcode string, i int, callback func(*Event)) {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif event, ok := irc.events[eventcode]; ok {\n\t\tif _, ok := event[i]; ok {\n\t\t\tevent[i] = callback\n\t\t\treturn\n\t\t}\n\t\tirc.Log.Printf(\"Event found, but no callback found at id %d\\n\", i)\n\t}\n\tirc.Log.Printf(\"Event not found. Use AddCallBack\\n\")\n}\n\n\/\/ Execute all callbacks associated with a given event.\nfunc (irc *Connection) RunCallbacks(event *Event) {\n\tmsg := event.Message()\n\tif event.Code == \"PRIVMSG\" && len(msg) > 2 && msg[0] == '\\x01' {\n\t\tevent.Code = \"CTCP\" \/\/Unknown CTCP\n\n\t\tif i := strings.LastIndex(msg, \"\\x01\"); i > 0 {\n\t\t\tmsg = msg[1:i]\n\t\t} else {\n\t\t\tirc.Log.Printf(\"Invalid CTCP Message: %s\\n\", strconv.Quote(msg))\n\t\t\treturn\n\t\t}\n\n\t\tif msg == \"VERSION\" {\n\t\t\tevent.Code = \"CTCP_VERSION\"\n\n\t\t} else if msg == \"TIME\" {\n\t\t\tevent.Code = \"CTCP_TIME\"\n\n\t\t} else if strings.HasPrefix(msg, \"PING\") {\n\t\t\tevent.Code = \"CTCP_PING\"\n\n\t\t} else if msg == \"USERINFO\" {\n\t\t\tevent.Code = \"CTCP_USERINFO\"\n\n\t\t} else if msg == \"CLIENTINFO\" {\n\t\t\tevent.Code = \"CTCP_CLIENTINFO\"\n\n\t\t} else if strings.HasPrefix(msg, \"ACTION\") {\n\t\t\tevent.Code = \"CTCP_ACTION\"\n\t\t\tif len(msg) > 6 {\n\t\t\t\tmsg = msg[7:]\n\t\t\t} else {\n\t\t\t\tmsg = \"\"\n\t\t\t}\n\t\t}\n\n\t\tevent.Arguments[len(event.Arguments)-1] = msg\n\t}\n\n\tif callbacks, ok := irc.events[event.Code]; ok {\n\t\tif irc.VerboseCallbackHandler {\n\t\t\tirc.Log.Printf(\"%v (%v) >> %#v\\n\", event.Code, len(callbacks), event)\n\t\t}\n\n\t\tfor _, callback := range callbacks {\n\t\t\tcallback(event)\n\t\t}\n\t} else if irc.VerboseCallbackHandler {\n\t\tirc.Log.Printf(\"%v (0) >> %#v\\n\", event.Code, event)\n\t}\n\n\tif callbacks, ok := irc.events[\"*\"]; ok {\n\t\tif irc.VerboseCallbackHandler {\n\t\t\tirc.Log.Printf(\"%v (0) >> %#v\\n\", event.Code, event)\n\t\t}\n\n\t\tfor _, callback := range callbacks {\n\t\t\tcallback(event)\n\t\t}\n\t}\n}\n\n\/\/ Set up some initial callbacks to handle the IRC\/CTCP protocol.\nfunc (irc *Connection) setupCallbacks() {\n\tirc.events = make(map[string]map[int]func(*Event))\n\n\t\/\/Handle error events. This has to be called in a new thred to allow\n\t\/\/readLoop to exit\n\tirc.AddCallback(\"ERROR\", func(e *Event) { irc.Disconnect() })\n\n\t\/\/Handle ping events\n\tirc.AddCallback(\"PING\", func(e *Event) { irc.SendRaw(\"PONG :\" + e.Message()) })\n\n\t\/\/Version handler\n\tirc.AddCallback(\"CTCP_VERSION\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01VERSION %s\\x01\", e.Nick, irc.Version)\n\t})\n\n\tirc.AddCallback(\"CTCP_USERINFO\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01USERINFO %s\\x01\", e.Nick, irc.user)\n\t})\n\n\tirc.AddCallback(\"CTCP_CLIENTINFO\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\\x01\", e.Nick)\n\t})\n\n\tirc.AddCallback(\"CTCP_TIME\", func(e *Event) {\n\t\tltime := time.Now()\n\t\tirc.SendRawf(\"NOTICE %s :\\x01TIME %s\\x01\", e.Nick, ltime.String())\n\t})\n\n\tirc.AddCallback(\"CTCP_PING\", func(e *Event) { irc.SendRawf(\"NOTICE %s :\\x01%s\\x01\", e.Nick, e.Message()) })\n\n\t\/\/ 437: ERR_UNAVAILRESOURCE \"<nick\/channel> :Nick\/channel is temporarily unavailable\"\n\t\/\/ Add a _ to current nick. If irc.nickcurrent is empty this cannot\n\t\/\/ work. It has to be set somewhere first in case the nick is already\n\t\/\/ taken or unavailable from the beginning.\n\tirc.AddCallback(\"437\", func(e *Event) {\n\t\t\/\/ If irc.nickcurrent hasn't been set yet, set to irc.nick\n\t\tif irc.nickcurrent == \"\" {\n\t\t\tirc.nickcurrent = irc.nick\n\t\t}\n\n\t\tif len(irc.nickcurrent) > 8 {\n\t\t\tirc.nickcurrent = \"_\" + irc.nickcurrent\n\t\t} else {\n\t\t\tirc.nickcurrent = irc.nickcurrent + \"_\"\n\t\t}\n\t\tirc.SendRawf(\"NICK %s\", irc.nickcurrent)\n\t})\n\n\t\/\/ 433: ERR_NICKNAMEINUSE \"<nick> :Nickname is already in use\"\n\t\/\/ Add a _ to current nick.\n\tirc.AddCallback(\"433\", func(e *Event) {\n\t\t\/\/ If irc.nickcurrent hasn't been set yet, set to irc.nick\n\t\tif irc.nickcurrent == \"\" {\n\t\t\tirc.nickcurrent = irc.nick\n\t\t}\n\n\t\tif len(irc.nickcurrent) > 8 {\n\t\t\tirc.nickcurrent = \"_\" + irc.nickcurrent\n\t\t} else {\n\t\t\tirc.nickcurrent = irc.nickcurrent + \"_\"\n\t\t}\n\t\tirc.SendRawf(\"NICK %s\", irc.nickcurrent)\n\t})\n\n\tirc.AddCallback(\"PONG\", func(e *Event) {\n\t\tns, _ := strconv.ParseInt(e.Message(), 10, 64)\n\t\tdelta := time.Duration(time.Now().UnixNano() - ns)\n\t\tif irc.Debug {\n\t\t\tirc.Log.Printf(\"Lag: %vs\\n\", delta)\n\t\t}\n\t})\n\n\t\/\/ NICK Define a nickname.\n\t\/\/ Set irc.nickcurrent to the new nick actually used in this connection.\n\tirc.AddCallback(\"NICK\", func(e *Event) {\n\t\tif e.Nick == irc.nick {\n\t\t\tirc.nickcurrent = e.Message()\n\t\t}\n\t})\n\n\t\/\/ 1: RPL_WELCOME \"Welcome to the Internet Relay Network <nick>!<user>@<host>\"\n\t\/\/ Set irc.nickcurrent to the actually used nick in this connection.\n\tirc.AddCallback(\"001\", func(e *Event) {\n\t\tirc.nickcurrent = e.Arguments[0]\n\t})\n}\n<commit_msg>update comment on handling error events<commit_after>package irc\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Register a callback to a connection and event code. A callback is a function\n\/\/ which takes only an Event pointer as parameter. Valid event codes are all\n\/\/ IRC\/CTCP commands and error\/response codes. This function returns the ID of\n\/\/ the registered callback for later management.\nfunc (irc *Connection) AddCallback(eventcode string, callback func(*Event)) int {\n\teventcode = strings.ToUpper(eventcode)\n\tid := 0\n\tif _, ok := irc.events[eventcode]; !ok {\n\t\tirc.events[eventcode] = make(map[int]func(*Event))\n\t\tid = 0\n\t} else {\n\t\tid = len(irc.events[eventcode])\n\t}\n\tirc.events[eventcode][id] = callback\n\treturn id\n}\n\n\/\/ Remove callback i (ID) from the given event code. This functions returns\n\/\/ true upon success, false if any error occurs.\nfunc (irc *Connection) RemoveCallback(eventcode string, i int) bool {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif event, ok := irc.events[eventcode]; ok {\n\t\tif _, ok := event[i]; ok {\n\t\t\tdelete(irc.events[eventcode], i)\n\t\t\treturn true\n\t\t}\n\t\tirc.Log.Printf(\"Event found, but no callback found at id %d\\n\", i)\n\t\treturn false\n\t}\n\n\tirc.Log.Println(\"Event not found\")\n\treturn false\n}\n\n\/\/ Remove all callbacks from a given event code. It returns true\n\/\/ if given event code is found and cleared.\nfunc (irc *Connection) ClearCallback(eventcode string) bool {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif _, ok := irc.events[eventcode]; ok {\n\t\tirc.events[eventcode] = make(map[int]func(*Event))\n\t\treturn true\n\t}\n\n\tirc.Log.Println(\"Event not found\")\n\treturn false\n}\n\n\/\/ Replace callback i (ID) associated with a given event code with a new callback function.\nfunc (irc *Connection) ReplaceCallback(eventcode string, i int, callback func(*Event)) {\n\teventcode = strings.ToUpper(eventcode)\n\n\tif event, ok := irc.events[eventcode]; ok {\n\t\tif _, ok := event[i]; ok {\n\t\t\tevent[i] = callback\n\t\t\treturn\n\t\t}\n\t\tirc.Log.Printf(\"Event found, but no callback found at id %d\\n\", i)\n\t}\n\tirc.Log.Printf(\"Event not found. Use AddCallBack\\n\")\n}\n\n\/\/ Execute all callbacks associated with a given event.\nfunc (irc *Connection) RunCallbacks(event *Event) {\n\tmsg := event.Message()\n\tif event.Code == \"PRIVMSG\" && len(msg) > 2 && msg[0] == '\\x01' {\n\t\tevent.Code = \"CTCP\" \/\/Unknown CTCP\n\n\t\tif i := strings.LastIndex(msg, \"\\x01\"); i > 0 {\n\t\t\tmsg = msg[1:i]\n\t\t} else {\n\t\t\tirc.Log.Printf(\"Invalid CTCP Message: %s\\n\", strconv.Quote(msg))\n\t\t\treturn\n\t\t}\n\n\t\tif msg == \"VERSION\" {\n\t\t\tevent.Code = \"CTCP_VERSION\"\n\n\t\t} else if msg == \"TIME\" {\n\t\t\tevent.Code = \"CTCP_TIME\"\n\n\t\t} else if strings.HasPrefix(msg, \"PING\") {\n\t\t\tevent.Code = \"CTCP_PING\"\n\n\t\t} else if msg == \"USERINFO\" {\n\t\t\tevent.Code = \"CTCP_USERINFO\"\n\n\t\t} else if msg == \"CLIENTINFO\" {\n\t\t\tevent.Code = \"CTCP_CLIENTINFO\"\n\n\t\t} else if strings.HasPrefix(msg, \"ACTION\") {\n\t\t\tevent.Code = \"CTCP_ACTION\"\n\t\t\tif len(msg) > 6 {\n\t\t\t\tmsg = msg[7:]\n\t\t\t} else {\n\t\t\t\tmsg = \"\"\n\t\t\t}\n\t\t}\n\n\t\tevent.Arguments[len(event.Arguments)-1] = msg\n\t}\n\n\tif callbacks, ok := irc.events[event.Code]; ok {\n\t\tif irc.VerboseCallbackHandler {\n\t\t\tirc.Log.Printf(\"%v (%v) >> %#v\\n\", event.Code, len(callbacks), event)\n\t\t}\n\n\t\tfor _, callback := range callbacks {\n\t\t\tcallback(event)\n\t\t}\n\t} else if irc.VerboseCallbackHandler {\n\t\tirc.Log.Printf(\"%v (0) >> %#v\\n\", event.Code, event)\n\t}\n\n\tif callbacks, ok := irc.events[\"*\"]; ok {\n\t\tif irc.VerboseCallbackHandler {\n\t\t\tirc.Log.Printf(\"%v (0) >> %#v\\n\", event.Code, event)\n\t\t}\n\n\t\tfor _, callback := range callbacks {\n\t\t\tcallback(event)\n\t\t}\n\t}\n}\n\n\/\/ Set up some initial callbacks to handle the IRC\/CTCP protocol.\nfunc (irc *Connection) setupCallbacks() {\n\tirc.events = make(map[string]map[int]func(*Event))\n\n\t\/\/Handle error events.\n\tirc.AddCallback(\"ERROR\", func(e *Event) { irc.Disconnect() })\n\n\t\/\/Handle ping events\n\tirc.AddCallback(\"PING\", func(e *Event) { irc.SendRaw(\"PONG :\" + e.Message()) })\n\n\t\/\/Version handler\n\tirc.AddCallback(\"CTCP_VERSION\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01VERSION %s\\x01\", e.Nick, irc.Version)\n\t})\n\n\tirc.AddCallback(\"CTCP_USERINFO\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01USERINFO %s\\x01\", e.Nick, irc.user)\n\t})\n\n\tirc.AddCallback(\"CTCP_CLIENTINFO\", func(e *Event) {\n\t\tirc.SendRawf(\"NOTICE %s :\\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\\x01\", e.Nick)\n\t})\n\n\tirc.AddCallback(\"CTCP_TIME\", func(e *Event) {\n\t\tltime := time.Now()\n\t\tirc.SendRawf(\"NOTICE %s :\\x01TIME %s\\x01\", e.Nick, ltime.String())\n\t})\n\n\tirc.AddCallback(\"CTCP_PING\", func(e *Event) { irc.SendRawf(\"NOTICE %s :\\x01%s\\x01\", e.Nick, e.Message()) })\n\n\t\/\/ 437: ERR_UNAVAILRESOURCE \"<nick\/channel> :Nick\/channel is temporarily unavailable\"\n\t\/\/ Add a _ to current nick. If irc.nickcurrent is empty this cannot\n\t\/\/ work. It has to be set somewhere first in case the nick is already\n\t\/\/ taken or unavailable from the beginning.\n\tirc.AddCallback(\"437\", func(e *Event) {\n\t\t\/\/ If irc.nickcurrent hasn't been set yet, set to irc.nick\n\t\tif irc.nickcurrent == \"\" {\n\t\t\tirc.nickcurrent = irc.nick\n\t\t}\n\n\t\tif len(irc.nickcurrent) > 8 {\n\t\t\tirc.nickcurrent = \"_\" + irc.nickcurrent\n\t\t} else {\n\t\t\tirc.nickcurrent = irc.nickcurrent + \"_\"\n\t\t}\n\t\tirc.SendRawf(\"NICK %s\", irc.nickcurrent)\n\t})\n\n\t\/\/ 433: ERR_NICKNAMEINUSE \"<nick> :Nickname is already in use\"\n\t\/\/ Add a _ to current nick.\n\tirc.AddCallback(\"433\", func(e *Event) {\n\t\t\/\/ If irc.nickcurrent hasn't been set yet, set to irc.nick\n\t\tif irc.nickcurrent == \"\" {\n\t\t\tirc.nickcurrent = irc.nick\n\t\t}\n\n\t\tif len(irc.nickcurrent) > 8 {\n\t\t\tirc.nickcurrent = \"_\" + irc.nickcurrent\n\t\t} else {\n\t\t\tirc.nickcurrent = irc.nickcurrent + \"_\"\n\t\t}\n\t\tirc.SendRawf(\"NICK %s\", irc.nickcurrent)\n\t})\n\n\tirc.AddCallback(\"PONG\", func(e *Event) {\n\t\tns, _ := strconv.ParseInt(e.Message(), 10, 64)\n\t\tdelta := time.Duration(time.Now().UnixNano() - ns)\n\t\tif irc.Debug {\n\t\t\tirc.Log.Printf(\"Lag: %vs\\n\", delta)\n\t\t}\n\t})\n\n\t\/\/ NICK Define a nickname.\n\t\/\/ Set irc.nickcurrent to the new nick actually used in this connection.\n\tirc.AddCallback(\"NICK\", func(e *Event) {\n\t\tif e.Nick == irc.nick {\n\t\t\tirc.nickcurrent = e.Message()\n\t\t}\n\t})\n\n\t\/\/ 1: RPL_WELCOME \"Welcome to the Internet Relay Network <nick>!<user>@<host>\"\n\t\/\/ Set irc.nickcurrent to the actually used nick in this connection.\n\tirc.AddCallback(\"001\", func(e *Event) {\n\t\tirc.nickcurrent = e.Arguments[0]\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package log\n\nimport (\n\t\"fmt\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Fields represents a map of entry level data used for structured logging.\ntype Fields map[string]interface{}\n\n\/\/ Names returns field names sorted.\n\/\/ map is not\nfunc (f Fields) Names() (v []string) {\n\tfor k := range f {\n\t\tv = append(v, k)\n\t}\n\n\tsort.Strings(v)\n\treturn\n}\n\n\/\/ Get field value by name.\nfunc (f Fields) Get(name string) interface{} {\n\treturn f[name]\n}\n\n\/\/ Entry defines a single log entry\ntype Entry struct {\n\tlogger *logger\n\tstart  time.Time\n\tfields []Fields \/\/ private used; store all fields when withFields is called.  improve performance.\n\n\tLevel     Level     `json:\"level\"`\n\tMessage   string    `json:\"message\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tFields    Fields    `json:\"fields\"` \/\/ single map; easy to use for handlers\n}\n\nfunc newEntry(l *logger) Entry {\n\te := Entry{}\n\te.logger = l\n\te.fields = l.defaultFields\n\treturn e\n}\n\n\/\/ Debug level message.\nfunc (e Entry) Debug(msg string) {\n\te.Level = DebugLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Debugf level message.\nfunc (e Entry) Debugf(msg string, v ...interface{}) {\n\te.Level = DebugLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Info level message.\nfunc (e Entry) Info(msg string) {\n\te.Level = InfoLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Infof level message.\nfunc (e Entry) Infof(msg string, v ...interface{}) {\n\te.Level = InfoLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Warn level message.\nfunc (e Entry) Warn(msg string) {\n\te.Level = WarnLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Warnf level message.\nfunc (e Entry) Warnf(msg string, v ...interface{}) {\n\te.Level = WarnLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Error level message.\nfunc (e Entry) Error(msg string) {\n\te.Level = ErrorLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Errorf level message.\nfunc (e Entry) Errorf(msg string, v ...interface{}) {\n\te.Level = ErrorLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Panic level message.\nfunc (e Entry) Panic(msg string) {\n\te.Level = PanicLevel\n\te.Message = msg\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Panicf level message.\nfunc (e Entry) Panicf(msg string, v ...interface{}) {\n\te.Level = PanicLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Fatal level message.\nfunc (e Entry) Fatal(msg string) {\n\te.Level = FatalLevel\n\te.Message = msg\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Fatalf level message.\nfunc (e Entry) Fatalf(msg string, v ...interface{}) {\n\te.Level = FatalLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ WithField returns a new entry with the `key` and `value` set.\nfunc (e Entry) WithField(key string, value interface{}) Entry {\n\treturn e.WithFields(Fields{key: value})\n}\n\n\/\/ WithFields adds the provided fields to the current entry\nfunc (e Entry) WithFields(fields Fields) Entry {\n\t\/\/f := []Fields{}\n\t\/\/f = append(f, e.Fields...)\n\t\/\/f = append(f, fields)\n\n\te.fields = append(e.fields, fields)\n\treturn e\n}\n\n\/\/ WithError returns a new entry with the \"error\" set to `err`.\nfunc (e Entry) WithError(err error) Entry {\n\tif err == nil {\n\t\treturn e\n\t}\n\treturn e.WithField(\"error\", fmt.Sprintf(\"%+v\", err))\n}\n\n\/\/ Trace returns a new entry with a Stop method to fire off\n\/\/ a corresponding completion log, useful with defer.\nfunc (e Entry) Trace(msg string) Entry {\n\te.Message = msg\n\te.start = time.Now().UTC()\n\treturn e\n}\n\n\/\/ mergedFields returns the fields list collapsed into a single map.\nfunc (e Entry) mergedFields() Fields {\n\tf := Fields{}\n\n\tfor _, fields := range e.fields {\n\t\tfor k, v := range fields {\n\t\t\tf[k] = v\n\t\t}\n\t}\n\n\treturn f\n}\n\nconst (\n\tday  = time.Minute * 60 * 24\n\tyear = 365 * day\n)\n\nfunc duration(d time.Duration) string {\n\tif d < day {\n\t\treturn d.String()\n\t}\n\n\tvar b strings.Builder\n\n\tif d >= year {\n\t\tyears := d \/ year\n\t\tfmt.Fprintf(&b, \"%dy\", years)\n\t\td -= years * year\n\t}\n\n\tdays := d \/ day\n\td -= days * day\n\tfmt.Fprintf(&b, \"%dd%s\", days, d)\n\n\treturn b.String()\n}\n\n\/\/ Stop should be used with Trace, to fire off the completion message. When\n\/\/ an `err` is passed the \"error\" field is set, and the log level is error.\nfunc (e Entry) Stop() {\n\te.WithField(\"duration\", duration(time.Since(e.start))).Info(e.Message)\n}\n\nfunc handler(e Entry) {\n\t\/\/ I guess we don't need to lock here and the performance can be improved\n\t\/\/ e.logger.rwMutex.RLock()\n\t\/\/ defer e.logger.rwMutex.RUnlock()\n\n\tvar err error\n\tfor _, h := range e.logger.cacheLeveledHandler(e.Level) {\n\t\te.Timestamp = time.Now().UTC()\n\t\te.Fields = e.mergedFields()\n\t\terr = h.Log(e)\n\t\tif err != nil {\n\t\t\tstdlog.Printf(\"log: log failed: %v\", err)\n\t\t}\n\t}\n}\n<commit_msg>change to use stack memory<commit_after>package log\n\nimport (\n\t\"fmt\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Fields represents a map of entry level data used for structured logging.\ntype Fields map[string]interface{}\n\n\/\/ Names returns field names sorted.\n\/\/ map is not\nfunc (f Fields) Names() (v []string) {\n\tfor k := range f {\n\t\tv = append(v, k)\n\t}\n\n\tsort.Strings(v)\n\treturn\n}\n\n\/\/ Get field value by name.\nfunc (f Fields) Get(name string) interface{} {\n\treturn f[name]\n}\n\n\/\/ Entry defines a single log entry\ntype Entry struct {\n\tlogger *logger\n\tstart  time.Time\n\tfields []Fields \/\/ private used; store all fields when withFields is called.  improve performance.\n\n\tLevel     Level     `json:\"level\"`\n\tMessage   string    `json:\"message\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tFields    Fields    `json:\"fields\"` \/\/ single map; easy to use for handlers\n}\n\nfunc newEntry(l *logger) Entry {\n\te := Entry{}\n\te.logger = l\n\te.fields = l.defaultFields\n\treturn e\n}\n\n\/\/ Debug level message.\nfunc (e Entry) Debug(msg string) {\n\te.Level = DebugLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Debugf level message.\nfunc (e Entry) Debugf(msg string, v ...interface{}) {\n\te.Level = DebugLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Info level message.\nfunc (e Entry) Info(msg string) {\n\te.Level = InfoLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Infof level message.\nfunc (e Entry) Infof(msg string, v ...interface{}) {\n\te.Level = InfoLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Warn level message.\nfunc (e Entry) Warn(msg string) {\n\te.Level = WarnLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Warnf level message.\nfunc (e Entry) Warnf(msg string, v ...interface{}) {\n\te.Level = WarnLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Error level message.\nfunc (e Entry) Error(msg string) {\n\te.Level = ErrorLevel\n\te.Message = msg\n\thandler(e)\n}\n\n\/\/ Errorf level message.\nfunc (e Entry) Errorf(msg string, v ...interface{}) {\n\te.Level = ErrorLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n}\n\n\/\/ Panic level message.\nfunc (e Entry) Panic(msg string) {\n\te.Level = PanicLevel\n\te.Message = msg\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Panicf level message.\nfunc (e Entry) Panicf(msg string, v ...interface{}) {\n\te.Level = PanicLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Fatal level message.\nfunc (e Entry) Fatal(msg string) {\n\te.Level = FatalLevel\n\te.Message = msg\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ Fatalf level message.\nfunc (e Entry) Fatalf(msg string, v ...interface{}) {\n\te.Level = FatalLevel\n\te.Message = fmt.Sprintf(msg, v...)\n\thandler(e)\n\tos.Exit(1)\n}\n\n\/\/ WithField returns a new entry with the `key` and `value` set.\nfunc (e Entry) WithField(key string, value interface{}) Entry {\n\treturn e.WithFields(Fields{key: value})\n}\n\n\/\/ WithFields adds the provided fields to the current entry\nfunc (e Entry) WithFields(fields Fields) Entry {\n\t\/\/f := []Fields{}\n\t\/\/f = append(f, e.Fields...)\n\t\/\/f = append(f, fields)\n\n\te.fields = append(e.fields, fields)\n\treturn e\n}\n\n\/\/ WithError returns a new entry with the \"error\" set to `err`.\nfunc (e Entry) WithError(err error) Entry {\n\tif err == nil {\n\t\treturn e\n\t}\n\treturn e.WithField(\"error\", fmt.Sprintf(\"%+v\", err))\n}\n\n\/\/ Trace returns a new entry with a Stop method to fire off\n\/\/ a corresponding completion log, useful with defer.\nfunc (e Entry) Trace(msg string) Entry {\n\te.Message = msg\n\te.start = time.Now().UTC()\n\treturn e\n}\n\n\/\/ mergedFields returns the fields list collapsed into a single map.\nfunc (e Entry) mergedFields() Fields {\n\tf := Fields{}\n\n\tfor _, fields := range e.fields {\n\t\tfor k, v := range fields {\n\t\t\tf[k] = v\n\t\t}\n\t}\n\n\treturn f\n}\n\nconst (\n\tday  = time.Minute * 60 * 24\n\tyear = 365 * day\n)\n\nfunc duration(d time.Duration) string {\n\tif d < day {\n\t\treturn d.String()\n\t}\n\n\tvar b strings.Builder\n\n\tif d >= year {\n\t\tyears := d \/ year\n\t\tfmt.Fprintf(&b, \"%dy\", years)\n\t\td -= years * year\n\t}\n\n\tdays := d \/ day\n\td -= days * day\n\tfmt.Fprintf(&b, \"%dd%s\", days, d)\n\n\treturn b.String()\n}\n\n\/\/ Stop should be used with Trace, to fire off the completion message. When\n\/\/ an `err` is passed the \"error\" field is set, and the log level is error.\nfunc (e Entry) Stop() {\n\te.WithField(\"duration\", duration(time.Since(e.start))).Info(e.Message)\n}\n\nfunc handler(e Entry) {\n\t\/\/ I guess we don't need to lock here and the performance can be improved\n\t\/\/ e.logger.rwMutex.RLock()\n\t\/\/ defer e.logger.rwMutex.RUnlock()\n\n\tfor _, h := range e.logger.cacheLeveledHandler(e.Level) {\n\t\te.Timestamp = time.Now().UTC()\n\t\te.Fields = e.mergedFields()\n\t\terr := h.Log(e)\n\t\tif err != nil {\n\t\t\tstdlog.Printf(\"log: log failed: %v\", err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package email\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/smtp\"\n\t\"strings\"\n)\n\n\/\/ Message creates a email to be sent\ntype Message struct {\n\tTo      string\n\tFrom    string\n\tSubject string\n\tBody    string\n}\n\nvar (\n\tports = []int{25, 2525, 587}\n)\n\n\/\/ Send sends a message to recipient(s) listed in the 'To' field of a Message\nfunc (m Message) Send() error {\n\tif !strings.Contains(m.To, \"@\") {\n\t\treturn fmt.Errorf(\"Invalid recipient address: <%s>\", m.To)\n\t}\n\n\thost := strings.Split(m.To, \"@\")[1]\n\taddrs, err := net.LookupMX(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := newClient(addrs, ports)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = send(m, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc newClient(mx []*net.MX, ports []int) (*smtp.Client, error) {\n\tfor i := range mx {\n\t\tfor j := range ports {\n\t\t\tserver := strings.TrimSuffix(mx[i].Host, \".\")\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", server, ports[j])\n\t\t\tclient, err := smtp.Dial(hostPort)\n\t\t\tif err != nil {\n\t\t\t\tif j == len(ports)-1 {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn client, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Couldn't connect to servers %v on any common port.\", mx)\n}\n\nfunc send(m Message, c *smtp.Client) error {\n\tif err := c.Mail(m.From); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Rcpt(m.To); err != nil {\n\t\treturn err\n\t}\n\n\tmsg, err := c.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif m.Subject != \"\" {\n\t\t_, err = msg.Write([]byte(\"Subject: \" + m.Subject + \"\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif m.From != \"\" {\n\t\t_, err = msg.Write([]byte(\"From: \" + m.From + \" <\" + m.From + \">\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif m.To != \"\" {\n\t\t_, err = msg.Write([]byte(\"To: \" + m.To + \" <\" + m.To + \">\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = fmt.Fprint(msg, m.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = msg.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Quit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>simplify to\/from to be more compliant with assortment of smtp servers<commit_after>package email\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/smtp\"\n\t\"strings\"\n)\n\n\/\/ Message creates a email to be sent\ntype Message struct {\n\tTo      string\n\tFrom    string\n\tSubject string\n\tBody    string\n}\n\nvar (\n\tports = []int{25, 2525, 587}\n)\n\n\/\/ Send sends a message to recipient(s) listed in the 'To' field of a Message\nfunc (m Message) Send() error {\n\tif !strings.Contains(m.To, \"@\") {\n\t\treturn fmt.Errorf(\"Invalid recipient address: <%s>\", m.To)\n\t}\n\n\thost := strings.Split(m.To, \"@\")[1]\n\taddrs, err := net.LookupMX(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := newClient(addrs, ports)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = send(m, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc newClient(mx []*net.MX, ports []int) (*smtp.Client, error) {\n\tfor i := range mx {\n\t\tfor j := range ports {\n\t\t\tserver := strings.TrimSuffix(mx[i].Host, \".\")\n\t\t\thostPort := fmt.Sprintf(\"%s:%d\", server, ports[j])\n\t\t\tclient, err := smtp.Dial(hostPort)\n\t\t\tif err != nil {\n\t\t\t\tif j == len(ports)-1 {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn client, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Couldn't connect to servers %v on any common port.\", mx)\n}\n\nfunc send(m Message, c *smtp.Client) error {\n\tif err := c.Mail(m.From); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Rcpt(m.To); err != nil {\n\t\treturn err\n\t}\n\n\tmsg, err := c.Data()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif m.Subject != \"\" {\n\t\t_, err = msg.Write([]byte(\"Subject: \" + m.Subject + \"\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif m.From != \"\" {\n\t\t_, err = msg.Write([]byte(\"From: <\" + m.From + \">\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif m.To != \"\" {\n\t\t_, err = msg.Write([]byte(\"To: <\" + m.To + \">\\r\\n\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = fmt.Fprint(msg, m.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = msg.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Quit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\nimport (\n\t\"reflect\"\n\t\"fmt\"\n)\n\ntype Tags map[string]string\n\nfunc (t Tags) Get(name string) string {\n\ttag, ok := t[name]\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"There no tag for %s\", name))\n\t}\n\treturn tag\n}\n\nfunc GetFieldsTag(o interface{}, tagname string) Tags {\n\tst := reflect.TypeOf(o)\n\ttags := make(map[string]string, st.NumField())\t\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield := st.Field(i)\n\t\tvalue := field.Tag.Get(tagname)\n\t\tif value != \"\" {\n\t\t\ttags[field.Name] = value\n\t\t}\n\t}\n\treturn tags\n}\n<commit_msg>Should instansiate with Tags<commit_after>package utils\nimport (\n\t\"reflect\"\n\t\"fmt\"\n)\n\ntype Tags map[string]string\n\nfunc (t Tags) Get(name string) string {\n\ttag, ok := t[name]\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"There no tag for %s\", name))\n\t}\n\treturn tag\n}\n\nfunc GetFieldsTag(o interface{}, tagname string) Tags {\n\tst := reflect.TypeOf(o)\n\ttags := Tags{}\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield := st.Field(i)\n\t\tvalue := field.Tag.Get(tagname)\n\t\tif value != \"\" {\n\t\t\ttags[field.Name] = value\n\t\t}\n\t}\n\treturn tags\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * 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 *\/\n\npackage main\n\n\/* This file will handle all file related business. It will explore the file\n * system for new files and will watch files for changes. In particular, this\n * file is the gate to the files table in the database. Other components (Parser)\n * should rely on this file to know if a file was explored or not. *\/\n\nimport (\n\t\"container\/list\"\n\tfsnotify \"gopkg.in\/fsnotify.v1\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nvar files chan string\nvar wg sync.WaitGroup\nvar watcher *fsnotify.Watcher\nvar writer chan *WriterDB\n\nfunc uptodateFile(file string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(file)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser is not executed\n\t\treturn true\n\t}\n\n\tif exist && uptodate {\n\t\treturn true\n\t} else {\n\t\twr.RemoveFileReferences(file)\n\t\twr.InsertFile(file, fi)\n\t\treturn false\n\t}\n}\n\nfunc processFile(parser *Parser) {\n\twg.Add(1)\n\tdefer wg.Done()\n\n\t\/\/ start exploring files\n\tfor {\n\t\tfile, ok := <-files\n\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif !uptodateFile(file) {\n\t\t\tlog.Println(\"parsing\", file)\n\t\t\tparser.Parse(file)\n\t\t}\n\t}\n}\n\nfunc explorePathToParse(path string,\n\tvisitDir func(string),\n\tvisitC func(string)) *list.List {\n\n\tpath = filepath.Clean(path)\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Println(err, \"opening\", path, \", ignoring\")\n\t\treturn nil\n\t}\n\tdefer f.Close()\n\n\tinfo, err := f.Stat()\n\tif err != nil {\n\t\tlog.Println(err, \"stating\", path, \", ignoring\")\n\t\treturn nil\n\t}\n\n\t\/\/ visit file\n\tif !info.IsDir() {\n\t\t\/\/ ignore non-C files\n\t\tvalidC, _ := regexp.MatchString(`.*\\.c$`, path)\n\t\tif validC {\n\t\t\tvisitC(path)\n\t\t}\n\t\treturn nil\n\t} else {\n\t\tvisitDir(path)\n\t}\n\n\t\/\/ add all the files in the directory to explore\n\tdirFiles, err := f.Readdir(0)\n\tif err != nil {\n\t\tlog.Println(err, \" readdir \", path, \", ignoring\")\n\t\treturn nil\n\t}\n\n\ttoExplore := list.New()\n\tfor _, subf := range dirFiles {\n\t\t\/\/ ignore hidden files\n\t\tif subf.Name()[0] == '.' {\n\t\t\tcontinue\n\t\t}\n\n\t\ttoExplore.PushBack(path + \"\/\" + subf.Name())\n\t}\n\treturn toExplore\n}\n\nfunc traversePath(path string, visitDir func(string), visitC func(string)) {\n\ttoExplore := list.New()\n\ttoExplore.PushBack(path)\n\n\tfor toExplore.Len() > 0 {\n\t\t\/\/ dequeue first path\n\t\tpath := toExplore.Front()\n\t\ttoExplore.Remove(path)\n\n\t\tnewDirs := explorePathToParse(\n\t\t\tpath.Value.(string),\n\t\t\tvisitDir,\n\t\t\tvisitC)\n\t\tif newDirs != nil {\n\t\t\ttoExplore.PushBackList(newDirs)\n\t\t}\n\t}\n}\n\nfunc removeFileAndReparseDepends(file string, db *WriterDB) {\n\tdeps := db.RemoveFileDepsReferences(file)\n\tdb.RemoveFileReferences(file)\n\n\tfor _, d := range deps {\n\t\tfiles <- d\n\t}\n}\n\nfunc handleChange(event fsnotify.Event,\n\twatcher *fsnotify.Watcher,\n\tfiles chan string) {\n\n\tdb := <-writer\n\n\tswitch {\n\tcase event.Op&(fsnotify.Write|fsnotify.Create|fsnotify.Chmod) != 0:\n\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\twatcher.Remove(event.Name)\n\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\t}\n\n\twriter <- db\n}\n\nfunc StartFilesHandler(indexDir []string, nIndexingThreads int, parser *Parser,\n\tdb *DBConnFactory) {\n\n\tfiles = make(chan string, nIndexingThreads)\n\twriter = make(chan *WriterDB, 1)\n\twriter <- db.NewWriter()\n\n\t\/\/ start threads to process files\n\tfor i := 0; i < nIndexingThreads; i++ {\n\t\tgo processFile(parser)\n\t}\n\n\t\/\/ start file watcher\n\twatcher, _ = fsnotify.NewWatcher()\n\tgo func() {\n\t\twg.Add(1)\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thandleChange(event, watcher, files)\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Println(\"watcher error: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ explore all the paths in indexDir and process all files\n\trd := db.NewReader()\n\tremovedFilesSet := rd.GetSetFilesInDB()\n\trd.Close()\n\tvisitorDir := func(path string) {\n\t\t\/\/ add watcher to directory\n\t\twatcher.Add(path)\n\t}\n\tvisitorC := func(path string) {\n\t\t\/\/ update set of removed files\n\t\tdelete(removedFilesSet, path)\n\t\t\/\/ add watcher\n\t\twatcher.Add(path)\n\t\t\/\/ put file in channel\n\t\tfiles <- path\n\t}\n\tfor _, path := range indexDir {\n\t\ttraversePath(path, visitorDir, visitorC)\n\t}\n\n\t\/\/ remove from DB deleted files\n\twr := <-writer\n\tfor path := range removedFilesSet {\n\t\twr.RemoveFileReferences(path)\n\t}\n\twriter <- wr\n}\n\nfunc UpdateDependency(file, dep string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(dep)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser move forward\n\t\treturn true\n\t}\n\n\tif !exist {\n\t\twr.InsertFile(dep, fi)\n\t\twatcher.Add(file)\n\t} else if !uptodate {\n\t\tremoveFileAndReparseDepends(file, wr)\n\t\tfiles <- file\n\t\treturn false\n\t}\n\n\twr.InsertDependency(file, dep)\n\treturn true\n}\n\nfunc CloseFilesHandler() {\n\tclose(files)\n\n\twr := <-writer\n\twr.Close()\n\tclose(writer)\n\n\twatcher.Close()\n\n\twg.Wait()\n}\n<commit_msg>Fixing handling of FS watcher<commit_after>\/*\n * 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 *\/\n\npackage main\n\n\/* This file will handle all file related business. It will explore the file\n * system for new files and will watch files for changes. In particular, this\n * file is the gate to the files table in the database. Other components (Parser)\n * should rely on this file to know if a file was explored or not. *\/\n\nimport (\n\t\"container\/list\"\n\tfsnotify \"gopkg.in\/fsnotify.v1\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nvar files chan string\nvar wg sync.WaitGroup\nvar watcher *fsnotify.Watcher\nvar writer chan *WriterDB\n\nfunc uptodateFile(file string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(file)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser is not executed\n\t\treturn true\n\t}\n\n\tif exist && uptodate {\n\t\treturn true\n\t} else {\n\t\twr.RemoveFileReferences(file)\n\t\twr.InsertFile(file, fi)\n\t\treturn false\n\t}\n}\n\nfunc processFile(parser *Parser) {\n\twg.Add(1)\n\tdefer wg.Done()\n\n\t\/\/ start exploring files\n\tfor {\n\t\tfile, ok := <-files\n\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif !uptodateFile(file) {\n\t\t\tlog.Println(\"parsing\", file)\n\t\t\tparser.Parse(file)\n\t\t}\n\t}\n}\n\nfunc explorePathToParse(path string,\n\tvisitDir func(string),\n\tvisitC func(string)) *list.List {\n\n\tpath = filepath.Clean(path)\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Println(err, \"opening\", path, \", ignoring\")\n\t\treturn nil\n\t}\n\tdefer f.Close()\n\n\tinfo, err := f.Stat()\n\tif err != nil {\n\t\tlog.Println(err, \"stating\", path, \", ignoring\")\n\t\treturn nil\n\t}\n\n\t\/\/ visit file\n\tif !info.IsDir() {\n\t\t\/\/ ignore non-C files\n\t\tvalidC, _ := regexp.MatchString(`.*\\.c$`, path)\n\t\tif validC {\n\t\t\tvisitC(path)\n\t\t}\n\t\treturn nil\n\t} else {\n\t\tvisitDir(path)\n\t}\n\n\t\/\/ add all the files in the directory to explore\n\tdirFiles, err := f.Readdir(0)\n\tif err != nil {\n\t\tlog.Println(err, \" readdir \", path, \", ignoring\")\n\t\treturn nil\n\t}\n\n\ttoExplore := list.New()\n\tfor _, subf := range dirFiles {\n\t\t\/\/ ignore hidden files\n\t\tif subf.Name()[0] == '.' {\n\t\t\tcontinue\n\t\t}\n\n\t\ttoExplore.PushBack(path + \"\/\" + subf.Name())\n\t}\n\treturn toExplore\n}\n\nfunc traversePath(path string, visitDir func(string), visitC func(string)) {\n\ttoExplore := list.New()\n\ttoExplore.PushBack(path)\n\n\tfor toExplore.Len() > 0 {\n\t\t\/\/ dequeue first path\n\t\tpath := toExplore.Front()\n\t\ttoExplore.Remove(path)\n\n\t\tnewDirs := explorePathToParse(\n\t\t\tpath.Value.(string),\n\t\t\tvisitDir,\n\t\t\tvisitC)\n\t\tif newDirs != nil {\n\t\t\ttoExplore.PushBackList(newDirs)\n\t\t}\n\t}\n}\n\nfunc removeFileAndReparseDepends(file string, db *WriterDB) {\n\tdeps := db.RemoveFileDepsReferences(file)\n\tdb.RemoveFileReferences(file)\n\n\tfor _, d := range deps {\n\t\tfiles <- d\n\t}\n}\n\nfunc handleFileChange(event fsnotify.Event) {\n\n\tvalidC, _ := regexp.MatchString(`.*\\.c$`, event.Name)\n\tvalidH, _ := regexp.MatchString(`.*\\.h$`, event.Name)\n\n\tswitch {\n\tcase validC:\n\t\tfiles <- event.Name\n\tcase validH:\n\t\tdb := <-writer\n\t\texist, uptodate, _, err := db.UptodateFile(event.Name)\n\n\t\tif err != nil || (exist && !uptodate) {\n\t\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\t\t}\n\n\t\twriter <- db\n\t}\n}\n\nfunc handleDirChange(event fsnotify.Event) {\n\tswitch {\n\tcase event.Op&(fsnotify.Create) != 0:\n\t\t\/\/ explore the new dir\n\t\tvisitorDir := func(path string) {\n\t\t\t\/\/ add watcher to directory\n\t\t\twatcher.Add(path)\n\t\t}\n\t\tvisitorC := func(path string) {\n\t\t\t\/\/ put file in channel\n\t\t\tfiles <- path\n\t\t}\n\t\ttraversePath(event.Name, visitorDir, visitorC)\n\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\t\/\/ remove watcher from dir\n\t\twatcher.Remove(event.Name)\n\t}\n}\n\nfunc isDirectory(path string) (bool, error) {\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t} else {\n\t\treturn fi.IsDir(), nil\n\t}\n}\n\nfunc handleChange(event fsnotify.Event) {\n\n\t\/\/ ignore if hidden\n\tif filepath.Base(event.Name)[0] == '.' {\n\t\treturn\n\t}\n\n\t\/\/ first, we need to check if the file is a directory or not\n\tisDir, err := isDirectory(event.Name)\n\tif err != nil {\n\t\t\/\/ ignoring this event\n\t\treturn\n\t}\n\n\tif isDir {\n\t\thandleDirChange(event)\n\t} else {\n\t\thandleFileChange(event)\n\t}\n}\n\nfunc StartFilesHandler(indexDir []string, nIndexingThreads int, parser *Parser,\n\tdb *DBConnFactory) {\n\n\tfiles = make(chan string, nIndexingThreads)\n\twriter = make(chan *WriterDB, 1)\n\twriter <- db.NewWriter()\n\n\t\/\/ start threads to process files\n\tfor i := 0; i < nIndexingThreads; i++ {\n\t\tgo processFile(parser)\n\t}\n\n\t\/\/ start file watcher\n\twatcher, _ = fsnotify.NewWatcher()\n\tgo func() {\n\t\twg.Add(1)\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thandleChange(event)\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Println(\"watcher error: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ explore all the paths in indexDir and process all files\n\trd := db.NewReader()\n\tremovedFilesSet := rd.GetSetFilesInDB()\n\trd.Close()\n\tvisitorDir := func(path string) {\n\t\t\/\/ add watcher to directory\n\t\twatcher.Add(path)\n\t}\n\tvisitorC := func(path string) {\n\t\t\/\/ update set of removed files\n\t\tdelete(removedFilesSet, path)\n\t\t\/\/ put file in channel\n\t\tfiles <- path\n\t}\n\tfor _, path := range indexDir {\n\t\ttraversePath(path, visitorDir, visitorC)\n\t}\n\n\t\/\/ remove from DB deleted files\n\twr := <-writer\n\tfor path := range removedFilesSet {\n\t\twr.RemoveFileReferences(path)\n\t}\n\twriter <- wr\n}\n\nfunc UpdateDependency(file, dep string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(dep)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser move forward\n\t\treturn true\n\t}\n\n\tif !exist {\n\t\twr.InsertFile(dep, fi)\n\t} else if !uptodate {\n\t\tremoveFileAndReparseDepends(dep, wr)\n\t\tfiles <- file\n\t\treturn false\n\t}\n\n\twr.InsertDependency(file, dep)\n\treturn true\n}\n\nfunc CloseFilesHandler() {\n\tclose(files)\n\n\twr := <-writer\n\twr.Close()\n\tclose(writer)\n\n\twatcher.Close()\n\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 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 prog\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestRotationRandom(t *testing.T) {\n\ttarget, rs, _ := initTest(t)\n\tfor _, ncalls := range []int{10, 100, 1000, 1e9} {\n\t\tncalls := ncalls\n\t\trnd := rand.New(rand.NewSource(rs.Int63()))\n\t\tt.Run(fmt.Sprint(ncalls), func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tcalls0 := selectCalls(target, rnd, ncalls)\n\t\t\tcalls := MakeRotator(target, calls0, rnd).Select()\n\t\t\tfor call := range calls {\n\t\t\t\tif !calls0[call] {\n\t\t\t\t\tt.Errorf(\"selected disabled syscall %v\", call.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tvar array []*Syscall\n\t\t\tfor call := range calls {\n\t\t\t\tarray = append(array, call)\n\t\t\t}\n\t\t\tsort.Slice(array, func(i, j int) bool {\n\t\t\t\treturn array[i].Name < array[j].Name\n\t\t\t})\n\t\t\tfor _, call := range array {\n\t\t\t\tfmt.Fprintf(buf, \"%v\\n\", call.Name)\n\t\t\t}\n\t\t\tt.Logf(\"calls %v->%v:\\n%s\", len(calls0), len(calls), buf.Bytes())\n\t\t})\n\t}\n}\n\nfunc TestRotationCoverage(t *testing.T) {\n\ttarget, rs, _ := initTest(t)\n\tcalls := make(map[*Syscall]bool)\n\tcounters := make(map[string]int)\n\tfor _, call := range target.Syscalls {\n\t\tcalls[call] = true\n\t\tcounters[call.Name] = 0\n\t}\n\trotator := MakeRotator(target, calls, rand.New(rs))\n\tfor iter := 0; iter < 1e3; iter++ {\n\t\tfor call := range rotator.Select() {\n\t\t\tcounters[call.Name]++\n\t\t}\n\t}\n\ttype pair struct {\n\t\tname  string\n\t\tcount int\n\t}\n\tvar pairs []pair\n\tremain := len(counters)\n\tfor name, count := range counters {\n\t\tpairs = append(pairs, pair{name, count})\n\t\tif count != 0 {\n\t\t\tremain--\n\t\t}\n\t}\n\tsort.Slice(pairs, func(i, j int) bool {\n\t\tif pairs[i].count != pairs[j].count {\n\t\t\treturn pairs[i].count > pairs[j].count\n\t\t}\n\t\treturn pairs[i].name < pairs[j].name\n\t})\n\tfor i, pair := range pairs {\n\t\tt.Logf(\"# %4d: % 4d %v\", i, pair.count, pair.name)\n\t}\n\tif remain != 0 {\n\t\tt.Fatalf(\"uncovered syscalls: %v\", remain)\n\t}\n}\n\nfunc selectCalls(target *Target, rnd *rand.Rand, ncalls int) map[*Syscall]bool {\nretry:\n\tcalls := make(map[*Syscall]bool)\n\tfor _, call := range target.Syscalls {\n\t\tcalls[call] = true\n\t}\n\tfor {\n\t\tfor {\n\t\t\tremove := 0\n\t\t\tswitch {\n\t\t\tcase len(calls) > ncalls+1000:\n\t\t\t\tremove = 100\n\t\t\tcase len(calls) > ncalls+50:\n\t\t\t\tremove = 20\n\t\t\tcase len(calls) > ncalls:\n\t\t\t\tremove = 1\n\t\t\tdefault:\n\t\t\t\treturn calls\n\t\t\t}\n\t\t\tvar array []*Syscall\n\t\t\tfor call := range calls {\n\t\t\t\tarray = append(array, call)\n\t\t\t}\n\t\t\tsort.Slice(array, func(i, j int) bool {\n\t\t\t\treturn array[i].ID < array[j].ID\n\t\t\t})\n\t\t\trnd.Shuffle(len(calls), func(i, j int) {\n\t\t\t\tarray[i], array[j] = array[j], array[i]\n\t\t\t})\n\t\t\tfor _, call := range array[:remove] {\n\t\t\t\tdelete(calls, call)\n\t\t\t}\n\t\t\tcalls, _ = target.transitivelyEnabled(calls)\n\t\t\tif len(calls) == 0 {\n\t\t\t\tgoto retry\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>prog: increase number of itereations in TestRotationCoverage<commit_after>\/\/ Copyright 2019 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 prog\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestRotationRandom(t *testing.T) {\n\ttarget, rs, _ := initTest(t)\n\tfor _, ncalls := range []int{10, 100, 1000, 1e9} {\n\t\tncalls := ncalls\n\t\trnd := rand.New(rand.NewSource(rs.Int63()))\n\t\tt.Run(fmt.Sprint(ncalls), func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tcalls0 := selectCalls(target, rnd, ncalls)\n\t\t\tcalls := MakeRotator(target, calls0, rnd).Select()\n\t\t\tfor call := range calls {\n\t\t\t\tif !calls0[call] {\n\t\t\t\t\tt.Errorf(\"selected disabled syscall %v\", call.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tvar array []*Syscall\n\t\t\tfor call := range calls {\n\t\t\t\tarray = append(array, call)\n\t\t\t}\n\t\t\tsort.Slice(array, func(i, j int) bool {\n\t\t\t\treturn array[i].Name < array[j].Name\n\t\t\t})\n\t\t\tfor _, call := range array {\n\t\t\t\tfmt.Fprintf(buf, \"%v\\n\", call.Name)\n\t\t\t}\n\t\t\tt.Logf(\"calls %v->%v:\\n%s\", len(calls0), len(calls), buf.Bytes())\n\t\t})\n\t}\n}\n\nfunc TestRotationCoverage(t *testing.T) {\n\ttarget, rs, _ := initTest(t)\n\tcalls := make(map[*Syscall]bool)\n\tcounters := make(map[string]int)\n\tfor _, call := range target.Syscalls {\n\t\tcalls[call] = true\n\t\tcounters[call.Name] = 0\n\t}\n\trotator := MakeRotator(target, calls, rand.New(rs))\n\tfor iter := 0; iter < 2e3; iter++ {\n\t\tfor call := range rotator.Select() {\n\t\t\tcounters[call.Name]++\n\t\t}\n\t}\n\ttype pair struct {\n\t\tname  string\n\t\tcount int\n\t}\n\tvar pairs []pair\n\tremain := len(counters)\n\tfor name, count := range counters {\n\t\tpairs = append(pairs, pair{name, count})\n\t\tif count != 0 {\n\t\t\tremain--\n\t\t}\n\t}\n\tsort.Slice(pairs, func(i, j int) bool {\n\t\tif pairs[i].count != pairs[j].count {\n\t\t\treturn pairs[i].count > pairs[j].count\n\t\t}\n\t\treturn pairs[i].name < pairs[j].name\n\t})\n\tfor i, pair := range pairs {\n\t\tt.Logf(\"# %4d: % 4d %v\", i, pair.count, pair.name)\n\t}\n\tif remain != 0 {\n\t\tt.Fatalf(\"uncovered syscalls: %v\", remain)\n\t}\n}\n\nfunc selectCalls(target *Target, rnd *rand.Rand, ncalls int) map[*Syscall]bool {\nretry:\n\tcalls := make(map[*Syscall]bool)\n\tfor _, call := range target.Syscalls {\n\t\tcalls[call] = true\n\t}\n\tfor {\n\t\tfor {\n\t\t\tremove := 0\n\t\t\tswitch {\n\t\t\tcase len(calls) > ncalls+1000:\n\t\t\t\tremove = 100\n\t\t\tcase len(calls) > ncalls+50:\n\t\t\t\tremove = 20\n\t\t\tcase len(calls) > ncalls:\n\t\t\t\tremove = 1\n\t\t\tdefault:\n\t\t\t\treturn calls\n\t\t\t}\n\t\t\tvar array []*Syscall\n\t\t\tfor call := range calls {\n\t\t\t\tarray = append(array, call)\n\t\t\t}\n\t\t\tsort.Slice(array, func(i, j int) bool {\n\t\t\t\treturn array[i].ID < array[j].ID\n\t\t\t})\n\t\t\trnd.Shuffle(len(calls), func(i, j int) {\n\t\t\t\tarray[i], array[j] = array[j], array[i]\n\t\t\t})\n\t\t\tfor _, call := range array[:remove] {\n\t\t\t\tdelete(calls, call)\n\t\t\t}\n\t\t\tcalls, _ = target.transitivelyEnabled(calls)\n\t\t\tif len(calls) == 0 {\n\t\t\t\tgoto retry\n\t\t\t}\n\t\t}\n\t}\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\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\ntype Entry struct {\n\tChainID string   `json:\"chainid\"`\n\tExtIDs  [][]byte `json:\"extids\"`\n\tContent []byte   `json:\"content\"`\n}\n\nfunc (e *Entry) Hash() []byte {\n\ta, err := e.MarshalBinary()\n\tif err != nil {\n\t\treturn make([]byte, 32)\n\t}\n\treturn sha52(a)\n}\n\nfunc (e *Entry) MarshalBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tids, err := e.MarshalExtIDsBinary()\n\tif err != nil {\n\t\treturn buf.Bytes(), err\n\t}\n\n\t\/\/ Header\n\n\t\/\/ 1 byte Version\n\tbuf.Write([]byte{0})\n\n\t\/\/ 32 byte chainid\n\tif p, err := hex.DecodeString(e.ChainID); err != nil {\n\t\treturn buf.Bytes(), err\n\t} else {\n\t\tbuf.Write(p)\n\t}\n\n\t\/\/ 2 byte size of extids\n\tif err := binary.Write(buf, binary.BigEndian, int16(len(ids))); err != nil {\n\t\treturn buf.Bytes(), err\n\t}\n\n\t\/\/ Body\n\n\t\/\/ ExtIDs\n\tbuf.Write(ids)\n\n\t\/\/ Content\n\tbuf.Write(e.Content)\n\n\treturn buf.Bytes(), nil\n}\n\nfunc (e *Entry) MarshalExtIDsBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tfor _, v := range e.ExtIDs {\n\t\t\/\/ 2 byte length of extid\n\t\tbinary.Write(buf, binary.BigEndian, int16(len(v)))\n\t\t\/\/ extid\n\t\tbuf.Write(v)\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc (e *Entry) MarshalJSON() ([]byte, error) {\n\ttype js struct {\n\t\tChainID string   `json:\"chainid\"`\n\t\tExtIDs  []string `json:\"extids\"`\n\t\tContent string   `json:\"content\"`\n\t}\n\n\tj := new(js)\n\n\tj.ChainID = e.ChainID\n\n\tfor _, id := range e.ExtIDs {\n\t\tj.ExtIDs = append(j.ExtIDs, hex.EncodeToString(id))\n\t}\n\n\tj.Content = hex.EncodeToString(e.Content)\n\n\treturn json.Marshal(j)\n}\n\nfunc (e *Entry) String() string {\n\tvar s string\n\ts += fmt.Sprintln(\"ChainID:\", e.ChainID)\n\tfor _, id := range e.ExtIDs {\n\t\ts += fmt.Sprintln(\"ExtID:\", string(id))\n\t}\n\ts += fmt.Sprintln(\"Content:\")\n\ts += fmt.Sprintln(string(e.Content))\n\treturn s\n}\n\nfunc (e *Entry) UnmarshalJSON(data []byte) error {\n\ttype js struct {\n\t\tChainID   string   `json:\"chainid\"`\n\t\tChainName []string `json:\"chainname\"`\n\t\tExtIDs    []string `json:\"extids\"`\n\t\tContent   string   `json:\"content\"`\n\t}\n\n\tj := new(js)\n\tif err := json.Unmarshal(data, j); err != nil {\n\t\treturn err\n\t}\n\n\te.ChainID = j.ChainID\n\n\tif e.ChainID == \"\" {\n\t\tn := new(Entry)\n\t\tfor _, v := range j.ChainName {\n\t\t\tif p, err := hex.DecodeString(v); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Could not decode ChainName %s: %s\", v, err)\n\t\t\t} else {\n\t\t\t\tn.ExtIDs = append(n.ExtIDs, p)\n\t\t\t}\n\t\t}\n\t\tm := NewChain(n)\n\t\te.ChainID = m.ChainID\n\t}\n\n\tfor _, v := range j.ExtIDs {\n\t\tif p, err := hex.DecodeString(v); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not decode ExtID %s: %s\", v, err)\n\t\t} else {\n\t\t\te.ExtIDs = append(e.ExtIDs, p)\n\t\t}\n\t}\n\n\tp, err := hex.DecodeString(j.Content)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not decode Content %s: %s\", j.Content, err)\n\t}\n\te.Content = p\n\n\treturn nil\n}\n\n\/\/ ComposeEntryCommit creates a JSON2Request to commit a new Entry via the\n\/\/ factomd web api. The request includes the marshaled MessageRequest with the\n\/\/ Entry Credit Signature.\nfunc ComposeEntryCommit(e *Entry, ec *ECAddress) (*JSON2Request, error) {\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ 1 byte version\n\tbuf.Write([]byte{0})\n\n\t\/\/ 6 byte milliTimestamp (truncated unix time)\n\tbuf.Write(milliTime())\n\n\t\/\/ 32 byte Entry Hash\n\tbuf.Write(e.Hash())\n\n\t\/\/ 1 byte number of entry credits to pay\n\tif c, err := entryCost(e); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tbuf.WriteByte(byte(c))\n\t}\n\n\t\/\/ 32 byte Entry Credit Address Public Key + 64 byte Signature\n\tsig := ec.Sign(buf.Bytes())\n\tbuf.Write(ec.PubBytes())\n\tbuf.Write(sig[:])\n\n\tparams := entryRequest{Entry: hex.EncodeToString(buf.Bytes())}\n\treq := NewJSON2Request(\"commit-entry\", APICounter(), params)\n\n\treturn req, nil\n}\n\n\/\/ ComposeEntryReveal creates a JSON2Request to reveal the Entry via the factomd\n\/\/ web api.\nfunc ComposeEntryReveal(e *Entry) (*JSON2Request, error) {\n\tp, err := e.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := entryRequest{Entry: hex.EncodeToString(p)}\n\treq := NewJSON2Request(\"reveal-entry\", APICounter(), params)\n\n\treturn req, nil\n}\n\n\/\/ CommitEntry sends the signed Entry Hash and the Entry Credit public key to\n\/\/ the factom network. Once the payment is verified and the network is commited\n\/\/ to publishing the Entry it may be published with a call to RevealEntry.\nfunc CommitEntry(e *Entry, ec *ECAddress) (string, error) {\n\ttype commitResponse struct {\n\t\tMessage string `json:\"message\"`\n\t\tTxID    string `json:\"txid\"`\n\t}\n\n\treq, err := ComposeEntryCommit(e, ec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.Error != nil {\n\t\treturn \"\", resp.Error\n\t}\n\tr := new(commitResponse)\n\tif err := json.Unmarshal(resp.JSONResult(), r); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn r.TxID, nil\n}\n\nfunc RevealEntry(e *Entry) (string, error) {\n\ttype revealResponse struct {\n\t\tMessage string `json:\"message\"`\n\t\tEntry   string `json:\"entryhash\"`\n\t}\n\n\treq, err := ComposeEntryReveal(e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.Error != nil {\n\t\treturn \"\", resp.Error\n\t}\n\n\tr := new(revealResponse)\n\tif err := json.Unmarshal(resp.JSONResult(), r); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Entry, nil\n}\n<commit_msg>add entryhash to printouts<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\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\ntype Entry struct {\n\tChainID string   `json:\"chainid\"`\n\tExtIDs  [][]byte `json:\"extids\"`\n\tContent []byte   `json:\"content\"`\n}\n\nfunc (e *Entry) Hash() []byte {\n\ta, err := e.MarshalBinary()\n\tif err != nil {\n\t\treturn make([]byte, 32)\n\t}\n\treturn sha52(a)\n}\n\nfunc (e *Entry) MarshalBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tids, err := e.MarshalExtIDsBinary()\n\tif err != nil {\n\t\treturn buf.Bytes(), err\n\t}\n\n\t\/\/ Header\n\n\t\/\/ 1 byte Version\n\tbuf.Write([]byte{0})\n\n\t\/\/ 32 byte chainid\n\tif p, err := hex.DecodeString(e.ChainID); err != nil {\n\t\treturn buf.Bytes(), err\n\t} else {\n\t\tbuf.Write(p)\n\t}\n\n\t\/\/ 2 byte size of extids\n\tif err := binary.Write(buf, binary.BigEndian, int16(len(ids))); err != nil {\n\t\treturn buf.Bytes(), err\n\t}\n\n\t\/\/ Body\n\n\t\/\/ ExtIDs\n\tbuf.Write(ids)\n\n\t\/\/ Content\n\tbuf.Write(e.Content)\n\n\treturn buf.Bytes(), nil\n}\n\nfunc (e *Entry) MarshalExtIDsBinary() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tfor _, v := range e.ExtIDs {\n\t\t\/\/ 2 byte length of extid\n\t\tbinary.Write(buf, binary.BigEndian, int16(len(v)))\n\t\t\/\/ extid\n\t\tbuf.Write(v)\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc (e *Entry) MarshalJSON() ([]byte, error) {\n\ttype js struct {\n\t\tChainID string   `json:\"chainid\"`\n\t\tExtIDs  []string `json:\"extids\"`\n\t\tContent string   `json:\"content\"`\n\t}\n\n\tj := new(js)\n\n\tj.ChainID = e.ChainID\n\n\tfor _, id := range e.ExtIDs {\n\t\tj.ExtIDs = append(j.ExtIDs, hex.EncodeToString(id))\n\t}\n\n\tj.Content = hex.EncodeToString(e.Content)\n\n\treturn json.Marshal(j)\n}\n\nfunc (e *Entry) String() string {\n\tvar s string\n\ts += fmt.Sprintf(\"Entryhash: %x\\n\", e.Hash())\n\ts += fmt.Sprintln(\"ChainID:\", e.ChainID)\n\tfor _, id := range e.ExtIDs {\n\t\ts += fmt.Sprintln(\"ExtID:\", string(id))\n\t}\n\ts += fmt.Sprintln(\"Content:\")\n\ts += fmt.Sprintln(string(e.Content))\n\treturn s\n}\n\nfunc (e *Entry) UnmarshalJSON(data []byte) error {\n\ttype js struct {\n\t\tChainID   string   `json:\"chainid\"`\n\t\tChainName []string `json:\"chainname\"`\n\t\tExtIDs    []string `json:\"extids\"`\n\t\tContent   string   `json:\"content\"`\n\t}\n\n\tj := new(js)\n\tif err := json.Unmarshal(data, j); err != nil {\n\t\treturn err\n\t}\n\n\te.ChainID = j.ChainID\n\n\tif e.ChainID == \"\" {\n\t\tn := new(Entry)\n\t\tfor _, v := range j.ChainName {\n\t\t\tif p, err := hex.DecodeString(v); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Could not decode ChainName %s: %s\", v, err)\n\t\t\t} else {\n\t\t\t\tn.ExtIDs = append(n.ExtIDs, p)\n\t\t\t}\n\t\t}\n\t\tm := NewChain(n)\n\t\te.ChainID = m.ChainID\n\t}\n\n\tfor _, v := range j.ExtIDs {\n\t\tif p, err := hex.DecodeString(v); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not decode ExtID %s: %s\", v, err)\n\t\t} else {\n\t\t\te.ExtIDs = append(e.ExtIDs, p)\n\t\t}\n\t}\n\n\tp, err := hex.DecodeString(j.Content)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not decode Content %s: %s\", j.Content, err)\n\t}\n\te.Content = p\n\n\treturn nil\n}\n\n\/\/ ComposeEntryCommit creates a JSON2Request to commit a new Entry via the\n\/\/ factomd web api. The request includes the marshaled MessageRequest with the\n\/\/ Entry Credit Signature.\nfunc ComposeEntryCommit(e *Entry, ec *ECAddress) (*JSON2Request, error) {\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ 1 byte version\n\tbuf.Write([]byte{0})\n\n\t\/\/ 6 byte milliTimestamp (truncated unix time)\n\tbuf.Write(milliTime())\n\n\t\/\/ 32 byte Entry Hash\n\tbuf.Write(e.Hash())\n\n\t\/\/ 1 byte number of entry credits to pay\n\tif c, err := entryCost(e); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tbuf.WriteByte(byte(c))\n\t}\n\n\t\/\/ 32 byte Entry Credit Address Public Key + 64 byte Signature\n\tsig := ec.Sign(buf.Bytes())\n\tbuf.Write(ec.PubBytes())\n\tbuf.Write(sig[:])\n\n\tparams := entryRequest{Entry: hex.EncodeToString(buf.Bytes())}\n\treq := NewJSON2Request(\"commit-entry\", APICounter(), params)\n\n\treturn req, nil\n}\n\n\/\/ ComposeEntryReveal creates a JSON2Request to reveal the Entry via the factomd\n\/\/ web api.\nfunc ComposeEntryReveal(e *Entry) (*JSON2Request, error) {\n\tp, err := e.MarshalBinary()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := entryRequest{Entry: hex.EncodeToString(p)}\n\treq := NewJSON2Request(\"reveal-entry\", APICounter(), params)\n\n\treturn req, nil\n}\n\n\/\/ CommitEntry sends the signed Entry Hash and the Entry Credit public key to\n\/\/ the factom network. Once the payment is verified and the network is commited\n\/\/ to publishing the Entry it may be published with a call to RevealEntry.\nfunc CommitEntry(e *Entry, ec *ECAddress) (string, error) {\n\ttype commitResponse struct {\n\t\tMessage string `json:\"message\"`\n\t\tTxID    string `json:\"txid\"`\n\t}\n\n\treq, err := ComposeEntryCommit(e, ec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.Error != nil {\n\t\treturn \"\", resp.Error\n\t}\n\tr := new(commitResponse)\n\tif err := json.Unmarshal(resp.JSONResult(), r); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn r.TxID, nil\n}\n\nfunc RevealEntry(e *Entry) (string, error) {\n\ttype revealResponse struct {\n\t\tMessage string `json:\"message\"`\n\t\tEntry   string `json:\"entryhash\"`\n\t}\n\n\treq, err := ComposeEntryReveal(e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.Error != nil {\n\t\treturn \"\", resp.Error\n\t}\n\n\tr := new(revealResponse)\n\tif err := json.Unmarshal(resp.JSONResult(), r); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Entry, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package niso\n\nimport (\n\t\"fmt\"\n\n\t\"net\/url\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ ErrorCode is an OAuth2 error code\ntype ErrorCode string\n\n\/\/ OAuth2 error codes (https:\/\/tools.ietf.org\/html\/rfc6749#section-4.1.2.1)\nconst (\n\tE_INVALID_REQUEST           ErrorCode = \"invalid_request\"\n\tE_UNAUTHORIZED_CLIENT       ErrorCode = \"unauthorized_client\"\n\tE_ACCESS_DENIED             ErrorCode = \"access_denied\"\n\tE_UNSUPPORTED_RESPONSE_TYPE ErrorCode = \"unsupported_response_type\"\n\tE_INVALID_SCOPE             ErrorCode = \"invalid_scope\"\n\tE_SERVER_ERROR              ErrorCode = \"server_error\"\n\tE_TEMPORARILY_UNAVAILABLE   ErrorCode = \"temporarily_unavailable\"\n\tE_UNSUPPORTED_GRANT_TYPE    ErrorCode = \"unsupported_grant_type\"\n\tE_INVALID_GRANT             ErrorCode = \"invalid_grant\"\n\tE_INVALID_CLIENT            ErrorCode = \"invalid_client\"\n)\n\n\/\/ NisoError is a wrapper around an existing error with an OAuth2 error code\ntype NisoError struct {\n\tCode ErrorCode\n\tErr  error\n\n\t\/\/ Human readable description of the error that occurred\n\tMessage string\n\n\t\/\/ redirectURI is the URI to which the request will be redirected to when using WriteErrorResponse\n\t\/\/ as per https:\/\/tools.ietf.org\/html\/rfc6749#section-4.2.2.1\n\tredirectURI string\n\n\t\/\/ State is the state parameter to be passed directly back to the client\n\tstate string\n}\n\n\/\/ NewNisoError creates a new NisoError for a response error code\nfunc NewNisoError(code ErrorCode, message string) *NisoError {\n\treturn &NisoError{\n\t\tCode:    code,\n\t\tErr:     errors.New(message),\n\t\tMessage: message,\n\t}\n}\n\n\/\/ NewWrappedNisoError creates a new NisoError for a response error code and wraps the original error with the given description\nfunc NewWrappedNisoError(code ErrorCode, error error, message string) *NisoError {\n\treturn &NisoError{\n\t\tCode:    code,\n\t\tErr:     errors.Wrap(error, message),\n\t\tMessage: message,\n\t}\n}\n\n\/\/ SetRedirectURI set redirect uri for this error to redirect to when written to a HTTP response\nfunc (e *NisoError) SetRedirectURI(redirectURI string) {\n\te.redirectURI = redirectURI\n}\n\n\/\/ SetState sets the \"state\" parameter to be returned to the user when this error is rendered\nfunc (e *NisoError) SetState(state string) {\n\te.state = state\n}\n\nfunc (e *NisoError) Error() string {\n\treturn fmt.Sprintf(\"(%s) %s\", e.Code, e.Err.Error())\n}\n\n\/\/ AsResponse creates a response object from this error, containing it's body or a redirect if specified\nfunc (e *NisoError) AsResponse() *Response {\n\tresp := NewResponse()\n\n\t\/\/ Redirect user if needed\n\tloc, err := e.GetRedirectURI()\n\tif err != nil {\n\t\treturn newInternalServerErrorResponse(\n\t\t\terrors.Wrap(err, \"failed to redirect on error\").Error(),\n\t\t)\n\t}\n\tif loc != \"\" {\n\t\tresp.responseType = REDIRECT\n\t\tresp.redirectURL = loc\n\t}\n\n\t\/\/ No redirect output error as a JSON response\n\tresp.StatusCode = statusCodeForError(e)\n\tfor k, v := range e.GetResponseDict() {\n\t\tif v != \"\" {\n\t\t\tresp.Data[k] = v\n\t\t}\n\t}\n\n\treturn resp\n}\n\n\/\/ GetRedirectURI returns location to redirect user to after processing this error, or empty string if there is none\nfunc (e *NisoError) GetRedirectURI() (string, error) {\n\tif e.redirectURI == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tu, err := url.Parse(e.redirectURI)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tq := u.Query()\n\tfor k, v := range e.GetResponseDict() {\n\t\tif v != \"\" {\n\t\t\tq.Set(k, v)\n\t\t}\n\t}\n\n\tu.RawQuery = q.Encode()\n\tu.Fragment = \"\"\n\treturn u.String(), nil\n}\n\n\/\/ GetResponseDict returns the fields for an error response as defined in https:\/\/tools.ietf.org\/html\/rfc6749#section-4.2.2.1\nfunc (e *NisoError) GetResponseDict() map[string]string {\n\treturn map[string]string{\n\t\t\"error\":             string(e.Code),\n\t\t\"error_description\": e.Message,\n\t\t\"state\":             e.state,\n\t}\n}\n\nfunc toNisoError(err error) *NisoError {\n\tif ne, ok := err.(*NisoError); ok {\n\t\treturn ne\n\t}\n\n\treturn NewWrappedNisoError(E_SERVER_ERROR, err, \"unknown error\")\n}\n\n\/\/ status code to return for a given error code as per (https:\/\/tools.ietf.org\/html\/rfc6749#section-5.2)\nfunc statusCodeForError(error *NisoError) int {\n\tif error.Code == E_SERVER_ERROR {\n\t\treturn 500\n\t} else if error.Code == E_TEMPORARILY_UNAVAILABLE {\n\t\treturn 503\n\t} else if error.Code == E_INVALID_CLIENT || error.Code == E_ACCESS_DENIED {\n\t\treturn 401\n\t}\n\n\treturn 400\n}\n<commit_msg>NewNiso error with args<commit_after>package niso\n\nimport (\n\t\"fmt\"\n\n\t\"net\/url\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ ErrorCode is an OAuth2 error code\ntype ErrorCode string\n\n\/\/ OAuth2 error codes (https:\/\/tools.ietf.org\/html\/rfc6749#section-4.1.2.1)\nconst (\n\tE_INVALID_REQUEST           ErrorCode = \"invalid_request\"\n\tE_UNAUTHORIZED_CLIENT       ErrorCode = \"unauthorized_client\"\n\tE_ACCESS_DENIED             ErrorCode = \"access_denied\"\n\tE_UNSUPPORTED_RESPONSE_TYPE ErrorCode = \"unsupported_response_type\"\n\tE_INVALID_SCOPE             ErrorCode = \"invalid_scope\"\n\tE_SERVER_ERROR              ErrorCode = \"server_error\"\n\tE_TEMPORARILY_UNAVAILABLE   ErrorCode = \"temporarily_unavailable\"\n\tE_UNSUPPORTED_GRANT_TYPE    ErrorCode = \"unsupported_grant_type\"\n\tE_INVALID_GRANT             ErrorCode = \"invalid_grant\"\n\tE_INVALID_CLIENT            ErrorCode = \"invalid_client\"\n)\n\n\/\/ NisoError is a wrapper around an existing error with an OAuth2 error code\ntype NisoError struct {\n\tCode ErrorCode\n\tErr  error\n\n\t\/\/ Human readable description of the error that occurred\n\tMessage string\n\n\t\/\/ redirectURI is the URI to which the request will be redirected to when using WriteErrorResponse\n\t\/\/ as per https:\/\/tools.ietf.org\/html\/rfc6749#section-4.2.2.1\n\tredirectURI string\n\n\t\/\/ State is the state parameter to be passed directly back to the client\n\tstate string\n}\n\n\/\/ NewNisoError creates a new NisoError for a response error code\nfunc NewNisoError(code ErrorCode, message string, args ...interface{}) *NisoError {\n\treturn &NisoError{\n\t\tCode:    code,\n\t\tErr:     errors.Errorf(message, args...),\n\t\tMessage: message,\n\t}\n}\n\n\/\/ NewWrappedNisoError creates a new NisoError for a response error code and wraps the original error with the given description\nfunc NewWrappedNisoError(code ErrorCode, error error, message string, args ...interface{}) *NisoError {\n\treturn &NisoError{\n\t\tCode:    code,\n\t\tErr:     errors.Wrapf(error, message, args...),\n\t\tMessage: message,\n\t}\n}\n\n\/\/ SetRedirectURI set redirect uri for this error to redirect to when written to a HTTP response\nfunc (e *NisoError) SetRedirectURI(redirectURI string) {\n\te.redirectURI = redirectURI\n}\n\n\/\/ SetState sets the \"state\" parameter to be returned to the user when this error is rendered\nfunc (e *NisoError) SetState(state string) {\n\te.state = state\n}\n\nfunc (e *NisoError) Error() string {\n\treturn fmt.Sprintf(\"(%s) %s\", e.Code, e.Err.Error())\n}\n\n\/\/ AsResponse creates a response object from this error, containing it's body or a redirect if specified\nfunc (e *NisoError) AsResponse() *Response {\n\tresp := NewResponse()\n\n\t\/\/ Redirect user if needed\n\tloc, err := e.GetRedirectURI()\n\tif err != nil {\n\t\treturn newInternalServerErrorResponse(\n\t\t\terrors.Wrap(err, \"failed to redirect on error\").Error(),\n\t\t)\n\t}\n\tif loc != \"\" {\n\t\tresp.responseType = REDIRECT\n\t\tresp.redirectURL = loc\n\t}\n\n\t\/\/ No redirect output error as a JSON response\n\tresp.StatusCode = statusCodeForError(e)\n\tfor k, v := range e.GetResponseDict() {\n\t\tif v != \"\" {\n\t\t\tresp.Data[k] = v\n\t\t}\n\t}\n\n\treturn resp\n}\n\n\/\/ GetRedirectURI returns location to redirect user to after processing this error, or empty string if there is none\nfunc (e *NisoError) GetRedirectURI() (string, error) {\n\tif e.redirectURI == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tu, err := url.Parse(e.redirectURI)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tq := u.Query()\n\tfor k, v := range e.GetResponseDict() {\n\t\tif v != \"\" {\n\t\t\tq.Set(k, v)\n\t\t}\n\t}\n\n\tu.RawQuery = q.Encode()\n\tu.Fragment = \"\"\n\treturn u.String(), nil\n}\n\n\/\/ GetResponseDict returns the fields for an error response as defined in https:\/\/tools.ietf.org\/html\/rfc6749#section-4.2.2.1\nfunc (e *NisoError) GetResponseDict() map[string]string {\n\treturn map[string]string{\n\t\t\"error\":             string(e.Code),\n\t\t\"error_description\": e.Message,\n\t\t\"state\":             e.state,\n\t}\n}\n\nfunc toNisoError(err error) *NisoError {\n\tif ne, ok := err.(*NisoError); ok {\n\t\treturn ne\n\t}\n\n\treturn NewWrappedNisoError(E_SERVER_ERROR, err, \"unknown error\")\n}\n\n\/\/ status code to return for a given error code as per (https:\/\/tools.ietf.org\/html\/rfc6749#section-5.2)\nfunc statusCodeForError(error *NisoError) int {\n\tif error.Code == E_SERVER_ERROR {\n\t\treturn 500\n\t} else if error.Code == E_TEMPORARILY_UNAVAILABLE {\n\t\treturn 503\n\t} else if error.Code == E_INVALID_CLIENT || error.Code == E_ACCESS_DENIED {\n\t\treturn 401\n\t}\n\n\treturn 400\n}\n<|endoftext|>"}
{"text":"<commit_before>package Golf\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n)\n\nvar errorTemplate = `<!DOCTYPE HTML>\n<html>\n  <head>\n    <meta http-equiv=\"content-type\" content=\"text\/html; charset=utf-8\">\n    <title>Error: {{.Code}} {{.Title}}<\/title>\n    <style type=\"text\/css\" media=\"screen\">\nhtml,body{\n  padding:0;\n  margin:0;\n  font-family: Tahoma;\n  color: #34495e;\n}\nh1 {\n  color: #fff;\n  margin: 0;\n}\n.container {\n  max-width: 1220px;\n  margin: 0 auto;\n  padding: 0 20px;\n}\n#header {\n  display: block;\n  background-color: #3498db;\n  height: 120px;\n  width: 100%;\n}\n#title {\n  padding: 40px 0;\n}\n.error {\n  color: #c0392b;\n}\n\n    <\/style>\n\n  <\/head>\n  <body style=\"background-color: #E4F9F5\">\n    <div id=\"header\">\n      <div class=\"container\">\n\n        <div id=\"title\">\n          <h1>Error: {{.Code}} {{.Title}}<\/h1>\n        <\/div>\n      <\/div>\n    <\/div>\n    <div class=\"container\">\n      <p>Sorry, the requested URL {{.URL}} caused an error: <\/p>\n      <pre><code>{{.Message}}<\/code><\/pre>\n      <pre><code>{{.StackTrace}}<\/code><\/pre>\n    <\/div>\n  <\/body>\n<\/html>`\n\nvar tmpl = template.New(\"error\")\n\ntype TemplateError struct {\n\tFormat     string\n\tParameters []interface{}\n}\n\nfunc (e *TemplateError) Error() string {\n\treturn fmt.Sprintf(e.Format, e.Parameters...)\n}\n\nfunc Errf(format string, parameters ...interface{}) error {\n\treturn &TemplateError{\n\t\tFormat:     format,\n\t\tParameters: parameters,\n\t}\n}\n\n\/\/ The default error handler\nfunc defaultErrorHandler(ctx *Context) {\n\ttmpl.Parse(errorTemplate)\n\tvar buf bytes.Buffer\n\ttmpl.Execute(&buf, map[string]interface{}{\n\t\t\"Code\":    ctx.StatusCode,\n\t\t\"Title\":   http.StatusText(ctx.StatusCode),\n\t\t\"Message\": http.StatusText(ctx.StatusCode),\n\t})\n\tctx.Write(buf.String())\n\tctx.Send()\n}\n<commit_msg>[refactor] Unexported templateError<commit_after>package Golf\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n)\n\nvar errorTemplate = `<!DOCTYPE HTML>\n<html>\n  <head>\n    <meta http-equiv=\"content-type\" content=\"text\/html; charset=utf-8\">\n    <title>Error: {{.Code}} {{.Title}}<\/title>\n    <style type=\"text\/css\" media=\"screen\">\nhtml,body{\n  padding:0;\n  margin:0;\n  font-family: Tahoma;\n  color: #34495e;\n}\nh1 {\n  color: #fff;\n  margin: 0;\n}\n.container {\n  max-width: 1220px;\n  margin: 0 auto;\n  padding: 0 20px;\n}\n#header {\n  display: block;\n  background-color: #3498db;\n  height: 120px;\n  width: 100%;\n}\n#title {\n  padding: 40px 0;\n}\n.error {\n  color: #c0392b;\n}\n\n    <\/style>\n\n  <\/head>\n  <body style=\"background-color: #E4F9F5\">\n    <div id=\"header\">\n      <div class=\"container\">\n\n        <div id=\"title\">\n          <h1>Error: {{.Code}} {{.Title}}<\/h1>\n        <\/div>\n      <\/div>\n    <\/div>\n    <div class=\"container\">\n      <p>Sorry, the requested URL {{.URL}} caused an error: <\/p>\n      <pre><code>{{.Message}}<\/code><\/pre>\n      <pre><code>{{.StackTrace}}<\/code><\/pre>\n    <\/div>\n  <\/body>\n<\/html>`\n\nvar tmpl = template.New(\"error\")\n\ntype templateError struct {\n\tFormat     string\n\tParameters []interface{}\n}\n\nfunc (e *templateError) Error() string {\n\treturn fmt.Sprintf(e.Format, e.Parameters...)\n}\n\nfunc Errf(format string, parameters ...interface{}) error {\n\treturn &templateError{\n\t\tFormat:     format,\n\t\tParameters: parameters,\n\t}\n}\n\n\/\/ The default error handler\nfunc defaultErrorHandler(ctx *Context) {\n\ttmpl.Parse(errorTemplate)\n\tvar buf bytes.Buffer\n\ttmpl.Execute(&buf, map[string]interface{}{\n\t\t\"Code\":    ctx.StatusCode,\n\t\t\"Title\":   http.StatusText(ctx.StatusCode),\n\t\t\"Message\": http.StatusText(ctx.StatusCode),\n\t})\n\tctx.Write(buf.String())\n\tctx.Send()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integration_tests\n\npackage websession\n\n\/\/ Integration tests; these operate against the test app in ..\/..\/internal\/testapp\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\"strconv\"\n\t\"testing\"\n)\n\nvar baseUrl string\n\nfunc init() {\n\t\/\/ Get the base URL for the test app from the environment. if\n\t\/\/ the requisite environment variable is not set, panic.\n\tbaseUrl = os.Getenv(\"GO_SANDSTORM_TEST_APP\")\n\tif baseUrl == \"\" {\n\t\tpanic(\"Integration test: GO_SANDSTORM_TEST_APP environment \" +\n\t\t\t\"variable not defined.\")\n\t}\n}\n\ntype echoBody struct {\n\tMethod  string         `json:\"method\"`\n\tUrl     *url.URL       `json:\"url\"`\n\tHeaders http.Header    `json:\"headers\"`\n\tBody    []byte         `json:\"body\"`\n\tCookies []*http.Cookie `json:\"cookies\"`\n}\n\nfunc chkfatal(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc expectStatus(t *testing.T, want, got int) {\n\tif want != got {\n\t\tt.Fatal(\"Unexpected status code; expected\", want, \"but got\", got)\n\t}\n}\n\nfunc TestBasicGetHead(t *testing.T) {\n\tsuccessfulResponse := func(resp *http.Response, err error) {\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, 200, resp.StatusCode)\n\t}\n\tsuccessfulResponse(http.Get(baseUrl + \"echo-request\/hello\"))\n\tsuccessfulResponse(http.Head(baseUrl + \"echo-request\/hello\"))\n}\n\nfunc TestGetCorrectInfo(t *testing.T) {\n\n\tresp, err := http.Get(baseUrl + \"echo-request\/hello\")\n\tchkfatal(t, err)\n\tdefer func() {\n\t\tif t.Failed() {\n\t\t\tt.Log(\"Response:\", resp)\n\t\t}\n\t}()\n\texpectStatus(t, 200, resp.StatusCode)\n\tbody := &echoBody{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\tchkfatal(t, err)\n\n\tif body.Method != \"GET\" {\n\t\tt.Error(\"Wrong method:\", body.Method)\n\t}\n\tif body.Url.Path != \"\/echo-request\/hello\" {\n\t\tt.Error(\"Wrong path:\", body.Url.Path)\n\t}\n}\n\nfunc testHeader(t *testing.T, name, sendVal, wantRecvVal string) {\n\treq, err := http.NewRequest(\"GET\", baseUrl+\"echo-request\/\"+name+\"-header\", nil)\n\tchkfatal(t, err)\n\treq.Header.Set(name, sendVal)\n\n\tresp, err := http.DefaultClient.Do(req)\n\tchkfatal(t, err)\n\tdefer func() {\n\t\tif t.Failed() {\n\t\t\tt.Log(\"Response:\", resp)\n\t\t}\n\t}()\n\n\texpectStatus(t, 200, resp.StatusCode)\n\tbody := &echoBody{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\tchkfatal(t, err)\n\tgotRecvVal := body.Headers.Get(name)\n\tif gotRecvVal != wantRecvVal {\n\t\tt.Fatalf(\"Server did not see correct value for %s header; \"+\n\t\t\t\"wanted %q but got %q\", name, wantRecvVal, gotRecvVal)\n\t}\n}\n\nfunc TestAcceptHeader(t *testing.T) {\n\ttestHeader(t, \"Accept\", \"application\/json\", \"application\/json; q=1\")\n}\n\nfunc TestAcceptEncodingHeader(t *testing.T) {\n\ttestHeader(t, \"Accept-Encoding\", \"something-non-standard\", \"something-non-standard;q=1\")\n\ttestHeader(t, \"Accept-Encoding\", \"gzip\", \"gzip;q=1\")\n\ttestHeader(t, \"Accept-Encoding\", \"*;q=1\", \"*;q=1\")\n}\n\nfunc TestAdditionalHeaders(t *testing.T) {\n\ttestHeader(t, \"X-Foo-Disallowed-Header\", \"Bar\", \"\")\n\ttestHeader(t, \"X-Sandstorm-App-Baz\", \"quux\", \"quux\")\n\ttestHeader(t, \"OC-Total-Length\", \"234\", \"234\")\n}\n\nfunc TestETagPrecondition(t *testing.T) {\n\ttestHeader(t, \"If-Match\", \"*\", \"*\")\n\ttestHeader(t, \"If-None-Match\", `\"foobarbaz\"`, `\"foobarbaz\"`)\n\ttestHeader(t, \"If-None-Match\", `W\/\"foobarbaz\"`, `W\/\"foobarbaz\"`)\n\ttestHeader(t, \"If-None-Match\", `W\/\"foobarbaz\", \"quux\"`, `W\/\"foobarbaz\", \"quux\"`)\n\n\t\/\/ \"net\/http\" won't magically deal with the etag header unless we use\n\t\/\/ http.FileSystem, so even though the following should arguably\n\t\/\/ return \"Precondition Failed,\" we can ignore it to check whether the\n\t\/\/ header is getting through:\n\ttestHeader(t, \"If-None-Match\", \"*\", \"*\")\n\ttestHeader(t, \"If-Match\", `\"foobarbaz\"`, `\"foobarbaz\"`)\n\ttestHeader(t, \"If-Match\", `W\/\"foobarbaz\"`, `W\/\"foobarbaz\"`)\n\ttestHeader(t, \"If-Match\", `W\/\"foobarbaz\", \"quux\"`, `W\/\"foobarbaz\", \"quux\"`)\n}\n\nfunc TestResponseContentType(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"echo-request\/content-type\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif contentType != \"application\/json\" {\n\t\tt.Fatalf(\"Expected content type application\/json but got %q\", contentType)\n\t}\n}\n\nfunc TestResponseContentEncoding(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"echo-request\/content-encoding\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\n\tencoding := resp.Header.Get(\"Content-Encoding\")\n\tif encoding != \"identity\" {\n\t\tt.Fatalf(\"Expected content encoding identity, but got %q.\", encoding)\n\t}\n}\n\nfunc TestResponseContentLength(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"content-length\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\n\tcontentLength := resp.Header.Get(\"Content-Length\")\n\treportLength, err := strconv.ParseUint(contentLength, 10, 64)\n\tchkfatal(t, err)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tchkfatal(t, err)\n\n\trealLength := uint64(len(body))\n\tif realLength != reportLength {\n\t\tt.Fatal(\"Content-Header indicated a length of %d, but body was \",\n\t\t\t\"actually %d bytes long.\", reportLength, realLength)\n\t}\n}\n\nfunc TestWantStatus(t *testing.T) {\n\tfor _, wantStatus := range []int{200, 201, 202, 204, 205} {\n\t\tresp, err := http.Get(fmt.Sprintf(\n\t\t\t\"%secho-request\/status?want-status=%d\", baseUrl, wantStatus,\n\t\t))\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, wantStatus, resp.StatusCode)\n\t}\n}\n\nfunc TestWantLanguage(t *testing.T) {\n\tfor _, wantLang := range []string{\"en-US\", \"de-DE\"} {\n\t\tresp, err := http.Get(\n\t\t\tbaseUrl + \"echo-request\/lang?want-lang=\" + wantLang,\n\t\t)\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, 200, resp.StatusCode)\n\t\tgotLang := resp.Header.Get(\"Content-Language\")\n\t\tif wantLang != gotLang {\n\t\t\tt.Fatalf(\"Unexpected Content-Language; wanted %q but got %q.\",\n\t\t\t\twantLang, gotLang)\n\t\t}\n\t}\n}\n\nfunc TestNoOpHandler(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"no-op-handler\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n}\n\nfunc TestETag(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"etag\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tetag := resp.Header.Get(\"ETag\")\n\n\tif etag != `\"sometag\"` {\n\t\tt.Errorf(`Expected ETag value \"sometag\", but got %q`, etag)\n\t}\n\n\tresp, err = http.Get(baseUrl + \"etag?weak=true\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tetag = resp.Header.Get(\"ETag\")\n\n\tif etag != `W\/\"sometag\"` {\n\t\tt.Errorf(`Expected ETag value W\/\"sometag\", but got %q`, etag)\n\t}\n}\n<commit_msg>Add a test re: NoContent responses.<commit_after>\/\/ +build integration_tests\n\npackage websession\n\n\/\/ Integration tests; these operate against the test app in ..\/..\/internal\/testapp\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\"strconv\"\n\t\"testing\"\n)\n\nvar baseUrl string\n\nfunc init() {\n\t\/\/ Get the base URL for the test app from the environment. if\n\t\/\/ the requisite environment variable is not set, panic.\n\tbaseUrl = os.Getenv(\"GO_SANDSTORM_TEST_APP\")\n\tif baseUrl == \"\" {\n\t\tpanic(\"Integration test: GO_SANDSTORM_TEST_APP environment \" +\n\t\t\t\"variable not defined.\")\n\t}\n}\n\ntype echoBody struct {\n\tMethod  string         `json:\"method\"`\n\tUrl     *url.URL       `json:\"url\"`\n\tHeaders http.Header    `json:\"headers\"`\n\tBody    []byte         `json:\"body\"`\n\tCookies []*http.Cookie `json:\"cookies\"`\n}\n\nfunc chkfatal(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc expectStatus(t *testing.T, want, got int) {\n\tif want != got {\n\t\tt.Fatal(\"Unexpected status code; expected\", want, \"but got\", got)\n\t}\n}\n\nfunc TestBasicGetHead(t *testing.T) {\n\tsuccessfulResponse := func(resp *http.Response, err error) {\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, 200, resp.StatusCode)\n\t}\n\tsuccessfulResponse(http.Get(baseUrl + \"echo-request\/hello\"))\n\tsuccessfulResponse(http.Head(baseUrl + \"echo-request\/hello\"))\n}\n\nfunc TestGetCorrectInfo(t *testing.T) {\n\n\tresp, err := http.Get(baseUrl + \"echo-request\/hello\")\n\tchkfatal(t, err)\n\tdefer func() {\n\t\tif t.Failed() {\n\t\t\tt.Log(\"Response:\", resp)\n\t\t}\n\t}()\n\texpectStatus(t, 200, resp.StatusCode)\n\tbody := &echoBody{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\tchkfatal(t, err)\n\n\tif body.Method != \"GET\" {\n\t\tt.Error(\"Wrong method:\", body.Method)\n\t}\n\tif body.Url.Path != \"\/echo-request\/hello\" {\n\t\tt.Error(\"Wrong path:\", body.Url.Path)\n\t}\n}\n\nfunc testHeader(t *testing.T, name, sendVal, wantRecvVal string) {\n\treq, err := http.NewRequest(\"GET\", baseUrl+\"echo-request\/\"+name+\"-header\", nil)\n\tchkfatal(t, err)\n\treq.Header.Set(name, sendVal)\n\n\tresp, err := http.DefaultClient.Do(req)\n\tchkfatal(t, err)\n\tdefer func() {\n\t\tif t.Failed() {\n\t\t\tt.Log(\"Response:\", resp)\n\t\t}\n\t}()\n\n\texpectStatus(t, 200, resp.StatusCode)\n\tbody := &echoBody{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\tchkfatal(t, err)\n\tgotRecvVal := body.Headers.Get(name)\n\tif gotRecvVal != wantRecvVal {\n\t\tt.Fatalf(\"Server did not see correct value for %s header; \"+\n\t\t\t\"wanted %q but got %q\", name, wantRecvVal, gotRecvVal)\n\t}\n}\n\nfunc TestAcceptHeader(t *testing.T) {\n\ttestHeader(t, \"Accept\", \"application\/json\", \"application\/json; q=1\")\n}\n\nfunc TestAcceptEncodingHeader(t *testing.T) {\n\ttestHeader(t, \"Accept-Encoding\", \"something-non-standard\", \"something-non-standard;q=1\")\n\ttestHeader(t, \"Accept-Encoding\", \"gzip\", \"gzip;q=1\")\n\ttestHeader(t, \"Accept-Encoding\", \"*;q=1\", \"*;q=1\")\n}\n\nfunc TestAdditionalHeaders(t *testing.T) {\n\ttestHeader(t, \"X-Foo-Disallowed-Header\", \"Bar\", \"\")\n\ttestHeader(t, \"X-Sandstorm-App-Baz\", \"quux\", \"quux\")\n\ttestHeader(t, \"OC-Total-Length\", \"234\", \"234\")\n}\n\nfunc TestETagPrecondition(t *testing.T) {\n\ttestHeader(t, \"If-Match\", \"*\", \"*\")\n\ttestHeader(t, \"If-None-Match\", `\"foobarbaz\"`, `\"foobarbaz\"`)\n\ttestHeader(t, \"If-None-Match\", `W\/\"foobarbaz\"`, `W\/\"foobarbaz\"`)\n\ttestHeader(t, \"If-None-Match\", `W\/\"foobarbaz\", \"quux\"`, `W\/\"foobarbaz\", \"quux\"`)\n\n\t\/\/ \"net\/http\" won't magically deal with the etag header unless we use\n\t\/\/ http.FileSystem, so even though the following should arguably\n\t\/\/ return \"Precondition Failed,\" we can ignore it to check whether the\n\t\/\/ header is getting through:\n\ttestHeader(t, \"If-None-Match\", \"*\", \"*\")\n\ttestHeader(t, \"If-Match\", `\"foobarbaz\"`, `\"foobarbaz\"`)\n\ttestHeader(t, \"If-Match\", `W\/\"foobarbaz\"`, `W\/\"foobarbaz\"`)\n\ttestHeader(t, \"If-Match\", `W\/\"foobarbaz\", \"quux\"`, `W\/\"foobarbaz\", \"quux\"`)\n}\n\nfunc TestResponseContentType(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"echo-request\/content-type\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tcontentType := resp.Header.Get(\"Content-Type\")\n\tif contentType != \"application\/json\" {\n\t\tt.Fatalf(\"Expected content type application\/json but got %q\", contentType)\n\t}\n}\n\nfunc TestResponseContentEncoding(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"echo-request\/content-encoding\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\n\tencoding := resp.Header.Get(\"Content-Encoding\")\n\tif encoding != \"identity\" {\n\t\tt.Fatalf(\"Expected content encoding identity, but got %q.\", encoding)\n\t}\n}\n\nfunc TestResponseContentLength(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"content-length\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\n\tcontentLength := resp.Header.Get(\"Content-Length\")\n\treportLength, err := strconv.ParseUint(contentLength, 10, 64)\n\tchkfatal(t, err)\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tchkfatal(t, err)\n\n\trealLength := uint64(len(body))\n\tif realLength != reportLength {\n\t\tt.Fatal(\"Content-Header indicated a length of %d, but body was \",\n\t\t\t\"actually %d bytes long.\", reportLength, realLength)\n\t}\n}\n\nfunc TestWantStatus(t *testing.T) {\n\tfor _, wantStatus := range []int{200, 201, 202, 204, 205} {\n\t\tresp, err := http.Get(fmt.Sprintf(\n\t\t\t\"%secho-request\/status?want-status=%d\", baseUrl, wantStatus,\n\t\t))\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, wantStatus, resp.StatusCode)\n\t}\n}\n\nfunc TestWantLanguage(t *testing.T) {\n\tfor _, wantLang := range []string{\"en-US\", \"de-DE\"} {\n\t\tresp, err := http.Get(\n\t\t\tbaseUrl + \"echo-request\/lang?want-lang=\" + wantLang,\n\t\t)\n\t\tchkfatal(t, err)\n\t\texpectStatus(t, 200, resp.StatusCode)\n\t\tgotLang := resp.Header.Get(\"Content-Language\")\n\t\tif wantLang != gotLang {\n\t\t\tt.Fatalf(\"Unexpected Content-Language; wanted %q but got %q.\",\n\t\t\t\twantLang, gotLang)\n\t\t}\n\t}\n}\n\nfunc TestNoOpHandler(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"no-op-handler\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n}\n\nfunc TestETag(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"etag\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tetag := resp.Header.Get(\"ETag\")\n\n\tif etag != `\"sometag\"` {\n\t\tt.Errorf(`Expected ETag value \"sometag\", but got %q`, etag)\n\t}\n\n\tresp, err = http.Get(baseUrl + \"etag?weak=true\")\n\tchkfatal(t, err)\n\texpectStatus(t, 200, resp.StatusCode)\n\tetag = resp.Header.Get(\"ETag\")\n\n\tif etag != `W\/\"sometag\"` {\n\t\tt.Errorf(`Expected ETag value W\/\"sometag\", but got %q`, etag)\n\t}\n}\n\nfunc TestNoContentBodies(t *testing.T) {\n\tresp, err := http.Get(baseUrl + \"echo-request\/status?want-status=205\")\n\tchkfatal(t, err)\n\texpectStatus(t, 205, resp.StatusCode)\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tchkfatal(t, err)\n\tif len(data) != 0 {\n\t\tt.Fatalf(\"No-content response returned a body: %q\", data)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package linda\n\nimport (\n\t\"flag\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nfunc init() {\n\tflag.StringVar(&settings.Queue, \"queues\", \"\", \"queue name\")\n\tflag.Float64Var(&settings.IntervalFloat, \"interval\", 5.0, \"sleep interval when no jobs are found\")\n\tflag.IntVar(&settings.Concurrency, \"concurrency\", 2, \"the maximum number of concurrently workers\")\n\tflag.StringVar(&settings.Connection, \"connection\", \"redis:\/\/localhost:6379\/\", \"the url of the broker connection\")\n}\n\nfunc flags() error {\n\tif !flag.Parsed() {\n\t\tlogrus.Debug(\"parse the flag\")\n\t\tflag.Parse()\n\t}\n\n\tif err := settings.Interval.SetFloat(settings.IntervalFloat); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>modify flag queues to queue add default value of queue `default`<commit_after>package linda\n\nimport (\n\t\"flag\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nfunc init() {\n\tflag.StringVar(&settings.Queue, \"queue\", \"default\", \"queue name\")\n\tflag.Float64Var(&settings.IntervalFloat, \"interval\", 5.0, \"sleep interval when no jobs are found\")\n\tflag.IntVar(&settings.Concurrency, \"concurrency\", 2, \"the maximum number of concurrently workers\")\n\tflag.StringVar(&settings.Connection, \"connection\", \"redis:\/\/localhost:6379\/\", \"the url of the broker connection\")\n}\n\nfunc flags() error {\n\tif !flag.Parsed() {\n\t\tlogrus.Debug(\"parse the flag\")\n\t\tflag.Parse()\n\t}\n\n\tif err := settings.Interval.SetFloat(settings.IntervalFloat); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2017 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 main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/tgo\/tflag\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar (\n\tflagHelp           = tflag.Switch(\"h\", \"help\", \"Print this help message.\")\n\tflagVersion        = tflag.Switch(\"v\", \"version\", \"Print version information and quit.\")\n\tflagReport         = tflag.Switch(\"r\", \"report\", \"Print detailed version report and quit.\")\n\tflagModules        = tflag.Switch(\"l\", \"list\", \"Print plugin information and quit.\")\n\tflagConfigFile     = tflag.String(\"c\", \"config\", \"\", \"Use a given configuration file.\")\n\tflagTestConfigFile = tflag.String(\"tc\", \"testconfig\", \"\", \"Test the given configuration file and exit.\")\n\tflagLoglevel       = tflag.Int(\"ll\", \"loglevel\", 1, \"Set the loglevel [0-3] as in {0=Error, 1=+Warning, 2=+Info, 3=+Debug}.\")\n\tflagNumCPU         = tflag.Int(\"n\", \"numcpu\", 0, \"Number of CPUs to use. Set 0 for all CPUs.\")\n\tflagPidFile        = tflag.String(\"p\", \"pidfile\", \"\", \"Write the relayEntry id into a given file.\")\n\tflagMetricsAddress = tflag.String(\"m\", \"metrics\", \"\", \"Address to use for metric queries. Disabled by default.\")\n\tflagHealthCheck    = tflag.String(\"hc\", \"healthcheck\", \"\", \"Listening address ([IP]:PORT) to use for healthcheck HTTP endpoint. Disabled by default.\")\n\tflagCPUProfile     = tflag.String(\"pc\", \"profilecpu\", \"\", \"Write CPU profiler results to a given file.\")\n\tflagMemProfile     = tflag.String(\"pm\", \"profilemem\", \"\", \"Write heap profile results to a given file.\")\n\tflagProfile        = tflag.Switch(\"ps\", \"profilespeed\", \"Write msg\/sec measurements to log.\")\n\tflagTrace          = tflag.String(\"tr\", \"trace\", \"\", \"Write trace results to a given file.\")\n)\n\nfunc parseFlags() {\n\ttflag.Parse()\n}\n\nfunc printFlags() {\n\thelpMessageStr := fmt.Sprintf(\"Usage: gollum [OPTIONS]\\n\\nGollum - An n:m message multiplexer.\\nVersion: %s\\n\\nOptions:\", core.GetVersionString())\n\ttflag.PrintFlags(helpMessageStr)\n}\n\nfunc getLogrusLevel(intLevel int) logrus.Level {\n\tswitch intLevel {\n\tcase 0: return logrus.ErrorLevel\n\tcase 1: return logrus.WarnLevel\n\tcase 2: return logrus.InfoLevel\n\tcase 3: return logrus.DebugLevel\n\t}\n\treturn logrus.DebugLevel\n}\n<commit_msg>Revert auto-refactoring<commit_after>\/\/ Copyright 2015-2017 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 main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/tgo\/tflag\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar (\n\tflagHelp           = tflag.Switch(\"h\", \"help\", \"Print this help message.\")\n\tflagVersion        = tflag.Switch(\"v\", \"version\", \"Print version information and quit.\")\n\tflagReport         = tflag.Switch(\"r\", \"report\", \"Print detailed version report and quit.\")\n\tflagModules        = tflag.Switch(\"l\", \"list\", \"Print plugin information and quit.\")\n\tflagConfigFile     = tflag.String(\"c\", \"config\", \"\", \"Use a given configuration file.\")\n\tflagTestConfigFile = tflag.String(\"tc\", \"testconfig\", \"\", \"Test the given configuration file and exit.\")\n\tflagLoglevel       = tflag.Int(\"ll\", \"loglevel\", 1, \"Set the loglevel [0-3] as in {0=Error, 1=+Warning, 2=+Info, 3=+Debug}.\")\n\tflagNumCPU         = tflag.Int(\"n\", \"numcpu\", 0, \"Number of CPUs to use. Set 0 for all CPUs.\")\n\tflagPidFile        = tflag.String(\"p\", \"pidfile\", \"\", \"Write the process id into a given file.\")\n\tflagMetricsAddress = tflag.String(\"m\", \"metrics\", \"\", \"Address to use for metric queries. Disabled by default.\")\n\tflagHealthCheck    = tflag.String(\"hc\", \"healthcheck\", \"\", \"Listening address ([IP]:PORT) to use for healthcheck HTTP endpoint. Disabled by default.\")\n\tflagCPUProfile     = tflag.String(\"pc\", \"profilecpu\", \"\", \"Write CPU profiler results to a given file.\")\n\tflagMemProfile     = tflag.String(\"pm\", \"profilemem\", \"\", \"Write heap profile results to a given file.\")\n\tflagProfile        = tflag.Switch(\"ps\", \"profilespeed\", \"Write msg\/sec measurements to log.\")\n\tflagTrace          = tflag.String(\"tr\", \"trace\", \"\", \"Write trace results to a given file.\")\n)\n\nfunc parseFlags() {\n\ttflag.Parse()\n}\n\nfunc printFlags() {\n\thelpMessageStr := fmt.Sprintf(\"Usage: gollum [OPTIONS]\\n\\nGollum - An n:m message multiplexer.\\nVersion: %s\\n\\nOptions:\", core.GetVersionString())\n\ttflag.PrintFlags(helpMessageStr)\n}\n\nfunc getLogrusLevel(intLevel int) logrus.Level {\n\tswitch intLevel {\n\tcase 0: return logrus.ErrorLevel\n\tcase 1: return logrus.WarnLevel\n\tcase 2: return logrus.InfoLevel\n\tcase 3: return logrus.DebugLevel\n\t}\n\treturn logrus.DebugLevel\n}\n<|endoftext|>"}
{"text":"<commit_before>package media_library\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\/driver\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/disintegration\/imaging\"\n)\n\nvar ErrNotImplemented = errors.New(\"not implemented\")\n\ntype Base struct {\n\tUrl        string\n\tValid      bool\n\tFileName   string\n\tFileHeader *multipart.FileHeader\n\tCropOption *CropOption\n\tReader     io.Reader\n}\n\nfunc (b *Base) Scan(value interface{}) error {\n\tswitch v := value.(type) {\n\tcase []*multipart.FileHeader:\n\t\tif len(v) > 0 {\n\t\t\tfile := v[0]\n\t\t\tb.FileHeader, b.FileName, b.Valid = file, file.Filename, true\n\t\t}\n\tcase []uint8:\n\t\tb.Url, b.Valid = string(v), true\n\tcase string:\n\t\tb.Url, b.Valid = v, true\n\tdefault:\n\t\tfmt.Errorf(\"unsupported driver -> Scan pair for MediaLibrary\")\n\t}\n\treturn nil\n}\n\nfunc (b Base) Value() (driver.Value, error) {\n\tif b.Valid {\n\t\treturn b.FileName, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (b Base) URL(styles ...string) string {\n\tif len(styles) > 0 {\n\t\text := path.Ext(b.Url)\n\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(b.Url, ext), styles[0], ext)\n\t}\n\treturn b.Url\n}\n\nfunc (b Base) String() string {\n\treturn b.URL()\n}\n\nfunc (b Base) GetFileName() string {\n\treturn b.FileName\n}\n\nfunc (b Base) GetFileHeader() *multipart.FileHeader {\n\treturn b.FileHeader\n}\n\nfunc (b Base) GetURLTemplate(option *Option) (path string) {\n\tif path = option.Get(\"url\"); path == \"\" {\n\t\tpath = \"\/system\/{{class}}\/{{primary_key}}\/{{column}}\/{{basename}}.{{nanotime}}.{{extension}}\"\n\t}\n\treturn\n}\n\nfunc (b *Base) SetCropOption(option *CropOption) {\n\tb.CropOption = option\n}\n\nfunc (b *Base) GetCropOption() *CropOption {\n\treturn b.CropOption\n}\n\nfunc (b Base) Retrieve(url string) (*os.File, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (b Base) Crop(ml MediaLibrary, option *Option) error {\n\tif file, err := ml.Retrieve(b.URL(\"original\")); err == nil {\n\t\tif img, err := imaging.Decode(file); err == nil {\n\t\t\tif format, err := b.GetImageFormat(); err == nil {\n\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\tvar cropOption = b.CropOption\n\t\t\t\trect := image.Rect(cropOption.X, cropOption.Y, cropOption.X+cropOption.Width, cropOption.Y+cropOption.Height)\n\t\t\t\timaging.Encode(&buffer, imaging.Crop(img, rect), *format)\n\t\t\t\treturn ml.Store(b.URL(), option, &buffer)\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b Base) IsImage() bool {\n\t_, err := b.GetImageFormat()\n\treturn err == nil\n}\n\nfunc (b Base) GetImageFormat() (*imaging.Format, error) {\n\tformats := map[string]imaging.Format{\n\t\t\".jpg\":  imaging.JPEG,\n\t\t\".jpeg\": imaging.JPEG,\n\t\t\".png\":  imaging.PNG,\n\t\t\".tif\":  imaging.TIFF,\n\t\t\".tiff\": imaging.TIFF,\n\t\t\".bmp\":  imaging.BMP,\n\t\t\".gif\":  imaging.GIF,\n\t}\n\n\text := strings.ToLower(filepath.Ext(b.Url))\n\tif f, ok := formats[ext]; ok {\n\t\treturn &f, nil\n\t} else {\n\t\treturn nil, imaging.ErrUnsupportedFormat\n\t}\n}\n<commit_msg>Don't download uncessary file<commit_after>package media_library\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\/driver\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/disintegration\/imaging\"\n)\n\nvar ErrNotImplemented = errors.New(\"not implemented\")\n\ntype Base struct {\n\tUrl        string\n\tValid      bool\n\tFileName   string\n\tFileHeader *multipart.FileHeader\n\tCropOption *CropOption\n\tReader     io.Reader\n}\n\nfunc (b *Base) Scan(value interface{}) error {\n\tswitch v := value.(type) {\n\tcase []*multipart.FileHeader:\n\t\tif len(v) > 0 {\n\t\t\tfile := v[0]\n\t\t\tb.FileHeader, b.FileName, b.Valid = file, file.Filename, true\n\t\t}\n\tcase []uint8:\n\t\tb.Url, b.Valid = string(v), true\n\tcase string:\n\t\tb.Url, b.Valid = v, true\n\tdefault:\n\t\tfmt.Errorf(\"unsupported driver -> Scan pair for MediaLibrary\")\n\t}\n\treturn nil\n}\n\nfunc (b Base) Value() (driver.Value, error) {\n\tif b.Valid {\n\t\treturn b.FileName, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (b Base) URL(styles ...string) string {\n\tif len(styles) > 0 {\n\t\text := path.Ext(b.Url)\n\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(b.Url, ext), styles[0], ext)\n\t}\n\treturn b.Url\n}\n\nfunc (b Base) String() string {\n\treturn b.URL()\n}\n\nfunc (b Base) GetFileName() string {\n\treturn b.FileName\n}\n\nfunc (b Base) GetFileHeader() *multipart.FileHeader {\n\treturn b.FileHeader\n}\n\nfunc (b Base) GetURLTemplate(option *Option) (path string) {\n\tif path = option.Get(\"url\"); path == \"\" {\n\t\tpath = \"\/system\/{{class}}\/{{primary_key}}\/{{column}}\/{{basename}}.{{nanotime}}.{{extension}}\"\n\t}\n\treturn\n}\n\nfunc (b *Base) SetCropOption(option *CropOption) {\n\tb.CropOption = option\n}\n\nfunc (b *Base) GetCropOption() *CropOption {\n\treturn b.CropOption\n}\n\nfunc (b Base) Retrieve(url string) (*os.File, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (b Base) Crop(ml MediaLibrary, option *Option) error {\n\tvar reader io.Reader\n\tvar hasReader bool\n\n\tif ml.GetFileHeader() != nil {\n\t\tif file, err := ml.GetFileHeader().Open(); err == nil {\n\t\t\treader = file\n\t\t\thasReader = true\n\t\t}\n\t} else if file, err := ml.Retrieve(b.URL(\"original\")); err == nil {\n\t\treader = file\n\t\thasReader = true\n\t}\n\n\tif hasReader {\n\t\tif img, err := imaging.Decode(reader); err == nil {\n\t\t\tif format, err := b.GetImageFormat(); err == nil {\n\t\t\t\tvar buffer bytes.Buffer\n\t\t\t\tvar cropOption = b.CropOption\n\t\t\t\trect := image.Rect(cropOption.X, cropOption.Y, cropOption.X+cropOption.Width, cropOption.Y+cropOption.Height)\n\t\t\t\timaging.Encode(&buffer, imaging.Crop(img, rect), *format)\n\t\t\t\treturn ml.Store(b.URL(), option, &buffer)\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b Base) IsImage() bool {\n\t_, err := b.GetImageFormat()\n\treturn err == nil\n}\n\nfunc (b Base) GetImageFormat() (*imaging.Format, error) {\n\tformats := map[string]imaging.Format{\n\t\t\".jpg\":  imaging.JPEG,\n\t\t\".jpeg\": imaging.JPEG,\n\t\t\".png\":  imaging.PNG,\n\t\t\".tif\":  imaging.TIFF,\n\t\t\".tiff\": imaging.TIFF,\n\t\t\".bmp\":  imaging.BMP,\n\t\t\".gif\":  imaging.GIF,\n\t}\n\n\text := strings.ToLower(filepath.Ext(b.Url))\n\tif f, ok := formats[ext]; ok {\n\t\treturn &f, nil\n\t} else {\n\t\treturn nil, imaging.ErrUnsupportedFormat\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gogame\n\n\/*\n#cgo pkg-config: sdl2\n#include \"SDL.h\"\n\nint getEventType(SDL_Event *e) {\n    return e->type;\n}\n\nint getKeyCode(SDL_Event *e) {\n    return e->key.keysym.sym;\n}\n\nint isKeyRepeat(SDL_Event *e) {\n    return e->key.repeat;\n}\n\nint isKeyPressed(int kcode) {\n    const Uint8 *state = SDL_GetKeyboardState(NULL);\n    int sc = SDL_GetScancodeFromKey(kcode);\n    return state[sc];\n}\n\n*\/\nimport \"C\"\n\nconst (\n\tK_LEFT   = C.SDLK_LEFT\n\tK_RIGHT  = C.SDLK_RIGHT\n\tK_SPACE  = C.SDLK_SPACE\n\tK_ESC    = C.SDLK_ESCAPE\n\tK_RETURN = C.SDLK_RETURN\n\tK_P      = C.SDLK_p\n\tK_I      = C.SDLK_i\n)\n\ntype Event interface{}\n\ntype EventQuit interface{}\n\ntype EventUnknown interface{}\n\ntype EventKey struct {\n\tCode int\n\tDown bool\n}\n\n\/\/ Poll for pending envents. Return nil if there is no event available\nfunc PollEvent() Event {\n\tvar cev C.SDL_Event\n\n\tfor {\n\t\tif 0 == C.SDL_PollEvent(&cev) {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch C.getEventType(&cev) {\n\n\t\tcase C.SDL_QUIT:\n\t\t\treturn new(EventQuit)\n\n\t\tcase C.SDL_KEYDOWN:\n\t\t\t\/\/ Ignore repeat key events\n\t\t\tif C.isKeyRepeat(&cev) != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tkde := new(EventKey)\n\t\t\tkde.Code = int(C.getKeyCode(&cev))\n\t\t\tkde.Down = true\n\t\t\treturn kde\n\n\t\tcase C.SDL_KEYUP:\n\t\t\tkde := new(EventKey)\n\t\t\tkde.Code = int(C.getKeyCode(&cev))\n\t\t\tkde.Down = false\n\t\t\treturn kde\n\n\t\tdefault:\n\t\t\treturn new(EventUnknown)\n\t\t}\n\t}\n\n}\n\n\/\/ Process events. Returns true if EventQuit has appeared\nfunc SlurpEvents() (quit bool) {\n\tquit = false\n\tfor {\n\t\tev := PollEvent()\n\t\tif ev == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch ev.(type) {\n\t\tcase *EventQuit:\n\t\t\tquit = true\n\t\t}\n\t}\n}\n\n\/\/ Returns true if key is pressed, false otherwise\nfunc IsKeyPressed(kcode int) bool {\n\treturn C.isKeyPressed(C.int(kcode)) == 1\n}\n<commit_msg>Added window resize event<commit_after>package gogame\n\n\/*\n#cgo pkg-config: sdl2\n#include \"SDL.h\"\n\nint getEventType(SDL_Event *e) {\n    return e->type;\n}\n\nint getKeyCode(SDL_Event *e) {\n    return e->key.keysym.sym;\n}\n\nint isKeyRepeat(SDL_Event *e) {\n    return e->key.repeat;\n}\n\nint isKeyPressed(int kcode) {\n    const Uint8 * state = SDL_GetKeyboardState(NULL);\n    int sc = SDL_GetScancodeFromKey(kcode);\n    return state[sc];\n}\n\nint getWinData(SDL_Event *e, int *w, int *h) {\n    if (e->window.event != SDL_WINDOWEVENT_RESIZED) {\n        return 0;\n    }\n    *w = e->window.data1;\n    *h = e->window.data2;\n    return 1;\n}\n\n*\/\nimport \"C\"\n\nconst (\n\tK_LEFT   = C.SDLK_LEFT\n\tK_RIGHT  = C.SDLK_RIGHT\n\tK_SPACE  = C.SDLK_SPACE\n\tK_ESC    = C.SDLK_ESCAPE\n\tK_RETURN = C.SDLK_RETURN\n\tK_P      = C.SDLK_p\n\tK_I      = C.SDLK_i\n\tK_M      = C.SDLK_m\n\tK_Q      = C.SDLK_q\n)\n\ntype Event interface{}\n\ntype EventQuit interface{}\n\ntype EventUnknown interface{}\n\ntype EventKey struct {\n\tCode int\n\tDown bool\n}\n\ntype EventResize struct {\n\tW, H int\n}\n\n\/\/ Poll for pending envents. Return nil if there is no event available\nfunc PollEvent() Event {\n\tvar cev C.SDL_Event\n\n\tfor {\n\t\tif 0 == C.SDL_PollEvent(&cev) {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch C.getEventType(&cev) {\n\n\t\tcase C.SDL_QUIT:\n\t\t\treturn new(EventQuit)\n\n\t\tcase C.SDL_KEYDOWN:\n\t\t\t\/\/ Ignore repeat key events\n\t\t\tif C.isKeyRepeat(&cev) != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tkde := new(EventKey)\n\t\t\tkde.Code = int(C.getKeyCode(&cev))\n\t\t\tkde.Down = true\n\t\t\treturn kde\n\n\t\tcase C.SDL_KEYUP:\n\t\t\tkde := new(EventKey)\n\t\t\tkde.Code = int(C.getKeyCode(&cev))\n\t\t\tkde.Down = false\n\t\t\treturn kde\n\n\t\tcase C.SDL_WINDOWEVENT:\n\t\t\tvar w, h C.int\n\t\t\tif 1 == C.getWinData(&cev, &w, &h) {\n\t\t\t\twr := new(EventResize)\n\t\t\t\twr.W = int(w)\n\t\t\t\twr.H = int(h)\n\t\t\t\treturn wr\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn new(EventUnknown)\n\t\t}\n\t}\n\n}\n\n\/\/ Process events. Returns true if EventQuit has appeared\nfunc SlurpEvents() (quit bool) {\n\tquit = false\n\tfor {\n\t\tev := PollEvent()\n\t\tif ev == nil {\n\t\t\treturn\n\t\t}\n\t\tswitch ev.(type) {\n\t\tcase *EventQuit:\n\t\t\tquit = true\n\t\t}\n\t}\n}\n\n\/\/ Returns true if key is pressed, false otherwise\nfunc IsKeyPressed(kcode int) bool {\n\treturn C.isKeyPressed(C.int(kcode)) == 1\n}\n<|endoftext|>"}
{"text":"<commit_before>package hec\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Event struct {\n\tHost       *string     `json:\"host,omitempty\"`\n\tIndex      *string     `json:\"index,omitempty\"`\n\tSource     *string     `json:\"source,omitempty\"`\n\tSourceType *string     `json:\"sourcetype,omitempty\"`\n\tTime       *string     `json:\"time,omitempty\"`\n\tEvent      interface{} `json:\"event\"`\n}\n\nfunc NewEvent(data interface{}) *Event {\n\t\/\/ Empty event is not allowed, but let HEC complain the error\n\tswitch data.(type) {\n\tcase *string:\n\t\treturn &Event{Event: *data.(*string)}\n\tcase string:\n\t\treturn &Event{Event: data.(string)}\n\tdefault:\n\t\treturn &Event{Event: data}\n\t}\n}\n\nfunc (e *Event) SetHost(host string) {\n\te.Host = &host\n}\n\nfunc (e *Event) SetIndex(index string) {\n\te.Index = &index\n}\n\nfunc (e *Event) SetSourceType(sourcetype string) {\n\te.SourceType = &sourcetype\n}\n\nfunc (e *Event) SetSource(source string) {\n\te.Source = &source\n}\n\nfunc (e *Event) SetTime(time time.Time) {\n\te.Time = String(epochTime(&time))\n}\n\nfunc (e *Event) empty() bool {\n\tswitch e.Event.(type) {\n\tcase *string:\n\t\treturn e.Event.(*string) == nil || *e.Event.(*string) == \"\"\n\tcase string:\n\t\treturn e.Event.(string) == \"\"\n\tdefault:\n\t\treturn e.Event == nil\n\t}\n}\n\nfunc epochTime(t *time.Time) string {\n\tmillis := t.UnixNano() \/ 1000000\n\treturn fmt.Sprintf(\"%d.%03d\", millis\/1000, millis%1000)\n}\n\nfunc String(str string) *string {\n\treturn &str\n}\n<commit_msg>Add support for Splunk indexed fields<commit_after>package hec\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype Event struct {\n\tHost       *string                `json:\"host,omitempty\"`\n\tIndex      *string                `json:\"index,omitempty\"`\n\tSource     *string                `json:\"source,omitempty\"`\n\tSourceType *string                `json:\"sourcetype,omitempty\"`\n\tTime       *string                `json:\"time,omitempty\"`\n\tFields     map[string]interface{} `json:\"fields,omitempty\"`\n\tEvent      interface{}            `json:\"event\"`\n}\n\nfunc NewEvent(data interface{}) *Event {\n\t\/\/ Empty event is not allowed, but let HEC complain the error\n\tswitch data.(type) {\n\tcase *string:\n\t\treturn &Event{Event: *data.(*string)}\n\tcase string:\n\t\treturn &Event{Event: data.(string)}\n\tdefault:\n\t\treturn &Event{Event: data}\n\t}\n}\n\nfunc (e *Event) SetHost(host string) {\n\te.Host = &host\n}\n\nfunc (e *Event) SetIndex(index string) {\n\te.Index = &index\n}\n\nfunc (e *Event) SetSourceType(sourcetype string) {\n\te.SourceType = &sourcetype\n}\n\nfunc (e *Event) SetSource(source string) {\n\te.Source = &source\n}\n\nfunc (e *Event) SetTime(time time.Time) {\n\te.Time = String(epochTime(&time))\n}\n\nfunc (e *Event) SetFields(fields map[string]interface{}) {\n\te.Fields = fields\n}\n\nfunc (e *Event) SetField(fieldName string, val interface{}) {\n\tif e.Fields == nil {\n\t\te.Fields = make(map[string]interface{})\n\t}\n\n\te.Fields[fieldName] = val\n}\n\nfunc (e *Event) empty() bool {\n\tswitch e.Event.(type) {\n\tcase *string:\n\t\treturn e.Event.(*string) == nil || *e.Event.(*string) == \"\"\n\tcase string:\n\t\treturn e.Event.(string) == \"\"\n\tdefault:\n\t\treturn e.Event == nil\n\t}\n}\n\nfunc epochTime(t *time.Time) string {\n\tmillis := t.UnixNano() \/ 1000000\n\treturn fmt.Sprintf(\"%d.%03d\", millis\/1000, millis%1000)\n}\n\nfunc String(str string) *string {\n\treturn &str\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package flake provides a very simple Twitter Snowflake generator and parser.\n\/\/ You can optionally set a custom epoch for you use.\npackage flake\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\ttimeBits = 41\n\tnodeBits = 10\n\tstepBits = 12\n\n\ttimeMask int64 = -1 ^ (-1 << timeBits)\n\tnodeMask int64 = -1 ^ (-1 << nodeBits)\n\tstepMask int64 = -1 ^ (-1 << stepBits)\n\n\tnodeMax = -1 ^ (-1 << nodeBits)\n\n\ttimeShift uint8 = nodeBits + stepBits\n\tnodeShift uint8 = stepBits\n)\n\n\/\/ Epoch is set to the twitter snowflake epoch of 2006-03-21:20:50:14 GMT\n\/\/ You may customize this to set a different epoch for your application.\nvar Epoch int64 = 1288834974657\n\n\/\/ A Node struct holds the basic information needed for a flake generator node\ntype Node struct {\n\tsync.Mutex\n\ttime int64\n\tnode int64\n\tstep int64\n}\n\n\/\/ An ID is a custom type used for a snowflake ID.  This is used so we can\n\/\/ attach methods onto the ID.\ntype ID int64\n\n\/\/ NewNode returns a new Flake node that can be used to generate flake IDs\nfunc NewNode(node int64) (*Node, error) {\n\n\tif node < 0 || node > nodeMax {\n\t\treturn nil, fmt.Errorf(\"Node number must be between 0 and 1023\")\n\t}\n\n\treturn &Node{\n\t\ttime: 0,\n\t\tnode: node,\n\t\tstep: 0,\n\t}, nil\n}\n\n\/\/ Generate creates and returns a unique snowflake ID\nfunc (n *Node) Generate() (ID, error) {\n\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tnow := time.Now().UnixNano() \/ 1000000\n\n\tif n.time == now {\n\t\tn.step = (n.step + 1) & stepMask\n\n\t\tif n.step == 0 {\n\t\t\tfor now <= n.time {\n\t\t\t\tnow = time.Now().UnixNano() \/ 1000000\n\t\t\t}\n\t\t}\n\t} else {\n\t\tn.step = 0\n\t}\n\n\tn.time = now\n\n\treturn ID((now-Epoch)<<timeShift |\n\t\t(n.node << nodeShift) |\n\t\t(n.step),\n\t), nil\n}\n\n\/\/ Int64 returns an int64 of the snowflake ID\nfunc (f ID) Int64() int64 {\n\treturn int64(f)\n}\n\n\/\/ String returns a string of the snowflake ID\nfunc (f ID) String() string {\n\treturn fmt.Sprintf(\"%d\", f)\n}\n\n\/\/ Base2 returns a string base2 of the snowflake ID\nfunc (f ID) Base2() string {\n\treturn strconv.FormatInt(int64(f), 2)\n}\n\n\/\/ Base36 returns a base36 string of the snowflake ID\nfunc (f ID) Base36() string {\n\treturn strconv.FormatInt(int64(f), 36)\n}\n\n\/\/ Base64 returns a base64 string of the snowflake ID\nfunc (f ID) Base64() string {\n\treturn base64.StdEncoding.EncodeToString(f.Bytes())\n}\n\n\/\/ Bytes returns a byte array of the snowflake ID\nfunc (f ID) Bytes() []byte {\n\treturn []byte(f.String())\n}\n\n\/\/ Time returns an int64 unix timestamp of the snowflake ID time\nfunc (f ID) Time() int64 {\n\treturn (int64(f) >> 22) + Epoch\n}\n\n\/\/ Node returns an int64 of the snowflake ID node number\nfunc (f ID) Node() int64 {\n\treturn int64(f) & 0x00000000003FF000 >> 12\n}\n\n\/\/ Step returns an int64 of the snowflake step (or sequence) number\nfunc (f ID) Step() int64 {\n\treturn int64(f) & 0x0000000000000FFF\n}\n\n\/\/ MarshalJSON returns a json byte array string of the snowflake ID.\nfunc (f ID) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + f.String() + `\"`), nil\n}\n\n\/\/ UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.\nfunc (f *ID) UnmarshalJSON(b []byte) error {\n\n\ts := strings.Replace(string(b), `\"`, ``, 2)\n\ti, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\t*f = ID(i)\n\n\treturn nil\n}\n<commit_msg>Remove fmt.Println<commit_after>\/\/ Package flake provides a very simple Twitter Snowflake generator and parser.\n\/\/ You can optionally set a custom epoch for you use.\npackage flake\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\ttimeBits = 41\n\tnodeBits = 10\n\tstepBits = 12\n\n\ttimeMask int64 = -1 ^ (-1 << timeBits)\n\tnodeMask int64 = -1 ^ (-1 << nodeBits)\n\tstepMask int64 = -1 ^ (-1 << stepBits)\n\n\tnodeMax = -1 ^ (-1 << nodeBits)\n\n\ttimeShift uint8 = nodeBits + stepBits\n\tnodeShift uint8 = stepBits\n)\n\n\/\/ Epoch is set to the twitter snowflake epoch of 2006-03-21:20:50:14 GMT\n\/\/ You may customize this to set a different epoch for your application.\nvar Epoch int64 = 1288834974657\n\n\/\/ A Node struct holds the basic information needed for a flake generator node\ntype Node struct {\n\tsync.Mutex\n\ttime int64\n\tnode int64\n\tstep int64\n}\n\n\/\/ An ID is a custom type used for a snowflake ID.  This is used so we can\n\/\/ attach methods onto the ID.\ntype ID int64\n\n\/\/ NewNode returns a new Flake node that can be used to generate flake IDs\nfunc NewNode(node int64) (*Node, error) {\n\n\tif node < 0 || node > nodeMax {\n\t\treturn nil, fmt.Errorf(\"Node number must be between 0 and 1023\")\n\t}\n\n\treturn &Node{\n\t\ttime: 0,\n\t\tnode: node,\n\t\tstep: 0,\n\t}, nil\n}\n\n\/\/ Generate creates and returns a unique snowflake ID\nfunc (n *Node) Generate() (ID, error) {\n\n\tn.Lock()\n\tdefer n.Unlock()\n\n\tnow := time.Now().UnixNano() \/ 1000000\n\n\tif n.time == now {\n\t\tn.step = (n.step + 1) & stepMask\n\n\t\tif n.step == 0 {\n\t\t\tfor now <= n.time {\n\t\t\t\tnow = time.Now().UnixNano() \/ 1000000\n\t\t\t}\n\t\t}\n\t} else {\n\t\tn.step = 0\n\t}\n\n\tn.time = now\n\n\treturn ID((now-Epoch)<<timeShift |\n\t\t(n.node << nodeShift) |\n\t\t(n.step),\n\t), nil\n}\n\n\/\/ Int64 returns an int64 of the snowflake ID\nfunc (f ID) Int64() int64 {\n\treturn int64(f)\n}\n\n\/\/ String returns a string of the snowflake ID\nfunc (f ID) String() string {\n\treturn fmt.Sprintf(\"%d\", f)\n}\n\n\/\/ Base2 returns a string base2 of the snowflake ID\nfunc (f ID) Base2() string {\n\treturn strconv.FormatInt(int64(f), 2)\n}\n\n\/\/ Base36 returns a base36 string of the snowflake ID\nfunc (f ID) Base36() string {\n\treturn strconv.FormatInt(int64(f), 36)\n}\n\n\/\/ Base64 returns a base64 string of the snowflake ID\nfunc (f ID) Base64() string {\n\treturn base64.StdEncoding.EncodeToString(f.Bytes())\n}\n\n\/\/ Bytes returns a byte array of the snowflake ID\nfunc (f ID) Bytes() []byte {\n\treturn []byte(f.String())\n}\n\n\/\/ Time returns an int64 unix timestamp of the snowflake ID time\nfunc (f ID) Time() int64 {\n\treturn (int64(f) >> 22) + Epoch\n}\n\n\/\/ Node returns an int64 of the snowflake ID node number\nfunc (f ID) Node() int64 {\n\treturn int64(f) & 0x00000000003FF000 >> 12\n}\n\n\/\/ Step returns an int64 of the snowflake step (or sequence) number\nfunc (f ID) Step() int64 {\n\treturn int64(f) & 0x0000000000000FFF\n}\n\n\/\/ MarshalJSON returns a json byte array string of the snowflake ID.\nfunc (f ID) MarshalJSON() ([]byte, error) {\n\treturn []byte(`\"` + f.String() + `\"`), nil\n}\n\n\/\/ UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.\nfunc (f *ID) UnmarshalJSON(b []byte) error {\n\n\ts := strings.Replace(string(b), `\"`, ``, 2)\n\ti, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*f = ID(i)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package promhttputil\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/prometheus\/common\/model\"\n)\n\nfunc ValueAddLabelSet(a model.Value, l model.LabelSet) error {\n\tswitch aTyped := a.(type) {\n\tcase model.Vector:\n\t\tfor _, item := range aTyped {\n\t\t\tfor k, v := range l {\n\t\t\t\titem.Metric[k] = v\n\t\t\t}\n\t\t}\n\n\tcase model.Matrix:\n\t\tfor _, item := range aTyped {\n\t\t\tfor k, v := range l {\n\t\t\t\titem.Metric[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}\n\n\/\/ TODO: always make copies? Now we sometimes return one, or make a copy, or do nothing\n\/\/ Merge 2 values and\nfunc MergeValues(a, b model.Value) (model.Value, error) {\n\tif a.Type() != b.Type() {\n\t\treturn nil, fmt.Errorf(\"Error!\")\n\t}\n\n\tswitch aTyped := a.(type) {\n\t\/\/ TODO: more logic? for now we assume both are correct if they exist\n\t\/\/ In the case where it is a single datapoint, we're going to assume that\n\t\/\/ either is valid, we just need one\n\tcase *model.Scalar:\n\t\tbTyped := b.(*model.Scalar)\n\n\t\tif aTyped.Value != 0 && aTyped.Timestamp != 0 {\n\t\t\treturn aTyped, nil\n\t\t} else {\n\t\t\treturn bTyped, nil\n\t\t}\n\n\t\/\/ In the case where it is a single datapoint, we're going to assume that\n\t\/\/ either is valid, we just need one\n\tcase *model.String:\n\t\tbTyped := b.(*model.String)\n\n\t\tif aTyped.Value != \"\" && aTyped.Timestamp != 0 {\n\t\t\treturn aTyped, nil\n\t\t} else {\n\t\t\treturn bTyped, nil\n\t\t}\n\n\t\/\/ List of *model.Sample -- only 1 value (guaranteed same timestamp)\n\tcase model.Vector:\n\t\tbTyped := b.(model.Vector)\n\n\t\tnewValue := make(model.Vector, 0, len(aTyped)+len(bTyped))\n\t\tfingerPrintMap := make(map[model.Fingerprint]int)\n\n\t\taddItem := func(item *model.Sample) {\n\t\t\tfinger := item.Metric.Fingerprint()\n\n\t\t\t\/\/ If we've seen this fingerPrint before, lets make sure that a value exists\n\t\t\tif index, ok := fingerPrintMap[finger]; ok {\n\t\t\t\t\/\/ TODO: better? For now we only replace if we have no value (which seems reasonable)\n\t\t\t\tif newValue[index].Value == model.SampleValue(0) {\n\t\t\t\t\tnewValue[index].Value = item.Value\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewValue = append(newValue, item)\n\t\t\t\tfingerPrintMap[finger] = len(newValue) - 1\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range aTyped {\n\t\t\taddItem(item)\n\t\t}\n\n\t\tfor _, item := range bTyped {\n\t\t\taddItem(item)\n\t\t}\n\t\treturn newValue, nil\n\n\tcase model.Matrix:\n\t\tbTyped := b.(model.Matrix)\n\n\t\tnewValue := make(model.Matrix, 0, len(aTyped)+len(bTyped))\n\t\tfingerPrintMap := make(map[model.Fingerprint]int)\n\n\t\taddStream := func(stream *model.SampleStream) {\n\t\t\tfinger := stream.Metric.Fingerprint()\n\n\t\t\t\/\/ If we've seen this fingerPrint before, lets make sure that a value exists\n\t\t\tif index, ok := fingerPrintMap[finger]; ok {\n\t\t\t\t\/\/ TODO: check this error? For now the only one is sig collision, which we check\n\t\t\t\tnewValue[index], _ = MergeSampleStream(newValue[index], stream)\n\t\t\t} else {\n\t\t\t\tnewValue = append(newValue, stream)\n\t\t\t\tfingerPrintMap[finger] = len(newValue) - 1\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range aTyped {\n\t\t\taddStream(item)\n\t\t}\n\n\t\tfor _, item := range bTyped {\n\t\t\taddStream(item)\n\t\t}\n\t\treturn newValue, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Unknown type! %v\", reflect.TypeOf(a))\n}\n\nfunc MergeSampleStream(a, b *model.SampleStream) (*model.SampleStream, error) {\n\tif a.Metric.Fingerprint() != b.Metric.Fingerprint() {\n\t\treturn nil, fmt.Errorf(\"Cannot merge mismatch fingerprints\")\n\t}\n\n\t\/\/ TODO: really there should be a library method for this in prometheus IMO\n\t\/\/ At this point we have 2 sorted lists of datapoints which we need to merge\n\tseenTimes := make(map[model.Time]struct{})\n\tnewValues := make([]model.SamplePair, 0, len(a.Values)+len(b.Values))\n\n\tai := 0 \/\/ Offset in a\n\tbi := 0 \/\/ Offset in b\n\n\t\/\/ When combining series from 2 different prometheus hosts we can run into some problems\n\t\/\/ with clock skew (from a variety of sources). The primary one I've run into is issues\n\t\/\/ with the time that prometheus stores. Since the time associated with the datapoint is\n\t\/\/ the *start* time of the scrape, there can be quite a lot of time (which can vary\n\t\/\/ dramatically between hosts) for the exporter to return. In an attempt to mitigate\n\t\/\/ this problem we're going to *not* merge any datapoint within 10s of another point\n\t\/\/ we have. This means we can tolerate 5s on either side (which can be used by either\n\t\/\/ clock skew or from this scrape skew).\n\n\t\/\/ TODO: config\n\tantiAffinityBuffer := model.TimeFromUnix(10) \/\/ 10s\n\tvar lastTime model.Time\n\n\tfor {\n\t\tif ai >= len(a.Values) && bi >= len(b.Values) {\n\t\t\tbreak\n\t\t}\n\n\t\tvar item model.SamplePair\n\n\t\tif ai < len(a.Values) { \/\/ If a exists\n\t\t\tif bi < len(b.Values) {\n\t\t\t\t\/\/ both items\n\t\t\t\tif a.Values[ai].Timestamp < b.Values[bi].Timestamp {\n\t\t\t\t\titem = a.Values[ai]\n\t\t\t\t\tai++\n\t\t\t\t} else {\n\t\t\t\t\titem = b.Values[bi]\n\t\t\t\t\tbi++\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Only A\n\t\t\t\titem = a.Values[ai]\n\t\t\t\tai++\n\t\t\t}\n\t\t} else {\n\t\t\tif bi < len(b.Values) {\n\t\t\t\t\/\/ Only B\n\t\t\t\titem = b.Values[bi]\n\t\t\t\tbi++\n\t\t\t}\n\t\t}\n\t\t\/\/ If we've already seen this timestamp, skip\n\t\tif _, ok := seenTimes[item.Timestamp]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif lastTime == 0 {\n\t\t\tlastTime = item.Timestamp\n\t\t}\n\n\t\tif item.Timestamp-lastTime < antiAffinityBuffer {\n\t\t\tcontinue\n\t\t}\n\t\tlastTime = item.Timestamp\n\n\t\t\/\/ Otherwise, lets add it\n\t\tnewValues = append(newValues, item)\n\t\tseenTimes[item.Timestamp] = struct{}{}\n\t}\n\n\treturn &model.SampleStream{\n\t\tMetric: a.Metric,\n\t\tValues: newValues,\n\t}, nil\n}\n<commit_msg>Support case where metric has no labels<commit_after>package promhttputil\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/prometheus\/common\/model\"\n)\n\nfunc ValueAddLabelSet(a model.Value, l model.LabelSet) error {\n\tswitch aTyped := a.(type) {\n\tcase model.Vector:\n\t\tfor _, item := range aTyped {\n\t\t\tfor k, v := range l {\n\t\t\t\titem.Metric[k] = v\n\t\t\t}\n\t\t}\n\n\tcase model.Matrix:\n\t\tfor _, item := range aTyped {\n\t\t\t\/\/ If the current metric has no labels, set them\n\t\t\tif item.Metric == nil {\n\t\t\t\titem.Metric = model.Metric(model.LabelSet(make(map[model.LabelName]model.LabelValue)))\n\t\t\t}\n\t\t\tfor k, v := range l {\n\t\t\t\titem.Metric[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n\n}\n\n\/\/ TODO: always make copies? Now we sometimes return one, or make a copy, or do nothing\n\/\/ Merge 2 values and\nfunc MergeValues(a, b model.Value) (model.Value, error) {\n\tif a.Type() != b.Type() {\n\t\treturn nil, fmt.Errorf(\"Error!\")\n\t}\n\n\tswitch aTyped := a.(type) {\n\t\/\/ TODO: more logic? for now we assume both are correct if they exist\n\t\/\/ In the case where it is a single datapoint, we're going to assume that\n\t\/\/ either is valid, we just need one\n\tcase *model.Scalar:\n\t\tbTyped := b.(*model.Scalar)\n\n\t\tif aTyped.Value != 0 && aTyped.Timestamp != 0 {\n\t\t\treturn aTyped, nil\n\t\t} else {\n\t\t\treturn bTyped, nil\n\t\t}\n\n\t\/\/ In the case where it is a single datapoint, we're going to assume that\n\t\/\/ either is valid, we just need one\n\tcase *model.String:\n\t\tbTyped := b.(*model.String)\n\n\t\tif aTyped.Value != \"\" && aTyped.Timestamp != 0 {\n\t\t\treturn aTyped, nil\n\t\t} else {\n\t\t\treturn bTyped, nil\n\t\t}\n\n\t\/\/ List of *model.Sample -- only 1 value (guaranteed same timestamp)\n\tcase model.Vector:\n\t\tbTyped := b.(model.Vector)\n\n\t\tnewValue := make(model.Vector, 0, len(aTyped)+len(bTyped))\n\t\tfingerPrintMap := make(map[model.Fingerprint]int)\n\n\t\taddItem := func(item *model.Sample) {\n\t\t\tfinger := item.Metric.Fingerprint()\n\n\t\t\t\/\/ If we've seen this fingerPrint before, lets make sure that a value exists\n\t\t\tif index, ok := fingerPrintMap[finger]; ok {\n\t\t\t\t\/\/ TODO: better? For now we only replace if we have no value (which seems reasonable)\n\t\t\t\tif newValue[index].Value == model.SampleValue(0) {\n\t\t\t\t\tnewValue[index].Value = item.Value\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewValue = append(newValue, item)\n\t\t\t\tfingerPrintMap[finger] = len(newValue) - 1\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range aTyped {\n\t\t\taddItem(item)\n\t\t}\n\n\t\tfor _, item := range bTyped {\n\t\t\taddItem(item)\n\t\t}\n\t\treturn newValue, nil\n\n\tcase model.Matrix:\n\t\tbTyped := b.(model.Matrix)\n\n\t\tnewValue := make(model.Matrix, 0, len(aTyped)+len(bTyped))\n\t\tfingerPrintMap := make(map[model.Fingerprint]int)\n\n\t\taddStream := func(stream *model.SampleStream) {\n\t\t\tfinger := stream.Metric.Fingerprint()\n\n\t\t\t\/\/ If we've seen this fingerPrint before, lets make sure that a value exists\n\t\t\tif index, ok := fingerPrintMap[finger]; ok {\n\t\t\t\t\/\/ TODO: check this error? For now the only one is sig collision, which we check\n\t\t\t\tnewValue[index], _ = MergeSampleStream(newValue[index], stream)\n\t\t\t} else {\n\t\t\t\tnewValue = append(newValue, stream)\n\t\t\t\tfingerPrintMap[finger] = len(newValue) - 1\n\t\t\t}\n\t\t}\n\n\t\tfor _, item := range aTyped {\n\t\t\taddStream(item)\n\t\t}\n\n\t\tfor _, item := range bTyped {\n\t\t\taddStream(item)\n\t\t}\n\t\treturn newValue, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Unknown type! %v\", reflect.TypeOf(a))\n}\n\nfunc MergeSampleStream(a, b *model.SampleStream) (*model.SampleStream, error) {\n\tif a.Metric.Fingerprint() != b.Metric.Fingerprint() {\n\t\treturn nil, fmt.Errorf(\"Cannot merge mismatch fingerprints\")\n\t}\n\n\t\/\/ TODO: really there should be a library method for this in prometheus IMO\n\t\/\/ At this point we have 2 sorted lists of datapoints which we need to merge\n\tseenTimes := make(map[model.Time]struct{})\n\tnewValues := make([]model.SamplePair, 0, len(a.Values)+len(b.Values))\n\n\tai := 0 \/\/ Offset in a\n\tbi := 0 \/\/ Offset in b\n\n\t\/\/ When combining series from 2 different prometheus hosts we can run into some problems\n\t\/\/ with clock skew (from a variety of sources). The primary one I've run into is issues\n\t\/\/ with the time that prometheus stores. Since the time associated with the datapoint is\n\t\/\/ the *start* time of the scrape, there can be quite a lot of time (which can vary\n\t\/\/ dramatically between hosts) for the exporter to return. In an attempt to mitigate\n\t\/\/ this problem we're going to *not* merge any datapoint within 10s of another point\n\t\/\/ we have. This means we can tolerate 5s on either side (which can be used by either\n\t\/\/ clock skew or from this scrape skew).\n\n\t\/\/ TODO: config\n\tantiAffinityBuffer := model.TimeFromUnix(10) \/\/ 10s\n\tvar lastTime model.Time\n\n\tfor {\n\t\tif ai >= len(a.Values) && bi >= len(b.Values) {\n\t\t\tbreak\n\t\t}\n\n\t\tvar item model.SamplePair\n\n\t\tif ai < len(a.Values) { \/\/ If a exists\n\t\t\tif bi < len(b.Values) {\n\t\t\t\t\/\/ both items\n\t\t\t\tif a.Values[ai].Timestamp < b.Values[bi].Timestamp {\n\t\t\t\t\titem = a.Values[ai]\n\t\t\t\t\tai++\n\t\t\t\t} else {\n\t\t\t\t\titem = b.Values[bi]\n\t\t\t\t\tbi++\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Only A\n\t\t\t\titem = a.Values[ai]\n\t\t\t\tai++\n\t\t\t}\n\t\t} else {\n\t\t\tif bi < len(b.Values) {\n\t\t\t\t\/\/ Only B\n\t\t\t\titem = b.Values[bi]\n\t\t\t\tbi++\n\t\t\t}\n\t\t}\n\t\t\/\/ If we've already seen this timestamp, skip\n\t\tif _, ok := seenTimes[item.Timestamp]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif lastTime == 0 {\n\t\t\tlastTime = item.Timestamp\n\t\t}\n\n\t\tif item.Timestamp-lastTime < antiAffinityBuffer {\n\t\t\tcontinue\n\t\t}\n\t\tlastTime = item.Timestamp\n\n\t\t\/\/ Otherwise, lets add it\n\t\tnewValues = append(newValues, item)\n\t\tseenTimes[item.Timestamp] = struct{}{}\n\t}\n\n\treturn &model.SampleStream{\n\t\tMetric: a.Metric,\n\t\tValues: newValues,\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"time\"\n)\n\ntype Pipeline struct {\n\tMongoPipeline []bson.M\n}\n\ntype QueryResult struct {\n\tTotal int `json:\"total\", bson:\"total\"`\n}\n\ntype QueryPatientList struct {\n\tPatientIds []string `json:\"patientids\", bson:\"patientids\"`\n}\n\ntype PipelineProducer func(q *models.Query) (p Pipeline)\n\nfunc NewPipeline(q *models.Query) Pipeline {\n\tpipeline := Pipeline{}\n\tpipeline.MongoPipeline = []bson.M{{\"$group\": bson.M{\"_id\": \"$patientid\", \"gender\": bson.M{\"$max\": \"$gender\"}, \"birthdate\": bson.M{\"$max\": \"$birthdate\"}, \"entries\": bson.M{\"$push\": bson.M{\"startdate\": \"$startdate\", \"enddate\": \"$enddate\", \"codes\": \"$codes\", \"type\": \"$type\"}}}}}\n\tfor _, extension := range q.Parameter {\n\t\tswitch extension.Url {\n\t\tcase \"http:\/\/interventionengine.org\/patientgender\":\n\t\t\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"gender\": extension.ValueString}})\n\t\tcase \"http:\/\/interventionengine.org\/patientage\":\n\t\t\tlowAgeDate, highAgeDate := ageRangeToTime(extension.ValueRange)\n\t\t\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"birthdate.time\": bson.M{\"$gte\": highAgeDate, \"$lte\": lowAgeDate}}})\n\t\tcase \"http:\/\/interventionengine.org\/conditioncode\":\n\t\t\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, codedPipelinePhase(\"Condition\", extension.ValueCodeableConcept))\n\t\tcase \"http:\/\/interventionengine.org\/encountercode\":\n\t\t\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, codedPipelinePhase(\"Encounter\", extension.ValueCodeableConcept))\n\n\t\t}\n\t}\n\n\treturn pipeline\n}\n\nfunc NewConditionPipeline(q *models.Query) Pipeline {\n\tpipeline := NewPipeline(q)\n\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$unwind\": \"$entries\"})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"entries.type\": \"Condition\"}})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": \"entries.codes.coding.code\", \"total\": bson.M{\"$sum\": 1}}})\n\treturn pipeline\n}\n\nfunc NewEncounterPipeline(q *models.Query) Pipeline {\n\tpipeline := NewPipeline(q)\n\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$unwind\": \"$entries\"})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"entries.type\": \"Encounter\"}})\n\treturn pipeline\n}\n\nfunc (p *Pipeline) MakeCountPipeline() {\n\tp.MongoPipeline = append(p.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": nil, \"total\": bson.M{\"$sum\": 1}}})\n}\n\nfunc (p *Pipeline) MakePatientListPipeline() {\n\tp.MongoPipeline = append(p.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": nil, \"patientids\": bson.M{\"$push\": \"$_id\"}}})\n}\n\nfunc (p *Pipeline) ExecuteCount(db *mgo.Database) (QueryResult, error) {\n\tfactCollection := db.C(\"facts\")\n\tqr := QueryResult{}\n\tp.MakeCountPipeline()\n\terr := factCollection.Pipe(p.MongoPipeline).One(&qr)\n\treturn qr, err\n}\n\nfunc (p *Pipeline) ExecutePatientList(db *mgo.Database) (QueryPatientList, error) {\n\tfactCollection := db.C(\"facts\")\n\tqpl := QueryPatientList{}\n\tp.MakePatientListPipeline()\n\terr := factCollection.Pipe(p.MongoPipeline).One(&qpl)\n\treturn qpl, err\n}\n\nfunc codedPipelinePhase(factType string, cc models.CodeableConcept) bson.M {\n\tif len(cc.Coding) == 1 {\n\t\tcode := cc.Coding[0].Code\n\t\tsystem := cc.Coding[0].System\n\t\treturn bson.M{\"$match\": bson.M{\"entries.type\": factType, \"entries.codes.coding.code\": code, \"entries.codes.coding.system\": system}}\n\t} else {\n\t\tvar codeList []bson.M\n\t\tfor _, coding := range cc.Coding {\n\t\t\tcode := coding.Code\n\t\t\tsystem := coding.System\n\t\t\tcodeList = append(codeList, bson.M{\"entries.codes.coding.code\": code, \"entries.codes.coding.system\": system})\n\t\t}\n\t\treturn bson.M{\"$match\": bson.M{\"entries.type\": factType, \"$or\": codeList}}\n\t}\n\n}\n\nfunc ageRangeToTime(ageRange models.Range) (lowAgeDate, highAgeDate time.Time) {\n\tlowAgeDate = time.Date(time.Now().Year()-int(ageRange.Low.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\thighAgeDate = time.Date(time.Now().Year()-int(ageRange.High.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\treturn\n}\n<commit_msg>Refactoring pipeline creation<commit_after>package models\n\nimport (\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"time\"\n)\n\ntype Pipeline struct {\n\tMongoPipeline []bson.M\n}\n\ntype MatchingStage struct {\n\tAndStatements bson.M\n\tOrStatements  []bson.M\n}\n\nfunc NewMS() *MatchingStage {\n\tms := &MatchingStage{}\n\tms.AndStatements = bson.M{}\n\tms.OrStatements = []bson.M{}\n\treturn ms\n}\n\nfunc (m *MatchingStage) AddAndStatement(key string, value interface{}) {\n\tm.AndStatements[key] = value\n}\n\nfunc (m *MatchingStage) AddOrStatement(statement bson.M) {\n\tm.OrStatements = append(m.OrStatements, statement)\n}\n\nfunc (m *MatchingStage) AddType(typeString string) {\n\tm.AndStatements[\"entries.type\"] = typeString\n}\n\nfunc (m *MatchingStage) AddCodableConecpt(cc models.CodeableConcept) {\n\tif len(cc.Coding) == 1 {\n\t\tcode := cc.Coding[0].Code\n\t\tsystem := cc.Coding[0].System\n\t\tm.AddAndStatement(\"entries.codes.coding.code\", code)\n\t\tm.AddAndStatement(\"entries.codes.coding.system\", system)\n\t} else {\n\t\tfor _, coding := range cc.Coding {\n\t\t\tcode := coding.Code\n\t\t\tsystem := coding.System\n\t\t\tm.AddOrStatement(bson.M{\"entries.codes.coding.code\": code, \"entries.codes.coding.system\": system})\n\t\t}\n\t}\n}\n\nfunc (m *MatchingStage) ToBSON() bson.M {\n\tif len(m.OrStatements) > 1 {\n\t\tm.AndStatements[\"$or\"] = m.OrStatements\n\t}\n\treturn bson.M{\"$match\": m.AndStatements}\n}\n\ntype QueryResult struct {\n\tTotal int `json:\"total\", bson:\"total\"`\n}\n\ntype QueryPatientList struct {\n\tPatientIds []string `json:\"patientids\", bson:\"patientids\"`\n}\n\ntype PipelineProducer func(q *models.Query) (p Pipeline)\n\nfunc NewPipeline(q *models.Query) Pipeline {\n\tpipeline := Pipeline{}\n\tpipeline.MongoPipeline = []bson.M{{\"$group\": bson.M{\"_id\": \"$patientid\", \"gender\": bson.M{\"$max\": \"$gender\"}, \"birthdate\": bson.M{\"$max\": \"$birthdate\"}, \"entries\": bson.M{\"$push\": bson.M{\"startdate\": \"$startdate\", \"enddate\": \"$enddate\", \"codes\": \"$codes\", \"type\": \"$type\"}}}}}\n\tfor _, extension := range q.Parameter {\n\t\tms := NewMS()\n\t\tswitch extension.Url {\n\t\tcase \"http:\/\/interventionengine.org\/patientgender\":\n\t\t\tms.AddAndStatement(\"gender\", extension.ValueString)\n\t\tcase \"http:\/\/interventionengine.org\/patientage\":\n\t\t\tlowAgeDate, highAgeDate := ageRangeToTime(extension.ValueRange)\n\t\t\tms.AddAndStatement(\"birthdate.time\", bson.M{\"$gte\": highAgeDate, \"$lte\": lowAgeDate})\n\t\tcase \"http:\/\/interventionengine.org\/conditioncode\":\n\t\t\tms.AddType(\"Condition\")\n\t\t\tms.AddCodableConecpt(extension.ValueCodeableConcept)\n\t\tcase \"http:\/\/interventionengine.org\/encountercode\":\n\t\t\tms.AddType(\"Encounter\")\n\t\t\tms.AddCodableConecpt(extension.ValueCodeableConcept)\n\t\tcase \"http:\/\/interventionengine.org\/observationcode\":\n\t\t\tms.AddType(\"Observation\")\n\t\t\tms.AddCodableConecpt(extension.ValueCodeableConcept)\n\t\t}\n\t\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, ms.ToBSON())\n\t}\n\n\treturn pipeline\n}\n\nfunc NewConditionPipeline(q *models.Query) Pipeline {\n\tpipeline := NewPipeline(q)\n\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$unwind\": \"$entries\"})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"entries.type\": \"Condition\"}})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": \"entries.codes.coding.code\", \"total\": bson.M{\"$sum\": 1}}})\n\treturn pipeline\n}\n\nfunc NewEncounterPipeline(q *models.Query) Pipeline {\n\tpipeline := NewPipeline(q)\n\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$unwind\": \"$entries\"})\n\tpipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{\"$match\": bson.M{\"entries.type\": \"Encounter\"}})\n\treturn pipeline\n}\n\nfunc (p *Pipeline) MakeCountPipeline() {\n\tp.MongoPipeline = append(p.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": nil, \"total\": bson.M{\"$sum\": 1}}})\n}\n\nfunc (p *Pipeline) MakePatientListPipeline() {\n\tp.MongoPipeline = append(p.MongoPipeline, bson.M{\"$group\": bson.M{\"_id\": nil, \"patientids\": bson.M{\"$push\": \"$_id\"}}})\n}\n\nfunc (p *Pipeline) ExecuteCount(db *mgo.Database) (QueryResult, error) {\n\tfactCollection := db.C(\"facts\")\n\tqr := QueryResult{}\n\tp.MakeCountPipeline()\n\terr := factCollection.Pipe(p.MongoPipeline).One(&qr)\n\treturn qr, err\n}\n\nfunc (p *Pipeline) ExecutePatientList(db *mgo.Database) (QueryPatientList, error) {\n\tfactCollection := db.C(\"facts\")\n\tqpl := QueryPatientList{}\n\tp.MakePatientListPipeline()\n\terr := factCollection.Pipe(p.MongoPipeline).One(&qpl)\n\treturn qpl, err\n}\n\nfunc ageRangeToTime(ageRange models.Range) (lowAgeDate, highAgeDate time.Time) {\n\tlowAgeDate = time.Date(time.Now().Year()-int(ageRange.Low.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\thighAgeDate = time.Date(time.Now().Year()-int(ageRange.High.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package frame provides plan9-like editable text images on a raster display. This implementation\n\/\/ preserves NUL bytes, and uses a set of replacement characters for undenderable text glyphs generated\n\/\/ with a smaller sized font (hexidecimal or ascii representation).\n\/\/\n\/\/ A frame's text is not addressable\npackage frame\n\nimport (\n\t\"github.com\/as\/drawcache\"\n\t\"github.com\/as\/frame\/box\"\n\t\"github.com\/as\/frame\/font\"\n\t\"image\"\n\t\"image\/draw\"\n)\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\treturn f.b\n}\nfunc (f *Frame) Size() image.Point {\n\tr := f.RGBA().Bounds()\n\treturn image.Pt(r.Dx(), r.Dy())\n}\n\ntype Frame struct {\n\tbox.Run\n\tColor\n\tFont         *font.Font\n\tb            *image.RGBA\n\tr, entire    image.Rectangle\n\tmaxtab       int\n\tlastlinefull int\n\n\tp0 int64\n\tp1 int64\n\n\ttick      draw.Image\n\ttickback  draw.Image\n\tTicked    bool\n\ttickscale int\n\ttickoff   bool\n\tmaxlines  int\n\tmodified  bool\n\tnoredraw  bool\n\top        draw.Op\n\n\tdrawcache.Drawer\n\tpts     [][2]image.Point\n\tScroll  func(int)\n\tir      *box.Run\n\thexFont *font.Font\n\thex     []draw.Image\n}\n\n\/\/ New creates a new frame on b with bounds r. The image b is used\n\/\/ as the frame's internal bitmap cache.\nfunc New(r image.Rectangle, ft *font.Font, b *image.RGBA, cols Color) *Frame {\n\tspaceDx := ft.Measure(' ')\n\tf := &Frame{\n\t\tFont:   ft,\n\t\tmaxtab: 4 * spaceDx,\n\t\tColor:  cols,\n\t\tRun:    box.NewRun(spaceDx, 5000, ft.MeasureByte),\n\t\top:     draw.Src,\n\t}\n\tf.setrects(r, b)\n\tf.inittick()\n\trun := box.NewRun(spaceDx, 5000, ft.MeasureByte)\n\tf.ir = &run\n\tf.Drawer = drawcache.New()\n\treturn f\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\nfunc (f *Frame) SetOp(op draw.Op) {\n\tf.op = op\n\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft *font.Font) {\n\tf.r = r\n\tf.b = b\n\tf.SetFont(ft)\n}\n\nfunc (f *Frame) SetFont(ft *font.Font) {\n\tf.Font = ft\n\tf.Run.Reset(f.Font.MeasureByte)\n\tf.Refresh()\n}\n\n\/\/ Dx returns the width of s in pixels\nfunc (f *Frame) Dx(s string) int {\n\treturn f.Font.Dx(s)\n}\n\n\/\/ Dy returns the height of a glyphs bounding box\nfunc (f *Frame) Dy() int {\n\treturn f.Font.Dy()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\n\/\/ Full returns true if the last line in the frame is full\nfunc (f *Frame) Full() bool {\n\treturn f.lastlinefull == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\treturn f.Nlines\n}\n\n\/\/ Len returns the number of bytes currently in the frame\nfunc (f *Frame) Len() int64 {\n\treturn f.Nchars\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\n\/\/ Select sets the range of the selected text\nfunc (f *Frame) Select(p0, p1 int64) {\n\tf.modified = true\n\tf.p0, f.p1 = p0, p1\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b *image.RGBA) {\n\tf.b = b\n\tf.entire = r\n\tf.r = r\n\tf.r.Max.Y -= f.r.Dy() % f.Font.Dy()\n\tf.maxlines = f.r.Dy() \/ f.Font.Dy()\n}\n\nfunc (f *Frame) clear(freeall bool) {\n\tif f.Nbox != 0 {\n\t\tf.Run.Delete(0, f.Nbox-1)\n\t}\n\tif f.Box != nil {\n\t\tfree(f.Box)\n\t}\n\tif freeall {\n\t\t\/\/ TODO: unnecessary\n\t\tfreeimage(f.tick)\n\t\tfreeimage(f.tickback)\n\t\tf.tick = nil\n\t\tf.tickback = nil\n\t}\n\tf.Box = nil\n\tf.Ticked = false\n}\n\nfunc free(i interface{}) {\n}\nfunc freeimage(i image.Image) {\n}\n<commit_msg>remove duplicate select method<commit_after>\/\/ Package frame provides plan9-like editable text images on a raster display. This implementation\n\/\/ preserves NUL bytes, and uses a set of replacement characters for undenderable text glyphs generated\n\/\/ with a smaller sized font (hexidecimal or ascii representation).\n\/\/\n\/\/ A frame's text is not addressable\npackage frame\n\nimport (\n\t\"github.com\/as\/drawcache\"\n\t\"github.com\/as\/frame\/box\"\n\t\"github.com\/as\/frame\/font\"\n\t\"image\"\n\t\"image\/draw\"\n)\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\treturn f.b\n}\nfunc (f *Frame) Size() image.Point {\n\tr := f.RGBA().Bounds()\n\treturn image.Pt(r.Dx(), r.Dy())\n}\n\ntype Frame struct {\n\tbox.Run\n\tColor\n\tFont         *font.Font\n\tb            *image.RGBA\n\tr, entire    image.Rectangle\n\tmaxtab       int\n\tlastlinefull int\n\n\tp0 int64\n\tp1 int64\n\n\ttick      draw.Image\n\ttickback  draw.Image\n\tTicked    bool\n\ttickscale int\n\ttickoff   bool\n\tmaxlines  int\n\tmodified  bool\n\tnoredraw  bool\n\top        draw.Op\n\n\tdrawcache.Drawer\n\tpts     [][2]image.Point\n\tScroll  func(int)\n\tir      *box.Run\n\thexFont *font.Font\n\thex     []draw.Image\n}\n\n\/\/ New creates a new frame on b with bounds r. The image b is used\n\/\/ as the frame's internal bitmap cache.\nfunc New(r image.Rectangle, ft *font.Font, b *image.RGBA, cols Color) *Frame {\n\tspaceDx := ft.Measure(' ')\n\tf := &Frame{\n\t\tFont:   ft,\n\t\tmaxtab: 4 * spaceDx,\n\t\tColor:  cols,\n\t\tRun:    box.NewRun(spaceDx, 5000, ft.MeasureByte),\n\t\top:     draw.Src,\n\t}\n\tf.setrects(r, b)\n\tf.inittick()\n\trun := box.NewRun(spaceDx, 5000, ft.MeasureByte)\n\tf.ir = &run\n\tf.Drawer = drawcache.New()\n\treturn f\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\nfunc (f *Frame) SetOp(op draw.Op) {\n\tf.op = op\n\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft *font.Font) {\n\tf.r = r\n\tf.b = b\n\tf.SetFont(ft)\n}\n\nfunc (f *Frame) SetFont(ft *font.Font) {\n\tf.Font = ft\n\tf.Run.Reset(f.Font.MeasureByte)\n\tf.Refresh()\n}\n\n\/\/ Dx returns the width of s in pixels\nfunc (f *Frame) Dx(s string) int {\n\treturn f.Font.Dx(s)\n}\n\n\/\/ Dy returns the height of a glyphs bounding box\nfunc (f *Frame) Dy() int {\n\treturn f.Font.Dy()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\n\/\/ Full returns true if the last line in the frame is full\nfunc (f *Frame) Full() bool {\n\treturn f.lastlinefull == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\treturn f.Nlines\n}\n\n\/\/ Len returns the number of bytes currently in the frame\nfunc (f *Frame) Len() int64 {\n\treturn f.Nchars\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b *image.RGBA) {\n\tf.b = b\n\tf.entire = r\n\tf.r = r\n\tf.r.Max.Y -= f.r.Dy() % f.Font.Dy()\n\tf.maxlines = f.r.Dy() \/ f.Font.Dy()\n}\n\nfunc (f *Frame) clear(freeall bool) {\n\tif f.Nbox != 0 {\n\t\tf.Run.Delete(0, f.Nbox-1)\n\t}\n\tif f.Box != nil {\n\t\tfree(f.Box)\n\t}\n\tif freeall {\n\t\t\/\/ TODO: unnecessary\n\t\tfreeimage(f.tick)\n\t\tfreeimage(f.tickback)\n\t\tf.tick = nil\n\t\tf.tickback = nil\n\t}\n\tf.Box = nil\n\tf.Ticked = false\n}\n\nfunc free(i interface{}) {\n}\nfunc freeimage(i image.Image) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype Faces struct {\n\txPos, zPos int\n\tcount      int\n\n\tvertexes Vertexes\n\tfaces    []Face\n\tboundary *BoundaryLocator\n}\n\nfunc (fs *Faces) ProcessChunk(enclosed *EnclosedChunk, w io.Writer) (count int) {\n\tfs.Clean(enclosed.xPos, enclosed.zPos)\n\tfs.processBlocks(enclosed, fs)\n\tfs.Write(w)\n\treturn len(fs.faces)\n}\n\nfunc (fs *Faces) Clean(xPos, zPos int) {\n\tfs.xPos = xPos\n\tfs.zPos = zPos\n\n\tif fs.vertexes == nil {\n\t\tfs.vertexes = make([]int16, (128+1)*(16+1)*(16+1))\n\t} else {\n\t\tfs.vertexes.Clear()\n\t}\n\n\tif fs.faces == nil {\n\t\tfs.faces = make([]Face, 0, 8192)\n\t} else {\n\t\tfs.faces = fs.faces[:0]\n\t}\n}\n\ntype AddFacer interface {\n\tAddFace(blockId uint16, v1, v2, v3, v4 Vertex)\n}\n\ntype Face struct {\n\tblockId uint16\n\tindexes [4]int\n}\n\nfunc (fs *Faces) AddFace(blockId uint16, v1, v2, v3, v4 Vertex) {\n\tvar face = Face{blockId, [4]int{fs.vertexes.Use(v1), fs.vertexes.Use(v2), fs.vertexes.Use(v3), fs.vertexes.Use(v4)}}\n\tfs.faces = append(fs.faces, face)\n}\n\nfunc (fs *Faces) Write(w io.Writer) {\n\tfs.vertexes.Number()\n\tvar vc = int16(fs.vertexes.Print(w, fs.xPos, fs.zPos))\n\n\tvar blockIds = make([]uint16, 0, 16)\n\tfor _, face := range fs.faces {\n\t\tvar found = false\n\t\tfor _, id := range blockIds {\n\t\t\tif id == face.blockId {\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\tblockIds = append(blockIds, face.blockId)\n\t\t}\n\t}\n\n\tfor _, blockId := range blockIds {\n\t\tprintMtl(w, blockId)\n\t\tfor _, face := range fs.faces {\n\t\t\tif face.blockId == blockId {\n\t\t\t\tfmt.Fprintln(w, \"f\", fs.vertexes.Get(face.indexes[0])-vc-1, fs.vertexes.Get(face.indexes[1])-vc-1, fs.vertexes.Get(face.indexes[2])-vc-1, fs.vertexes.Get(face.indexes[3])-vc-1)\n\t\t\t\tfaceCount++\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Vertexes []int16\n\nfunc (vs *Vertexes) Index(x, y, z int) int {\n\treturn y + (z*129 + (x * 129 * 17))\n}\n\nfunc (vs *Vertexes) Use(v Vertex) int {\n\tvar i = vs.Index(v.x, v.y, v.z)\n\t(*vs)[i]++\n\treturn i\n}\n\nfunc (vs *Vertexes) Release(v Vertex) int {\n\tvar i = vs.Index(v.x, v.y, v.z)\n\t(*vs)[i]--\n\treturn i\n}\n\nfunc (vs *Vertexes) Get(i int) int16 {\n\treturn (*vs)[i]\n}\n\nfunc (vs *Vertexes) Clear() {\n\tfor i, _ := range *vs {\n\t\t(*vs)[i] = 0\n\t}\n}\n\nfunc (vs *Vertexes) Number() {\n\tvar count int16 = 0\n\tfor i, references := range *vs {\n\t\tif references != 0 {\n\t\t\tcount++\n\t\t\t(*vs)[i] = count\n\t\t} else {\n\t\t\t(*vs)[i] = -1\n\t\t}\n\t}\n}\n\nfunc (vs *Vertexes) Print(w io.Writer, xPos, zPos int) (count int) {\n\tvar buf = make([]byte, 64)\n\tcopy(buf[0:2], \"v \")\n\n\tcount = 0\n\tfor i := 0; i < len(*vs); i += 129 {\n\t\tvar x, z = (i \/ 129) \/ 17, (i \/ 129) % 17\n\n\t\tvar column = (*vs)[i : i+129]\n\t\tfor y, offset := range column {\n\t\t\tif offset != -1 {\n\n\t\t\t\tcount++\n\n\t\t\t\tvar (\n\t\t\t\t\txa = x + xPos*16\n\t\t\t\t\tya = y - 64\n\t\t\t\t\tza = z + zPos*16\n\t\t\t\t)\n\n\t\t\t\tbuf = buf[:2]\n\t\t\t\tbuf = appendCoord(buf, xa)\n\t\t\t\tbuf = append(buf, ' ')\n\t\t\t\tbuf = appendCoord(buf, ya)\n\t\t\t\tbuf = append(buf, ' ')\n\t\t\t\tbuf = appendCoord(buf, za)\n\t\t\t\tbuf = append(buf, '\\n')\n\n\t\t\t\tw.Write(buf)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc appendCoord(buf []byte, x int) []byte {\n\tvar b [64]byte\n\tvar j = len(b)\n\n\tvar neg = x < 0\n\tif neg {\n\t\tx = -x\n\t}\n\n\tvar (\n\t\thigh    = x \/ 20\n\t\tlow     = (x % 20) * 5\n\t\tnumbers = \"0123456789\"\n\t)\n\n\tfor i := 0; i < 2; i++ {\n\t\tj--\n\t\tb[j] = numbers[low%10]\n\t\tlow \/= 10\n\t}\n\n\tj--\n\tb[j] = '.'\n\n\tif high == 0 {\n\t\tj--\n\t\tb[j] = '0'\n\t} else {\n\t\tfor high > 0 {\n\t\t\tj--\n\t\t\tb[j] = numbers[high%10]\n\t\t\thigh \/= 10\n\t\t}\n\t}\n\n\tif neg {\n\t\tj--\n\t\tb[j] = '-'\n\t}\n\n\tvar end = len(buf) + len(b) - j\n\tvar d = buf[len(buf):end]\n\tcopy(d, b[j:])\n\treturn buf[:end]\n}\n\ntype Vertex struct {\n\tx, y, z int\n}\n\ntype blockRun struct {\n\tblockId        uint16\n\tv1, v2, v3, v4 Vertex\n\tdirty          bool\n}\n\nfunc (r *blockRun) AddFace(faces AddFacer) {\n\tif r.dirty {\n\t\tfaces.AddFace(r.blockId, r.v1, r.v2, r.v3, r.v4)\n\t\tr.dirty = false\n\t}\n}\n\nfunc (r *blockRun) Update(faces AddFacer, nr *blockRun, flag bool) {\n\tif !blockFaces {\n\t\tif r.dirty {\n\t\t\tif nr.blockId == r.blockId {\n\t\t\t\tif flag {\n\t\t\t\t\tr.v3 = nr.v3\n\t\t\t\t\tr.v4 = nr.v4\n\t\t\t\t} else {\n\t\t\t\t\tr.v2 = nr.v2\n\t\t\t\t\tr.v3 = nr.v3\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.AddFace(faces)\n\t\t\t\t*r = *nr\n\t\t\t}\n\t\t} else {\n\t\t\t*r = *nr\n\t\t}\n\t} else {\n\t\tnr.AddFace(faces)\n\t\tnr.dirty = false\n\t}\n}\n\nfunc (fs *Faces) processBlocks(enclosedChunk *EnclosedChunk, faces AddFacer) {\n\tfor i := 0; i < len(enclosedChunk.blocks); i += 128 {\n\t\tvar x, z = (i \/ 128) \/ 16, (i \/ 128) % 16\n\n\t\tvar r1, r2, r3, r4 blockRun\n\n\t\tvar column = BlockColumn(enclosedChunk.blocks[i : i+128])\n\t\tfor y, blockId := range column {\n\t\t\tif y < yMin {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y-1, z)) {\n\t\t\t\tfaces.AddFace(blockId, Vertex{x, y, z}, Vertex{x + 1, y, z}, Vertex{x + 1, y, z + 1}, Vertex{x, y, z + 1})\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y+1, z)) {\n\t\t\t\tfaces.AddFace(blockId, Vertex{x, y + 1, z}, Vertex{x, y + 1, z + 1}, Vertex{x + 1, y + 1, z + 1}, Vertex{x + 1, y + 1, z})\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x-1, y, z)) {\n\t\t\t\tr1.Update(faces, &blockRun{blockId, Vertex{x, y, z}, Vertex{x, y, z + 1}, Vertex{x, y + 1, z + 1}, Vertex{x, y + 1, z}, true}, true)\n\t\t\t} else {\n\t\t\t\tr1.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x+1, y, z)) {\n\t\t\t\tr2.Update(faces, &blockRun{blockId, Vertex{x + 1, y, z}, Vertex{x + 1, y + 1, z}, Vertex{x + 1, y + 1, z + 1}, Vertex{x + 1, y, z + 1}, true}, false)\n\t\t\t} else {\n\t\t\t\tr2.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y, z-1)) {\n\t\t\t\tr3.Update(faces, &blockRun{blockId, Vertex{x, y, z}, Vertex{x, y + 1, z}, Vertex{x + 1, y + 1, z}, Vertex{x + 1, y, z}, true}, false)\n\t\t\t} else {\n\t\t\t\tr3.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y, z+1)) {\n\t\t\t\tr4.Update(faces, &blockRun{blockId, Vertex{x, y, z + 1}, Vertex{x + 1, y, z + 1}, Vertex{x + 1, y + 1, z + 1}, Vertex{x, y + 1, z + 1}, true}, true)\n\t\t\t} else {\n\t\t\t\tr4.AddFace(faces)\n\t\t\t}\n\t\t}\n\n\t\tr1.AddFace(faces)\n\t\tr2.AddFace(faces)\n\t\tr3.AddFace(faces)\n\t\tr4.AddFace(faces)\n\t}\n}\n<commit_msg>Rename Faces.Clean() to Faces.clean()<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype Faces struct {\n\txPos, zPos int\n\tcount      int\n\n\tvertexes Vertexes\n\tfaces    []Face\n\tboundary *BoundaryLocator\n}\n\nfunc (fs *Faces) ProcessChunk(enclosed *EnclosedChunk, w io.Writer) (count int) {\n\tfs.clean(enclosed.xPos, enclosed.zPos)\n\tfs.processBlocks(enclosed)\n\tfs.Write(w)\n\treturn len(fs.faces)\n}\n\nfunc (fs *Faces) clean(xPos, zPos int) {\n\tfs.xPos = xPos\n\tfs.zPos = zPos\n\n\tif fs.vertexes == nil {\n\t\tfs.vertexes = make([]int16, (128+1)*(16+1)*(16+1))\n\t} else {\n\t\tfs.vertexes.Clear()\n\t}\n\n\tif fs.faces == nil {\n\t\tfs.faces = make([]Face, 0, 8192)\n\t} else {\n\t\tfs.faces = fs.faces[:0]\n\t}\n}\n\ntype AddFacer interface {\n\tAddFace(blockId uint16, v1, v2, v3, v4 Vertex)\n}\n\ntype Face struct {\n\tblockId uint16\n\tindexes [4]int\n}\n\nfunc (fs *Faces) AddFace(blockId uint16, v1, v2, v3, v4 Vertex) {\n\tvar face = Face{blockId, [4]int{fs.vertexes.Use(v1), fs.vertexes.Use(v2), fs.vertexes.Use(v3), fs.vertexes.Use(v4)}}\n\tfs.faces = append(fs.faces, face)\n}\n\nfunc (fs *Faces) Write(w io.Writer) {\n\tfs.vertexes.Number()\n\tvar vc = int16(fs.vertexes.Print(w, fs.xPos, fs.zPos))\n\n\tvar blockIds = make([]uint16, 0, 16)\n\tfor _, face := range fs.faces {\n\t\tvar found = false\n\t\tfor _, id := range blockIds {\n\t\t\tif id == face.blockId {\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\tblockIds = append(blockIds, face.blockId)\n\t\t}\n\t}\n\n\tfor _, blockId := range blockIds {\n\t\tprintMtl(w, blockId)\n\t\tfor _, face := range fs.faces {\n\t\t\tif face.blockId == blockId {\n\t\t\t\tfmt.Fprintln(w, \"f\", fs.vertexes.Get(face.indexes[0])-vc-1, fs.vertexes.Get(face.indexes[1])-vc-1, fs.vertexes.Get(face.indexes[2])-vc-1, fs.vertexes.Get(face.indexes[3])-vc-1)\n\t\t\t\tfaceCount++\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Vertexes []int16\n\nfunc (vs *Vertexes) Index(x, y, z int) int {\n\treturn y + (z*129 + (x * 129 * 17))\n}\n\nfunc (vs *Vertexes) Use(v Vertex) int {\n\tvar i = vs.Index(v.x, v.y, v.z)\n\t(*vs)[i]++\n\treturn i\n}\n\nfunc (vs *Vertexes) Release(v Vertex) int {\n\tvar i = vs.Index(v.x, v.y, v.z)\n\t(*vs)[i]--\n\treturn i\n}\n\nfunc (vs *Vertexes) Get(i int) int16 {\n\treturn (*vs)[i]\n}\n\nfunc (vs *Vertexes) Clear() {\n\tfor i, _ := range *vs {\n\t\t(*vs)[i] = 0\n\t}\n}\n\nfunc (vs *Vertexes) Number() {\n\tvar count int16 = 0\n\tfor i, references := range *vs {\n\t\tif references != 0 {\n\t\t\tcount++\n\t\t\t(*vs)[i] = count\n\t\t} else {\n\t\t\t(*vs)[i] = -1\n\t\t}\n\t}\n}\n\nfunc (vs *Vertexes) Print(w io.Writer, xPos, zPos int) (count int) {\n\tvar buf = make([]byte, 64)\n\tcopy(buf[0:2], \"v \")\n\n\tcount = 0\n\tfor i := 0; i < len(*vs); i += 129 {\n\t\tvar x, z = (i \/ 129) \/ 17, (i \/ 129) % 17\n\n\t\tvar column = (*vs)[i : i+129]\n\t\tfor y, offset := range column {\n\t\t\tif offset != -1 {\n\n\t\t\t\tcount++\n\n\t\t\t\tvar (\n\t\t\t\t\txa = x + xPos*16\n\t\t\t\t\tya = y - 64\n\t\t\t\t\tza = z + zPos*16\n\t\t\t\t)\n\n\t\t\t\tbuf = buf[:2]\n\t\t\t\tbuf = appendCoord(buf, xa)\n\t\t\t\tbuf = append(buf, ' ')\n\t\t\t\tbuf = appendCoord(buf, ya)\n\t\t\t\tbuf = append(buf, ' ')\n\t\t\t\tbuf = appendCoord(buf, za)\n\t\t\t\tbuf = append(buf, '\\n')\n\n\t\t\t\tw.Write(buf)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc appendCoord(buf []byte, x int) []byte {\n\tvar b [64]byte\n\tvar j = len(b)\n\n\tvar neg = x < 0\n\tif neg {\n\t\tx = -x\n\t}\n\n\tvar (\n\t\thigh    = x \/ 20\n\t\tlow     = (x % 20) * 5\n\t\tnumbers = \"0123456789\"\n\t)\n\n\tfor i := 0; i < 2; i++ {\n\t\tj--\n\t\tb[j] = numbers[low%10]\n\t\tlow \/= 10\n\t}\n\n\tj--\n\tb[j] = '.'\n\n\tif high == 0 {\n\t\tj--\n\t\tb[j] = '0'\n\t} else {\n\t\tfor high > 0 {\n\t\t\tj--\n\t\t\tb[j] = numbers[high%10]\n\t\t\thigh \/= 10\n\t\t}\n\t}\n\n\tif neg {\n\t\tj--\n\t\tb[j] = '-'\n\t}\n\n\tvar end = len(buf) + len(b) - j\n\tvar d = buf[len(buf):end]\n\tcopy(d, b[j:])\n\treturn buf[:end]\n}\n\ntype Vertex struct {\n\tx, y, z int\n}\n\ntype blockRun struct {\n\tblockId        uint16\n\tv1, v2, v3, v4 Vertex\n\tdirty          bool\n}\n\nfunc (r *blockRun) AddFace(faces AddFacer) {\n\tif r.dirty {\n\t\tfaces.AddFace(r.blockId, r.v1, r.v2, r.v3, r.v4)\n\t\tr.dirty = false\n\t}\n}\n\nfunc (r *blockRun) Update(faces AddFacer, nr *blockRun, flag bool) {\n\tif !blockFaces {\n\t\tif r.dirty {\n\t\t\tif nr.blockId == r.blockId {\n\t\t\t\tif flag {\n\t\t\t\t\tr.v3 = nr.v3\n\t\t\t\t\tr.v4 = nr.v4\n\t\t\t\t} else {\n\t\t\t\t\tr.v2 = nr.v2\n\t\t\t\t\tr.v3 = nr.v3\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tr.AddFace(faces)\n\t\t\t\t*r = *nr\n\t\t\t}\n\t\t} else {\n\t\t\t*r = *nr\n\t\t}\n\t} else {\n\t\tnr.AddFace(faces)\n\t\tnr.dirty = false\n\t}\n}\n\nfunc (fs *Faces) processBlocks(enclosedChunk *EnclosedChunk, faces AddFacer) {\n\tfor i := 0; i < len(enclosedChunk.blocks); i += 128 {\n\t\tvar x, z = (i \/ 128) \/ 16, (i \/ 128) % 16\n\n\t\tvar r1, r2, r3, r4 blockRun\n\n\t\tvar column = BlockColumn(enclosedChunk.blocks[i : i+128])\n\t\tfor y, blockId := range column {\n\t\t\tif y < yMin {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y-1, z)) {\n\t\t\t\tfaces.AddFace(blockId, Vertex{x, y, z}, Vertex{x + 1, y, z}, Vertex{x + 1, y, z + 1}, Vertex{x, y, z + 1})\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y+1, z)) {\n\t\t\t\tfaces.AddFace(blockId, Vertex{x, y + 1, z}, Vertex{x, y + 1, z + 1}, Vertex{x + 1, y + 1, z + 1}, Vertex{x + 1, y + 1, z})\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x-1, y, z)) {\n\t\t\t\tr1.Update(faces, &blockRun{blockId, Vertex{x, y, z}, Vertex{x, y, z + 1}, Vertex{x, y + 1, z + 1}, Vertex{x, y + 1, z}, true}, true)\n\t\t\t} else {\n\t\t\t\tr1.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x+1, y, z)) {\n\t\t\t\tr2.Update(faces, &blockRun{blockId, Vertex{x + 1, y, z}, Vertex{x + 1, y + 1, z}, Vertex{x + 1, y + 1, z + 1}, Vertex{x + 1, y, z + 1}, true}, false)\n\t\t\t} else {\n\t\t\t\tr2.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y, z-1)) {\n\t\t\t\tr3.Update(faces, &blockRun{blockId, Vertex{x, y, z}, Vertex{x, y + 1, z}, Vertex{x + 1, y + 1, z}, Vertex{x + 1, y, z}, true}, false)\n\t\t\t} else {\n\t\t\t\tr3.AddFace(faces)\n\t\t\t}\n\n\t\t\tif fs.boundary.IsBoundary(blockId, enclosedChunk.Get(x, y, z+1)) {\n\t\t\t\tr4.Update(faces, &blockRun{blockId, Vertex{x, y, z + 1}, Vertex{x + 1, y, z + 1}, Vertex{x + 1, y + 1, z + 1}, Vertex{x, y + 1, z + 1}, true}, true)\n\t\t\t} else {\n\t\t\t\tr4.AddFace(faces)\n\t\t\t}\n\t\t}\n\n\t\tr1.AddFace(faces)\n\t\tr2.AddFace(faces)\n\t\tr3.AddFace(faces)\n\t\tr4.AddFace(faces)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package MQTTg\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Broker struct {\n\tBt *Transport\n\t\/\/ TODO: check whether not good to use addr as key\n\tClients   map[*net.UDPAddr]*ClientInfo \/\/ map[addr]*ClientInfo\n\tClientIDs map[string]*ClientInfo       \/\/ map[clientID]*ClientInfo\n\tTopicRoot *TopicNode\n}\n\ntype ClientInfo struct {\n\t*Client\n\tKeepAliveTimer *time.Timer\n\tDuration       time.Duration\n}\n\nfunc (self *ClientInfo) NewTimer() {\n\tself.KeepAliveTimer = time.NewTimer(self.Duration)\n}\n\nfunc (self *ClientInfo) ResetTimer() {\n\tself.KeepAliveTimer.Reset(self.Duration)\n}\n\nfunc (self *ClientInfo) RunTimer() {\n\t<-self.KeepAliveTimer.C\n\tself.DisconnectFromBroker()\n\t\/\/ TODO: logging?\n}\n\nfunc (self *ClientInfo) DisconnectFromBroker() {\n\tself.Will = nil\n\tself.IsConnecting = false\n\tself.KeepAliveTimer.Stop()\n\t\/\/ TODO: free used clientID due to clean session?\n}\n\nfunc (self *Broker) ApplyDummyClientID() string {\n\treturn \"DummyClientID:\" + strconv.Itoa(len(self.ClientIDs)+1)\n}\n\nfunc (self *Broker) ReadLoop() error {\n\tfor {\n\t\tm, addr, err := self.Bt.ReadMessageFrom()\n\t\tif err != nil {\n\t\t\tEmitError(err)\n\t\t\tcontinue\n\t\t}\n\t\tswitch message := m.(type) {\n\t\tcase *ConnectMessage:\n\t\t\tif message.Protocol.Level != MQTT_3_1_1.Level {\n\t\t\t\t\/\/ CHECK: Is false correct?\n\t\t\t\terr = self.Bt.SendMessage(NewConnackMessage(false, UnacceptableProtocolVersion), addr)\n\t\t\t\tEmitError(INVALID_PROTOCOL_LEVEL)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tclient, ok := self.ClientIDs[message.ClientID]\n\t\t\tif ok {\n\t\t\t\t\/\/ TODO: this might cause problem\n\t\t\t\terr = self.Bt.SendMessage(NewConnackMessage(false, IdentifierRejected), addr)\n\t\t\t\tEmitError(CLIENT_ID_IS_USED_ALREADY)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(message.ClientID) == 0 {\n\t\t\t\tmessage.ClientID = self.ApplyDummyClientID()\n\t\t\t}\n\n\t\t\tif message.Flags&Reserved_Flag == Reserved_Flag {\n\t\t\t\t\/\/ TODO: disconnect the connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Flags&UserName_Flag != UserName_Flag && message.Flags&Password_Flag == Password_Flag {\n\t\t\t\tEmitError(USERNAME_DOES_NOT_EXIST_WITH_PASSWORD)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO: authorization\n\n\t\t\tclient, ok = self.Clients[addr]\n\t\t\tsessionPresent := false\n\t\t\tif message.Flags&CleanSession_Flag == CleanSession_Flag || !ok {\n\t\t\t\t\/\/ TODO: need to manage QoS base processing\n\t\t\t\tduration := time.Duration(float32(message.KeepAlive) * 100000000 * 1.5)\n\t\t\t\tclient = &ClientInfo{\n\t\t\t\t\tClient: NewClient(self.Bt, addr, message.ClientID,\n\t\t\t\t\t\tmessage.User, message.KeepAlive, message.Will),\n\t\t\t\t\tKeepAliveTimer: nil,\n\t\t\t\t\tDuretion:       duration,\n\t\t\t\t}\n\t\t\t\tclient.NewTimer()\n\t\t\t\tself.Clients[addr] = client\n\t\t\t\tself.ClientIDs[message.ClientID] = client\n\t\t\t} else if message.Flags&CleanSession_Flag != CleanSession_Flag || ok {\n\t\t\t\tsessionPresent = true\n\t\t\t}\n\n\t\t\tif message.Flags&Will_Flag == Will_Flag {\n\t\t\t\tclient.Will = message.Will\n\t\t\t\t\/\/ TODO: consider QoS and Retain as broker need\n\t\t\t} else {\n\n\t\t\t}\n\n\t\t\tgo client.RunTimer()\n\t\t\terr = self.Bt.SendMessage(NewConnackMessage(sessionPresent, Accepted), addr)\n\t\tcase *PublishMessage:\n\t\t\tif message.QoS == 3 {\n\t\t\t\t\/\/ error\n\t\t\t\t\/\/ close connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Dup {\n\t\t\t\t\/\/ re-delivered\n\t\t\t} else {\n\t\t\t\t\/\/ first time delivery\n\t\t\t}\n\n\t\t\tif message.Retain {\n\t\t\t\t\/\/ store the application message to designated topic\n\t\t\t\tif len(message.Payload) == 0 {\n\t\t\t\t\t\/\/ discard(remove) retained message\n\t\t\t\t}\n\n\t\t\t\tif message.QoS == 0 {\n\t\t\t\t\t\/\/ discard retained message\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch message.QoS {\n\t\t\t\/\/ in any case, Dub must be 0\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\terr = self.Bt.SendMessage(NewPubackMessage(message.PacketID), addr)\n\t\t\tcase 2:\n\t\t\t\terr = self.Bt.SendMessage(NewPubrecMessage(message.PacketID), addr)\n\t\t\t}\n\t\tcase *PubackMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\tcase *PubrecMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\t\terr = self.Bt.SendMessage(NewPubrelMessage(message.PacketID), addr)\n\t\tcase *PubrelMessage:\n\t\t\terr = self.Bt.SendMessage(NewPubcompMessage(message.PacketID), addr)\n\t\tcase *PubcompMessage:\n\t\t\t\/\/ acknowledge the sent Pubrel packet\n\t\tcase *SubscribeMessage:\n\t\t\t\/\/ TODO: check The wild card is permitted\n\t\t\tcodes := make([]SubscribeReturnCode, len(message.SubscribeTopics))\n\t\t\tfor i, subTopic := range message.SubscribeTopics {\n\t\t\t\t\/\/ TODO: need to validate wheter there are same topics or not\n\t\t\t\tclient, ok := self.Clients[addr]\n\t\t\t\tif ok {\n\t\t\t\t\tretains, code := self.TopicRoot.ApplySubscriber(client.ID, string(subTopic.Topic), subTopic.QoS)\n\t\t\t\t\tcodes[i] = code\n\t\t\t\t\tclient.SubTopics = append(client.SubTopics,\n\t\t\t\t\t\tSubscribeTopic{SubscribeAck,\n\t\t\t\t\t\t\tsubTopic.Topic,\n\t\t\t\t\t\t\tuint8(code),\n\t\t\t\t\t\t})\n\t\t\t\t\tif len(retains) > 0 {\n\t\t\t\t\t\tfor k, v := range retains {\n\t\t\t\t\t\t\t\/\/Publish(k,v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcodes[i] = SubscribeFailure \/\/ TODO: correct?\n\t\t\t\t}\n\n\t\t\t}\n\t\t\terr = self.Bt.SendMessage(NewSubackMessage(message.PacketID, codes), addr)\n\t\tcase *UnsubscribeMessage:\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\tEmitError(CLIENT_NOT_EXIST)\n\t\t\t\tcontinue \/\/ TODO: ?\n\t\t\t}\n\t\t\tif len(message.TopicNames) == 0 {\n\t\t\t\t\/\/ protocol violation\n\t\t\t}\n\t\t\t\/\/ TODO: optimize here\n\t\t\tresult := []SubscribeTopic{}\n\t\t\tfor _, t := range client.SubTopics {\n\t\t\t\tdel := false\n\t\t\t\tfor _, name := range message.TopicNames {\n\t\t\t\t\tif string(t.Topic) == string(name) {\n\t\t\t\t\t\tdel = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !del {\n\t\t\t\t\tresult = append(result, t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tclient.SubTopics = result\n\t\t\terr = self.Bt.SendMessage(NewUnsubackMessage(message.PacketID), addr)\n\t\tcase *PingreqMessage:\n\t\t\t\/\/ Pingresp\n\t\t\t\/\/ TODO: calc elapsed time from previous pingreq.\n\t\t\t\/\/       and store the time to duration of Transport\n\t\t\terr = self.Bt.SendMessage(NewPingrespMessage(), addr)\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO: error\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclient.ResetTimer()\n\t\t\tgo client.RunTimer()\n\t\tcase *DisconnectMessage:\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO: emit error\/warnning\n\t\t\t\tEmitError(CLIENT_NOT_EXIST)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclient.DisconnectFromBroker()\n\n\t\t\t\/\/ close the client\n\t\tdefault:\n\t\t\t\/\/ when invalid messages come\n\t\t\terr = INVALID_MESSAGE_CAME\n\t\t}\n\t\tif err != nil {\n\t\t\tEmitError(err)\n\t\t}\n\t}\n}\n<commit_msg>remove TODO<commit_after>package MQTTg\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Broker struct {\n\tBt *Transport\n\t\/\/ TODO: check whether not good to use addr as key\n\tClients   map[*net.UDPAddr]*ClientInfo \/\/ map[addr]*ClientInfo\n\tClientIDs map[string]*ClientInfo       \/\/ map[clientID]*ClientInfo\n\tTopicRoot *TopicNode\n}\n\ntype ClientInfo struct {\n\t*Client\n\tKeepAliveTimer *time.Timer\n\tDuration       time.Duration\n}\n\nfunc (self *ClientInfo) NewTimer() {\n\tself.KeepAliveTimer = time.NewTimer(self.Duration)\n}\n\nfunc (self *ClientInfo) ResetTimer() {\n\tself.KeepAliveTimer.Reset(self.Duration)\n}\n\nfunc (self *ClientInfo) RunTimer() {\n\t<-self.KeepAliveTimer.C\n\tself.DisconnectFromBroker()\n\t\/\/ TODO: logging?\n}\n\nfunc (self *ClientInfo) DisconnectFromBroker() {\n\tself.Will = nil\n\tself.IsConnecting = false\n\tself.KeepAliveTimer.Stop()\n\t\/\/ TODO: free used clientID due to clean session?\n}\n\nfunc (self *Broker) ApplyDummyClientID() string {\n\treturn \"DummyClientID:\" + strconv.Itoa(len(self.ClientIDs)+1)\n}\n\nfunc (self *Broker) ReadLoop() error {\n\tfor {\n\t\tm, addr, err := self.Bt.ReadMessageFrom()\n\t\tif err != nil {\n\t\t\tEmitError(err)\n\t\t\tcontinue\n\t\t}\n\t\tswitch message := m.(type) {\n\t\tcase *ConnectMessage:\n\t\t\tif message.Protocol.Level != MQTT_3_1_1.Level {\n\t\t\t\t\/\/ CHECK: Is false correct?\n\t\t\t\terr = self.Bt.SendMessage(NewConnackMessage(false, UnacceptableProtocolVersion), addr)\n\t\t\t\tEmitError(INVALID_PROTOCOL_LEVEL)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tclient, ok := self.ClientIDs[message.ClientID]\n\t\t\tif ok {\n\t\t\t\t\/\/ TODO: this might cause problem\n\t\t\t\terr = self.Bt.SendMessage(NewConnackMessage(false, IdentifierRejected), addr)\n\t\t\t\tEmitError(CLIENT_ID_IS_USED_ALREADY)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(message.ClientID) == 0 {\n\t\t\t\tmessage.ClientID = self.ApplyDummyClientID()\n\t\t\t}\n\n\t\t\tif message.Flags&Reserved_Flag == Reserved_Flag {\n\t\t\t\t\/\/ TODO: disconnect the connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Flags&UserName_Flag != UserName_Flag && message.Flags&Password_Flag == Password_Flag {\n\t\t\t\tEmitError(USERNAME_DOES_NOT_EXIST_WITH_PASSWORD)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO: authorization\n\n\t\t\tclient, ok = self.Clients[addr]\n\t\t\tsessionPresent := false\n\t\t\tif message.Flags&CleanSession_Flag == CleanSession_Flag || !ok {\n\t\t\t\t\/\/ TODO: need to manage QoS base processing\n\t\t\t\tduration := time.Duration(float32(message.KeepAlive) * 100000000 * 1.5)\n\t\t\t\tclient = &ClientInfo{\n\t\t\t\t\tClient: NewClient(self.Bt, addr, message.ClientID,\n\t\t\t\t\t\tmessage.User, message.KeepAlive, message.Will),\n\t\t\t\t\tKeepAliveTimer: nil,\n\t\t\t\t\tDuretion:       duration,\n\t\t\t\t}\n\t\t\t\tclient.NewTimer()\n\t\t\t\tself.Clients[addr] = client\n\t\t\t\tself.ClientIDs[message.ClientID] = client\n\t\t\t} else if message.Flags&CleanSession_Flag != CleanSession_Flag || ok {\n\t\t\t\tsessionPresent = true\n\t\t\t}\n\n\t\t\tif message.Flags&Will_Flag == Will_Flag {\n\t\t\t\tclient.Will = message.Will\n\t\t\t\t\/\/ TODO: consider QoS and Retain as broker need\n\t\t\t} else {\n\n\t\t\t}\n\n\t\t\tgo client.RunTimer()\n\t\t\terr = self.Bt.SendMessage(NewConnackMessage(sessionPresent, Accepted), addr)\n\t\tcase *PublishMessage:\n\t\t\tif message.QoS == 3 {\n\t\t\t\t\/\/ error\n\t\t\t\t\/\/ close connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Dup {\n\t\t\t\t\/\/ re-delivered\n\t\t\t} else {\n\t\t\t\t\/\/ first time delivery\n\t\t\t}\n\n\t\t\tif message.Retain {\n\t\t\t\t\/\/ store the application message to designated topic\n\t\t\t\tif len(message.Payload) == 0 {\n\t\t\t\t\t\/\/ discard(remove) retained message\n\t\t\t\t}\n\n\t\t\t\tif message.QoS == 0 {\n\t\t\t\t\t\/\/ discard retained message\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch message.QoS {\n\t\t\t\/\/ in any case, Dub must be 0\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\terr = self.Bt.SendMessage(NewPubackMessage(message.PacketID), addr)\n\t\t\tcase 2:\n\t\t\t\terr = self.Bt.SendMessage(NewPubrecMessage(message.PacketID), addr)\n\t\t\t}\n\t\tcase *PubackMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\tcase *PubrecMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\t\terr = self.Bt.SendMessage(NewPubrelMessage(message.PacketID), addr)\n\t\tcase *PubrelMessage:\n\t\t\terr = self.Bt.SendMessage(NewPubcompMessage(message.PacketID), addr)\n\t\tcase *PubcompMessage:\n\t\t\t\/\/ acknowledge the sent Pubrel packet\n\t\tcase *SubscribeMessage:\n\t\t\t\/\/ TODO: check The wild card is permitted\n\t\t\tcodes := make([]SubscribeReturnCode, len(message.SubscribeTopics))\n\t\t\tfor i, subTopic := range message.SubscribeTopics {\n\t\t\t\t\/\/ TODO: need to validate wheter there are same topics or not\n\t\t\t\tclient, ok := self.Clients[addr]\n\t\t\t\tif ok {\n\t\t\t\t\tretains, code := self.TopicRoot.ApplySubscriber(client.ID, string(subTopic.Topic), subTopic.QoS)\n\t\t\t\t\tcodes[i] = code\n\t\t\t\t\tclient.SubTopics = append(client.SubTopics,\n\t\t\t\t\t\tSubscribeTopic{SubscribeAck,\n\t\t\t\t\t\t\tsubTopic.Topic,\n\t\t\t\t\t\t\tuint8(code),\n\t\t\t\t\t\t})\n\t\t\t\t\tif len(retains) > 0 {\n\t\t\t\t\t\tfor k, v := range retains {\n\t\t\t\t\t\t\t\/\/Publish(k,v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcodes[i] = SubscribeFailure \/\/ TODO: correct?\n\t\t\t\t}\n\n\t\t\t}\n\t\t\terr = self.Bt.SendMessage(NewSubackMessage(message.PacketID, codes), addr)\n\t\tcase *UnsubscribeMessage:\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\tEmitError(CLIENT_NOT_EXIST)\n\t\t\t\tcontinue \/\/ TODO: ?\n\t\t\t}\n\t\t\tif len(message.TopicNames) == 0 {\n\t\t\t\t\/\/ protocol violation\n\t\t\t}\n\t\t\t\/\/ TODO: optimize here\n\t\t\tresult := []SubscribeTopic{}\n\t\t\tfor _, t := range client.SubTopics {\n\t\t\t\tdel := false\n\t\t\t\tfor _, name := range message.TopicNames {\n\t\t\t\t\tif string(t.Topic) == string(name) {\n\t\t\t\t\t\tdel = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !del {\n\t\t\t\t\tresult = append(result, t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tclient.SubTopics = result\n\t\t\terr = self.Bt.SendMessage(NewUnsubackMessage(message.PacketID), addr)\n\t\tcase *PingreqMessage:\n\t\t\t\/\/ Pingresp\n\t\t\t\/\/ TODO: calc elapsed time from previous pingreq.\n\t\t\t\/\/       and store the time to duration of Transport\n\t\t\terr = self.Bt.SendMessage(NewPingrespMessage(), addr)\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\tEmitError(CLIENT_NOT_EXIST)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclient.ResetTimer()\n\t\t\tgo client.RunTimer()\n\t\tcase *DisconnectMessage:\n\t\t\tclient, ok := self.Clients[addr]\n\t\t\tif !ok {\n\t\t\t\tEmitError(CLIENT_NOT_EXIST)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclient.DisconnectFromBroker()\n\n\t\t\t\/\/ close the client\n\t\tdefault:\n\t\t\t\/\/ when invalid messages come\n\t\t\terr = INVALID_MESSAGE_CAME\n\t\t}\n\t\tif err != nil {\n\t\t\tEmitError(err)\n\t\t}\n\t}\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 fs\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"github.com\/jacobsa\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\ntype fileSystem struct {\n\tfuseutil.NotImplementedFileSystem\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tclock  timeutil.Clock\n\tbucket gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ When acquiring this lock, the caller must hold no inode or dir handle\n\t\/\/ locks.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ The user and group owning everything in the file system.\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tuid uint32\n\tgid uint32\n\n\t\/\/ The collection of live inodes, keyed by inode ID. No ID less than\n\t\/\/ fuse.RootInodeID is ever used.\n\t\/\/\n\t\/\/ TODO(jacobsa): Implement ForgetInode support in the fuse package, then\n\t\/\/ implement the method here and clean up these maps.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *inode.DirInode or *inode.FileInode\n\t\/\/ INVARIANT: For all keys k, k >= fuse.RootInodeID\n\t\/\/ INVARIANT: For all keys k, inodes[k].ID() == k\n\t\/\/ INVARIANT: inodes[fuse.RootInodeID] is of type *inode.DirInode\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tinodes map[fuse.InodeID]inode.Inode\n\n\t\/\/ The next inode ID to hand out. We assume that this will never overflow,\n\t\/\/ since even if we were handing out inode IDs at 4 GHz, it would still take\n\t\/\/ over a century to do so.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in inodes, k < nextInodeID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextInodeID fuse.InodeID\n\n\t\/\/ An index of all directory inodes by Name().\n\t\/\/\n\t\/\/ INVARIANT: For each key k, isDirName(k)\n\t\/\/ INVARIANT: For each key k, dirIndex[k].Name() == k\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.DirInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdirIndex map[string]*inode.DirInode\n\n\t\/\/ An index of all file inodes by (Name(), SourceGeneration()) pairs.\n\t\/\/\n\t\/\/ INVARIANT: For each key k, !isDirName(k)\n\t\/\/ INVARIANT: For each key k, fileIndex[k].Name() == k.name\n\t\/\/ INVARIANT: For each key k, fileIndex[k].SourceGeneration() == k.gen\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.FileInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tfileIndex map[nameAndGen]*inode.FileInode\n\n\t\/\/ The collection of live handles, keyed by handle ID.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *dirHandle\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\thandles map[fuse.HandleID]interface{}\n\n\t\/\/ The next handle ID to hand out. We assume that this will never overflow.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in handles, k < nextHandleID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextHandleID fuse.HandleID\n}\n\ntype nameAndGen struct {\n\tname string\n\tgen  int64\n}\n\n\/\/ Create a fuse file system whose root directory is the root of the supplied\n\/\/ bucket. The supplied clock will be used for cache invalidation, modification\n\/\/ times, etc.\nfunc NewFileSystem(\n\tclock timeutil.Clock,\n\tbucket gcs.Bucket) (ffs fuse.FileSystem, err error) {\n\t\/\/ Set up the basic struct.\n\tfs := &fileSystem{\n\t\tclock:       clock,\n\t\tbucket:      bucket,\n\t\tinodes:      make(map[fuse.InodeID]inode.Inode),\n\t\tnextInodeID: fuse.RootInodeID + 1,\n\t\tdirIndex:    make(map[string]*inode.DirInode),\n\t\tfileIndex:   make(map[nameAndGen]*inode.FileInode),\n\t\thandles:     make(map[fuse.HandleID]interface{}),\n\t}\n\n\t\/\/ Set up the root inode.\n\troot := inode.NewDirInode(bucket, fuse.RootInodeID, \"\")\n\tfs.inodes[fuse.RootInodeID] = root\n\tfs.dirIndex[\"\"] = root\n\n\t\/\/ Set up invariant checking.\n\tfs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)\n\n\tffs = fs\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc isDirName(name string) bool {\n\treturn name == \"\" || name[len(name)-1] == '\/'\n}\n\nfunc (fs *fileSystem) checkInvariants() {\n\t\/\/ Check inode keys.\n\tfor id, _ := range fs.inodes {\n\t\tif id < fuse.RootInodeID || id >= fs.nextInodeID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal inode ID: %v\", id))\n\t\t}\n\t}\n\n\t\/\/ Check the root inode.\n\t_ = fs.inodes[fuse.RootInodeID].(*inode.DirInode)\n\n\t\/\/ Check each inode, and the indexes over them. Keep a count of each type\n\t\/\/ seen.\n\tdirsSeen := 0\n\tfilesSeen := 0\n\tfor id, in := range fs.inodes {\n\t\t\/\/ Check the ID.\n\t\tif in.ID() != id {\n\t\t\tpanic(fmt.Sprintf(\"ID mismatch: %v vs. %v\", in.ID(), id))\n\t\t}\n\n\t\t\/\/ Check type-specific stuff.\n\t\tswitch typed := in.(type) {\n\t\tcase *inode.DirInode:\n\t\t\tdirsSeen++\n\n\t\t\tif !isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected directory name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tif fs.dirIndex[typed.Name()] != typed {\n\t\t\t\tpanic(fmt.Sprintf(\"dirIndex mismatch: %s\", typed.Name()))\n\t\t\t}\n\n\t\tcase *inode.FileInode:\n\t\t\tfilesSeen++\n\n\t\t\tif isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected file name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tnandg := nameAndGen{typed.Name(), typed.SourceGeneration()}\n\t\t\tif fs.fileIndex[nandg] != typed {\n\t\t\t\tpanic(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"fileIndex mismatch: %s, %v\",\n\t\t\t\t\t\ttyped.Name(),\n\t\t\t\t\t\ttyped.SourceGeneration()))\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected inode type: %v\", reflect.TypeOf(in)))\n\t\t}\n\t}\n\n\t\/\/ Make sure that the indexes are exhaustive.\n\tif len(fs.dirIndex) != dirsSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"dirIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.dirIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\tif len(fs.fileIndex) != filesSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"fileIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.fileIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\t\/\/ Check handles.\n\tfor id, h := range fs.handles {\n\t\tif id >= fs.nextHandleID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal handle ID: %v\", id))\n\t\t}\n\n\t\t_ = h.(*dirHandle)\n\t}\n}\n\n\/\/ Get attributes for the inode, fixing up ownership information.\n\/\/\n\/\/ SHARED_LOCKS_REQUIRED(fs.mu)\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(in)\nfunc (fs *fileSystem) getAttributes(\n\tctx context.Context,\n\tin inode.Inode) (attrs fuse.InodeAttributes, err error) {\n\tattrs, err = in.Attributes(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tattrs.Uid = fs.uid\n\tattrs.Gid = fs.gid\n\n\treturn\n}\n\n\/\/ Find a directory inode for the given object record. Create one if there\n\/\/ isn't already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateDirInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.DirInode, err error) {\n\t\/\/ Do we already have an inode for this name?\n\tif in = fs.dirIndex[o.Name]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewDirInode(fs.bucket, id, o.Name)\n\tfs.inodes[id] = in\n\tfs.dirIndex[in.Name()] = in\n\n\treturn\n}\n\n\/\/ Find a file inode for the given object record. Create one if there isn't\n\/\/ already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateFileInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.FileInode, err error) {\n\tnandg := nameAndGen{\n\t\tname: o.Name,\n\t\tgen:  o.Generation,\n\t}\n\n\t\/\/ Do we already have an inode for this (name, generation) pair?\n\tif in = fs.fileIndex[nandg]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewFileInode(fs.bucket, id, o)\n\tfs.inodes[id] = in\n\tfs.fileIndex[nandg] = in\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fuse.FileSystem methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) Init(\n\tctx context.Context,\n\treq *fuse.InitRequest) (resp *fuse.InitResponse, err error) {\n\tresp = &fuse.InitResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Store the mounting user's info for later.\n\tfs.uid = req.Header.Uid\n\tfs.gid = req.Header.Gid\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) LookUpInode(\n\tctx context.Context,\n\treq *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {\n\tresp = &fuse.LookUpInodeResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Find the parent directory in question.\n\tparent := fs.inodes[req.Parent].(*inode.DirInode)\n\n\t\/\/ Find a record for the child with the given name.\n\to, err := parent.LookUpChild(ctx, req.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Is the child a directory or a file?\n\tvar in inode.Inode\n\tif isDirName(o.Name) {\n\t\tin, err = fs.lookUpOrCreateDirInode(ctx, o)\n\t} else {\n\t\tin, err = fs.lookUpOrCreateFileInode(ctx, o)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Fill out the response.\n\tresp.Entry.Child = in.ID()\n\tif resp.Entry.Attributes, err = fs.getAttributes(ctx, in); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) GetInodeAttributes(\n\tctx context.Context,\n\treq *fuse.GetInodeAttributesRequest) (\n\tresp *fuse.GetInodeAttributesResponse, err error) {\n\tresp = &fuse.GetInodeAttributesResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the inode.\n\tin := fs.inodes[req.Inode]\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Grab its attributes.\n\tresp.Attributes, err = fs.getAttributes(ctx, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenDir(\n\tctx context.Context,\n\treq *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {\n\tresp = &fuse.OpenDirResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Make sure the inode still exists and is a directory. If not, something has\n\t\/\/ screwed up because the VFS layer shouldn't have let us forget the inode\n\t\/\/ before opening it.\n\tin := fs.inodes[req.Inode].(*inode.DirInode)\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Allocate a handle.\n\thandleID := fs.nextHandleID\n\tfs.nextHandleID++\n\n\tfs.handles[handleID] = newDirHandle(in)\n\tresp.Handle = handleID\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReadDir(\n\tctx context.Context,\n\treq *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the handle.\n\tdh := fs.handles[req.Handle].(*dirHandle)\n\tdh.Mu.Lock()\n\tdefer dh.Mu.Unlock()\n\n\t\/\/ Serve the request.\n\tresp, err = dh.ReadDir(ctx, req)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReleaseDirHandle(\n\tctx context.Context,\n\treq *fuse.ReleaseDirHandleRequest) (\n\tresp *fuse.ReleaseDirHandleResponse, err error) {\n\tresp = &fuse.ReleaseDirHandleResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Sanity check that this handle exists and is of the correct type.\n\t_ = fs.handles[req.Handle].(*dirHandle)\n\n\t\/\/ Clear the entry from the map.\n\tdelete(fs.handles, req.Handle)\n\n\treturn\n}\n\n\/\/ TODO(jacobsa): Make sure we have failing tests for O_CREAT and O_TRUNC\n\/\/ behavior, then implement those.\n\/\/\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenFile(\n\tctx context.Context,\n\treq *fuse.OpenFileRequest) (\n\tresp *fuse.OpenFileResponse, err error) {\n\tresp = &fuse.OpenFileResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Sanity check that this inode exists and is of the correct type.\n\t_ = fs.inodes[req.Inode].(*inode.FileInode)\n\n\treturn\n}\n<commit_msg>Fixed a TODO.<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 fs\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"github.com\/jacobsa\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\ntype fileSystem struct {\n\tfuseutil.NotImplementedFileSystem\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tclock  timeutil.Clock\n\tbucket gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ When acquiring this lock, the caller must hold no inode or dir handle\n\t\/\/ locks.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ The user and group owning everything in the file system.\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tuid uint32\n\tgid uint32\n\n\t\/\/ The collection of live inodes, keyed by inode ID. No ID less than\n\t\/\/ fuse.RootInodeID is ever used.\n\t\/\/\n\t\/\/ TODO(jacobsa): Implement ForgetInode support in the fuse package, then\n\t\/\/ implement the method here and clean up these maps.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *inode.DirInode or *inode.FileInode\n\t\/\/ INVARIANT: For all keys k, k >= fuse.RootInodeID\n\t\/\/ INVARIANT: For all keys k, inodes[k].ID() == k\n\t\/\/ INVARIANT: inodes[fuse.RootInodeID] is of type *inode.DirInode\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tinodes map[fuse.InodeID]inode.Inode\n\n\t\/\/ The next inode ID to hand out. We assume that this will never overflow,\n\t\/\/ since even if we were handing out inode IDs at 4 GHz, it would still take\n\t\/\/ over a century to do so.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in inodes, k < nextInodeID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextInodeID fuse.InodeID\n\n\t\/\/ An index of all directory inodes by Name().\n\t\/\/\n\t\/\/ INVARIANT: For each key k, isDirName(k)\n\t\/\/ INVARIANT: For each key k, dirIndex[k].Name() == k\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.DirInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdirIndex map[string]*inode.DirInode\n\n\t\/\/ An index of all file inodes by (Name(), SourceGeneration()) pairs.\n\t\/\/\n\t\/\/ INVARIANT: For each key k, !isDirName(k)\n\t\/\/ INVARIANT: For each key k, fileIndex[k].Name() == k.name\n\t\/\/ INVARIANT: For each key k, fileIndex[k].SourceGeneration() == k.gen\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.FileInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tfileIndex map[nameAndGen]*inode.FileInode\n\n\t\/\/ The collection of live handles, keyed by handle ID.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *dirHandle\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\thandles map[fuse.HandleID]interface{}\n\n\t\/\/ The next handle ID to hand out. We assume that this will never overflow.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in handles, k < nextHandleID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextHandleID fuse.HandleID\n}\n\ntype nameAndGen struct {\n\tname string\n\tgen  int64\n}\n\n\/\/ Create a fuse file system whose root directory is the root of the supplied\n\/\/ bucket. The supplied clock will be used for cache invalidation, modification\n\/\/ times, etc.\nfunc NewFileSystem(\n\tclock timeutil.Clock,\n\tbucket gcs.Bucket) (ffs fuse.FileSystem, err error) {\n\t\/\/ Set up the basic struct.\n\tfs := &fileSystem{\n\t\tclock:       clock,\n\t\tbucket:      bucket,\n\t\tinodes:      make(map[fuse.InodeID]inode.Inode),\n\t\tnextInodeID: fuse.RootInodeID + 1,\n\t\tdirIndex:    make(map[string]*inode.DirInode),\n\t\tfileIndex:   make(map[nameAndGen]*inode.FileInode),\n\t\thandles:     make(map[fuse.HandleID]interface{}),\n\t}\n\n\t\/\/ Set up the root inode.\n\troot := inode.NewDirInode(bucket, fuse.RootInodeID, \"\")\n\tfs.inodes[fuse.RootInodeID] = root\n\tfs.dirIndex[\"\"] = root\n\n\t\/\/ Set up invariant checking.\n\tfs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)\n\n\tffs = fs\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc isDirName(name string) bool {\n\treturn name == \"\" || name[len(name)-1] == '\/'\n}\n\nfunc (fs *fileSystem) checkInvariants() {\n\t\/\/ Check inode keys.\n\tfor id, _ := range fs.inodes {\n\t\tif id < fuse.RootInodeID || id >= fs.nextInodeID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal inode ID: %v\", id))\n\t\t}\n\t}\n\n\t\/\/ Check the root inode.\n\t_ = fs.inodes[fuse.RootInodeID].(*inode.DirInode)\n\n\t\/\/ Check each inode, and the indexes over them. Keep a count of each type\n\t\/\/ seen.\n\tdirsSeen := 0\n\tfilesSeen := 0\n\tfor id, in := range fs.inodes {\n\t\t\/\/ Check the ID.\n\t\tif in.ID() != id {\n\t\t\tpanic(fmt.Sprintf(\"ID mismatch: %v vs. %v\", in.ID(), id))\n\t\t}\n\n\t\t\/\/ Check type-specific stuff.\n\t\tswitch typed := in.(type) {\n\t\tcase *inode.DirInode:\n\t\t\tdirsSeen++\n\n\t\t\tif !isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected directory name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tif fs.dirIndex[typed.Name()] != typed {\n\t\t\t\tpanic(fmt.Sprintf(\"dirIndex mismatch: %s\", typed.Name()))\n\t\t\t}\n\n\t\tcase *inode.FileInode:\n\t\t\tfilesSeen++\n\n\t\t\tif isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected file name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tnandg := nameAndGen{typed.Name(), typed.SourceGeneration()}\n\t\t\tif fs.fileIndex[nandg] != typed {\n\t\t\t\tpanic(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"fileIndex mismatch: %s, %v\",\n\t\t\t\t\t\ttyped.Name(),\n\t\t\t\t\t\ttyped.SourceGeneration()))\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected inode type: %v\", reflect.TypeOf(in)))\n\t\t}\n\t}\n\n\t\/\/ Make sure that the indexes are exhaustive.\n\tif len(fs.dirIndex) != dirsSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"dirIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.dirIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\tif len(fs.fileIndex) != filesSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"fileIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.fileIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\t\/\/ Check handles.\n\tfor id, h := range fs.handles {\n\t\tif id >= fs.nextHandleID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal handle ID: %v\", id))\n\t\t}\n\n\t\t_ = h.(*dirHandle)\n\t}\n}\n\n\/\/ Get attributes for the inode, fixing up ownership information.\n\/\/\n\/\/ SHARED_LOCKS_REQUIRED(fs.mu)\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(in)\nfunc (fs *fileSystem) getAttributes(\n\tctx context.Context,\n\tin inode.Inode) (attrs fuse.InodeAttributes, err error) {\n\tattrs, err = in.Attributes(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tattrs.Uid = fs.uid\n\tattrs.Gid = fs.gid\n\n\treturn\n}\n\n\/\/ Find a directory inode for the given object record. Create one if there\n\/\/ isn't already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateDirInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.DirInode, err error) {\n\t\/\/ Do we already have an inode for this name?\n\tif in = fs.dirIndex[o.Name]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewDirInode(fs.bucket, id, o.Name)\n\tfs.inodes[id] = in\n\tfs.dirIndex[in.Name()] = in\n\n\treturn\n}\n\n\/\/ Find a file inode for the given object record. Create one if there isn't\n\/\/ already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateFileInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.FileInode, err error) {\n\tnandg := nameAndGen{\n\t\tname: o.Name,\n\t\tgen:  o.Generation,\n\t}\n\n\t\/\/ Do we already have an inode for this (name, generation) pair?\n\tif in = fs.fileIndex[nandg]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewFileInode(fs.bucket, id, o)\n\tfs.inodes[id] = in\n\tfs.fileIndex[nandg] = in\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fuse.FileSystem methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) Init(\n\tctx context.Context,\n\treq *fuse.InitRequest) (resp *fuse.InitResponse, err error) {\n\tresp = &fuse.InitResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Store the mounting user's info for later.\n\tfs.uid = req.Header.Uid\n\tfs.gid = req.Header.Gid\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) LookUpInode(\n\tctx context.Context,\n\treq *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {\n\tresp = &fuse.LookUpInodeResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Find the parent directory in question.\n\tparent := fs.inodes[req.Parent].(*inode.DirInode)\n\n\t\/\/ Find a record for the child with the given name.\n\to, err := parent.LookUpChild(ctx, req.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Is the child a directory or a file?\n\tvar in inode.Inode\n\tif isDirName(o.Name) {\n\t\tin, err = fs.lookUpOrCreateDirInode(ctx, o)\n\t} else {\n\t\tin, err = fs.lookUpOrCreateFileInode(ctx, o)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Fill out the response.\n\tresp.Entry.Child = in.ID()\n\tif resp.Entry.Attributes, err = fs.getAttributes(ctx, in); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) GetInodeAttributes(\n\tctx context.Context,\n\treq *fuse.GetInodeAttributesRequest) (\n\tresp *fuse.GetInodeAttributesResponse, err error) {\n\tresp = &fuse.GetInodeAttributesResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the inode.\n\tin := fs.inodes[req.Inode]\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Grab its attributes.\n\tresp.Attributes, err = fs.getAttributes(ctx, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenDir(\n\tctx context.Context,\n\treq *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {\n\tresp = &fuse.OpenDirResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Make sure the inode still exists and is a directory. If not, something has\n\t\/\/ screwed up because the VFS layer shouldn't have let us forget the inode\n\t\/\/ before opening it.\n\tin := fs.inodes[req.Inode].(*inode.DirInode)\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Allocate a handle.\n\thandleID := fs.nextHandleID\n\tfs.nextHandleID++\n\n\tfs.handles[handleID] = newDirHandle(in)\n\tresp.Handle = handleID\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReadDir(\n\tctx context.Context,\n\treq *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the handle.\n\tdh := fs.handles[req.Handle].(*dirHandle)\n\tdh.Mu.Lock()\n\tdefer dh.Mu.Unlock()\n\n\t\/\/ Serve the request.\n\tresp, err = dh.ReadDir(ctx, req)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReleaseDirHandle(\n\tctx context.Context,\n\treq *fuse.ReleaseDirHandleRequest) (\n\tresp *fuse.ReleaseDirHandleResponse, err error) {\n\tresp = &fuse.ReleaseDirHandleResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Sanity check that this handle exists and is of the correct type.\n\t_ = fs.handles[req.Handle].(*dirHandle)\n\n\t\/\/ Clear the entry from the map.\n\tdelete(fs.handles, req.Handle)\n\n\treturn\n}\n\n\/\/ TODO(jacobsa): Make sure we have failing tests for O_TRUNC behavior, then\n\/\/ implement it.\n\/\/\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenFile(\n\tctx context.Context,\n\treq *fuse.OpenFileRequest) (\n\tresp *fuse.OpenFileResponse, err error) {\n\tresp = &fuse.OpenFileResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Sanity check that this inode exists and is of the correct type.\n\t_ = fs.inodes[req.Inode].(*inode.FileInode)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package btcRPC\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ CoinDefaultHost   default coin address\nconst CoinDefaultHost string = \"localhost\"\n\n\/\/CoinDefaultPort   default coin port\nconst CoinDefaultPort int = 8332\n\n\/\/CoinDefaultProto  default coin protp\nconst CoinDefaultProto string = \"http\"\n\n\/\/RPCTimeOut default timeout(second)\nconst RPCTimeOut = 5\n\n\/\/Coin RPC struct\ntype Coin struct {\n\t\/\/ Configuration options\n\tusername    string\n\tpassword    string\n\tproto       string\n\thost        string\n\tport        int\n\turl         string\n\tcertificate string\n\t\/\/ Information and debugging\n\tStatus    int\n\tLastError error\n\t\/\/ rawResponse string\n\tresponseData map[string]interface{}\n\tid           int\n\tclient       *http.Client\n}\n\n\/\/NewCoin   create a new RPC instance\nfunc NewCoin(coinUser, coinPasswd, coinHost, coinURL string, coinPort int) (cn *Coin, err error) {\n\tcn = &Coin{\n\t\tusername: coinUser,\n\t\tpassword: coinPasswd,\n\t\thost:     coinHost,\n\t\tport:     coinPort,\n\t\turl:      coinURL,\n\t\tproto:    CoinDefaultProto,\n\t}\n\tif len(coinHost) == 0 {\n\t\tcn.host = CoinDefaultHost\n\t}\n\tif coinPort < 0 || coinPort > 65535 {\n\t\tcn.port = CoinDefaultPort\n\t}\n\tcn.client = &http.Client{}\n\tcn.client.Timeout = time.Duration(RPCTimeOut) * time.Second\n\tcn.client.Transport = &http.Transport{}\n\tcn.responseData = make(map[string]interface{})\n\t\/\/first access\n\tif _, err = cn.Call(\"getinfo\"); err != nil {\n\t\treturn nil, err\n\t}\n\tif cn.Status != http.StatusOK || cn.LastError != nil {\n\t\treturn nil, cn.LastError\n\t}\n\treturn cn, nil\n}\n\n\/\/SetSSL    setup certificate\nfunc (cn *Coin) SetSSL(certificate string) {\n\tcn.proto = \"https\"\n\tcn.certificate = certificate\n}\n\nfunc (cn *Coin) access(data map[string]interface{}) (err error) {\n\tif len(data) != 2 {\n\t\terr = errors.New(\"params count error\")\n\t\treturn\n\t}\n\tif cn.client == nil {\n\t\terr = errors.New(\"http client error\")\n\t\treturn\n\t}\n\tcn.id++\n\tdata[\"id\"] = cn.id\n\tcn.LastError = nil\n\tcn.responseData = nil\n\tcn.Status = http.StatusOK\n\tvar (\n\t\tjbuf, body []byte\n\t\treq        *http.Request\n\t\tresp       *http.Response\n\t)\n\tif jbuf, err = json.Marshal(data); err != nil {\n\t\treturn\n\t}\n\n\taddr := cn.proto + \":\/\/\" + cn.username + \":\" + cn.password + \"@\" + cn.host + \":\" + strconv.Itoa(cn.port) + \"\/\" + cn.url\n\tif req, err = http.NewRequest(\"POST\", addr, bytes.NewReader(jbuf)); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\/\/todo: setup ssl\n\tif resp, err = cn.client.Do(req); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\tcn.Status = resp.StatusCode\n\tif cn.Status != http.StatusOK {\n\t\terr = errors.New(resp.Status)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\tif len(body) == 0 {\n\t\terr = errors.New(\"response data is empty\")\n\t\treturn\n\t}\n\t\/\/decode\n\tif err = json.Unmarshal(body, &cn.responseData); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/Call run RPC command\nfunc (cn *Coin) Call(method string, args ...interface{}) (data map[string]interface{}, err error) {\n\tif method == \"\" {\n\t\terr = errors.New(\"method is not set\")\n\t\treturn\n\t}\n\trequestData := make(map[string]interface{})\n\trequestData[\"method\"] = method\n\trequestData[\"params\"] = args\n\tif err = cn.access(requestData); err == nil {\n\t\tdata = cn.responseData\n\t}\n\treturn\n}\n<commit_msg>do not unmarshal http response data<commit_after>package btcRPC\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ CoinDefaultHost   default coin address\nconst CoinDefaultHost string = \"localhost\"\n\n\/\/CoinDefaultPort   default coin port\nconst CoinDefaultPort int = 8332\n\n\/\/CoinDefaultProto  default coin protp\nconst CoinDefaultProto string = \"http\"\n\n\/\/RPCTimeOut default timeout(second)\nconst RPCTimeOut = 5\n\n\/\/Coin RPC struct\ntype Coin struct {\n\t\/\/ Configuration options\n\tusername    string\n\tpassword    string\n\tproto       string\n\thost        string\n\tport        int\n\turl         string\n\tcertificate string\n\t\/\/ Information and debugging\n\tStatus    int\n\tLastError error\n\t\/\/ rawResponse string\n\tresponseData []byte\n\tid           int\n\tclient       *http.Client\n}\n\n\/\/NewCoin   create a new RPC instance\nfunc NewCoin(coinUser, coinPasswd, coinHost, coinURL string, coinPort int) (cn *Coin, err error) {\n\tcn = &Coin{\n\t\tusername: coinUser,\n\t\tpassword: coinPasswd,\n\t\thost:     coinHost,\n\t\tport:     coinPort,\n\t\turl:      coinURL,\n\t\tproto:    CoinDefaultProto,\n\t}\n\tif len(coinHost) == 0 {\n\t\tcn.host = CoinDefaultHost\n\t}\n\tif coinPort < 0 || coinPort > 65535 {\n\t\tcn.port = CoinDefaultPort\n\t}\n\tcn.client = &http.Client{}\n\tcn.client.Timeout = time.Duration(RPCTimeOut) * time.Second\n\tcn.client.Transport = &http.Transport{}\n\t\/\/first access\n\tif _, err = cn.Call(\"getinfo\"); err != nil {\n\t\treturn nil, err\n\t}\n\tif cn.Status != http.StatusOK || cn.LastError != nil {\n\t\treturn nil, cn.LastError\n\t}\n\treturn cn, nil\n}\n\n\/\/SetSSL    setup certificate\nfunc (cn *Coin) SetSSL(certificate string) {\n\tcn.proto = \"https\"\n\tcn.certificate = certificate\n}\n\nfunc (cn *Coin) access(data map[string]interface{}) (err error) {\n\tif len(data) != 2 {\n\t\terr = errors.New(\"params count error\")\n\t\treturn\n\t}\n\tif cn.client == nil {\n\t\terr = errors.New(\"http client error\")\n\t\treturn\n\t}\n\tcn.id++\n\tdata[\"id\"] = cn.id\n\tcn.LastError = nil\n\tcn.responseData = nil\n\tcn.Status = http.StatusOK\n\tvar (\n\t\tjbuf []byte\n\t\treq  *http.Request\n\t\tresp *http.Response\n\t)\n\tif jbuf, err = json.Marshal(data); err != nil {\n\t\treturn\n\t}\n\n\taddr := cn.proto + \":\/\/\" + cn.username + \":\" + cn.password + \"@\" + cn.host + \":\" + strconv.Itoa(cn.port) + \"\/\" + cn.url\n\tif req, err = http.NewRequest(\"POST\", addr, bytes.NewReader(jbuf)); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\/\/todo: setup ssl\n\tif resp, err = cn.client.Do(req); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\tcn.Status = resp.StatusCode\n\tif cn.Status != http.StatusOK {\n\t\terr = errors.New(resp.Status)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tif cn.responseData, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\tcn.LastError = err\n\t\treturn\n\t}\n\tif len(cn.responseData) == 0 {\n\t\terr = errors.New(\"response data is empty\")\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/Call run RPC command\nfunc (cn *Coin) Call(method string, args ...interface{}) (data []byte, err error) {\n\tif method == \"\" {\n\t\terr = errors.New(\"method is not set\")\n\t\treturn\n\t}\n\trequestData := make(map[string]interface{})\n\trequestData[\"method\"] = method\n\trequestData[\"params\"] = args\n\tif err = cn.access(requestData); err == nil {\n\t\tdata = cn.responseData\n\t}\n\treturn\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 main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io\/test-infra\/testgrid\/util\/gcs\"\n\n\t\"cloud.google.com\/go\/storage\"\n)\n\ntype multiString []string\n\nfunc (m multiString) String() string {\n\treturn strings.Join(m, \",\")\n}\n\nfunc (m *multiString) Set(v string) error {\n\t*m = strings.Split(v, \",\")\n\treturn nil\n}\n\ntype options struct {\n\tcreds     string\n\tinputs    multiString\n\toneshot   bool\n\toutput    string\n\tprintText bool\n}\n\nfunc gatherOptions() options {\n\to := options{}\n\tflag.StringVar(&o.creds, \"gcp-service-account\", \"\", \"\/path\/to\/gcp\/creds (use local creds if empty\")\n\tflag.BoolVar(&o.oneshot, \"oneshot\", false, \"Write proto once and exit instead of monitoring --yaml files for changes\")\n\tflag.StringVar(&o.output, \"output\", \"\", \"write proto to gs:\/\/bucket\/obj or \/local\/path\")\n\tflag.BoolVar(&o.printText, \"print-text\", false, \"print generated proto in text format to stdout\")\n\tflag.Var(&o.inputs, \"yaml\", \"comma-separated list of input YAML files\")\n\tflag.Parse()\n\treturn o\n}\n\nfunc (o *options) validate() error {\n\tif len(o.inputs) == 0 || o.inputs[0] == \"\" {\n\t\treturn errors.New(\"--yaml must include at least one file\")\n\t}\n\n\tif !o.printText && o.output == \"\" {\n\t\treturn errors.New(\"--print-text or --output=gs:\/\/path required\")\n\t}\n\treturn nil\n}\n\n\/\/ announceChanges watches for changes to files and writes one of them to the channel\nfunc announceChanges(ctx context.Context, paths []string, channel chan []string) {\n\tdefer close(channel)\n\tmodified := map[string]time.Time{}\n\tfor _, p := range paths {\n\t\tmodified[p] = time.Time{} \/\/ Never seen\n\t}\n\n\t\/\/ TODO(fejta): consider waiting for a notification rather than polling\n\t\/\/ but performance isn't that big a deal here.\n\tfor {\n\t\tvar changed []string\n\t\tfor p, last := range modified {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t\tswitch info, err := os.Stat(p); {\n\t\t\tcase os.IsNotExist(err) && !last.IsZero():\n\t\t\t\t\/\/ File deleted\n\t\t\t\tmodified[p] = time.Time{}\n\t\t\t\tchanged = append(changed, p)\n\t\t\tcase err != nil:\n\t\t\t\tlog.Printf(\"Error reading %s: %v\", p, err)\n\t\t\tdefault:\n\t\t\t\tif t := info.ModTime(); t.After(last) {\n\t\t\t\t\tchanged = append(changed, p)\n\t\t\t\t\tmodified[p] = t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(changed) > 0 {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase channel <- changed:\n\t\t\t}\n\t\t} else {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n}\n\nfunc readConfig(paths []string) (*Config, error) {\n\tvar c Config\n\tfor _, file := range paths {\n\t\tb, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read %s: %v\", file, err)\n\t\t}\n\t\tif err = c.Update(b); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to merge %s into config: %v\", file, err)\n\t\t}\n\t}\n\treturn &c, nil\n}\n\nfunc write(ctx context.Context, client *storage.Client, path string, bytes []byte) error {\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid url %s: %v\", path, err)\n\t}\n\tif u.Scheme != \"gs\" {\n\t\treturn ioutil.WriteFile(path, bytes, 0644)\n\t}\n\tvar p gcs.Path\n\tif err = p.SetURL(u); err != nil {\n\t\treturn err\n\t}\n\treturn gcs.Upload(ctx, client, p, bytes)\n}\n\nfunc doOneshot(ctx context.Context, client *storage.Client, opt options) error {\n\t\/\/ Ignore what changed for now and just recompute everything\n\tc, err := readConfig(opt.inputs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read config: %v\", err)\n\t}\n\n\t\/\/ Print proto if requested\n\tif opt.printText {\n\t\tif err := c.MarshalText(os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"could not print config: %v\", err)\n\t\t}\n\t}\n\n\t\/\/ Write proto if requested\n\tif opt.output != \"\" {\n\t\tb, err := c.MarshalBytes()\n\t\tif err == nil {\n\t\t\terr = write(ctx, client, opt.output, b)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not write config: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\t\/\/ Parse flags\n\topt := gatherOptions()\n\tif err := opt.validate(); err != nil {\n\t\tlog.Fatalf(\"Bad flags: %v\", err)\n\t}\n\n\t\/\/ Setup stuff\n\tctx := context.Background()\n\tclient, err := gcs.ClientWithCreds(ctx, opt.creds)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create storage client: %v\", err)\n\t}\n\n\t\/\/ Oneshot mode, write config and exit\n\tif opt.oneshot {\n\t\tif err := doOneshot(ctx, client, opt); err != nil {\n\t\t\tlog.Fatalf(\"FAIL: %v\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Service mode, monitor input files for changes\n\tchannel := make(chan []string)\n\t\/\/ Monitor files for changes\n\tgo announceChanges(ctx, opt.inputs, channel)\n\n\t\/\/ Wait for changed files\n\tfor changes := range channel {\n\t\tlog.Printf(\"Changed: %v\", changes)\n\t\tlog.Println(\"Writing config...\")\n\t\tif err := doOneshot(ctx, client, opt); err != nil {\n\t\t\tlog.Printf(\"FAIL: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"Wrote config to %s\", opt.output)\n\t}\n}\n<commit_msg>Add --validate to testgrid\/cmd\/configurator<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 main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io\/test-infra\/testgrid\/util\/gcs\"\n\n\t\"cloud.google.com\/go\/storage\"\n)\n\ntype multiString []string\n\nfunc (m multiString) String() string {\n\treturn strings.Join(m, \",\")\n}\n\nfunc (m *multiString) Set(v string) error {\n\t*m = strings.Split(v, \",\")\n\treturn nil\n}\n\ntype options struct {\n\tcreds     string\n\tinputs    multiString\n\toneshot   bool\n\toutput    string\n\tprintText bool\n\tvalidate  bool\n}\n\nfunc gatherOptions() (options, error) {\n\to := options{}\n\tflag.StringVar(&o.creds, \"gcp-service-account\", \"\", \"\/path\/to\/gcp\/creds (use local creds if empty\")\n\tflag.BoolVar(&o.oneshot, \"oneshot\", false, \"Write proto once and exit instead of monitoring --yaml files for changes\")\n\tflag.StringVar(&o.output, \"output\", \"\", \"write proto to gs:\/\/bucket\/obj or \/local\/path\")\n\tflag.BoolVar(&o.printText, \"print-text\", false, \"print generated proto in text format to stdout\")\n\tflag.BoolVar(&o.validate, \"validate\", false, \"validate the given config files\")\n\tflag.Var(&o.inputs, \"yaml\", \"comma-separated list of input YAML files\")\n\tflag.Parse()\n\tif len(o.inputs) == 0 || o.inputs[0] == \"\" {\n\t\treturn o, errors.New(\"--yaml must include at least one file\")\n\t}\n\n\tif !o.printText && !o.validate && o.output == \"\" {\n\t\treturn o, errors.New(\"--print-text or --output=gs:\/\/path required\")\n\t}\n\tif o.validate && o.output != \"\" {\n\t\treturn o, errors.New(\"--validate implies no output\")\n\t}\n\treturn o, nil\n}\n\n\/\/ announceChanges watches for changes to files and writes one of them to the channel\nfunc announceChanges(ctx context.Context, paths []string, channel chan []string) {\n\tdefer close(channel)\n\tmodified := map[string]time.Time{}\n\tfor _, p := range paths {\n\t\tmodified[p] = time.Time{} \/\/ Never seen\n\t}\n\n\t\/\/ TODO(fejta): consider waiting for a notification rather than polling\n\t\/\/ but performance isn't that big a deal here.\n\tfor {\n\t\tvar changed []string\n\t\tfor p, last := range modified {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t\tswitch info, err := os.Stat(p); {\n\t\t\tcase os.IsNotExist(err) && !last.IsZero():\n\t\t\t\t\/\/ File deleted\n\t\t\t\tmodified[p] = time.Time{}\n\t\t\t\tchanged = append(changed, p)\n\t\t\tcase err != nil:\n\t\t\t\tlog.Printf(\"Error reading %s: %v\", p, err)\n\t\t\tdefault:\n\t\t\t\tif t := info.ModTime(); t.After(last) {\n\t\t\t\t\tchanged = append(changed, p)\n\t\t\t\t\tmodified[p] = t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(changed) > 0 {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase channel <- changed:\n\t\t\t}\n\t\t} else {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t}\n\t}\n}\n\nfunc readConfig(paths []string) (*Config, error) {\n\tvar c Config\n\tfor _, file := range paths {\n\t\tb, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read %s: %v\", file, err)\n\t\t}\n\t\tif err = c.Update(b); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to merge %s into config: %v\", file, err)\n\t\t}\n\t}\n\treturn &c, nil\n}\n\nfunc write(ctx context.Context, client *storage.Client, path string, bytes []byte) error {\n\tu, err := url.Parse(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid url %s: %v\", path, err)\n\t}\n\tif u.Scheme != \"gs\" {\n\t\treturn ioutil.WriteFile(path, bytes, 0644)\n\t}\n\tvar p gcs.Path\n\tif err = p.SetURL(u); err != nil {\n\t\treturn err\n\t}\n\treturn gcs.Upload(ctx, client, p, bytes)\n}\n\nfunc doOneshot(ctx context.Context, client *storage.Client, opt options) error {\n\t\/\/ Ignore what changed for now and just recompute everything\n\tc, err := readConfig(opt.inputs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read config: %v\", err)\n\t}\n\n\t\/\/ Print proto if requested\n\tif opt.printText {\n\t\tif err := c.MarshalText(os.Stdout); err != nil {\n\t\t\treturn fmt.Errorf(\"could not print config: %v\", err)\n\t\t}\n\t}\n\n\t\/\/ Write proto if requested\n\tif opt.output != \"\" {\n\t\tb, err := c.MarshalBytes()\n\t\tif err == nil {\n\t\t\terr = write(ctx, client, opt.output, b)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not write config: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\t\/\/ Parse flags\n\topt, err := gatherOptions()\n\tif err != nil {\n\t\tlog.Fatalf(\"Bad flags: %v\", err)\n\t}\n\n\tctx := context.Background()\n\n\t\/\/ Validation only\n\tif opt.validate {\n\t\tif err := doOneshot(ctx, nil, opt); err != nil {\n\t\t\tlog.Fatalf(\"FAIL: %v\", err)\n\t\t}\n\t\tlog.Println(\"Config validated successfully\")\n\t\treturn\n\t}\n\n\t\/\/ Setup GCS client\n\tclient, err := gcs.ClientWithCreds(ctx, opt.creds)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create storage client: %v\", err)\n\t}\n\n\t\/\/ Oneshot mode, write config and exit\n\tif opt.oneshot {\n\t\tif err := doOneshot(ctx, client, opt); err != nil {\n\t\t\tlog.Fatalf(\"FAIL: %v\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Service mode, monitor input files for changes\n\tchannel := make(chan []string)\n\t\/\/ Monitor files for changes\n\tgo announceChanges(ctx, opt.inputs, channel)\n\n\t\/\/ Wait for changed files\n\tfor changes := range channel {\n\t\tlog.Printf(\"Changed: %v\", changes)\n\t\tlog.Println(\"Writing config...\")\n\t\tif err := doOneshot(ctx, client, opt); err != nil {\n\t\t\tlog.Printf(\"FAIL: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"Wrote config to %s\", opt.output)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Serviced 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 unit\n\npackage metrics\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/control-center\/serviced\/utils\"\n)\n\nfunc TestCache(t *testing.T) {\n\n\tclock := utils.NewTestClock()\n\n\tcache := MemoryUsageCache{\n\t\tUsages: make(map[string]*MemoryUsageItem),\n\t\tTTL:    time.Minute,\n\t\tClock:  clock,\n\t}\n\n\tmemusage1 := []MemoryUsageStats{\n\t\tMemoryUsageStats{ServiceID: \"memusage1\"},\n\t}\n\tmemusage2 := []MemoryUsageStats{\n\t\tMemoryUsageStats{ServiceID: \"memusage2\"},\n\t}\n\n\tgetter1 := func() ([]MemoryUsageStats, error) {\n\t\treturn memusage1, nil\n\t}\n\n\tgetter2 := func() ([]MemoryUsageStats, error) {\n\t\treturn memusage2, nil\n\t}\n\n\terrgetter := func() ([]MemoryUsageStats, error) {\n\t\treturn nil, errors.New(\"\")\n\t}\n\n\t\/\/ Cache is empty, test error propagation in getter\n\tx, err := cache.Get(\"first\", errgetter)\n\tif err == nil {\n\t\tt.Errorf(\"Cache did not propagate error in getter properly\")\n\t}\n\n\t\/\/ Cache still empty, test getter\n\tx, err = cache.Get(\"first\", getter1)\n\tif !reflect.DeepEqual(x, memusage1) {\n\t\tt.Errorf(\"Empty cache did not return a new item when a key did not yet exist\")\n\t}\n\n\t\/\/ Cache has value for key, try error getter again\n\tx, err = cache.Get(\"first\", errgetter)\n\tif err != nil {\n\t\tt.Errorf(\"Cache returned an error when it should have returned a cached value\")\n\t}\n\n\t\/\/ Cache has value for key, try a new key with a different getter\n\tx, err = cache.Get(\"second\", getter2)\n\tif !reflect.DeepEqual(x, memusage2) {\n\t\tt.Errorf(\"Non-empty cache did not return a new item when a key did not yet exist\")\n\t}\n\n\t\/\/ Cache has a value for key, try different getter\n\tx, err = cache.Get(\"first\", getter2)\n\tif !reflect.DeepEqual(x, memusage1) {\n\t\tt.Errorf(\"Cache did not return the correct item\")\n\t}\n\n\t\/\/ Force expiration\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tclose(done)\n\t\tclock.Fire()\n\t}()\n\t<-done\n\n\t\/\/ Cache should no longer have a value for key, try with different getter\n\tx, err = cache.Get(\"first\", getter2)\n\tif !reflect.DeepEqual(x, memusage2) {\n\t\tt.Errorf(\"Cache returned a value that should have expired\")\n\t}\n}\n<commit_msg>elaborated on a test process<commit_after>\/\/ Copyright 2015 The Serviced 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 unit\n\npackage metrics\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/control-center\/serviced\/utils\"\n)\n\nfunc TestCache(t *testing.T) {\n\n\tclock := utils.NewTestClock()\n\n\tcache := MemoryUsageCache{\n\t\tUsages: make(map[string]*MemoryUsageItem),\n\t\tTTL:    time.Minute,\n\t\tClock:  clock,\n\t}\n\n\tmemusage1 := []MemoryUsageStats{\n\t\tMemoryUsageStats{ServiceID: \"memusage1\"},\n\t}\n\tmemusage2 := []MemoryUsageStats{\n\t\tMemoryUsageStats{ServiceID: \"memusage2\"},\n\t}\n\n\tgetter1 := func() ([]MemoryUsageStats, error) {\n\t\treturn memusage1, nil\n\t}\n\n\tgetter2 := func() ([]MemoryUsageStats, error) {\n\t\treturn memusage2, nil\n\t}\n\n\terrgetter := func() ([]MemoryUsageStats, error) {\n\t\treturn nil, errors.New(\"\")\n\t}\n\n\t\/\/ Cache is empty, test error propagation in getter\n\tx, err := cache.Get(\"first\", errgetter)\n\tif err == nil {\n\t\tt.Errorf(\"Cache did not propagate error in getter properly\")\n\t}\n\n\t\/\/ Cache still empty, test getter\n\tx, err = cache.Get(\"first\", getter1)\n\tif !reflect.DeepEqual(x, memusage1) {\n\t\tt.Errorf(\"Empty cache did not return a new item when a key did not yet exist\")\n\t}\n\n\t\/\/ Cache has value for key, try error getter again\n\tx, err = cache.Get(\"first\", errgetter)\n\tif err != nil {\n\t\tt.Errorf(\"Cache returned an error when it should have returned a cached value\")\n\t}\n\n\t\/\/ Cache has value for key, try a new key with a different getter\n\tx, err = cache.Get(\"second\", getter2)\n\tif !reflect.DeepEqual(x, memusage2) {\n\t\tt.Errorf(\"Non-empty cache did not return a new item when a key did not yet exist\")\n\t}\n\n\t\/\/ Cache has a value for key, try different getter\n\tx, err = cache.Get(\"first\", getter2)\n\tif !reflect.DeepEqual(x, memusage1) {\n\t\tt.Errorf(\"Cache did not return the correct item\")\n\t}\n\n\t\/\/ Force expiration\n\t\/\/ I know this seems crazy, but go clock.Fire() may not trigger before\n\t\/\/ cache.Get is called.\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tclose(done)\n\t\tclock.Fire()\n\t}()\n\t<-done\n\n\t\/\/ Cache should no longer have a value for key, try with different getter\n\tx, err = cache.Get(\"first\", getter2)\n\tif !reflect.DeepEqual(x, memusage2) {\n\t\tt.Errorf(\"Cache returned a value that should have expired\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package metrics\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype SlowQueryMetrics struct {\n\tmutex        sync.Mutex\n\tmetrics      map[string]prometheus.Gauge\n\tmilliseconds int64\n}\n\nfunc NewSlowQueryMetrics(durationToConsiderSlow time.Duration) *SlowQueryMetrics {\n\treturn &SlowQueryMetrics{\n\t\tmilliseconds: durationToConsiderSlow.Nanoseconds() \/ 1000000,\n\t\tmetrics: map[string]prometheus.Gauge{\n\t\t\t\"slow_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_queries_total\",\n\t\t\t\tHelp:      \"Number of slow queries\",\n\t\t\t}),\n\t\t\t\"slow_select_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_select_queries_total\",\n\t\t\t\tHelp:      \"Number of slow SELECT queries\",\n\t\t\t}),\n\t\t\t\"slow_dml_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_dml_queries_total\",\n\t\t\t\tHelp:      \"Number of slow data manipulation queries (INSERT, UPDATE, DELETE)\",\n\t\t\t}),\n\t\t},\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Scrape(db *sql.DB) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tcount := new(float64)\n\terr := db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds' )::interval AND \n\t\t\t\tquery ilike 'select%'`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow select queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_select_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval AND \n\t\t\t\t(query ilike 'insert%' OR query ilike 'update%' OR query ilike 'delete%')`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow dml queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_dml_queries\"].Set(*count)\n\n\treturn nil\n}\n\nfunc (s *SlowQueryMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range s.metrics {\n\t\tm.Describe(ch)\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range s.metrics {\n\t\tm.Collect(ch)\n\t}\n}\n\n\/\/ check interface\nvar _ Collection = new(SlowQueryMetrics)\n<commit_msg>MFD-7 use named constant<commit_after>package metrics\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype SlowQueryMetrics struct {\n\tmutex        sync.Mutex\n\tmetrics      map[string]prometheus.Gauge\n\tmilliseconds int64\n}\n\nfunc NewSlowQueryMetrics(durationToConsiderSlow time.Duration) *SlowQueryMetrics {\n\treturn &SlowQueryMetrics{\n\t\tmilliseconds: durationToConsiderSlow.Nanoseconds() \/ int64(time.Millisecond),\n\t\tmetrics: map[string]prometheus.Gauge{\n\t\t\t\"slow_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_queries_total\",\n\t\t\t\tHelp:      \"Number of slow queries\",\n\t\t\t}),\n\t\t\t\"slow_select_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_select_queries_total\",\n\t\t\t\tHelp:      \"Number of slow SELECT queries\",\n\t\t\t}),\n\t\t\t\"slow_dml_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_dml_queries_total\",\n\t\t\t\tHelp:      \"Number of slow data manipulation queries (INSERT, UPDATE, DELETE)\",\n\t\t\t}),\n\t\t},\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Scrape(db *sql.DB) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tcount := new(float64)\n\terr := db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds' )::interval AND \n\t\t\t\tquery ilike 'select%'`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow select queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_select_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval AND \n\t\t\t\t(query ilike 'insert%' OR query ilike 'update%' OR query ilike 'delete%')`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow dml queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_dml_queries\"].Set(*count)\n\n\treturn nil\n}\n\nfunc (s *SlowQueryMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range s.metrics {\n\t\tm.Describe(ch)\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range s.metrics {\n\t\tm.Collect(ch)\n\t}\n}\n\n\/\/ check interface\nvar _ Collection = new(SlowQueryMetrics)\n<|endoftext|>"}
{"text":"<commit_before>package monitor\n\nimport (\n\t\"errors\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/cloud-tools\/mm\"\n\t\"github.com\/percona\/cloud-tools\/mm\/mysql\"\n\t\"github.com\/percona\/cloud-tools\/pct\"\n)\n\ntype Factory struct {\n\tlogChan chan *proto.LogEntry\n}\n\nfunc NewFactory(logChan chan *proto.LogEntry) *Factory {\n\tf := &Factory{\n\t\tlogChan: logChan,\n\t}\n\treturn f\n}\n\nfunc (f *Factory) Make(mtype, name string) (mm.Monitor, error) {\n\tvar monitor mm.Monitor\n\tswitch mtype {\n\tcase \"mysql\":\n\t\tmonitor = mysql.NewMonitor(pct.NewLogger(f.logChan, name))\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown monitor type: \" + mtype)\n\t}\n\treturn monitor, nil\n}\n<commit_msg>Add system monitor type to mm factory.<commit_after>package monitor\n\nimport (\n\t\"errors\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/cloud-tools\/mm\"\n\t\"github.com\/percona\/cloud-tools\/mm\/mysql\"\n\t\"github.com\/percona\/cloud-tools\/mm\/system\"\n\t\"github.com\/percona\/cloud-tools\/pct\"\n)\n\ntype Factory struct {\n\tlogChan chan *proto.LogEntry\n}\n\nfunc NewFactory(logChan chan *proto.LogEntry) *Factory {\n\tf := &Factory{\n\t\tlogChan: logChan,\n\t}\n\treturn f\n}\n\nfunc (f *Factory) Make(mtype, name string) (mm.Monitor, error) {\n\tvar monitor mm.Monitor\n\tswitch mtype {\n\tcase \"mysql\":\n\t\tmonitor = mysql.NewMonitor(pct.NewLogger(f.logChan, name))\n\tcase \"system\":\n\t\tmonitor = system.NewMonitor(pct.NewLogger(f.logChan, name))\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown monitor type: \" + mtype)\n\t}\n\treturn monitor, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package tests\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/deis\/deis\/tests\/dockercliutils\"\n\t\"github.com\/deis\/deis\/tests\/etcdutils\"\n\t\"github.com\/deis\/deis\/tests\/mockserviceutils\"\n\t\"github.com\/deis\/deis\/tests\/utils\"\n)\n\nfunc runDeisControllerTest(t *testing.T, testSessionUID string, etcdPort string, servicePort string) {\n\tcli, stdout, stdoutPipe := dockercliutils.GetNewClient()\n\tdone := make(chan bool, 1)\n\tdockercliutils.BuildDockerfile(t, \"..\/\", \"deis\/controller:\"+testSessionUID)\n\t\/\/docker run --name deis-controller -p 8000:8000 -e PUBLISH=8000\n\t\/\/ -e HOST=${COREOS_PRIVATE_IPV4} --volumes-from=deis-logger deis\/controller\n\tIPAddress := utils.GetHostIPAddress()\n\tdone <- true\n\tgo func() {\n\t\t<-done\n\t\tdockercliutils.RunContainer(t, cli, \"--name\",\n\t\t\t\"deis-controller-\"+testSessionUID,\n\t\t\t\"-p\", servicePort+\":8000\",\n\t\t\t\"-e\", \"PUBLISH=\"+servicePort,\n\t\t\t\"-e\", \"HOST=\"+IPAddress,\n\t\t\t\"-e\", \"ETCD_PORT=\"+etcdPort,\n\t\t\t\"deis\/controller:\"+testSessionUID)\n\t}()\n\ttime.Sleep(5000 * time.Millisecond)\n\tdockercliutils.PrintToStdout(t, stdout, stdoutPipe, \"Booting\")\n\n}\n\nfunc TestBuild(t *testing.T) {\n\tsetkeys := []string{\"\/deis\/registry\/protocol\",\n\t\t\"deis\/registry\/host\",\n\t\t\"\/deis\/registry\/port\",\n\t\t\"\/deis\/cache\/host\",\n\t\t\"\/deis\/cache\/port\"}\n\tsetdir := []string{\"\/deis\/controller\",\n\t\t\"\/deis\/cache\",\n\t\t\"\/deis\/database\",\n\t\t\"\/deis\/registry\",\n\t\t\"\/deis\/domains\"}\n\tvar testSessionUID = utils.NewUuid()\n\tfmt.Println(\"UUID for the session Controller Test :\" + testSessionUID)\n\tetcdPort := utils.GetRandomPort()\n\tservicePort := utils.GetRandomPort()\n\tdbPort := utils.GetRandomPort()\n\tdockercliutils.RunEtcdTest(t, testSessionUID, etcdPort)\n\tfmt.Println(\"starting controller test:\")\n\tControllerhandler := etcdutils.InitetcdValues(setdir, setkeys, etcdPort)\n\tetcdutils.Publishvalues(t, Controllerhandler)\n\tmockserviceutils.RunMockDatabase(t, testSessionUID, etcdPort, dbPort)\n\tfmt.Println(\"starting Controller component test\")\n\trunDeisControllerTest(t, testSessionUID, etcdPort, servicePort)\n\tdockercliutils.DeisServiceTest(\n\t\tt, \"deis-controller-\"+testSessionUID, servicePort, \"http\")\n\tdockercliutils.ClearTestSession(t, testSessionUID)\n}\n<commit_msg>fix(tests): use `docker run --rm` instead of explicitly removing containers<commit_after>package tests\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/deis\/deis\/tests\/dockercliutils\"\n\t\"github.com\/deis\/deis\/tests\/etcdutils\"\n\t\"github.com\/deis\/deis\/tests\/mockserviceutils\"\n\t\"github.com\/deis\/deis\/tests\/utils\"\n)\n\nfunc runDeisControllerTest(t *testing.T, testSessionUID string, etcdPort string, servicePort string) {\n\tcli, stdout, stdoutPipe := dockercliutils.GetNewClient()\n\tdone := make(chan bool, 1)\n\tdockercliutils.BuildDockerfile(t, \"..\/\", \"deis\/controller:\"+testSessionUID)\n\t\/\/docker run --name deis-controller -p 8000:8000 -e PUBLISH=8000\n\t\/\/ -e HOST=${COREOS_PRIVATE_IPV4} --volumes-from=deis-logger deis\/controller\n\tIPAddress := utils.GetHostIPAddress()\n\tdone <- true\n\tgo func() {\n\t\t<-done\n\t\tdockercliutils.RunContainer(t, cli,\n\t\t\t\"--name\", \"deis-controller-\"+testSessionUID,\n\t\t\t\"--rm\",\n\t\t\t\"-p\", servicePort+\":8000\",\n\t\t\t\"-e\", \"PUBLISH=\"+servicePort,\n\t\t\t\"-e\", \"HOST=\"+IPAddress,\n\t\t\t\"-e\", \"ETCD_PORT=\"+etcdPort,\n\t\t\t\"deis\/controller:\"+testSessionUID)\n\t}()\n\ttime.Sleep(5000 * time.Millisecond)\n\tdockercliutils.PrintToStdout(t, stdout, stdoutPipe, \"Booting\")\n\n}\n\nfunc TestBuild(t *testing.T) {\n\tsetkeys := []string{\"\/deis\/registry\/protocol\",\n\t\t\"deis\/registry\/host\",\n\t\t\"\/deis\/registry\/port\",\n\t\t\"\/deis\/cache\/host\",\n\t\t\"\/deis\/cache\/port\"}\n\tsetdir := []string{\"\/deis\/controller\",\n\t\t\"\/deis\/cache\",\n\t\t\"\/deis\/database\",\n\t\t\"\/deis\/registry\",\n\t\t\"\/deis\/domains\"}\n\tvar testSessionUID = utils.NewUuid()\n\tfmt.Println(\"UUID for the session Controller Test :\" + testSessionUID)\n\tetcdPort := utils.GetRandomPort()\n\tservicePort := utils.GetRandomPort()\n\tdbPort := utils.GetRandomPort()\n\tdockercliutils.RunEtcdTest(t, testSessionUID, etcdPort)\n\tfmt.Println(\"starting controller test:\")\n\tControllerhandler := etcdutils.InitetcdValues(setdir, setkeys, etcdPort)\n\tetcdutils.Publishvalues(t, Controllerhandler)\n\tmockserviceutils.RunMockDatabase(t, testSessionUID, etcdPort, dbPort)\n\tfmt.Println(\"starting Controller component test\")\n\trunDeisControllerTest(t, testSessionUID, etcdPort, servicePort)\n\tdockercliutils.DeisServiceTest(\n\t\tt, \"deis-controller-\"+testSessionUID, servicePort, \"http\")\n\tdockercliutils.ClearTestSession(t, testSessionUID)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 The KidStuff 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 model\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\tErrDuplicateName = errors.New(\"auth: duplicate Group Name\")\n)\n\ntype Group struct {\n\tId        *string    `bson:\"Id,omitempty\"`\n\tName      *string    `bson:\"Name,omitempty\" json:\",omitempty\"`\n\tInfo      *GroupInfo `bson:\"Info,omitempty\" json:\",omitempty\"`\n\tPrivilege []string   `bson:\"Privilege,omitempty\" json:\",omitempty\"`\n}\n\ntype GroupInfo struct {\n\tDescription *string `bson:\"Description\" json:\",omitempty\"`\n}\n\ntype GroupManager interface {\n\t\/\/ AddDetail adds a group with full detail to database.\n\tAddDetail(*Group) (*Group, error)\n\t\/\/ UpdateDetail updates group detail specific by id.\n\tUpdateDetail(*Group) error\n\t\/\/ Find find the group specific by id.\n\tFind(id string) (*Group, error)\n\t\/\/ FindByName find the group specific by name.\n\tFindByName(name string) (*Group, error)\n\t\/\/ FindSome find and return a slice of group specific by thier id.\n\tFindSome(id ...string) ([]*Group, error)\n\t\/\/ FindAll finds and return a slice of group.\n\t\/\/ If limit < 0 the mean using the default upper limit.\n\t\/\/ If limit == 0 return empty result with error indicate no result found.\n\t\/\/ If limit can't be greater than the default upper limit.\n\t\/\/ Specific fields name for porjection select.\n\tFindAll(limit int, offsetId string, fields []string) ([]*Group, error)\n\t\/\/ Delete deletes a group from database base on the given id;\n\t\/\/ It returns an error describes the first issue encountered, if any.\n\tDelete(id string) error\n}\n<commit_msg>change interface of group manager according to user nanaer<commit_after>\/\/ Copyright 2012 The KidStuff 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 model\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\tErrDuplicateName = errors.New(\"auth: duplicate Group Name\")\n)\n\ntype Group struct {\n\tId        *string    `bson:\"Id,omitempty\"`\n\tName      *string    `bson:\"Name,omitempty\" json:\",omitempty\"`\n\tInfo      *GroupInfo `bson:\"Info,omitempty\" json:\",omitempty\"`\n\tPrivilege []string   `bson:\"Privilege,omitempty\" json:\",omitempty\"`\n}\n\ntype GroupInfo struct {\n\tDescription *string `bson:\"Description\" json:\",omitempty\"`\n}\n\ntype GroupManager interface {\n\t\/\/ AddDetail adds a group with full detail to database.\n\tAddDetail(name string, pri []string, info *GroupInfo) (*Group, error)\n\t\/\/ UpdateDetail updates group detail specific by id.\n\tUpdateDetail(id string, pri []string, info *GroupInfo) error\n\t\/\/ Find find the group specific by id.\n\tFind(id string) (*Group, error)\n\t\/\/ FindByName find the group specific by name.\n\tFindByName(name string) (*Group, error)\n\t\/\/ FindSome find and return a slice of group specific by thier id.\n\tFindSome(id ...string) ([]*Group, error)\n\t\/\/ FindAll finds and return a slice of group.\n\t\/\/ If limit < 0 the mean using the default upper limit.\n\t\/\/ If limit == 0 return empty result with error indicate no result found.\n\t\/\/ If limit can't be greater than the default upper limit.\n\t\/\/ Specific fields name for porjection select.\n\tFindAll(limit int, offsetId string, fields []string) ([]*Group, error)\n\t\/\/ Delete deletes a group from database base on the given id;\n\t\/\/ It returns an error describes the first issue encountered, if any.\n\tDelete(id string) error\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"bufio\"\n\t\"crypto\/md5\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"github.com\/APTrust\/exchange\/constants\"\n\t\"github.com\/APTrust\/exchange\/platform\"\n\t\"github.com\/APTrust\/exchange\/util\"\n\t\"github.com\/APTrust\/exchange\/util\/fileutil\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ VirtualBag creates an IntellectualObject from a bag on disk.\n\/\/ The IntellectualObject can then be validated by workers.BagValidator.\ntype VirtualBag struct {\n\tpathToBag       string\n\tcalculateMd5    bool\n\tcalculateSha256 bool\n\ttagFilesToParse []string\n\tobj             *IntellectualObject\n\tsummary         *WorkSummary\n\treadIterator    fileutil.ReadIterator\n}\n\n\/\/ NewVirtualBag creates a new virtual bag. Param pathToBag should\n\/\/ be an absolute path to either a tar file or a directory containing\n\/\/ an untarred bag. It pathToBag points to a tar file, the Read()\n\/\/ function will read the bag without untarring it. Param tagFilesToParse\n\/\/ should be a list of relative paths, pointing to tag files within the\n\/\/ bag that should be parsed. For example, \"aptrust-info.txt\" or\n\/\/ \"dpn_tags\/dpn-info.txt\" Params calculateMd5 and calculateSha256\n\/\/ indicate whether we should calculate md5 and\/or sha256 checksums\n\/\/ on the files in the bag.\nfunc NewVirtualBag(pathToBag string, tagFilesToParse []string, calculateMd5, calculateSha256 bool) *VirtualBag {\n\tif tagFilesToParse == nil {\n\t\ttagFilesToParse = make([]string, 0)\n\t}\n\treturn &VirtualBag{\n\t\tcalculateMd5:    calculateMd5,\n\t\tcalculateSha256: calculateSha256,\n\t\tpathToBag:       pathToBag,\n\t\ttagFilesToParse: tagFilesToParse,\n\t}\n}\n\n\/\/ Read() reads the bag and returns an IntellectualObject and a WorkSummary.\n\/\/ The WorkSummary will include a list of errors, if there were any.\n\/\/ The list of files contained in IntellectualObject.GenericFiles will include\n\/\/ ALL files found in the bag, even some we may not want to save, such as\n\/\/ those beginning with dots and dashes. If you don't want to preserve those\n\/\/ files you can delete them from the IntellectualObject manually later.\nfunc (vbag *VirtualBag) Read() (*IntellectualObject, *WorkSummary) {\n\tvbag.summary = NewWorkSummary()\n\tvbag.summary.Start()\n\tvbag.obj = NewIntellectualObject()\n\tvbag.obj.Identifier = util.CleanBagName(path.Base(vbag.pathToBag))\n\tif strings.HasSuffix(vbag.pathToBag, \".tar\") {\n\t\tvbag.obj.IngestTarFilePath = vbag.pathToBag\n\t} else {\n\t\tvbag.obj.IngestUntarredPath = vbag.pathToBag\n\t}\n\n\t\/\/ Compile a list of the bag's contents (GenericFiles),\n\t\/\/ and calculate checksums for everything in the bag.\n\tvar err error\n\tif vbag.obj.IngestTarFilePath != \"\" {\n\t\tvbag.readIterator, err = fileutil.NewTarFileIterator(vbag.obj.IngestTarFilePath)\n\t} else {\n\t\tvbag.readIterator, err = fileutil.NewFileSystemIterator(vbag.obj.IngestUntarredPath)\n\t}\n\tif err != nil {\n\t\tvbag.summary.AddError(\"Could not read bag: %v\", err)\n\t\tvbag.summary.Finish()\n\t\treturn vbag.obj, vbag.summary\n\t} else {\n\t\tvbag.addGenericFiles()\n\t}\n\tvbag.obj.IngestTopLevelDirNames = vbag.readIterator.GetTopLevelDirNames()\n\n\t\/\/ Golang's tar file reader is forward-only, so we need to\n\t\/\/ open a new iterator to read through a handful of tag files,\n\t\/\/ manifests and tag manifests.\n\tvbag.readIterator = nil\n\tif vbag.obj.IngestTarFilePath != \"\" {\n\t\tvbag.readIterator, err = fileutil.NewTarFileIterator(vbag.obj.IngestTarFilePath)\n\t} else {\n\t\tvbag.readIterator, err = fileutil.NewFileSystemIterator(vbag.obj.IngestUntarredPath)\n\t}\n\tif err != nil {\n\t\tvbag.summary.AddError(\"Could not read bag: %v\", err)\n\t} else {\n\t\tvbag.parseManifestsTagFilesAndMimeTypes()\n\t}\n\tvbag.summary.Finish()\n\treturn vbag.obj, vbag.summary\n}\n\n\/\/ Add every file in the bag to the list of generic files.\nfunc (vbag *VirtualBag) addGenericFiles() {\n\tfor {\n\t\terr := vbag.addGenericFile()\n\t\tif err != nil && (err == io.EOF || err.Error() == \"EOF\") {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tvbag.summary.AddError(err.Error())\n\t\t}\n\t}\n}\n\n\/\/ Adds a single generic file to the bag.\nfunc (vbag *VirtualBag) addGenericFile() error {\n\treader, fileSummary, err := vbag.readIterator.Next()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !fileSummary.IsRegularFile {\n\t\treturn nil\n\t}\n\t_uuid := uuid.NewV4()\n\tgf := NewGenericFile()\n\tgf.Identifier = fmt.Sprintf(\"%s\/%s\", vbag.obj.Identifier, fileSummary.RelPath)\n\tgf.IntellectualObjectIdentifier = vbag.obj.Identifier\n\tgf.Size = fileSummary.Size\n\tgf.FileModified = fileSummary.ModTime\n\tgf.IngestLocalPath = fileSummary.AbsPath \/\/ will be empty if bag is tarred\n\tgf.IngestUUID = _uuid.String()\n\tgf.IngestUUIDGeneratedAt = time.Now().UTC()\n\tgf.IngestFileUid = fileSummary.Uid\n\tgf.IngestFileGid = fileSummary.Gid\n\tvbag.obj.GenericFiles = append(vbag.obj.GenericFiles, gf)\n\tvbag.setIngestFileType(gf, fileSummary)\n\treturn vbag.calculateChecksums(reader, gf)\n}\n\n\/\/ Figure out what type of file this is.\nfunc (vbag *VirtualBag) setIngestFileType(gf *GenericFile, fileSummary *fileutil.FileSummary) {\n\tif strings.HasPrefix(fileSummary.RelPath, \"tagmanifest-\") {\n\t\tgf.IngestFileType = constants.TAG_MANIFEST\n\t\tgf.FileFormat = \"text\/plain\"\n\t\tvbag.obj.IngestTagManifests = append(vbag.obj.IngestTagManifests, fileSummary.RelPath)\n\t} else if strings.HasPrefix(fileSummary.RelPath, \"manifest-\") {\n\t\tgf.IngestFileType = constants.PAYLOAD_MANIFEST\n\t\tgf.FileFormat = \"text\/plain\"\n\t\tvbag.obj.IngestManifests = append(vbag.obj.IngestManifests, fileSummary.RelPath)\n\t} else if strings.HasPrefix(fileSummary.RelPath, \"data\/\") {\n\t\tgf.IngestFileType = constants.PAYLOAD_FILE\n\t} else {\n\t\tgf.IngestFileType = constants.TAG_FILE\n\t}\n}\n\n\/\/ Calculate the md5 and\/or sha256 checksums on a file.\nfunc (vbag *VirtualBag) calculateChecksums(reader io.Reader, gf *GenericFile) error {\n\thashes := make([]io.Writer, 0)\n\tvar md5Hash hash.Hash\n\tvar sha256Hash hash.Hash\n\tif vbag.calculateMd5 {\n\t\tmd5Hash = md5.New()\n\t\thashes = append(hashes, md5Hash)\n\t}\n\tif vbag.calculateSha256 {\n\t\tsha256Hash = sha256.New()\n\t\thashes = append(hashes, sha256Hash)\n\t}\n\tif len(hashes) > 0 {\n\t\tmultiWriter := io.MultiWriter(hashes...)\n\t\tio.Copy(multiWriter, reader)\n\t\tutcNow := time.Now().UTC()\n\t\tif md5Hash != nil {\n\t\t\tgf.IngestMd5 = fmt.Sprintf(\"%x\", md5Hash.Sum(nil))\n\t\t\tgf.IngestMd5GeneratedAt = utcNow\n\t\t}\n\t\tif sha256Hash != nil {\n\t\t\tgf.IngestSha256 = fmt.Sprintf(\"%x\", sha256Hash.Sum(nil))\n\t\t\tgf.IngestSha256GeneratedAt = utcNow\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (vbag *VirtualBag) setMimeType(reader io.Reader, gf *GenericFile) {\n\t\/\/ on err, defaults to application\/binary\n\tbufLen := 128\n\tif gf.Size < int64(bufLen) {\n\t\tbufLen = int(gf.Size - 1)\n\t\tif bufLen < 1 {\n\t\t\t\/\/ We actually do permit zero-length files, and we can\n\t\t\t\/\/ save them in S3. These files can be necessary in\n\t\t\t\/\/ certain cases, such as __init__.py files for Python,\n\t\t\t\/\/ PHP templates whose presence is required, \".keep\" files, etc.\n\t\t\tgf.FileFormat = \"text\/empty\"\n\t\t\treturn\n\t\t}\n\t}\n\tbuf := make([]byte, bufLen)\n\t_, err := reader.Read(buf)\n\tif err != nil {\n\t\tvbag.summary.AddError(err.Error())\n\t}\n\tgf.FileFormat, err = platform.GuessMimeTypeByBuffer(buf)\n\tif err != nil {\n\t\tvbag.summary.AddError(err.Error())\n\t}\n}\n\nfunc (vbag *VirtualBag) parseManifestsTagFilesAndMimeTypes() {\n\tfor {\n\t\treader, fileSummary, err := vbag.readIterator.Next()\n\t\tif reader != nil {\n\t\t\tdefer reader.Close()\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tvbag.summary.AddError(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ genericFile will sometimes be nil because the iterator\n\t\t\/\/ returns directory names as well as file names\n\t\tgenericFile := vbag.obj.FindGenericFile(fileSummary.RelPath)\n\t\tif util.StringListContains(vbag.tagFilesToParse, fileSummary.RelPath) {\n\t\t\tvbag.parseTags(reader, fileSummary.RelPath)\n\t\t\tif genericFile != nil {\n\t\t\t\t\/\/ Our vbag library can only parse text files, so this\n\t\t\t\t\/\/ should be a plain text file.\n\t\t\t\tif strings.HasSuffix(genericFile.Identifier, \".txt\") {\n\t\t\t\t\tgenericFile.FileFormat = \"text\/plain\"\n\t\t\t\t} else {\n\t\t\t\t\tgenericFile.FileFormat = \"application\/binary\"\n\t\t\t\t}\n\t\t\t}\n\t\t} else if util.StringListContains(vbag.obj.IngestManifests, fileSummary.RelPath) ||\n\t\t\tutil.StringListContains(vbag.obj.IngestTagManifests, fileSummary.RelPath) {\n\t\t\tvbag.parseManifest(reader, fileSummary.RelPath)\n\t\t} else {\n\t\t\tif genericFile != nil {\n\t\t\t\tvbag.setMimeType(reader, genericFile)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Parse the checksums in a manifest.\nfunc (vbag *VirtualBag) parseManifest(reader io.Reader, relFilePath string) {\n\talg := \"\"\n\tif strings.Contains(relFilePath, constants.AlgSha256) {\n\t\talg = constants.AlgSha256\n\t} else if strings.Contains(relFilePath, constants.AlgMd5) {\n\t\talg = constants.AlgMd5\n\t} else {\n\t\tfmt.Fprintln(os.Stderr, \"Not verifying checksums in\", relFilePath,\n\t\t\t\"- unsupported algorithm. Will still verify any md5 or sha256 checksums.\")\n\t\treturn\n\t}\n\tre := regexp.MustCompile(`^(\\S*)\\s*(.*)`)\n\tscanner := bufio.NewScanner(reader)\n\tlineNum := 1\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif re.MatchString(line) {\n\t\t\tdata := re.FindStringSubmatch(line)\n\t\t\tdigest := data[1]\n\t\t\tfilePath := data[2]\n\t\t\tgenericFile := vbag.obj.FindGenericFile(filePath)\n\t\t\tif genericFile == nil {\n\t\t\t\tvbag.summary.AddError(\n\t\t\t\t\t\"File '%s' in manifest '%s' is missing from bag\",\n\t\t\t\t\tfilePath, relFilePath)\n\t\t\t\tvbag.obj.IngestMissingFiles = append(vbag.obj.IngestMissingFiles,\n\t\t\t\t\tNewMissingFile(relFilePath, lineNum, filePath, digest))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif alg == constants.AlgMd5 {\n\t\t\t\tgenericFile.IngestManifestMd5 = digest\n\t\t\t} else if alg == constants.AlgSha256 {\n\t\t\t\tgenericFile.IngestManifestSha256 = digest\n\t\t\t}\n\t\t} else {\n\t\t\tvbag.summary.AddError(fmt.Sprintf(\n\t\t\t\t\"Unable to parse data from line %d of manifest %s: %s\",\n\t\t\t\tlineNum, relFilePath, line))\n\t\t}\n\t\tlineNum += 1\n\t}\n}\n\n\/\/ Parse the tag fields in a file.\nfunc (vbag *VirtualBag) parseTags(reader io.Reader, relFilePath string) {\n\tre := regexp.MustCompile(`^(\\S*\\:)?(\\s.*)?$`)\n\tscanner := bufio.NewScanner(reader)\n\tvar tag *Tag\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif re.MatchString(line) {\n\t\t\tdata := re.FindStringSubmatch(line)\n\t\t\tdata[1] = strings.Replace(data[1], \":\", \"\", 1)\n\t\t\tif data[1] != \"\" {\n\t\t\t\tif tag != nil && tag.Label != \"\" {\n\t\t\t\t\tvbag.obj.IngestTags = append(vbag.obj.IngestTags, tag)\n\t\t\t\t}\n\t\t\t\ttag = NewTag(relFilePath, data[1], strings.Trim(data[2], \" \"))\n\t\t\t\tvbag.setIntelObjTagValue(tag)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvalue := strings.Trim(data[2], \" \")\n\t\t\ttag.Value = strings.Join([]string{tag.Value, value}, \" \")\n\t\t\tvbag.setIntelObjTagValue(tag)\n\t\t} else {\n\t\t\tvbag.summary.AddError(\"Unable to parse tag data from line: '%s'\", line)\n\t\t}\n\t}\n\tif tag.Label != \"\" {\n\t\tvbag.obj.IngestTags = append(vbag.obj.IngestTags, tag)\n\t}\n\tif scanner.Err() != nil {\n\t\tvbag.summary.AddError(\"Error reading tag file '%s': %v\",\n\t\t\trelFilePath, scanner.Err().Error())\n\t}\n}\n\n\/\/ Copy certain values from the aptrust-info.txt file into\n\/\/ properties of the IntellectualObject.\nfunc (vbag *VirtualBag) setIntelObjTagValue(tag *Tag) {\n\tif tag.SourceFile == \"aptrust-info.txt\" {\n\t\tlabel := strings.ToLower(tag.Label)\n\t\tswitch label {\n\t\tcase \"title\":\n\t\t\tvbag.obj.Title = tag.Value\n\t\tcase \"access\":\n\t\t\tvbag.obj.Access = tag.Value\n\t\t}\n\t} else if tag.SourceFile == \"bag-info.txt\" {\n\t\tlabel := strings.ToLower(tag.Label)\n\t\tswitch label {\n\t\tcase \"source-organization\":\n\t\t\tvbag.obj.Institution = tag.Value\n\t\tcase \"internal-sender-description\":\n\t\t\tvbag.obj.Description = tag.Value\n\t\tcase \"internal-sender-identifier\":\n\t\t\tvbag.obj.AltIdentifier = tag.Value\n\t\t}\n\t}\n\n}\n<commit_msg>PT #144107747: Handle nil tag<commit_after>package models\n\nimport (\n\t\"bufio\"\n\t\"crypto\/md5\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"github.com\/APTrust\/exchange\/constants\"\n\t\"github.com\/APTrust\/exchange\/platform\"\n\t\"github.com\/APTrust\/exchange\/util\"\n\t\"github.com\/APTrust\/exchange\/util\/fileutil\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ VirtualBag creates an IntellectualObject from a bag on disk.\n\/\/ The IntellectualObject can then be validated by workers.BagValidator.\ntype VirtualBag struct {\n\tpathToBag       string\n\tcalculateMd5    bool\n\tcalculateSha256 bool\n\ttagFilesToParse []string\n\tobj             *IntellectualObject\n\tsummary         *WorkSummary\n\treadIterator    fileutil.ReadIterator\n}\n\n\/\/ NewVirtualBag creates a new virtual bag. Param pathToBag should\n\/\/ be an absolute path to either a tar file or a directory containing\n\/\/ an untarred bag. It pathToBag points to a tar file, the Read()\n\/\/ function will read the bag without untarring it. Param tagFilesToParse\n\/\/ should be a list of relative paths, pointing to tag files within the\n\/\/ bag that should be parsed. For example, \"aptrust-info.txt\" or\n\/\/ \"dpn_tags\/dpn-info.txt\" Params calculateMd5 and calculateSha256\n\/\/ indicate whether we should calculate md5 and\/or sha256 checksums\n\/\/ on the files in the bag.\nfunc NewVirtualBag(pathToBag string, tagFilesToParse []string, calculateMd5, calculateSha256 bool) *VirtualBag {\n\tif tagFilesToParse == nil {\n\t\ttagFilesToParse = make([]string, 0)\n\t}\n\treturn &VirtualBag{\n\t\tcalculateMd5:    calculateMd5,\n\t\tcalculateSha256: calculateSha256,\n\t\tpathToBag:       pathToBag,\n\t\ttagFilesToParse: tagFilesToParse,\n\t}\n}\n\n\/\/ Read() reads the bag and returns an IntellectualObject and a WorkSummary.\n\/\/ The WorkSummary will include a list of errors, if there were any.\n\/\/ The list of files contained in IntellectualObject.GenericFiles will include\n\/\/ ALL files found in the bag, even some we may not want to save, such as\n\/\/ those beginning with dots and dashes. If you don't want to preserve those\n\/\/ files you can delete them from the IntellectualObject manually later.\nfunc (vbag *VirtualBag) Read() (*IntellectualObject, *WorkSummary) {\n\tvbag.summary = NewWorkSummary()\n\tvbag.summary.Start()\n\tvbag.obj = NewIntellectualObject()\n\tvbag.obj.Identifier = util.CleanBagName(path.Base(vbag.pathToBag))\n\tif strings.HasSuffix(vbag.pathToBag, \".tar\") {\n\t\tvbag.obj.IngestTarFilePath = vbag.pathToBag\n\t} else {\n\t\tvbag.obj.IngestUntarredPath = vbag.pathToBag\n\t}\n\n\t\/\/ Compile a list of the bag's contents (GenericFiles),\n\t\/\/ and calculate checksums for everything in the bag.\n\tvar err error\n\tif vbag.obj.IngestTarFilePath != \"\" {\n\t\tvbag.readIterator, err = fileutil.NewTarFileIterator(vbag.obj.IngestTarFilePath)\n\t} else {\n\t\tvbag.readIterator, err = fileutil.NewFileSystemIterator(vbag.obj.IngestUntarredPath)\n\t}\n\tif err != nil {\n\t\tvbag.summary.AddError(\"Could not read bag: %v\", err)\n\t\tvbag.summary.Finish()\n\t\treturn vbag.obj, vbag.summary\n\t} else {\n\t\tvbag.addGenericFiles()\n\t}\n\tvbag.obj.IngestTopLevelDirNames = vbag.readIterator.GetTopLevelDirNames()\n\n\t\/\/ Golang's tar file reader is forward-only, so we need to\n\t\/\/ open a new iterator to read through a handful of tag files,\n\t\/\/ manifests and tag manifests.\n\tvbag.readIterator = nil\n\tif vbag.obj.IngestTarFilePath != \"\" {\n\t\tvbag.readIterator, err = fileutil.NewTarFileIterator(vbag.obj.IngestTarFilePath)\n\t} else {\n\t\tvbag.readIterator, err = fileutil.NewFileSystemIterator(vbag.obj.IngestUntarredPath)\n\t}\n\tif err != nil {\n\t\tvbag.summary.AddError(\"Could not read bag: %v\", err)\n\t} else {\n\t\tvbag.parseManifestsTagFilesAndMimeTypes()\n\t}\n\tvbag.summary.Finish()\n\treturn vbag.obj, vbag.summary\n}\n\n\/\/ Add every file in the bag to the list of generic files.\nfunc (vbag *VirtualBag) addGenericFiles() {\n\tfor {\n\t\terr := vbag.addGenericFile()\n\t\tif err != nil && (err == io.EOF || err.Error() == \"EOF\") {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tvbag.summary.AddError(err.Error())\n\t\t}\n\t}\n}\n\n\/\/ Adds a single generic file to the bag.\nfunc (vbag *VirtualBag) addGenericFile() error {\n\treader, fileSummary, err := vbag.readIterator.Next()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !fileSummary.IsRegularFile {\n\t\treturn nil\n\t}\n\t_uuid := uuid.NewV4()\n\tgf := NewGenericFile()\n\tgf.Identifier = fmt.Sprintf(\"%s\/%s\", vbag.obj.Identifier, fileSummary.RelPath)\n\tgf.IntellectualObjectIdentifier = vbag.obj.Identifier\n\tgf.Size = fileSummary.Size\n\tgf.FileModified = fileSummary.ModTime\n\tgf.IngestLocalPath = fileSummary.AbsPath \/\/ will be empty if bag is tarred\n\tgf.IngestUUID = _uuid.String()\n\tgf.IngestUUIDGeneratedAt = time.Now().UTC()\n\tgf.IngestFileUid = fileSummary.Uid\n\tgf.IngestFileGid = fileSummary.Gid\n\tvbag.obj.GenericFiles = append(vbag.obj.GenericFiles, gf)\n\tvbag.setIngestFileType(gf, fileSummary)\n\treturn vbag.calculateChecksums(reader, gf)\n}\n\n\/\/ Figure out what type of file this is.\nfunc (vbag *VirtualBag) setIngestFileType(gf *GenericFile, fileSummary *fileutil.FileSummary) {\n\tif strings.HasPrefix(fileSummary.RelPath, \"tagmanifest-\") {\n\t\tgf.IngestFileType = constants.TAG_MANIFEST\n\t\tgf.FileFormat = \"text\/plain\"\n\t\tvbag.obj.IngestTagManifests = append(vbag.obj.IngestTagManifests, fileSummary.RelPath)\n\t} else if strings.HasPrefix(fileSummary.RelPath, \"manifest-\") {\n\t\tgf.IngestFileType = constants.PAYLOAD_MANIFEST\n\t\tgf.FileFormat = \"text\/plain\"\n\t\tvbag.obj.IngestManifests = append(vbag.obj.IngestManifests, fileSummary.RelPath)\n\t} else if strings.HasPrefix(fileSummary.RelPath, \"data\/\") {\n\t\tgf.IngestFileType = constants.PAYLOAD_FILE\n\t} else {\n\t\tgf.IngestFileType = constants.TAG_FILE\n\t}\n}\n\n\/\/ Calculate the md5 and\/or sha256 checksums on a file.\nfunc (vbag *VirtualBag) calculateChecksums(reader io.Reader, gf *GenericFile) error {\n\thashes := make([]io.Writer, 0)\n\tvar md5Hash hash.Hash\n\tvar sha256Hash hash.Hash\n\tif vbag.calculateMd5 {\n\t\tmd5Hash = md5.New()\n\t\thashes = append(hashes, md5Hash)\n\t}\n\tif vbag.calculateSha256 {\n\t\tsha256Hash = sha256.New()\n\t\thashes = append(hashes, sha256Hash)\n\t}\n\tif len(hashes) > 0 {\n\t\tmultiWriter := io.MultiWriter(hashes...)\n\t\tio.Copy(multiWriter, reader)\n\t\tutcNow := time.Now().UTC()\n\t\tif md5Hash != nil {\n\t\t\tgf.IngestMd5 = fmt.Sprintf(\"%x\", md5Hash.Sum(nil))\n\t\t\tgf.IngestMd5GeneratedAt = utcNow\n\t\t}\n\t\tif sha256Hash != nil {\n\t\t\tgf.IngestSha256 = fmt.Sprintf(\"%x\", sha256Hash.Sum(nil))\n\t\t\tgf.IngestSha256GeneratedAt = utcNow\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (vbag *VirtualBag) setMimeType(reader io.Reader, gf *GenericFile) {\n\t\/\/ on err, defaults to application\/binary\n\tbufLen := 128\n\tif gf.Size < int64(bufLen) {\n\t\tbufLen = int(gf.Size - 1)\n\t\tif bufLen < 1 {\n\t\t\t\/\/ We actually do permit zero-length files, and we can\n\t\t\t\/\/ save them in S3. These files can be necessary in\n\t\t\t\/\/ certain cases, such as __init__.py files for Python,\n\t\t\t\/\/ PHP templates whose presence is required, \".keep\" files, etc.\n\t\t\tgf.FileFormat = \"text\/empty\"\n\t\t\treturn\n\t\t}\n\t}\n\tbuf := make([]byte, bufLen)\n\t_, err := reader.Read(buf)\n\tif err != nil {\n\t\tvbag.summary.AddError(err.Error())\n\t}\n\tgf.FileFormat, err = platform.GuessMimeTypeByBuffer(buf)\n\tif err != nil {\n\t\tvbag.summary.AddError(err.Error())\n\t}\n}\n\nfunc (vbag *VirtualBag) parseManifestsTagFilesAndMimeTypes() {\n\tfor {\n\t\treader, fileSummary, err := vbag.readIterator.Next()\n\t\tif reader != nil {\n\t\t\tdefer reader.Close()\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tvbag.summary.AddError(err.Error())\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ genericFile will sometimes be nil because the iterator\n\t\t\/\/ returns directory names as well as file names\n\t\tgenericFile := vbag.obj.FindGenericFile(fileSummary.RelPath)\n\t\tif util.StringListContains(vbag.tagFilesToParse, fileSummary.RelPath) {\n\t\t\tvbag.parseTags(reader, fileSummary.RelPath)\n\t\t\tif genericFile != nil {\n\t\t\t\t\/\/ Our vbag library can only parse text files, so this\n\t\t\t\t\/\/ should be a plain text file.\n\t\t\t\tif strings.HasSuffix(genericFile.Identifier, \".txt\") {\n\t\t\t\t\tgenericFile.FileFormat = \"text\/plain\"\n\t\t\t\t} else {\n\t\t\t\t\tgenericFile.FileFormat = \"application\/binary\"\n\t\t\t\t}\n\t\t\t}\n\t\t} else if util.StringListContains(vbag.obj.IngestManifests, fileSummary.RelPath) ||\n\t\t\tutil.StringListContains(vbag.obj.IngestTagManifests, fileSummary.RelPath) {\n\t\t\tvbag.parseManifest(reader, fileSummary.RelPath)\n\t\t} else {\n\t\t\tif genericFile != nil {\n\t\t\t\tvbag.setMimeType(reader, genericFile)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Parse the checksums in a manifest.\nfunc (vbag *VirtualBag) parseManifest(reader io.Reader, relFilePath string) {\n\talg := \"\"\n\tif strings.Contains(relFilePath, constants.AlgSha256) {\n\t\talg = constants.AlgSha256\n\t} else if strings.Contains(relFilePath, constants.AlgMd5) {\n\t\talg = constants.AlgMd5\n\t} else {\n\t\tfmt.Fprintln(os.Stderr, \"Not verifying checksums in\", relFilePath,\n\t\t\t\"- unsupported algorithm. Will still verify any md5 or sha256 checksums.\")\n\t\treturn\n\t}\n\tre := regexp.MustCompile(`^(\\S*)\\s*(.*)`)\n\tscanner := bufio.NewScanner(reader)\n\tlineNum := 1\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif re.MatchString(line) {\n\t\t\tdata := re.FindStringSubmatch(line)\n\t\t\tdigest := data[1]\n\t\t\tfilePath := data[2]\n\t\t\tgenericFile := vbag.obj.FindGenericFile(filePath)\n\t\t\tif genericFile == nil {\n\t\t\t\tvbag.summary.AddError(\n\t\t\t\t\t\"File '%s' in manifest '%s' is missing from bag\",\n\t\t\t\t\tfilePath, relFilePath)\n\t\t\t\tvbag.obj.IngestMissingFiles = append(vbag.obj.IngestMissingFiles,\n\t\t\t\t\tNewMissingFile(relFilePath, lineNum, filePath, digest))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif alg == constants.AlgMd5 {\n\t\t\t\tgenericFile.IngestManifestMd5 = digest\n\t\t\t} else if alg == constants.AlgSha256 {\n\t\t\t\tgenericFile.IngestManifestSha256 = digest\n\t\t\t}\n\t\t} else {\n\t\t\tvbag.summary.AddError(fmt.Sprintf(\n\t\t\t\t\"Unable to parse data from line %d of manifest %s: %s\",\n\t\t\t\tlineNum, relFilePath, line))\n\t\t}\n\t\tlineNum += 1\n\t}\n}\n\n\/\/ Parse the tag fields in a file.\nfunc (vbag *VirtualBag) parseTags(reader io.Reader, relFilePath string) {\n\tre := regexp.MustCompile(`^(\\S*\\:)?(\\s.*)?$`)\n\tscanner := bufio.NewScanner(reader)\n\tvar tag *Tag\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif re.MatchString(line) {\n\t\t\tdata := re.FindStringSubmatch(line)\n\t\t\tdata[1] = strings.Replace(data[1], \":\", \"\", 1)\n\t\t\tif data[1] != \"\" {\n\t\t\t\tif tag != nil && tag.Label != \"\" {\n\t\t\t\t\tvbag.obj.IngestTags = append(vbag.obj.IngestTags, tag)\n\t\t\t\t}\n\t\t\t\ttag = NewTag(relFilePath, data[1], strings.Trim(data[2], \" \"))\n\t\t\t\tvbag.setIntelObjTagValue(tag)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvalue := strings.Trim(data[2], \" \")\n\t\t\ttag.Value = strings.Join([]string{tag.Value, value}, \" \")\n\t\t\tvbag.setIntelObjTagValue(tag)\n\t\t} else {\n\t\t\tvbag.summary.AddError(\"Unable to parse tag data from line: '%s'\", line)\n\t\t}\n\t}\n\tif tag != nil && tag.Label != \"\" {\n\t\tvbag.obj.IngestTags = append(vbag.obj.IngestTags, tag)\n\t}\n\tif scanner.Err() != nil {\n\t\tvbag.summary.AddError(\"Error reading tag file '%s': %v\",\n\t\t\trelFilePath, scanner.Err().Error())\n\t}\n}\n\n\/\/ Copy certain values from the aptrust-info.txt file into\n\/\/ properties of the IntellectualObject.\nfunc (vbag *VirtualBag) setIntelObjTagValue(tag *Tag) {\n\tif tag.SourceFile == \"aptrust-info.txt\" {\n\t\tlabel := strings.ToLower(tag.Label)\n\t\tswitch label {\n\t\tcase \"title\":\n\t\t\tvbag.obj.Title = tag.Value\n\t\tcase \"access\":\n\t\t\tvbag.obj.Access = tag.Value\n\t\t}\n\t} else if tag.SourceFile == \"bag-info.txt\" {\n\t\tlabel := strings.ToLower(tag.Label)\n\t\tswitch label {\n\t\tcase \"source-organization\":\n\t\t\tvbag.obj.Institution = tag.Value\n\t\tcase \"internal-sender-description\":\n\t\t\tvbag.obj.Description = tag.Value\n\t\tcase \"internal-sender-identifier\":\n\t\t\tvbag.obj.AltIdentifier = tag.Value\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\ntype ItemBoard interface {\n}\n\ntype ItemBoards interface {\n\tGetBoard(string) (ItemBoard, bool)\n}\n\ntype Board struct {\n\tID string `json:\"id\"`\n}\n\ntype Boards map[string]Board\n\nfunc (bs *Boards) GetBoard(id string) (ItemBoard, bool) {\n\tboard, ok := (*bs)[id]\n\treturn board, ok\n}\n\nfunc NewItemBoard() ItemBoard {\n\treturn &Board{}\n}\n\nfunc NewItemBoards() ItemBoards {\n\treturn &Boards{}\n}\n<commit_msg>Add dummy board.<commit_after>package models\n\ntype ItemBoard interface {\n}\n\ntype ItemBoards interface {\n\tGetBoard(string) (ItemBoard, bool)\n}\n\ntype Board struct {\n\tID string `json:\"id\"`\n}\n\ntype Boards map[string]ItemBoard\n\nfunc (bs Boards) GetBoard(id string) (ItemBoard, bool) {\n\tboard, ok := bs[id]\n\treturn board, ok\n}\n\nfunc NewItemBoard(id string) ItemBoard {\n\treturn &Board{\n\t\tID: id,\n\t}\n}\n\nfunc NewItemBoards() ItemBoards {\n\tboard := Boards{}\n\tboard[\"123\"] = NewItemBoard(\"123\")\n\treturn board\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ 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, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage url\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/nmeum\/marvin\/irc\"\n\t\"github.com\/nmeum\/marvin\/modules\"\n\t\"golang.org\/x\/net\/html\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Module struct {\n\tclient   *http.Client\n\tregex    *regexp.Regexp\n\tRegexStr string `json:\"regex\"`\n}\n\nfunc Init(moduleSet *modules.ModuleSet) {\n\tmoduleSet.Register(new(Module))\n}\n\nfunc (m *Module) Name() string {\n\treturn \"url\"\n}\n\nfunc (m *Module) Help() string {\n\treturn \"Displays information about posted URLs.\"\n}\n\nfunc (m *Module) Defaults() {\n\tm.RegexStr = `(?i)\\b((http|https)\\:\/\/(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s` + \"`\" + `!()\\[\\]{};:'\".,<>?«»“”‘’]))`\n}\n\nfunc (m *Module) Load(client *irc.Client) error {\n\tregex, err := regexp.Compile(m.RegexStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tm.client = &http.Client{Transport: tr}\n\n\tm.regex = regex\n\tclient.CmdHook(\"privmsg\", m.urlCmd)\n\n\treturn nil\n}\n\nfunc (m *Module) urlCmd(client *irc.Client, msg irc.Message) error {\n\turl := m.regex.FindString(msg.Data)\n\tif len(url) <= 0 {\n\t\treturn nil\n\t}\n\n\tresp, err := m.client.Head(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp.Body.Close() \/\/ HEAD response doesn't have a body\n\n\tinfo := m.infoString(resp)\n\tif len(info) <= 0 {\n\t\treturn nil\n\t}\n\n\treturn client.Write(\"NOTICE %s :%s\", msg.Receiver, info)\n}\n\nfunc (m *Module) infoString(resp *http.Response) string {\n\tvar mtype string\n\tvar infos []string\n\n\tctype := resp.Header.Get(\"Content-Type\")\n\tif len(ctype) > 0 {\n\t\tm, _, err := mime.ParseMediaType(ctype)\n\t\tif err == nil {\n\t\t\tmtype = m\n\t\t\tinfos = append(infos, fmt.Sprintf(\"Type: %s\", mtype))\n\t\t}\n\t}\n\n\tcsize := resp.ContentLength\n\tif csize >= 0 {\n\t\tinfos = append(infos, fmt.Sprintf(\"Size: %s\", m.humanize(csize)))\n\t}\n\n\tif mtype == \"text\/html\" {\n\t\ttitle, err := m.extractTitle(resp.Request.URL.String())\n\t\tif err == nil {\n\t\t\tinfos = append(infos, fmt.Sprintf(\"Title: %s\", title))\n\t\t}\n\t}\n\n\tinfo := strings.Join(infos, \" | \")\n\tif len(info) > 0 {\n\t\tinfo = fmt.Sprintf(\"%s -- %s\", strings.ToUpper(m.Name()), info)\n\t}\n\n\treturn info\n}\n\nfunc (m *Module) extractTitle(url string) (title string, err error) {\n\tresp, err := m.client.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar parseFunc func(n *html.Node)\n\tparseFunc = func(n *html.Node) {\n\t\tif n.Type == html.ElementNode && n.Data == \"title\" {\n\t\t\tchild := n.FirstChild\n\t\t\tif child != nil {\n\t\t\t\ttitle = child.Data\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\t\tparseFunc(c)\n\t\t}\n\t}\n\n\tparseFunc(doc)\n\tif len(title) <= 0 {\n\t\terr = errors.New(\"couldn't extract title\")\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (m *Module) humanize(count int64) string {\n\tswitch {\n\tcase count > (1 << 40):\n\t\treturn fmt.Sprintf(\"%v TiB\", count\/(1<<40))\n\tcase count > (1 << 30):\n\t\treturn fmt.Sprintf(\"%v GiB\", count\/(1<<30))\n\tcase count > (1 << 20):\n\t\treturn fmt.Sprintf(\"%v MiB\", count\/(1<<20))\n\tcase count > (1 << 10):\n\t\treturn fmt.Sprintf(\"%v KiB\", count\/(1<<10))\n\tdefault:\n\t\treturn fmt.Sprintf(\"%v B\", count)\n\t}\n}\n<commit_msg>Revert \"url: don't verify TLS certificates\"<commit_after>\/\/ 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, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public\n\/\/ License along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage url\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/nmeum\/marvin\/irc\"\n\t\"github.com\/nmeum\/marvin\/modules\"\n\t\"golang.org\/x\/net\/html\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Module struct {\n\tregex    *regexp.Regexp\n\tRegexStr string `json:\"regex\"`\n}\n\nfunc Init(moduleSet *modules.ModuleSet) {\n\tmoduleSet.Register(new(Module))\n}\n\nfunc (m *Module) Name() string {\n\treturn \"url\"\n}\n\nfunc (m *Module) Help() string {\n\treturn \"Displays information about posted URLs.\"\n}\n\nfunc (m *Module) Defaults() {\n\tm.RegexStr = `(?i)\\b((http|https)\\:\/\/(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s` + \"`\" + `!()\\[\\]{};:'\".,<>?«»“”‘’]))`\n}\n\nfunc (m *Module) Load(client *irc.Client) error {\n\tregex, err := regexp.Compile(m.RegexStr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.regex = regex\n\tclient.CmdHook(\"privmsg\", m.urlCmd)\n\n\treturn nil\n}\n\nfunc (m *Module) urlCmd(client *irc.Client, msg irc.Message) error {\n\turl := m.regex.FindString(msg.Data)\n\tif len(url) <= 0 {\n\t\treturn nil\n\t}\n\n\tresp, err := http.Head(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp.Body.Close() \/\/ HEAD response doesn't have a body\n\n\tinfo := m.infoString(resp)\n\tif len(info) <= 0 {\n\t\treturn nil\n\t}\n\n\treturn client.Write(\"NOTICE %s :%s\", msg.Receiver, info)\n}\n\nfunc (m *Module) infoString(resp *http.Response) string {\n\tvar mtype string\n\tvar infos []string\n\n\tctype := resp.Header.Get(\"Content-Type\")\n\tif len(ctype) > 0 {\n\t\tm, _, err := mime.ParseMediaType(ctype)\n\t\tif err == nil {\n\t\t\tmtype = m\n\t\t\tinfos = append(infos, fmt.Sprintf(\"Type: %s\", mtype))\n\t\t}\n\t}\n\n\tcsize := resp.ContentLength\n\tif csize >= 0 {\n\t\tinfos = append(infos, fmt.Sprintf(\"Size: %s\", m.humanize(csize)))\n\t}\n\n\tif mtype == \"text\/html\" {\n\t\ttitle, err := m.extractTitle(resp.Request.URL.String())\n\t\tif err == nil {\n\t\t\tinfos = append(infos, fmt.Sprintf(\"Title: %s\", title))\n\t\t}\n\t}\n\n\tinfo := strings.Join(infos, \" | \")\n\tif len(info) > 0 {\n\t\tinfo = fmt.Sprintf(\"%s -- %s\", strings.ToUpper(m.Name()), info)\n\t}\n\n\treturn info\n}\n\nfunc (m *Module) extractTitle(url string) (title string, err error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar parseFunc func(n *html.Node)\n\tparseFunc = func(n *html.Node) {\n\t\tif n.Type == html.ElementNode && n.Data == \"title\" {\n\t\t\tchild := n.FirstChild\n\t\t\tif child != nil {\n\t\t\t\ttitle = child.Data\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tfor c := n.FirstChild; c != nil; c = c.NextSibling {\n\t\t\tparseFunc(c)\n\t\t}\n\t}\n\n\tparseFunc(doc)\n\tif len(title) <= 0 {\n\t\terr = errors.New(\"couldn't extract title\")\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (m *Module) humanize(count int64) string {\n\tswitch {\n\tcase count > (1 << 40):\n\t\treturn fmt.Sprintf(\"%v TiB\", count\/(1<<40))\n\tcase count > (1 << 30):\n\t\treturn fmt.Sprintf(\"%v GiB\", count\/(1<<30))\n\tcase count > (1 << 20):\n\t\treturn fmt.Sprintf(\"%v MiB\", count\/(1<<20))\n\tcase count > (1 << 10):\n\t\treturn fmt.Sprintf(\"%v KiB\", count\/(1<<10))\n\tdefault:\n\t\treturn fmt.Sprintf(\"%v B\", count)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/talbor49\/HoneyBee\/grammar\"\n)\n\nconst (\n\tsuccess        = \"OK\"\n\terror          = \"ERR\"\n\terrNoBucket    = \"You are not connected to any bucket. use the 'SET {BUCKET}'\"\n\terrNotLoggedIn = \"You are not logged in. Use 'Auth <username> <password>'\"\n)\n\n\/\/ HandleQuery recieves a plain text string query, and hanles it.\n\/\/ In most cases it adds it to the requests queue.\n\/\/ Whilst in AUTH requests it validates the credentials and returns an answer.\nfunc HandleQuery(query string, conn *DatabaseConnection) (returnCode string) {\n\t\/\/ TODO: write query in plain text to log\n\trequestType, tokens, err := grammar.ParseQuery(query)\n\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\tswitch requestType {\n\tcase \"AUTH\":\n\t\t\/\/ AUTH {username} {password} {database_name}\n\t\tfmt.Println(\"Client wants to authenticate.\")\n\t\tusername := tokens[0]\n\t\tpassword := tokens[1]\n\t\t\/\/ bucketname := tokens[2]\n\t\tif credentialsValid(username, password) {\n\t\t\tconn.Username = username\n\t\t}\n\t\tfmt.Println(\"User logged in as: \", username)\n\t\treturn success\n\tcase \"SET\":\n\t\t\/\/ SET {key} {value} [ttl] [nooverride]\n\t\tfmt.Println(\"Client wants to set key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\tkey := tokens[0]\n\t\tvalue := tokens[1]\n\t\tfmt.Println(\"Setting \" + key + \":\" + value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\treturn handleSetRequest(setRequest)\n\n\tcase \"GET\":\n\t\t\/\/ GET {key}\n\t\tfmt.Println(\"Client wants to get key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\tkey := tokens[0]\n\t\tfmt.Println(\"Returning value of key: \" + key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\treturn handleGetRequest(getRequest)\n\n\tcase \"DELETE\":\n\t\t\/\/ DELETE {key}\n\t\tfmt.Println(\"Client wants to delete a bucket\/key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\treturn success\n\tcase \"CREATE\":\n\t\tfmt.Println(\"Client wants to create a bucket\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\treturn success\n\tcase \"USE\":\n\t\tfmt.Println(\"Client wants to use a specific bucket\")\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\n\t\tbucketname := tokens[0]\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\n\t\treturn handleUseRequest(useRequest)\n\tdefault:\n\t\treturn error\n\t}\n\n}\n<commit_msg>Changed DB error messages<commit_after>package server\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/talbor49\/HoneyBee\/grammar\"\n)\n\nconst (\n\tsuccess        = \"OK\"\n\terror          = \"ERR\"\n\terrNoBucket    = \"You are not connected to any bucket. use the 'USE <BUCKET>'\"\n\terrNotLoggedIn = \"You are not logged in. Use 'AUTH <username> <password>'\"\n)\n\n\/\/ HandleQuery recieves a plain text string query, and hanles it.\n\/\/ In most cases it adds it to the requests queue.\n\/\/ Whilst in AUTH requests it validates the credentials and returns an answer.\nfunc HandleQuery(query string, conn *DatabaseConnection) (returnCode string) {\n\t\/\/ TODO: write query in plain text to log\n\trequestType, tokens, err := grammar.ParseQuery(query)\n\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\n\tswitch requestType {\n\tcase \"AUTH\":\n\t\t\/\/ AUTH {username} {password} {database_name}\n\t\tfmt.Println(\"Client wants to authenticate.\")\n\t\tusername := tokens[0]\n\t\tpassword := tokens[1]\n\t\t\/\/ bucketname := tokens[2]\n\t\tif credentialsValid(username, password) {\n\t\t\tconn.Username = username\n\t\t}\n\t\tfmt.Println(\"User logged in as: \", username)\n\t\treturn success\n\tcase \"SET\":\n\t\t\/\/ SET {key} {value} [ttl] [nooverride]\n\t\tfmt.Println(\"Client wants to set key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\tkey := tokens[0]\n\t\tvalue := tokens[1]\n\t\tfmt.Println(\"Setting \" + key + \":\" + value)\n\t\tsetRequest := SetRequest{Key: key, Value: value, Conn: conn}\n\t\treturn handleSetRequest(setRequest)\n\n\tcase \"GET\":\n\t\t\/\/ GET {key}\n\t\tfmt.Println(\"Client wants to get key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\tkey := tokens[0]\n\t\tfmt.Println(\"Returning value of key: \" + key)\n\t\tgetRequest := GetRequest{Key: key, Conn: conn}\n\t\treturn handleGetRequest(getRequest)\n\n\tcase \"DELETE\":\n\t\t\/\/ DELETE {key}\n\t\tfmt.Println(\"Client wants to delete a bucket\/key\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\treturn success\n\tcase \"CREATE\":\n\t\tfmt.Println(\"Client wants to create a bucket\")\n\t\tif conn.Bucket == \"\" {\n\t\t\treturn errNoBucket\n\t\t}\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\t\treturn success\n\tcase \"USE\":\n\t\tfmt.Println(\"Client wants to use a specific bucket\")\n\t\tif conn.Username == \"\" {\n\t\t\treturn errNotLoggedIn\n\t\t}\n\n\t\tbucketname := tokens[0]\n\n\t\tuseRequest := UseRequest{BucketName: bucketname, Conn: conn}\n\n\t\treturn handleUseRequest(useRequest)\n\tdefault:\n\t\treturn error\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package http\n\nimport (\n\t\"fmt\"\n\t\"github.com\/vanng822\/imgscale\/imagick\"\n\t\"github.com\/vanng822\/imgscale\/imgscale\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype imageProviderHTTP struct {\n\tbaseUrl string\n}\n\nfunc (imageProvider imageProviderHTTP) Fetch(filename string) (*imagick.MagickWand, error) {\n\timg := imagick.NewMagickWand()\n\t\/\/ %s%s will make it possible for using on arbitrary remote image\n\t\/\/ like http:\/\/127.0.0.1:8081\/img\/100x100\/http:\/\/127.0.0.1:8080\/img\/original\/kth.jpg\n\tresp, err := http.Get(fmt.Sprintf(\"%s%s\", imageProvider.baseUrl, filename))\n\tif err != nil {\n\t\treturn img, err\n\t}\n\tdefer resp.Body.Close()\n\n\timgData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn img, err\n\t}\n\terr = img.ReadImageBlob(imgData)\n\treturn img, err\n}\n\n\/*\n\tNewImageProviderHTTP returns an instance of imageProviderHTTP\n\twhere baseUrl is absolute url, together with filename it should become\n\ta valid url to image resource.\n\n\tOne can leave baseUrl empty and specify filename as a remote image like\n\thttp:\/\/127.0.0.1:8081\/img\/100x100\/http:\/\/127.0.0.1:8080\/img\/original\/kth.jpg\n\tBe aware what you do and also that it may not work for some handler\/frameworks\n*\/\nfunc New(baseUrl string) imgscale.ImageProvider {\n\tprovider := imageProviderHTTP{}\n\tif baseUrl != \"\" {\n\t\t\/\/ assume we have a valid base url\n\t\tprovider.baseUrl = fmt.Sprintf(\"%s\/\", strings.TrimSuffix(baseUrl, \"\/\"))\n\t}\n\treturn provider\n}\n<commit_msg>Pointer reciever<commit_after>package http\n\nimport (\n\t\"fmt\"\n\t\"github.com\/vanng822\/imgscale\/imagick\"\n\t\"github.com\/vanng822\/imgscale\/imgscale\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype imageProviderHTTP struct {\n\tbaseUrl string\n}\n\nfunc (imageProvider *imageProviderHTTP) Fetch(filename string) (*imagick.MagickWand, error) {\n\timg := imagick.NewMagickWand()\n\t\/\/ %s%s will make it possible for using on arbitrary remote image\n\t\/\/ like http:\/\/127.0.0.1:8081\/img\/100x100\/http:\/\/127.0.0.1:8080\/img\/original\/kth.jpg\n\tresp, err := http.Get(fmt.Sprintf(\"%s%s\", imageProvider.baseUrl, filename))\n\tif err != nil {\n\t\treturn img, err\n\t}\n\tdefer resp.Body.Close()\n\n\timgData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn img, err\n\t}\n\terr = img.ReadImageBlob(imgData)\n\treturn img, err\n}\n\n\/*\n\tNewImageProviderHTTP returns an instance of imageProviderHTTP\n\twhere baseUrl is absolute url, together with filename it should become\n\ta valid url to image resource.\n\n\tOne can leave baseUrl empty and specify filename as a remote image like\n\thttp:\/\/127.0.0.1:8081\/img\/100x100\/http:\/\/127.0.0.1:8080\/img\/original\/kth.jpg\n\tBe aware what you do and also that it may not work for some handler\/frameworks\n*\/\nfunc New(baseUrl string) imgscale.ImageProvider {\n\tprovider := &imageProviderHTTP{}\n\tif baseUrl != \"\" {\n\t\t\/\/ assume we have a valid base url\n\t\tprovider.baseUrl = fmt.Sprintf(\"%s\/\", strings.TrimSuffix(baseUrl, \"\/\"))\n\t}\n\treturn provider\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 provides an extensive command line option parser.\n\/\/ The flags package is similar in functionality to the go builtin flag package\n\/\/ but provides more options and uses reflection to provide a convenient and\n\/\/ succinct way of specifying command line options.\n\/\/\n\/\/ Supported features:\n\/\/     Options with short names (-v)\n\/\/     Options with long names (--verbose)\n\/\/     Options with and without arguments (bool v.s. other type)\n\/\/     Options with optional arguments and default values\n\/\/     Multiple option groups each containing a set of options\n\/\/     Generate and print well-formatted help message\n\/\/     Passing remaining command line arguments after -- (optional)\n\/\/     Ignoring unknown command line options (optional)\n\/\/     Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n\/\/     Supports multiple short options -aux\n\/\/     Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n\/\/     Supports same option multiple times (can store in slice or last option counts)\n\/\/     Supports maps\n\/\/     Supports function callbacks\n\/\/\n\/\/ Additional features specific to Windows:\n\/\/     Options with short names (\/v)\n\/\/     Options with long names (\/verbose)\n\/\/     Windows-style options with arguments use a colon as the delimiter\n\/\/     Modify generated help message with Windows-style \/ options\n\/\/\n\/\/ The flags package uses structs, reflection and struct field tags\n\/\/ to allow users to specify command line options. This results in very simple\n\/\/ and consise specification of your application options. For example:\n\/\/\n\/\/     type Options struct {\n\/\/         Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n\/\/     }\n\/\/\n\/\/ This specifies one option with a short name -v and a long name --verbose.\n\/\/ When either -v or --verbose is found on the command line, a 'true' value\n\/\/ will be appended to the Verbose field. e.g. when specifying -vvv, the\n\/\/ resulting value of Verbose will be {[true, true, true]}.\n\/\/\n\/\/ Slice options work exactly the same as primitive type options, except that\n\/\/ whenever the option is encountered, a value is appended to the slice.\n\/\/\n\/\/ Map options from string to primitive type are also supported. On the command\n\/\/ line, you specify the value for such an option as key:value. For example\n\/\/\n\/\/     type Options struct {\n\/\/         AuthorInfo string[string] `short:\"a\"`\n\/\/     }\n\/\/\n\/\/ Then, the AuthorInfo map can be filled with something like\n\/\/ -a name:Jesse -a \"surname:van den Kieboom\".\n\/\/\n\/\/ Finally, for full control over the conversion between command line argument\n\/\/ values and options, user defined types can choose to implement the Marshaler\n\/\/ and Unmarshaler interfaces.\n\/\/\n\/\/ Available field tags:\n\/\/     short:          the short name of the option (single character)\n\/\/     long:           the long name of the option\n\/\/     description:    the description of the option (optional)\n\/\/     optional:       whether an argument of the option is optional (optional)\n\/\/     optional-value: the value of an optional option when the option occurs\n\/\/                     without an argument. This tag can be specified multiple\n\/\/                     times in the case of maps or slices (optional)\n\/\/     default:        the default value of an option. This tag can be specified\n\/\/                     multiple times in the case of slices or maps (optional).\n\/\/     default-mask:   when specified, this value will be displayed in the help\n\/\/                     instead of the actual default value. This is useful\n\/\/                     mostly for hiding otherwise sensitive information from\n\/\/                     showing up in the help. If default-mask takes the special\n\/\/                     value \"-\", then no default value will be shown at all\n\/\/                     (optional)\n\/\/     required:       whether an option is required to appear on the command\n\/\/                     line. If a required option is not present, the parser\n\/\/                     will return ErrRequired.\n\/\/     base:           a base (radix) used to convert strings to integer values,\n\/\/                     the default base is 10 (i.e. decimal) (optional)\n\/\/     value-name:     the name of the argument value (to be shown in the help,\n\/\/                     (optional)\n\/\/     group:          when specified on a struct field, makes the struct field\n\/\/                     a separate group with the given name (optional).\n\/\/     command:        when specified on a struct field, makes the struct field\n\/\/                     a (sub)command with the given name (optional).\n\/\/     name:           the display name of the command. This name is the name\n\/\/                     shown in the builtin generated help and can be used\n\/\/                     to provide a more informative title of a command. If not\n\/\/                     specified this defaults to the name given in the command\n\/\/                     command tag (optional).\n\/\/\n\/\/ Either short: or long: must be specified to make the field eligible as an\n\/\/ option.\n\/\/\n\/\/\n\/\/ Option groups:\n\/\/\n\/\/ Option groups are a simple way to semantically separate your options. The\n\/\/ only real difference is in how your options will appear in the builtin\n\/\/ generated help. All options in a particular group are shown together in the\n\/\/ help under the name of the group.\n\/\/\n\/\/ There are currently three ways to specify option groups.\n\/\/\n\/\/     1. Use NewNamedParser specifying the various option groups.\n\/\/     2. Use AddGroup to add a group to an existing parser.\n\/\/     3. Add a struct field to the toplevel options annotated with the\n\/\/        group:\"group-name\" tag.\n\/\/\n\/\/\n\/\/\n\/\/ Commands:\n\/\/\n\/\/ The flags package also has basic support for commands. Commands are often\n\/\/ used in monolithic applications that support various commands or actions.\n\/\/ Take git for example, all of the add, commit, checkout, etc. are called\n\/\/ commands. Using commands you can easily separate multiple functions of your\n\/\/ application.\n\/\/\n\/\/ There are currently two ways to specifiy a command.\n\/\/\n\/\/     1. Use AddCommand on an existing parser.\n\/\/     2. Add a struct field to your options struct annotated with the\n\/\/        command:\"command-name\" tag.\n\/\/\n\/\/ The most common, idiomatic way to implement commands is to define a global\n\/\/ parser instance and implement each command in a separate file. These\n\/\/ command files should define a go init function which calls AddCommand on\n\/\/ the global parser.\n\/\/\n\/\/ When parsing ends and there is an active command and that command implements\n\/\/ the Commander interface, then its Execute method will be run with the\n\/\/ remaining command line arguments.\n\/\/\n\/\/ Command structs can have options which become valid to parse after the\n\/\/ command has been specified on the command line. It is currently not valid\n\/\/ to specify options from the parent level of the command after the command\n\/\/ name has occurred. Thus, given a toplevel option \"-v\" and a command \"add\":\n\/\/\n\/\/     Valid:   .\/app -v add\n\/\/     Invalid: .\/app add -v\n\/\/\npackage flags\n<commit_msg>Remove docs for unsupported name tag<commit_after>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 provides an extensive command line option parser.\n\/\/ The flags package is similar in functionality to the go builtin flag package\n\/\/ but provides more options and uses reflection to provide a convenient and\n\/\/ succinct way of specifying command line options.\n\/\/\n\/\/ Supported features:\n\/\/     Options with short names (-v)\n\/\/     Options with long names (--verbose)\n\/\/     Options with and without arguments (bool v.s. other type)\n\/\/     Options with optional arguments and default values\n\/\/     Multiple option groups each containing a set of options\n\/\/     Generate and print well-formatted help message\n\/\/     Passing remaining command line arguments after -- (optional)\n\/\/     Ignoring unknown command line options (optional)\n\/\/     Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n\/\/     Supports multiple short options -aux\n\/\/     Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n\/\/     Supports same option multiple times (can store in slice or last option counts)\n\/\/     Supports maps\n\/\/     Supports function callbacks\n\/\/\n\/\/ Additional features specific to Windows:\n\/\/     Options with short names (\/v)\n\/\/     Options with long names (\/verbose)\n\/\/     Windows-style options with arguments use a colon as the delimiter\n\/\/     Modify generated help message with Windows-style \/ options\n\/\/\n\/\/ The flags package uses structs, reflection and struct field tags\n\/\/ to allow users to specify command line options. This results in very simple\n\/\/ and consise specification of your application options. For example:\n\/\/\n\/\/     type Options struct {\n\/\/         Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n\/\/     }\n\/\/\n\/\/ This specifies one option with a short name -v and a long name --verbose.\n\/\/ When either -v or --verbose is found on the command line, a 'true' value\n\/\/ will be appended to the Verbose field. e.g. when specifying -vvv, the\n\/\/ resulting value of Verbose will be {[true, true, true]}.\n\/\/\n\/\/ Slice options work exactly the same as primitive type options, except that\n\/\/ whenever the option is encountered, a value is appended to the slice.\n\/\/\n\/\/ Map options from string to primitive type are also supported. On the command\n\/\/ line, you specify the value for such an option as key:value. For example\n\/\/\n\/\/     type Options struct {\n\/\/         AuthorInfo string[string] `short:\"a\"`\n\/\/     }\n\/\/\n\/\/ Then, the AuthorInfo map can be filled with something like\n\/\/ -a name:Jesse -a \"surname:van den Kieboom\".\n\/\/\n\/\/ Finally, for full control over the conversion between command line argument\n\/\/ values and options, user defined types can choose to implement the Marshaler\n\/\/ and Unmarshaler interfaces.\n\/\/\n\/\/ Available field tags:\n\/\/     short:          the short name of the option (single character)\n\/\/     long:           the long name of the option\n\/\/     description:    the description of the option (optional)\n\/\/     optional:       whether an argument of the option is optional (optional)\n\/\/     optional-value: the value of an optional option when the option occurs\n\/\/                     without an argument. This tag can be specified multiple\n\/\/                     times in the case of maps or slices (optional)\n\/\/     default:        the default value of an option. This tag can be specified\n\/\/                     multiple times in the case of slices or maps (optional).\n\/\/     default-mask:   when specified, this value will be displayed in the help\n\/\/                     instead of the actual default value. This is useful\n\/\/                     mostly for hiding otherwise sensitive information from\n\/\/                     showing up in the help. If default-mask takes the special\n\/\/                     value \"-\", then no default value will be shown at all\n\/\/                     (optional)\n\/\/     required:       whether an option is required to appear on the command\n\/\/                     line. If a required option is not present, the parser\n\/\/                     will return ErrRequired.\n\/\/     base:           a base (radix) used to convert strings to integer values,\n\/\/                     the default base is 10 (i.e. decimal) (optional)\n\/\/     value-name:     the name of the argument value (to be shown in the help,\n\/\/                     (optional)\n\/\/     group:          when specified on a struct field, makes the struct field\n\/\/                     a separate group with the given name (optional).\n\/\/     command:        when specified on a struct field, makes the struct field\n\/\/                     a (sub)command with the given name (optional).\n\/\/\n\/\/ Either short: or long: must be specified to make the field eligible as an\n\/\/ option.\n\/\/\n\/\/\n\/\/ Option groups:\n\/\/\n\/\/ Option groups are a simple way to semantically separate your options. The\n\/\/ only real difference is in how your options will appear in the builtin\n\/\/ generated help. All options in a particular group are shown together in the\n\/\/ help under the name of the group.\n\/\/\n\/\/ There are currently three ways to specify option groups.\n\/\/\n\/\/     1. Use NewNamedParser specifying the various option groups.\n\/\/     2. Use AddGroup to add a group to an existing parser.\n\/\/     3. Add a struct field to the toplevel options annotated with the\n\/\/        group:\"group-name\" tag.\n\/\/\n\/\/\n\/\/\n\/\/ Commands:\n\/\/\n\/\/ The flags package also has basic support for commands. Commands are often\n\/\/ used in monolithic applications that support various commands or actions.\n\/\/ Take git for example, all of the add, commit, checkout, etc. are called\n\/\/ commands. Using commands you can easily separate multiple functions of your\n\/\/ application.\n\/\/\n\/\/ There are currently two ways to specifiy a command.\n\/\/\n\/\/     1. Use AddCommand on an existing parser.\n\/\/     2. Add a struct field to your options struct annotated with the\n\/\/        command:\"command-name\" tag.\n\/\/\n\/\/ The most common, idiomatic way to implement commands is to define a global\n\/\/ parser instance and implement each command in a separate file. These\n\/\/ command files should define a go init function which calls AddCommand on\n\/\/ the global parser.\n\/\/\n\/\/ When parsing ends and there is an active command and that command implements\n\/\/ the Commander interface, then its Execute method will be run with the\n\/\/ remaining command line arguments.\n\/\/\n\/\/ Command structs can have options which become valid to parse after the\n\/\/ command has been specified on the command line. It is currently not valid\n\/\/ to specify options from the parent level of the command after the command\n\/\/ name has occurred. Thus, given a toplevel option \"-v\" and a command \"add\":\n\/\/\n\/\/     Valid:   .\/app -v add\n\/\/     Invalid: .\/app add -v\n\/\/\npackage flags\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 clonerefs\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/test-infra\/prow\/kube\"\n\t\"k8s.io\/test-infra\/prow\/pod-utils\/clone\"\n)\n\n\/\/ Run clones the configured refs\nfunc (o Options) Run() error {\n\tvar env []string\n\tif len(o.KeyFiles) > 0 {\n\t\tvar err error\n\t\tenv, err = addSSHKeys(o.KeyFiles)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add SSH keys: %v\", err)\n\t\t}\n\t}\n\n\tvar numWorkers int\n\tif o.MaxParallelWorkers != 0 {\n\t\tnumWorkers = o.MaxParallelWorkers\n\t} else {\n\t\tnumWorkers = len(o.GitRefs)\n\t}\n\n\twg := &sync.WaitGroup{}\n\twg.Add(numWorkers)\n\n\tinput := make(chan *kube.Refs)\n\toutput := make(chan clone.Record, len(o.GitRefs))\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor ref := range input {\n\t\t\t\toutput <- clone.Run(ref, o.SrcRoot, o.GitUserName, o.GitUserEmail, env)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor _, ref := range o.GitRefs {\n\t\tinput <- ref\n\t}\n\n\tclose(input)\n\twg.Wait()\n\tclose(output)\n\n\tvar results []clone.Record\n\tfor record := range output {\n\t\tresults = append(results, record)\n\t}\n\n\tlogData, err := json.Marshal(results)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal clone records: %v\", err)\n\t}\n\n\tif err := ioutil.WriteFile(o.Log, logData, 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to write clone records: %v\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ addSSHKeys will start the ssh-agent and add all the specified\n\/\/ keys, returning the ssh-agent environment variables for reuse\nfunc addSSHKeys(paths []string) ([]string, error) {\n\tvars, err := exec.Command(\"ssh-agent\").CombinedOutput()\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"failed to start ssh-agent: %v\", err)\n\t}\n\tlogrus.Info(\"Started SSH agent\")\n\t\/\/ ssh-agent will output three lines of text, in the form:\n\t\/\/ SSH_AUTH_SOCK=xxx; export SSH_AUTH_SOCK;\n\t\/\/ SSH_AGENT_PID=xxx; export SSH_AGENT_PID;\n\t\/\/ echo Agent pid xxx;\n\t\/\/ We need to parse out the environment variables from that.\n\tparts := strings.Split(string(vars), \";\")\n\tenv := []string{strings.TrimSpace(parts[0]), strings.TrimSpace(parts[2])}\n\tfor _, keyPath := range paths {\n\t\t\/\/ we can be given literal paths to keys or paths to dirs\n\t\t\/\/ that are mounted from a secret, so we need to check which\n\t\t\/\/ we have\n\t\tif err := filepath.Walk(keyPath, func(path string, info os.FileInfo, err error) error {\n\t\t\tif strings.HasPrefix(info.Name(), \"..\") {\n\t\t\t\t\/\/ kubernetes volumes also include files we\n\t\t\t\t\/\/ should not look be looking into for keys\n\t\t\t\tif info.IsDir() {\n\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tcmd := exec.Command(\"ssh-add\", path)\n\t\t\tcmd.Env = append(cmd.Env, env...)\n\t\t\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to add ssh key at %s: %v: %s\", path, err, output)\n\t\t\t}\n\t\t\tlogrus.Infof(\"Added SSH key at %s\", path)\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\treturn env, fmt.Errorf(\"error walking path %q: %v\", keyPath, err)\n\t\t}\n\t}\n\treturn env, nil\n}\n<commit_msg>Make clonerefs write errors to log on ssh error.<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 clonerefs\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/test-infra\/prow\/kube\"\n\t\"k8s.io\/test-infra\/prow\/pod-utils\/clone\"\n)\n\n\/\/ Run clones the configured refs\nfunc (o Options) Run() error {\n\tvar env []string\n\tif len(o.KeyFiles) > 0 {\n\t\tvar err error\n\t\tenv, err = addSSHKeys(o.KeyFiles)\n\t\tif err != nil {\n\t\t\tlogrus.WithError(err).Error(\"Failed to add SSH keys.\")\n\t\t\t\/\/ Continue on error. Clones will fail with an appropriate error message\n\t\t\t\/\/ that initupload can consume whereas quiting without writing the clone\n\t\t\t\/\/ record log is silent and results in an errored prow job instead of a\n\t\t\t\/\/ failed one.\n\t\t}\n\t}\n\n\tvar numWorkers int\n\tif o.MaxParallelWorkers != 0 {\n\t\tnumWorkers = o.MaxParallelWorkers\n\t} else {\n\t\tnumWorkers = len(o.GitRefs)\n\t}\n\n\twg := &sync.WaitGroup{}\n\twg.Add(numWorkers)\n\n\tinput := make(chan *kube.Refs)\n\toutput := make(chan clone.Record, len(o.GitRefs))\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor ref := range input {\n\t\t\t\toutput <- clone.Run(ref, o.SrcRoot, o.GitUserName, o.GitUserEmail, env)\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor _, ref := range o.GitRefs {\n\t\tinput <- ref\n\t}\n\n\tclose(input)\n\twg.Wait()\n\tclose(output)\n\n\tvar results []clone.Record\n\tfor record := range output {\n\t\tresults = append(results, record)\n\t}\n\n\tlogData, err := json.Marshal(results)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal clone records: %v\", err)\n\t}\n\n\tif err := ioutil.WriteFile(o.Log, logData, 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to write clone records: %v\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ addSSHKeys will start the ssh-agent and add all the specified\n\/\/ keys, returning the ssh-agent environment variables for reuse\nfunc addSSHKeys(paths []string) ([]string, error) {\n\tvars, err := exec.Command(\"ssh-agent\").CombinedOutput()\n\tif err != nil {\n\t\treturn []string{}, fmt.Errorf(\"failed to start ssh-agent: %v\", err)\n\t}\n\tlogrus.Info(\"Started SSH agent\")\n\t\/\/ ssh-agent will output three lines of text, in the form:\n\t\/\/ SSH_AUTH_SOCK=xxx; export SSH_AUTH_SOCK;\n\t\/\/ SSH_AGENT_PID=xxx; export SSH_AGENT_PID;\n\t\/\/ echo Agent pid xxx;\n\t\/\/ We need to parse out the environment variables from that.\n\tparts := strings.Split(string(vars), \";\")\n\tenv := []string{strings.TrimSpace(parts[0]), strings.TrimSpace(parts[2])}\n\tfor _, keyPath := range paths {\n\t\t\/\/ we can be given literal paths to keys or paths to dirs\n\t\t\/\/ that are mounted from a secret, so we need to check which\n\t\t\/\/ we have\n\t\tif err := filepath.Walk(keyPath, func(path string, info os.FileInfo, err error) error {\n\t\t\tif strings.HasPrefix(info.Name(), \"..\") {\n\t\t\t\t\/\/ kubernetes volumes also include files we\n\t\t\t\t\/\/ should not look be looking into for keys\n\t\t\t\tif info.IsDir() {\n\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tcmd := exec.Command(\"ssh-add\", path)\n\t\t\tcmd.Env = append(cmd.Env, env...)\n\t\t\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to add ssh key at %s: %v: %s\", path, err, output)\n\t\t\t}\n\t\t\tlogrus.Infof(\"Added SSH key at %s\", path)\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\treturn env, fmt.Errorf(\"error walking path %q: %v\", keyPath, err)\n\t\t}\n\t}\n\treturn env, 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\n\/\/ Package config knows how to read and parse config.yaml.\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"regexp\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/ghodss\/yaml\"\n\n\t\"k8s.io\/test-infra\/prow\/kube\"\n)\n\n\/\/ Config is a read-only snapshot of the config.\ntype Config struct {\n\t\/\/ Full repo name (such as \"kubernetes\/kubernetes\") -> list of jobs.\n\tPresubmits  map[string][]Presubmit  `json:\"presubmits,omitempty\"`\n\tPostsubmits map[string][]Postsubmit `json:\"postsubmits,omitempty\"`\n\n\t\/\/ Periodics are not associated with any repo.\n\tPeriodics []Periodic `json:\"periodics,omitempty\"`\n\n\tTide     Tide      `json:\"tide,omitempty\"`\n\tPlank    Plank     `json:\"plank,omitempty\"`\n\tSinker   Sinker    `json:\"sinker,omitempty\"`\n\tTriggers []Trigger `json:\"triggers,omitempty\"`\n\tHeart    Heart     `json:\"heart,omitempty\"`\n\n\t\/\/ ProwJobNamespace is the namespace in the cluster that prow\n\t\/\/ components will use for looking up ProwJobs. The namespace\n\t\/\/ needs to exist and will not be created by prow.\n\tProwJobNamespace string `json:\"prowjob_namespace,omitempty\"`\n\t\/\/ PodNamespace is the namespace in the cluster that prow\n\t\/\/ components will use for looking up Pods owned by ProwJobs.\n\t\/\/ The namespace needs to exist and will not be created by prow.\n\tPodNamespace string       `json:\"pod_namespace,omitempty\"`\n\tSlackEvents  []SlackEvent `json:\"slackevents,omitempty\"`\n}\n\n\/\/ Tide is config for the tide pool.\ntype Tide struct {\n\t\/\/ These must be valid GitHub search queries. They should not overlap,\n\t\/\/ which is to say two queries should never return the same PR.\n\tQueries []string `json:\"queries,omitempty\"`\n}\n\n\/\/ Plank is config for the plank controller.\ntype Plank struct {\n\t\/\/ JobURLTemplateString compiles into JobURLTemplate at load time.\n\tJobURLTemplateString string `json:\"job_url_template,omitempty\"`\n\t\/\/ JobURLTemplate is compiled at load time from JobURLTemplateString. It\n\t\/\/ will be passed a kube.ProwJob and is used to set the URL for the\n\t\/\/ \"details\" link on GitHub as well as the link from deck.\n\tJobURLTemplate *template.Template `json:\"-\"`\n\n\t\/\/ ReportTemplateString compiles into ReportTemplate at load time.\n\tReportTemplateString string `json:\"report_template,omitempty\"`\n\t\/\/ ReportTemplate is compiled at load time from ReportTemplateString. It\n\t\/\/ will be passed a kube.ProwJob and can provide an optional blurb below\n\t\/\/ the test failures comment.\n\tReportTemplate *template.Template `json:\"-\"`\n}\n\n\/\/ Sinker is config for the sinker controller.\ntype Sinker struct {\n\t\/\/ ResyncPeriodString compiles into ResyncPeriod at load time.\n\tResyncPeriodString string `json:\"resync_period,omitempty\"`\n\t\/\/ ResyncPeriod is how often the controller will perform a garbage\n\t\/\/ collection.\n\tResyncPeriod time.Duration `json:\"-\"`\n\t\/\/ MaxProwJobAgeString compiles into MaxProwJobAge at load time.\n\tMaxProwJobAgeString string `json:\"max_prowjob_age,omitempty\"`\n\t\/\/ MaxProwJobAge is how old a ProwJob can be before it is garbage-collected.\n\tMaxProwJobAge time.Duration `json:\"-\"`\n\t\/\/ MaxPodAgeString compiles into MaxPodAge at load time.\n\tMaxPodAgeString string `json:\"max_pod_age,omitempty\"`\n\t\/\/ MaxPodAge is how old a Pod can be before it is garbage-collected.\n\tMaxPodAge time.Duration `json:\"-\"`\n}\n\n\/\/ Trigger is config for the trigger plugin.\ntype Trigger struct {\n\t\/\/ Repos is either of the form org\/repos or just org.\n\tRepos []string `json:\"repos,omitempty\"`\n\t\/\/ TrustedOrg is the org whose members' PRs will be automatically built\n\t\/\/ for PRs to the above repos.\n\tTrustedOrg string `json:\"trusted_org,omitempty\"`\n}\n\n\/\/ Heart is config for the heart plugin\ntype Heart struct {\n\t\/\/ Adorees is a list of GitHub logins for members\n\t\/\/ for whom we will add emojis to comments\n\tAdorees []string `json:\"adorees,omitempty\"`\n}\n\n\/\/ SlackEvent is config for the slackevents plugin.\n\/\/ If a PR is pushed to any of the repos listed in the config\n\/\/ then sent message to the all the  slack channels listed if pusher is NOT in the whitelist.\ntype SlackEvent struct {\n\t\/\/ Repos is either of the form org\/repos or just org.\n\tRepos []string `json:\"repos,omitempty\"`\n\t\/\/ List of channels on which a event is published.\n\tChannels []string `json:\"channels,omitempty\"`\n\t\/\/ A slack event is published if the user is not part of the WhiteList.\n\tWhiteList []string `json:\"whitelist,omitempty\"`\n}\n\n\/\/ Load loads and parses the config at path.\nfunc Load(path string) (*Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %v\", path, err)\n\t}\n\tnc := &Config{}\n\tif err := yaml.Unmarshal(b, nc); err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshaling %s: %v\", path, err)\n\t}\n\tif err := parseConfig(nc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn nc, nil\n}\n\nfunc parseConfig(c *Config) error {\n\t\/\/ Ensure that presubmit regexes are valid.\n\tfor _, vs := range c.Presubmits {\n\t\tif err := setRegexes(vs); err != nil {\n\t\t\treturn fmt.Errorf(\"could not set regex: %v\", err)\n\t\t}\n\t\tfor v := range vs {\n\t\t\tname := vs[v].Name\n\t\t\tagent := vs[v].Agent\n\t\t\tif agent == string(kube.KubernetesAgent) && vs[v].Spec == nil {\n\t\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t\t}\n\t\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure that postsubmits have a pod spec.\n\tfor _, js := range c.Postsubmits {\n\t\tfor j := range js {\n\t\t\tname := js[j].Name\n\t\t\tagent := js[j].Agent\n\t\t\tif agent == string(kube.KubernetesAgent) && js[j].Spec == nil {\n\t\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t\t}\n\t\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure that the periodic durations are valid and specs exist.\n\tfor j := range c.Periodics {\n\t\tname := c.Periodics[j].Name\n\t\tagent := c.Periodics[j].Agent\n\t\tif agent == string(kube.KubernetesAgent) && c.Periodics[j].Spec == nil {\n\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t}\n\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t}\n\t\td, err := time.ParseDuration(c.Periodics[j].Interval)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot parse duration for %s: %v\", c.Periodics[j].Name, err)\n\t\t}\n\t\tc.Periodics[j].interval = d\n\t}\n\n\turlTmpl, err := template.New(\"JobURL\").Parse(c.Plank.JobURLTemplateString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template: %v\", err)\n\t}\n\tc.Plank.JobURLTemplate = urlTmpl\n\n\treportTmpl, err := template.New(\"Report\").Parse(c.Plank.ReportTemplateString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template: %v\", err)\n\t}\n\tc.Plank.ReportTemplate = reportTmpl\n\n\tresyncPeriod, err := time.ParseDuration(c.Sinker.ResyncPeriodString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for resync_period: %v\", err)\n\t}\n\tc.Sinker.ResyncPeriod = resyncPeriod\n\tmaxProwJobAge, err := time.ParseDuration(c.Sinker.MaxProwJobAgeString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for max_prowjob_age: %v\", err)\n\t}\n\tc.Sinker.MaxProwJobAge = maxProwJobAge\n\tmaxPodAge, err := time.ParseDuration(c.Sinker.MaxPodAgeString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for max_pod_age: %v\", err)\n\t}\n\tc.Sinker.MaxPodAge = maxPodAge\n\treturn nil\n}\n\nfunc setRegexes(js []Presubmit) error {\n\tfor i, j := range js {\n\t\tif re, err := regexp.Compile(j.Trigger); err == nil {\n\t\t\tjs[i].re = re\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"could not compile trigger regex for %s: %v\", j.Name, err)\n\t\t}\n\t\tif err := setRegexes(j.RunAfterSuccess); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif j.RunIfChanged != \"\" {\n\t\t\tre, err := regexp.Compile(j.RunIfChanged)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not compile changes regex for %s: %v\", j.Name, err)\n\t\t\t}\n\t\t\tjs[i].reChanges = re\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Fix the test for nil pod specs in child jobs.<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\/\/ Package config knows how to read and parse config.yaml.\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"regexp\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/ghodss\/yaml\"\n\n\t\"k8s.io\/test-infra\/prow\/kube\"\n)\n\n\/\/ Config is a read-only snapshot of the config.\ntype Config struct {\n\t\/\/ Full repo name (such as \"kubernetes\/kubernetes\") -> list of jobs.\n\tPresubmits  map[string][]Presubmit  `json:\"presubmits,omitempty\"`\n\tPostsubmits map[string][]Postsubmit `json:\"postsubmits,omitempty\"`\n\n\t\/\/ Periodics are not associated with any repo.\n\tPeriodics []Periodic `json:\"periodics,omitempty\"`\n\n\tTide     Tide      `json:\"tide,omitempty\"`\n\tPlank    Plank     `json:\"plank,omitempty\"`\n\tSinker   Sinker    `json:\"sinker,omitempty\"`\n\tTriggers []Trigger `json:\"triggers,omitempty\"`\n\tHeart    Heart     `json:\"heart,omitempty\"`\n\n\t\/\/ ProwJobNamespace is the namespace in the cluster that prow\n\t\/\/ components will use for looking up ProwJobs. The namespace\n\t\/\/ needs to exist and will not be created by prow.\n\tProwJobNamespace string `json:\"prowjob_namespace,omitempty\"`\n\t\/\/ PodNamespace is the namespace in the cluster that prow\n\t\/\/ components will use for looking up Pods owned by ProwJobs.\n\t\/\/ The namespace needs to exist and will not be created by prow.\n\tPodNamespace string       `json:\"pod_namespace,omitempty\"`\n\tSlackEvents  []SlackEvent `json:\"slackevents,omitempty\"`\n}\n\n\/\/ Tide is config for the tide pool.\ntype Tide struct {\n\t\/\/ These must be valid GitHub search queries. They should not overlap,\n\t\/\/ which is to say two queries should never return the same PR.\n\tQueries []string `json:\"queries,omitempty\"`\n}\n\n\/\/ Plank is config for the plank controller.\ntype Plank struct {\n\t\/\/ JobURLTemplateString compiles into JobURLTemplate at load time.\n\tJobURLTemplateString string `json:\"job_url_template,omitempty\"`\n\t\/\/ JobURLTemplate is compiled at load time from JobURLTemplateString. It\n\t\/\/ will be passed a kube.ProwJob and is used to set the URL for the\n\t\/\/ \"details\" link on GitHub as well as the link from deck.\n\tJobURLTemplate *template.Template `json:\"-\"`\n\n\t\/\/ ReportTemplateString compiles into ReportTemplate at load time.\n\tReportTemplateString string `json:\"report_template,omitempty\"`\n\t\/\/ ReportTemplate is compiled at load time from ReportTemplateString. It\n\t\/\/ will be passed a kube.ProwJob and can provide an optional blurb below\n\t\/\/ the test failures comment.\n\tReportTemplate *template.Template `json:\"-\"`\n}\n\n\/\/ Sinker is config for the sinker controller.\ntype Sinker struct {\n\t\/\/ ResyncPeriodString compiles into ResyncPeriod at load time.\n\tResyncPeriodString string `json:\"resync_period,omitempty\"`\n\t\/\/ ResyncPeriod is how often the controller will perform a garbage\n\t\/\/ collection.\n\tResyncPeriod time.Duration `json:\"-\"`\n\t\/\/ MaxProwJobAgeString compiles into MaxProwJobAge at load time.\n\tMaxProwJobAgeString string `json:\"max_prowjob_age,omitempty\"`\n\t\/\/ MaxProwJobAge is how old a ProwJob can be before it is garbage-collected.\n\tMaxProwJobAge time.Duration `json:\"-\"`\n\t\/\/ MaxPodAgeString compiles into MaxPodAge at load time.\n\tMaxPodAgeString string `json:\"max_pod_age,omitempty\"`\n\t\/\/ MaxPodAge is how old a Pod can be before it is garbage-collected.\n\tMaxPodAge time.Duration `json:\"-\"`\n}\n\n\/\/ Trigger is config for the trigger plugin.\ntype Trigger struct {\n\t\/\/ Repos is either of the form org\/repos or just org.\n\tRepos []string `json:\"repos,omitempty\"`\n\t\/\/ TrustedOrg is the org whose members' PRs will be automatically built\n\t\/\/ for PRs to the above repos.\n\tTrustedOrg string `json:\"trusted_org,omitempty\"`\n}\n\n\/\/ Heart is config for the heart plugin\ntype Heart struct {\n\t\/\/ Adorees is a list of GitHub logins for members\n\t\/\/ for whom we will add emojis to comments\n\tAdorees []string `json:\"adorees,omitempty\"`\n}\n\n\/\/ SlackEvent is config for the slackevents plugin.\n\/\/ If a PR is pushed to any of the repos listed in the config\n\/\/ then sent message to the all the  slack channels listed if pusher is NOT in the whitelist.\ntype SlackEvent struct {\n\t\/\/ Repos is either of the form org\/repos or just org.\n\tRepos []string `json:\"repos,omitempty\"`\n\t\/\/ List of channels on which a event is published.\n\tChannels []string `json:\"channels,omitempty\"`\n\t\/\/ A slack event is published if the user is not part of the WhiteList.\n\tWhiteList []string `json:\"whitelist,omitempty\"`\n}\n\n\/\/ Load loads and parses the config at path.\nfunc Load(path string) (*Config, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading %s: %v\", path, err)\n\t}\n\tnc := &Config{}\n\tif err := yaml.Unmarshal(b, nc); err != nil {\n\t\treturn nil, fmt.Errorf(\"error unmarshaling %s: %v\", path, err)\n\t}\n\tif err := parseConfig(nc); err != nil {\n\t\treturn nil, err\n\t}\n\treturn nc, nil\n}\n\nfunc parseConfig(c *Config) error {\n\t\/\/ Ensure that presubmit regexes are valid.\n\tfor _, vs := range c.Presubmits {\n\t\tif err := setRegexes(vs); err != nil {\n\t\t\treturn fmt.Errorf(\"could not set regex: %v\", err)\n\t\t}\n\t}\n\n\t\/\/ Ensure that presubmits have a pod spec.\n\tfor _, v := range c.AllPresubmits(nil) {\n\t\tname := v.Name\n\t\tagent := v.Agent\n\t\tif agent == string(kube.KubernetesAgent) && v.Spec == nil {\n\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t}\n\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t}\n\t}\n\n\t\/\/ Ensure that postsubmits have a pod spec.\n\tfor _, j := range c.AllPostsubmits(nil) {\n\t\tname := j.Name\n\t\tagent := j.Agent\n\t\tif agent == string(kube.KubernetesAgent) && j.Spec == nil {\n\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t}\n\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t}\n\t}\n\n\t\/\/ Ensure that the periodic durations are valid and specs exist.\n\tfor _, p := range c.AllPeriodics() {\n\t\tname := p.Name\n\t\tagent := p.Agent\n\t\tif agent == string(kube.KubernetesAgent) && p.Spec == nil {\n\t\t\treturn fmt.Errorf(\"job %s has no spec\", name)\n\t\t}\n\t\tif agent != string(kube.KubernetesAgent) && agent != string(kube.JenkinsAgent) {\n\t\t\treturn fmt.Errorf(\"job %s has invalid agent (%s), it needs to be one of the following: %s %s\",\n\t\t\t\tname, agent, kube.KubernetesAgent, kube.JenkinsAgent)\n\t\t}\n\t}\n\t\/\/ Set the interval on the periodic jobs. It doesn't make sense to do this\n\t\/\/ for child jobs.\n\tfor j := range c.Periodics {\n\t\td, err := time.ParseDuration(c.Periodics[j].Interval)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot parse duration for %s: %v\", c.Periodics[j].Name, err)\n\t\t}\n\t\tc.Periodics[j].interval = d\n\t}\n\n\turlTmpl, err := template.New(\"JobURL\").Parse(c.Plank.JobURLTemplateString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template: %v\", err)\n\t}\n\tc.Plank.JobURLTemplate = urlTmpl\n\n\treportTmpl, err := template.New(\"Report\").Parse(c.Plank.ReportTemplateString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template: %v\", err)\n\t}\n\tc.Plank.ReportTemplate = reportTmpl\n\n\tresyncPeriod, err := time.ParseDuration(c.Sinker.ResyncPeriodString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for resync_period: %v\", err)\n\t}\n\tc.Sinker.ResyncPeriod = resyncPeriod\n\tmaxProwJobAge, err := time.ParseDuration(c.Sinker.MaxProwJobAgeString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for max_prowjob_age: %v\", err)\n\t}\n\tc.Sinker.MaxProwJobAge = maxProwJobAge\n\tmaxPodAge, err := time.ParseDuration(c.Sinker.MaxPodAgeString)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse duration for max_pod_age: %v\", err)\n\t}\n\tc.Sinker.MaxPodAge = maxPodAge\n\treturn nil\n}\n\nfunc setRegexes(js []Presubmit) error {\n\tfor i, j := range js {\n\t\tif re, err := regexp.Compile(j.Trigger); err == nil {\n\t\t\tjs[i].re = re\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"could not compile trigger regex for %s: %v\", j.Name, err)\n\t\t}\n\t\tif err := setRegexes(j.RunAfterSuccess); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif j.RunIfChanged != \"\" {\n\t\t\tre, err := regexp.Compile(j.RunIfChanged)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not compile changes regex for %s: %v\", j.Name, err)\n\t\t\t}\n\t\t\tjs[i].reChanges = re\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bird\n\nimport \"sync\"\n\n\/\/ Operation type of manipulation\ntype Operation int\n\n\/\/ Possible operation types\nconst (\n\tLand Operation = iota\n\tRaise\n\tInclude\n\tExclude\n)\n\nfunc (op Operation) String() string {\n\tswitch op {\n\tcase Land:\n\t\treturn \"Land\"\n\tcase Raise:\n\t\treturn \"Raise\"\n\tcase Include:\n\t\treturn \"Include\"\n\tcase Exclude:\n\t\treturn \"Exclude\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}\n\n\/\/ Action details of single manipulation with birds group\ntype Action struct {\n\tBirds     []*SmartBird\n\tOperation Operation\n}\n\n\/\/ Flock is a collection of smart birds\ntype Flock struct {\n\tbirds          map[*SmartBird]bool\n\taccess         sync.RWMutex\n\tjournalEnabled bool\n\tjournal        chan Action\n}\n\n\/\/ NewFlock initializes new flock of smart birds\nfunc NewFlock() *Flock {\n\treturn &Flock{birds: make(map[*SmartBird]bool), journal: make(chan Action)}\n}\n\n\/\/ Journal of all manipulations with birds in the flock. If journal was invoked,\n\/\/ reader must read it all otherwise all block\nfunc (f *Flock) Journal() <-chan Action {\n\tf.journalEnabled = true\n\treturn f.journal\n}\n\n\/\/ Include new smart bird to a flock or do nothing if it is already in\nfunc (f *Flock) Include(smartBird *SmartBird) {\n\tif f.birds[smartBird] {\n\t\treturn\n\t}\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tif !f.birds[smartBird] {\n\t\tf.birds[smartBird] = true\n\t\tf.log(Include, smartBird)\n\t}\n}\n\n\/\/ Take out smart bird from a flock, land it (if required) and return it.\n\/\/ If bird wasn't be in a flock then returns nil\nfunc (f *Flock) Take(birdToExclude *SmartBird, landBird bool) *SmartBird {\n\tif !f.birds[birdToExclude] {\n\t\treturn nil\n\t}\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tif f.birds[birdToExclude] {\n\t\tif landBird {\n\t\t\tbirdToExclude.Stop()\n\t\t\tf.log(Land, birdToExclude)\n\t\t}\n\t\tdelete(f.birds, birdToExclude)\n\t\tf.log(Exclude, birdToExclude)\n\t\treturn birdToExclude\n\t}\n\treturn nil\n}\n\n\/\/ Exclude some smart birds from a flock by their names and then returns them as list\nfunc (f *Flock) Exclude(landBird bool, birdNames ...string) []*SmartBird {\n\tvar ans []*SmartBird\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tselected := f.selectUnsafe(birdNames...)\n\tfor _, bird := range selected {\n\t\tif landBird {\n\t\t\tbird.Stop()\n\t\t}\n\t\tdelete(f.birds, bird)\n\t}\n\tif landBird {\n\t\tf.log(Land, selected...)\n\t}\n\tf.log(Exclude, selected...)\n\treturn ans\n}\n\n\/\/ Land some smart birds in a flock by their names.\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Land(names ...string) {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\twg := sync.WaitGroup{}\n\tselected := f.selectUnsafe(names...)\n\twg.Add(len(selected))\n\tfor _, bird := range selected {\n\t\tgo func(bird *SmartBird) {\n\t\t\tdefer wg.Done()\n\t\t\tbird.Stop()\n\t\t}(bird) \/\/ run stop in separate routing because of Stop() may be slow operation\n\t}\n\twg.Wait()\n\tf.log(Land, selected...)\n}\n\n\/\/ Raise all smart birds in a flock.\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Raise(names ...string) {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\tselected := f.selectUnsafe(names...)\n\tfor _, bird := range selected {\n\t\tbird.Start()\n\t}\n\tf.log(Raise, selected...)\n}\n\n\/\/ Select some smart birds from a flock by their names\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Select(names ...string) []*SmartBird {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\treturn f.selectUnsafe(names...)\n}\n\n\/\/ Dissolve all smart birds from a flock and optionally land them\nfunc (f *Flock) Dissolve(land bool) {\n\tf.Exclude(land)\n}\n\nfunc (f *Flock) log(operation Operation, birds ...*SmartBird) {\n\tif f.journalEnabled && len(birds) > 0 {\n\t\tf.journal <- Action{birds, operation}\n\t}\n}\n\nfunc (f *Flock) selectUnsafe(names ...string) []*SmartBird {\n\tans := make([]*SmartBird, 0, len(f.birds))\n\tswitch { \/\/ Some nano-optimization\n\tcase len(names) > 1:\n\t\tset := make(map[string]bool)\n\t\tfor _, name := range names {\n\t\t\tset[name] = true\n\t\t}\n\t\tfor bird := range f.birds {\n\t\t\tif set[bird.name] {\n\t\t\t\tans = append(ans, bird)\n\t\t\t}\n\t\t}\n\tcase len(names) == 1:\n\t\tfor bird := range f.birds {\n\t\t\tif names[0] == bird.name {\n\t\t\t\tans = append(ans, bird)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tfor bird := range f.birds {\n\t\t\tans = append(ans, bird)\n\t\t}\n\n\t}\n\n\treturn ans\n}\n<commit_msg>typedef for journal channel<commit_after>package bird\n\nimport \"sync\"\n\n\/\/ Operation type of manipulation\ntype Operation int\n\n\/\/ Possible operation types\nconst (\n\tLand Operation = iota\n\tRaise\n\tInclude\n\tExclude\n)\n\nfunc (op Operation) String() string {\n\tswitch op {\n\tcase Land:\n\t\treturn \"Land\"\n\tcase Raise:\n\t\treturn \"Raise\"\n\tcase Include:\n\t\treturn \"Include\"\n\tcase Exclude:\n\t\treturn \"Exclude\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}\n\n\/\/ Journal channel of actions in flock\ntype Journal <-chan Action\n\n\/\/ Action details of single manipulation with birds group\ntype Action struct {\n\tBirds     []*SmartBird\n\tOperation Operation\n}\n\n\/\/ Flock is a collection of smart birds\ntype Flock struct {\n\tbirds          map[*SmartBird]bool\n\taccess         sync.RWMutex\n\tjournalEnabled bool\n\tjournal        chan Action\n}\n\n\/\/ NewFlock initializes new flock of smart birds\nfunc NewFlock() *Flock {\n\treturn &Flock{birds: make(map[*SmartBird]bool), journal: make(chan Action)}\n}\n\n\/\/ Journal of all manipulations with birds in the flock. If journal was invoked,\n\/\/ reader must read it all otherwise all block\nfunc (f *Flock) Journal() Journal {\n\tf.journalEnabled = true\n\treturn f.journal\n}\n\n\/\/ Include new smart bird to a flock or do nothing if it is already in\nfunc (f *Flock) Include(smartBird *SmartBird) {\n\tif f.birds[smartBird] {\n\t\treturn\n\t}\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tif !f.birds[smartBird] {\n\t\tf.birds[smartBird] = true\n\t\tf.log(Include, smartBird)\n\t}\n}\n\n\/\/ Take out smart bird from a flock, land it (if required) and return it.\n\/\/ If bird wasn't be in a flock then returns nil\nfunc (f *Flock) Take(birdToExclude *SmartBird, landBird bool) *SmartBird {\n\tif !f.birds[birdToExclude] {\n\t\treturn nil\n\t}\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tif f.birds[birdToExclude] {\n\t\tif landBird {\n\t\t\tbirdToExclude.Stop()\n\t\t\tf.log(Land, birdToExclude)\n\t\t}\n\t\tdelete(f.birds, birdToExclude)\n\t\tf.log(Exclude, birdToExclude)\n\t\treturn birdToExclude\n\t}\n\treturn nil\n}\n\n\/\/ Exclude some smart birds from a flock by their names and then returns them as list\nfunc (f *Flock) Exclude(landBird bool, birdNames ...string) []*SmartBird {\n\tvar ans []*SmartBird\n\tf.access.Lock()\n\tdefer f.access.Unlock()\n\tselected := f.selectUnsafe(birdNames...)\n\tfor _, bird := range selected {\n\t\tif landBird {\n\t\t\tbird.Stop()\n\t\t}\n\t\tdelete(f.birds, bird)\n\t}\n\tif landBird {\n\t\tf.log(Land, selected...)\n\t}\n\tf.log(Exclude, selected...)\n\treturn ans\n}\n\n\/\/ Land some smart birds in a flock by their names.\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Land(names ...string) {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\twg := sync.WaitGroup{}\n\tselected := f.selectUnsafe(names...)\n\twg.Add(len(selected))\n\tfor _, bird := range selected {\n\t\tgo func(bird *SmartBird) {\n\t\t\tdefer wg.Done()\n\t\t\tbird.Stop()\n\t\t}(bird) \/\/ run stop in separate routing because of Stop() may be slow operation\n\t}\n\twg.Wait()\n\tf.log(Land, selected...)\n}\n\n\/\/ Raise all smart birds in a flock.\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Raise(names ...string) {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\tselected := f.selectUnsafe(names...)\n\tfor _, bird := range selected {\n\t\tbird.Start()\n\t}\n\tf.log(Raise, selected...)\n}\n\n\/\/ Select some smart birds from a flock by their names\n\/\/ If names not specified - all birds are used\nfunc (f *Flock) Select(names ...string) []*SmartBird {\n\tf.access.RLock()\n\tdefer f.access.RUnlock()\n\treturn f.selectUnsafe(names...)\n}\n\n\/\/ Dissolve all smart birds from a flock and optionally land them\nfunc (f *Flock) Dissolve(land bool) {\n\tf.Exclude(land)\n}\n\nfunc (f *Flock) log(operation Operation, birds ...*SmartBird) {\n\tif f.journalEnabled && len(birds) > 0 {\n\t\tf.journal <- Action{birds, operation}\n\t}\n}\n\nfunc (f *Flock) selectUnsafe(names ...string) []*SmartBird {\n\tans := make([]*SmartBird, 0, len(f.birds))\n\tswitch { \/\/ Some nano-optimization\n\tcase len(names) > 1:\n\t\tset := make(map[string]bool)\n\t\tfor _, name := range names {\n\t\t\tset[name] = true\n\t\t}\n\t\tfor bird := range f.birds {\n\t\t\tif set[bird.name] {\n\t\t\t\tans = append(ans, bird)\n\t\t\t}\n\t\t}\n\tcase len(names) == 1:\n\t\tfor bird := range f.birds {\n\t\t\tif names[0] == bird.name {\n\t\t\t\tans = append(ans, bird)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tfor bird := range f.birds {\n\t\t\tans = append(ans, bird)\n\t\t}\n\n\t}\n\n\treturn ans\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\n\/\/ +k8s:defaulter-gen=TypeMeta\n\/\/ +groupName=kubeadm.k8s.io\n\/\/ +k8s:deepcopy-gen=package\n\/\/ +k8s:conversion-gen=k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\n\n\/\/ Package v1beta1 defines the v1beta1 version of the kubeadm configuration file format.\n\/\/ This version graduates the configuration format to BETA and is a big step towards GA.\n\/\/\n\/\/A list of changes since v1alpha3:\n\/\/\t- \"apiServerEndpoint\" in InitConfiguration was renamed to \"localAPIEndpoint\" for better clarity of what the field\n\/\/\trepresents.\n\/\/\t- Common fields in ClusterConfiguration such as \"*extraArgs\" and \"*extraVolumes\" for control plane components are now moved\n\/\/\tunder component structs - i.e. \"apiServer\", \"controllerManager\", \"scheduler\".\n\/\/\t- \"auditPolicy\" was removed from ClusterConfiguration. Please use \"extraArgs\" in \"apiServer\" to configure this feature instead.\n\/\/\t- \"unifiedControlPlaneImage\" in ClusterConfiguration was changed to a boolean field called \"useHyperKubeImage\".\n\/\/\t- ClusterConfiguration now has a \"dns\" field which can be used to select and configure the cluster DNS addon.\n\/\/\t- \"featureGates\" still exists under ClusterConfiguration, but there are no supported feature gates in 1.13.\n\/\/\tSee the Kubernetes 1.13 changelog for further details.\n\/\/\t- Both \"localEtcd\" and \"dns\" configurations now support custom image repositories.\n\/\/\t- The \"controlPlane*\"-related fields in JoinConfiguration were refactored into a sub-structure.\n\/\/\t- \"clusterName\" was removed from JoinConfiguration and the name is now fetched from the existing cluster.\n\/\/\n\/\/ Migration from old kubeadm config versions\n\/\/\n\/\/ Please convert your v1alpha3 configuration files to v1beta1 using the \"kubeadm config migrate\" command of kubeadm v1.13.x\n\/\/ (conversion from older releases of kubeadm config files requires older release of kubeadm as well e.g.\n\/\/\tkubeadm v1.11 should be used to migrate v1alpha1 to v1alpha2; kubeadm v1.12 should be used to translate v1alpha2 to v1alpha3)\n\/\/\n\/\/ Nevertheless, kubeadm v1.13.x will support reading from v1alpha3 version of the kubeadm config file format, but this support\n\/\/ will be dropped in the v1.14 release.\n\/\/\n\/\/ Basics\n\/\/\n\/\/ The preferred way to configure kubeadm is to pass an YAML configuration file with the --config option. Some of the\n\/\/ configuration options defined in the kubeadm config file are also available as command line flags, but only\n\/\/ the most common\/simple use case are supported with this approach.\n\/\/\n\/\/ A kubeadm config file could contain multiple configuration types separated using three dashes (“---”).\n\/\/\n\/\/ kubeadm supports the following configuration types:\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: InitConfiguration\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: ClusterConfiguration\n\/\/\n\/\/     apiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/     kind: KubeletConfiguration\n\/\/\n\/\/     apiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/     kind: KubeProxyConfiguration\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: JoinConfiguration\n\/\/\n\/\/ To print the defaults for \"init\" and \"join\" actions use the following commands:\n\/\/  kubeadm config print init-defaults\n\/\/  kubeadm config print join-defaults\n\/\/\n\/\/ The list of configuration types that must be included in a configuration file depends by the action you are\n\/\/ performing (init or join) and by the configuration options you are going to use (defaults or advanced customization).\n\/\/\n\/\/ If some configuration types are not provided, or provided only partially, kubeadm will use default values; defaults\n\/\/ provided by kubeadm includes also enforcing consistency of values across components when required (e.g.\n\/\/ cluster-cidr flag on controller manager and clusterCIDR on kube-proxy).\n\/\/\n\/\/ Users are always allowed to override default values, with the only exception of a small subset of setting with\n\/\/ relevance for security (e.g. enforce authorization-mode Node and RBAC on api server)\n\/\/\n\/\/ If the user provides a configuration types that is not expected for the action you are performing, kubeadm will\n\/\/ ignore those types and print a warning.\n\/\/\n\/\/ Kubeadm init configuration types\n\/\/\n\/\/ When executing kubeadm init with the --config option, the following configuration types could be used:\n\/\/ InitConfiguration, ClusterConfiguration, KubeProxyConfiguration, KubeletConfiguration, but only one\n\/\/ between InitConfiguration and ClusterConfiguration is mandatory.\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: InitConfiguration\n\/\/     bootstrapTokens:\n\/\/         ...\n\/\/     nodeRegistration:\n\/\/         ...\n\/\/\n\/\/ The InitConfiguration type should be used to configure runtime settings, that in case of kubeadm init\n\/\/ are the configuration of the bootstrap token and all the setting which are specific to the node where kubeadm\n\/\/ is executed, including:\n\/\/\n\/\/ - NodeRegistration, that holds fields that relate to registering the new node to the cluster;\n\/\/ use it to customize the node name, the CRI socket to use or any other settings that should apply to this\n\/\/ node only (e.g. the node ip).\n\/\/\n\/\/ - LocalAPIEndpoint, that represents the endpoint of the instance of the API server to be deployed on this node;\n\/\/ use it e.g. to customize the API server advertise address.\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: ClusterConfiguration\n\/\/     networking:\n\/\/         ...\n\/\/     etcd:\n\/\/         ...\n\/\/     apiServer:\n\/\/       extraArgs:\n\/\/         ...\n\/\/       extraVolumes:\n\/\/         ...\n\/\/     ...\n\/\/\n\/\/ The ClusterConfiguration type should be used to configure cluster-wide settings,\n\/\/ including settings for:\n\/\/\n\/\/ - Networking, that holds configuration for the networking topology of the cluster; use it e.g. to customize\n\/\/ node subnet or services subnet.\n\/\/\n\/\/ - Etcd configurations; use it e.g. to customize the local etcd or to configure the API server\n\/\/ for using an external etcd cluster.\n\/\/\n\/\/ - kube-apiserver, kube-scheduler, kube-controller-manager configurations; use it to customize control-plane\n\/\/ components by adding customized setting or overriding kubeadm default settings.\n\/\/\n\/\/    apiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/    kind: KubeProxyConfiguration\n\/\/       ...\n\/\/\n\/\/ The KubeProxyConfiguration type should be used to change the configuration passed to kube-proxy instances deployed\n\/\/ in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults.\n\/\/\n\/\/ See https:\/\/kubernetes.io\/docs\/reference\/command-line-tools-reference\/kube-proxy\/ or https:\/\/godoc.org\/k8s.io\/kube-proxy\/config\/v1alpha1#KubeProxyConfiguration\n\/\/ for kube proxy official documentation.\n\/\/\n\/\/    apiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/    kind: KubeletConfiguration\n\/\/       ...\n\/\/\n\/\/ The KubeletConfiguration type should be used to change the configurations that will be passed to all kubelet instances\n\/\/ deployed in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults.\n\/\/\n\/\/ See https:\/\/kubernetes.io\/docs\/reference\/command-line-tools-reference\/kubelet\/ or https:\/\/godoc.org\/k8s.io\/kubelet\/config\/v1beta1#KubeletConfiguration\n\/\/ for kube proxy official documentation.\n\/\/\n\/\/ Here is a fully populated example of a single YAML file containing multiple\n\/\/ configuration types to be used during a `kubeadm init` run.\n\/\/\n\/\/ \tapiVersion: kubeadm.k8s.io\/v1beta1\n\/\/ \tkind: InitConfiguration\n\/\/ \tbootstrapTokens:\n\/\/ \t- token: \"9a08jv.c0izixklcxtmnze7\"\n\/\/ \t  description: \"kubeadm bootstrap token\"\n\/\/ \t  ttl: \"24h\"\n\/\/ \t- token: \"783bde.3f89s0fje9f38fhf\"\n\/\/ \t  description: \"another bootstrap token\"\n\/\/ \t  usages:\n\/\/ \t  - authentication\n\/\/ \t  - signing\n\/\/ \t  groups:\n\/\/ \t  - system:bootstrappers:kubeadm:default-node-token\n\/\/ \tnodeRegistration:\n\/\/ \t  name: \"ec2-10-100-0-1\"\n\/\/ \t  criSocket: \"\/var\/run\/dockershim.sock\"\n\/\/ \t  taints:\n\/\/ \t  - key: \"kubeadmNode\"\n\/\/ \t    value: \"master\"\n\/\/ \t    effect: \"NoSchedule\"\n\/\/ \t  kubeletExtraArgs:\n\/\/ \t    cgroupDriver: \"cgroupfs\"\n\/\/ \tlocalAPIEndpoint:\n\/\/ \t  advertiseAddress: \"10.100.0.1\"\n\/\/ \t  bindPort: 6443\n\/\/ \t---\n\/\/ \tapiVersion: kubeadm.k8s.io\/v1beta1\n\/\/ \tkind: ClusterConfiguration\n\/\/ \tetcd:\n\/\/ \t  # one of local or external\n\/\/ \t  local:\n\/\/ \t    imageRepository: \"k8s.gcr.io\"\n\/\/ \t    imageTag: \"3.2.24\"\n\/\/ \t    dataDir: \"\/var\/lib\/etcd\"\n\/\/ \t    extraArgs:\n\/\/ \t      listen-client-urls: \"http:\/\/10.100.0.1:2379\"\n\/\/ \t    serverCertSANs:\n\/\/ \t    -  \"ec2-10-100-0-1.compute-1.amazonaws.com\"\n\/\/ \t    peerCertSANs:\n\/\/ \t    - \"10.100.0.1\"\n\/\/ \t  # external:\n\/\/ \t    # endpoints:\n\/\/ \t    # - \"10.100.0.1:2379\"\n\/\/ \t    # - \"10.100.0.2:2379\"\n\/\/ \t    # caFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd-ca.crt\"\n\/\/ \t    # certFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd.crt\"\n\/\/ \t    # keyFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd.key\"\n\/\/ \tnetworking:\n\/\/ \t  serviceSubnet: \"10.96.0.0\/12\"\n\/\/ \t  podSubnet: \"10.100.0.1\/24\"\n\/\/ \t  dnsDomain: \"cluster.local\"\n\/\/ \tkubernetesVersion: \"v1.12.0\"\n\/\/ \tcontrolPlaneEndpoint: \"10.100.0.1:6443\"\n\/\/ \tapiServer:\n\/\/ \t  extraArgs:\n\/\/ \t    authorization-mode: \"Node,RBAC\"\n\/\/ \t  extraVolumes:\n\/\/ \t  - name: \"some-volume\"\n\/\/ \t    hostPath: \"\/etc\/some-path\"\n\/\/ \t    mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t    readOnly: false\n\/\/ \t    pathType: File\n\/\/ \t  certSANs:\n\/\/ \t  - \"10.100.1.1\"\n\/\/ \t  - \"ec2-10-100-0-1.compute-1.amazonaws.com\"\n\/\/ \t  timeoutForControlPlane: 4m0s\n\/\/ \tcontrollerManager:\n\/\/ \t  extraArgs:\n\/\/ \t    \"node-cidr-mask-size\": \"20\"\n\/\/ \t  extraVolumes:\n\/\/ \t  - name: \"some-volume\"\n\/\/ \t    hostPath: \"\/etc\/some-path\"\n\/\/ \t    mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t    readOnly: false\n\/\/ \t    pathType: File\n\/\/ \tscheduler:\n\/\/ \t  extraArgs:\n\/\/ \t    address: \"10.100.0.1\"\n\/\/ \textraVolumes:\n\/\/ \t- name: \"some-volume\"\n\/\/ \t  hostPath: \"\/etc\/some-path\"\n\/\/ \t  mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t  readOnly: false\n\/\/ \t  pathType: File\n\/\/ \tcertificatesDir: \"\/etc\/kubernetes\/pki\"\n\/\/ \timageRepository: \"k8s.gcr.io\"\n\/\/ \tuseHyperKubeImage: false\n\/\/ \tclusterName: \"example-cluster\"\n\/\/ \t---\n\/\/ \tapiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/ \tkind: KubeletConfiguration\n\/\/ \t# kubelet specific options here\n\/\/ \t---\n\/\/ \tapiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/ \tkind: KubeProxyConfiguration\n\/\/ \t# kube-proxy specific options here\n\/\/\n\/\/ Kubeadm join configuration types\n\/\/\n\/\/ When executing kubeadm join with the --config option, the JoinConfiguration type should be provided.\n\/\/\n\/\/    apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/    kind: JoinConfiguration\n\/\/       ...\n\/\/\n\/\/ The JoinConfiguration type should be used to configure runtime settings, that in case of kubeadm join\n\/\/ are the discovery method used for accessing the cluster info and all the setting which are specific\n\/\/ to the node where kubeadm is executed, including:\n\/\/\n\/\/ - NodeRegistration, that holds fields that relate to registering the new node to the cluster;\n\/\/ use it to customize the node name, the CRI socket to use or any other settings that should apply to this\n\/\/ node only (e.g. the node ip).\n\/\/\n\/\/ - APIEndpoint, that represents the endpoint of the instance of the API server to be eventually deployed on this node.\n\/\/\npackage v1beta1 \/\/ import \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/v1beta1\"\n\n\/\/TODO: The BootstrapTokenString object should move out to either k8s.io\/client-go or k8s.io\/api in the future\n\/\/(probably as part of Bootstrap Tokens going GA). It should not be staged under the kubeadm API as it is now.\n<commit_msg>replace proxy with kubelet at kubeadm v1beta1 docs<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\n\/\/ +k8s:defaulter-gen=TypeMeta\n\/\/ +groupName=kubeadm.k8s.io\n\/\/ +k8s:deepcopy-gen=package\n\/\/ +k8s:conversion-gen=k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\n\n\/\/ Package v1beta1 defines the v1beta1 version of the kubeadm configuration file format.\n\/\/ This version graduates the configuration format to BETA and is a big step towards GA.\n\/\/\n\/\/A list of changes since v1alpha3:\n\/\/\t- \"apiServerEndpoint\" in InitConfiguration was renamed to \"localAPIEndpoint\" for better clarity of what the field\n\/\/\trepresents.\n\/\/\t- Common fields in ClusterConfiguration such as \"*extraArgs\" and \"*extraVolumes\" for control plane components are now moved\n\/\/\tunder component structs - i.e. \"apiServer\", \"controllerManager\", \"scheduler\".\n\/\/\t- \"auditPolicy\" was removed from ClusterConfiguration. Please use \"extraArgs\" in \"apiServer\" to configure this feature instead.\n\/\/\t- \"unifiedControlPlaneImage\" in ClusterConfiguration was changed to a boolean field called \"useHyperKubeImage\".\n\/\/\t- ClusterConfiguration now has a \"dns\" field which can be used to select and configure the cluster DNS addon.\n\/\/\t- \"featureGates\" still exists under ClusterConfiguration, but there are no supported feature gates in 1.13.\n\/\/\tSee the Kubernetes 1.13 changelog for further details.\n\/\/\t- Both \"localEtcd\" and \"dns\" configurations now support custom image repositories.\n\/\/\t- The \"controlPlane*\"-related fields in JoinConfiguration were refactored into a sub-structure.\n\/\/\t- \"clusterName\" was removed from JoinConfiguration and the name is now fetched from the existing cluster.\n\/\/\n\/\/ Migration from old kubeadm config versions\n\/\/\n\/\/ Please convert your v1alpha3 configuration files to v1beta1 using the \"kubeadm config migrate\" command of kubeadm v1.13.x\n\/\/ (conversion from older releases of kubeadm config files requires older release of kubeadm as well e.g.\n\/\/\tkubeadm v1.11 should be used to migrate v1alpha1 to v1alpha2; kubeadm v1.12 should be used to translate v1alpha2 to v1alpha3)\n\/\/\n\/\/ Nevertheless, kubeadm v1.13.x will support reading from v1alpha3 version of the kubeadm config file format, but this support\n\/\/ will be dropped in the v1.14 release.\n\/\/\n\/\/ Basics\n\/\/\n\/\/ The preferred way to configure kubeadm is to pass an YAML configuration file with the --config option. Some of the\n\/\/ configuration options defined in the kubeadm config file are also available as command line flags, but only\n\/\/ the most common\/simple use case are supported with this approach.\n\/\/\n\/\/ A kubeadm config file could contain multiple configuration types separated using three dashes (“---”).\n\/\/\n\/\/ kubeadm supports the following configuration types:\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: InitConfiguration\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: ClusterConfiguration\n\/\/\n\/\/     apiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/     kind: KubeletConfiguration\n\/\/\n\/\/     apiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/     kind: KubeProxyConfiguration\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: JoinConfiguration\n\/\/\n\/\/ To print the defaults for \"init\" and \"join\" actions use the following commands:\n\/\/  kubeadm config print init-defaults\n\/\/  kubeadm config print join-defaults\n\/\/\n\/\/ The list of configuration types that must be included in a configuration file depends by the action you are\n\/\/ performing (init or join) and by the configuration options you are going to use (defaults or advanced customization).\n\/\/\n\/\/ If some configuration types are not provided, or provided only partially, kubeadm will use default values; defaults\n\/\/ provided by kubeadm includes also enforcing consistency of values across components when required (e.g.\n\/\/ cluster-cidr flag on controller manager and clusterCIDR on kube-proxy).\n\/\/\n\/\/ Users are always allowed to override default values, with the only exception of a small subset of setting with\n\/\/ relevance for security (e.g. enforce authorization-mode Node and RBAC on api server)\n\/\/\n\/\/ If the user provides a configuration types that is not expected for the action you are performing, kubeadm will\n\/\/ ignore those types and print a warning.\n\/\/\n\/\/ Kubeadm init configuration types\n\/\/\n\/\/ When executing kubeadm init with the --config option, the following configuration types could be used:\n\/\/ InitConfiguration, ClusterConfiguration, KubeProxyConfiguration, KubeletConfiguration, but only one\n\/\/ between InitConfiguration and ClusterConfiguration is mandatory.\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: InitConfiguration\n\/\/     bootstrapTokens:\n\/\/         ...\n\/\/     nodeRegistration:\n\/\/         ...\n\/\/\n\/\/ The InitConfiguration type should be used to configure runtime settings, that in case of kubeadm init\n\/\/ are the configuration of the bootstrap token and all the setting which are specific to the node where kubeadm\n\/\/ is executed, including:\n\/\/\n\/\/ - NodeRegistration, that holds fields that relate to registering the new node to the cluster;\n\/\/ use it to customize the node name, the CRI socket to use or any other settings that should apply to this\n\/\/ node only (e.g. the node ip).\n\/\/\n\/\/ - LocalAPIEndpoint, that represents the endpoint of the instance of the API server to be deployed on this node;\n\/\/ use it e.g. to customize the API server advertise address.\n\/\/\n\/\/     apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/     kind: ClusterConfiguration\n\/\/     networking:\n\/\/         ...\n\/\/     etcd:\n\/\/         ...\n\/\/     apiServer:\n\/\/       extraArgs:\n\/\/         ...\n\/\/       extraVolumes:\n\/\/         ...\n\/\/     ...\n\/\/\n\/\/ The ClusterConfiguration type should be used to configure cluster-wide settings,\n\/\/ including settings for:\n\/\/\n\/\/ - Networking, that holds configuration for the networking topology of the cluster; use it e.g. to customize\n\/\/ node subnet or services subnet.\n\/\/\n\/\/ - Etcd configurations; use it e.g. to customize the local etcd or to configure the API server\n\/\/ for using an external etcd cluster.\n\/\/\n\/\/ - kube-apiserver, kube-scheduler, kube-controller-manager configurations; use it to customize control-plane\n\/\/ components by adding customized setting or overriding kubeadm default settings.\n\/\/\n\/\/    apiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/    kind: KubeProxyConfiguration\n\/\/       ...\n\/\/\n\/\/ The KubeProxyConfiguration type should be used to change the configuration passed to kube-proxy instances deployed\n\/\/ in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults.\n\/\/\n\/\/ See https:\/\/kubernetes.io\/docs\/reference\/command-line-tools-reference\/kube-proxy\/ or https:\/\/godoc.org\/k8s.io\/kube-proxy\/config\/v1alpha1#KubeProxyConfiguration\n\/\/ for kube proxy official documentation.\n\/\/\n\/\/    apiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/    kind: KubeletConfiguration\n\/\/       ...\n\/\/\n\/\/ The KubeletConfiguration type should be used to change the configurations that will be passed to all kubelet instances\n\/\/ deployed in the cluster. If this object is not provided or provided only partially, kubeadm applies defaults.\n\/\/\n\/\/ See https:\/\/kubernetes.io\/docs\/reference\/command-line-tools-reference\/kubelet\/ or https:\/\/godoc.org\/k8s.io\/kubelet\/config\/v1beta1#KubeletConfiguration\n\/\/ for kubelet official documentation.\n\/\/\n\/\/ Here is a fully populated example of a single YAML file containing multiple\n\/\/ configuration types to be used during a `kubeadm init` run.\n\/\/\n\/\/ \tapiVersion: kubeadm.k8s.io\/v1beta1\n\/\/ \tkind: InitConfiguration\n\/\/ \tbootstrapTokens:\n\/\/ \t- token: \"9a08jv.c0izixklcxtmnze7\"\n\/\/ \t  description: \"kubeadm bootstrap token\"\n\/\/ \t  ttl: \"24h\"\n\/\/ \t- token: \"783bde.3f89s0fje9f38fhf\"\n\/\/ \t  description: \"another bootstrap token\"\n\/\/ \t  usages:\n\/\/ \t  - authentication\n\/\/ \t  - signing\n\/\/ \t  groups:\n\/\/ \t  - system:bootstrappers:kubeadm:default-node-token\n\/\/ \tnodeRegistration:\n\/\/ \t  name: \"ec2-10-100-0-1\"\n\/\/ \t  criSocket: \"\/var\/run\/dockershim.sock\"\n\/\/ \t  taints:\n\/\/ \t  - key: \"kubeadmNode\"\n\/\/ \t    value: \"master\"\n\/\/ \t    effect: \"NoSchedule\"\n\/\/ \t  kubeletExtraArgs:\n\/\/ \t    cgroupDriver: \"cgroupfs\"\n\/\/ \tlocalAPIEndpoint:\n\/\/ \t  advertiseAddress: \"10.100.0.1\"\n\/\/ \t  bindPort: 6443\n\/\/ \t---\n\/\/ \tapiVersion: kubeadm.k8s.io\/v1beta1\n\/\/ \tkind: ClusterConfiguration\n\/\/ \tetcd:\n\/\/ \t  # one of local or external\n\/\/ \t  local:\n\/\/ \t    imageRepository: \"k8s.gcr.io\"\n\/\/ \t    imageTag: \"3.2.24\"\n\/\/ \t    dataDir: \"\/var\/lib\/etcd\"\n\/\/ \t    extraArgs:\n\/\/ \t      listen-client-urls: \"http:\/\/10.100.0.1:2379\"\n\/\/ \t    serverCertSANs:\n\/\/ \t    -  \"ec2-10-100-0-1.compute-1.amazonaws.com\"\n\/\/ \t    peerCertSANs:\n\/\/ \t    - \"10.100.0.1\"\n\/\/ \t  # external:\n\/\/ \t    # endpoints:\n\/\/ \t    # - \"10.100.0.1:2379\"\n\/\/ \t    # - \"10.100.0.2:2379\"\n\/\/ \t    # caFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd-ca.crt\"\n\/\/ \t    # certFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd.crt\"\n\/\/ \t    # keyFile: \"\/etcd\/kubernetes\/pki\/etcd\/etcd.key\"\n\/\/ \tnetworking:\n\/\/ \t  serviceSubnet: \"10.96.0.0\/12\"\n\/\/ \t  podSubnet: \"10.100.0.1\/24\"\n\/\/ \t  dnsDomain: \"cluster.local\"\n\/\/ \tkubernetesVersion: \"v1.12.0\"\n\/\/ \tcontrolPlaneEndpoint: \"10.100.0.1:6443\"\n\/\/ \tapiServer:\n\/\/ \t  extraArgs:\n\/\/ \t    authorization-mode: \"Node,RBAC\"\n\/\/ \t  extraVolumes:\n\/\/ \t  - name: \"some-volume\"\n\/\/ \t    hostPath: \"\/etc\/some-path\"\n\/\/ \t    mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t    readOnly: false\n\/\/ \t    pathType: File\n\/\/ \t  certSANs:\n\/\/ \t  - \"10.100.1.1\"\n\/\/ \t  - \"ec2-10-100-0-1.compute-1.amazonaws.com\"\n\/\/ \t  timeoutForControlPlane: 4m0s\n\/\/ \tcontrollerManager:\n\/\/ \t  extraArgs:\n\/\/ \t    \"node-cidr-mask-size\": \"20\"\n\/\/ \t  extraVolumes:\n\/\/ \t  - name: \"some-volume\"\n\/\/ \t    hostPath: \"\/etc\/some-path\"\n\/\/ \t    mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t    readOnly: false\n\/\/ \t    pathType: File\n\/\/ \tscheduler:\n\/\/ \t  extraArgs:\n\/\/ \t    address: \"10.100.0.1\"\n\/\/ \textraVolumes:\n\/\/ \t- name: \"some-volume\"\n\/\/ \t  hostPath: \"\/etc\/some-path\"\n\/\/ \t  mountPath: \"\/etc\/some-pod-path\"\n\/\/ \t  readOnly: false\n\/\/ \t  pathType: File\n\/\/ \tcertificatesDir: \"\/etc\/kubernetes\/pki\"\n\/\/ \timageRepository: \"k8s.gcr.io\"\n\/\/ \tuseHyperKubeImage: false\n\/\/ \tclusterName: \"example-cluster\"\n\/\/ \t---\n\/\/ \tapiVersion: kubelet.config.k8s.io\/v1beta1\n\/\/ \tkind: KubeletConfiguration\n\/\/ \t# kubelet specific options here\n\/\/ \t---\n\/\/ \tapiVersion: kubeproxy.config.k8s.io\/v1alpha1\n\/\/ \tkind: KubeProxyConfiguration\n\/\/ \t# kube-proxy specific options here\n\/\/\n\/\/ Kubeadm join configuration types\n\/\/\n\/\/ When executing kubeadm join with the --config option, the JoinConfiguration type should be provided.\n\/\/\n\/\/    apiVersion: kubeadm.k8s.io\/v1beta1\n\/\/    kind: JoinConfiguration\n\/\/       ...\n\/\/\n\/\/ The JoinConfiguration type should be used to configure runtime settings, that in case of kubeadm join\n\/\/ are the discovery method used for accessing the cluster info and all the setting which are specific\n\/\/ to the node where kubeadm is executed, including:\n\/\/\n\/\/ - NodeRegistration, that holds fields that relate to registering the new node to the cluster;\n\/\/ use it to customize the node name, the CRI socket to use or any other settings that should apply to this\n\/\/ node only (e.g. the node ip).\n\/\/\n\/\/ - APIEndpoint, that represents the endpoint of the instance of the API server to be eventually deployed on this node.\n\/\/\npackage v1beta1 \/\/ import \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/v1beta1\"\n\n\/\/TODO: The BootstrapTokenString object should move out to either k8s.io\/client-go or k8s.io\/api in the future\n\/\/(probably as part of Bootstrap Tokens going GA). It should not be staged under the kubeadm API as it is now.\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 upgrade\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/coredns\/corefile-migration\/migration\"\n\t\"github.com\/pkg\/errors\"\n\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\/v2\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\tkubeadmconstants \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/phases\/addons\/dns\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/preflight\"\n)\n\n\/\/ CoreDNSCheck validates installed kubelet version\ntype CoreDNSCheck struct {\n\tname   string\n\tclient clientset.Interface\n\tf      func(clientset.Interface) error\n}\n\n\/\/ Name is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Name() string {\n\treturn c.name\n}\n\n\/\/ Check is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Check() (warnings, errors []error) {\n\tif err := c.f(c.client); err != nil {\n\t\treturn nil, []error{err}\n\t}\n\treturn nil, nil\n}\n\n\/\/ RunCoreDNSMigrationCheck initializes checks related to CoreDNS migration.\nfunc RunCoreDNSMigrationCheck(client clientset.Interface, ignorePreflightErrors sets.String, dnsType kubeadmapi.DNSAddOnType) error {\n\tif dnsType != kubeadmapi.CoreDNS {\n\t\treturn nil\n\t}\n\tmigrationChecks := []preflight.Checker{\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"CoreDNSUnsupportedPlugins\",\n\t\t\tclient: client,\n\t\t\tf:      checkUnsupportedPlugins,\n\t\t},\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"CoreDNSMigration\",\n\t\t\tclient: client,\n\t\t\tf:      checkMigration,\n\t\t},\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"kubeDNSTranslation\",\n\t\t\tclient: client,\n\t\t\tf:      checkKubeDNSConfigMap,\n\t\t},\n\t}\n\n\treturn preflight.RunChecks(migrationChecks, os.Stderr, ignorePreflightErrors)\n}\n\n\/\/ checkUnsupportedPlugins checks if there are any plugins included in the current configuration\n\/\/ that are unsupported for migration.\nfunc checkUnsupportedPlugins(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if there are any unsupported CoreDNS plugins in the Corefile\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tunsupportedCoreDNS, err := migration.Unsupported(currentInstalledCoreDNSversion, currentInstalledCoreDNSversion, corefile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(unsupportedCoreDNS) != 0 {\n\t\tvar UnsupportedPlugins []string\n\t\tfor _, unsup := range unsupportedCoreDNS {\n\t\t\tUnsupportedPlugins = append(UnsupportedPlugins, unsup.ToString())\n\t\t}\n\t\tfmt.Println(\"[preflight] The corefile contains plugins that kubeadm\/CoreDNS does not know how to migrate. \" +\n\t\t\t\"Each plugin listed should be manually verified for compatibility with the newer version of CoreDNS. \" +\n\t\t\t\"Once ready, the upgrade can be initiated by skipping the preflight check. During the upgrade, \" +\n\t\t\t\"kubeadm will migrate the configuration while leaving the listed plugin configs untouched, \" +\n\t\t\t\"but cannot guarantee that they will work with the newer version of CoreDNS.\")\n\t\treturn errors.Errorf(\"CoreDNS cannot migrate the following plugins:\\n%s\", UnsupportedPlugins)\n\t}\n\treturn nil\n}\n\n\/\/ checkMigration validates if migration of the current CoreDNS ConfigMap is possible.\nfunc checkMigration(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if migration can be done for the current CoreDNS release.\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = migration.Migrate(currentInstalledCoreDNSversion, kubeadmconstants.CoreDNSVersion, corefile, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"CoreDNS will not be upgraded\")\n\t}\n\treturn nil\n}\n\n\/\/ checkKubeDNSConfigMap checks if the translation of kube-dns to CoreDNS ConfigMap is supported\nfunc checkKubeDNSConfigMap(client clientset.Interface) error {\n\tkubeDNSConfigMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(context.TODO(), kubeadmconstants.KubeDNSConfigMap, metav1.GetOptions{})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif _, ok := kubeDNSConfigMap.Data[\"federations\"]; ok {\n\t\tklog.V(1).Infoln(\"CoreDNS no longer supports Federation and \" +\n\t\t\t\"hence will not translate the federation data from kube-dns to CoreDNS ConfigMap\")\n\t\treturn errors.New(\"kube-dns Federation data will not be translated\")\n\t}\n\treturn nil\n}\n<commit_msg>CoreDNS preflight: Remove \"v\" from version<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 upgrade\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/coredns\/corefile-migration\/migration\"\n\t\"github.com\/pkg\/errors\"\n\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\/v2\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\tkubeadmconstants \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/phases\/addons\/dns\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/preflight\"\n)\n\n\/\/ CoreDNSCheck validates installed kubelet version\ntype CoreDNSCheck struct {\n\tname   string\n\tclient clientset.Interface\n\tf      func(clientset.Interface) error\n}\n\n\/\/ Name is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Name() string {\n\treturn c.name\n}\n\n\/\/ Check is part of the preflight.Checker interface\nfunc (c CoreDNSCheck) Check() (warnings, errors []error) {\n\tif err := c.f(c.client); err != nil {\n\t\treturn nil, []error{err}\n\t}\n\treturn nil, nil\n}\n\n\/\/ RunCoreDNSMigrationCheck initializes checks related to CoreDNS migration.\nfunc RunCoreDNSMigrationCheck(client clientset.Interface, ignorePreflightErrors sets.String, dnsType kubeadmapi.DNSAddOnType) error {\n\tif dnsType != kubeadmapi.CoreDNS {\n\t\treturn nil\n\t}\n\tmigrationChecks := []preflight.Checker{\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"CoreDNSUnsupportedPlugins\",\n\t\t\tclient: client,\n\t\t\tf:      checkUnsupportedPlugins,\n\t\t},\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"CoreDNSMigration\",\n\t\t\tclient: client,\n\t\t\tf:      checkMigration,\n\t\t},\n\t\t&CoreDNSCheck{\n\t\t\tname:   \"kubeDNSTranslation\",\n\t\t\tclient: client,\n\t\t\tf:      checkKubeDNSConfigMap,\n\t\t},\n\t}\n\n\treturn preflight.RunChecks(migrationChecks, os.Stderr, ignorePreflightErrors)\n}\n\n\/\/ checkUnsupportedPlugins checks if there are any plugins included in the current configuration\n\/\/ that are unsupported for migration.\nfunc checkUnsupportedPlugins(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if there are any unsupported CoreDNS plugins in the Corefile\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tunsupportedCoreDNS, err := migration.Unsupported(currentInstalledCoreDNSversion, currentInstalledCoreDNSversion, corefile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(unsupportedCoreDNS) != 0 {\n\t\tvar UnsupportedPlugins []string\n\t\tfor _, unsup := range unsupportedCoreDNS {\n\t\t\tUnsupportedPlugins = append(UnsupportedPlugins, unsup.ToString())\n\t\t}\n\t\tfmt.Println(\"[preflight] The corefile contains plugins that kubeadm\/CoreDNS does not know how to migrate. \" +\n\t\t\t\"Each plugin listed should be manually verified for compatibility with the newer version of CoreDNS. \" +\n\t\t\t\"Once ready, the upgrade can be initiated by skipping the preflight check. During the upgrade, \" +\n\t\t\t\"kubeadm will migrate the configuration while leaving the listed plugin configs untouched, \" +\n\t\t\t\"but cannot guarantee that they will work with the newer version of CoreDNS.\")\n\t\treturn errors.Errorf(\"CoreDNS cannot migrate the following plugins:\\n%s\", UnsupportedPlugins)\n\t}\n\treturn nil\n}\n\n\/\/ checkMigration validates if migration of the current CoreDNS ConfigMap is possible.\nfunc checkMigration(client clientset.Interface) error {\n\tklog.V(1).Infoln(\"validating if migration can be done for the current CoreDNS release.\")\n\t_, corefile, currentInstalledCoreDNSversion, err := dns.GetCoreDNSInfo(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = migration.Migrate(currentInstalledCoreDNSversion, strings.TrimLeft(kubeadmconstants.CoreDNSVersion, \"v\"), corefile, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"CoreDNS will not be upgraded\")\n\t}\n\treturn nil\n}\n\n\/\/ checkKubeDNSConfigMap checks if the translation of kube-dns to CoreDNS ConfigMap is supported\nfunc checkKubeDNSConfigMap(client clientset.Interface) error {\n\tkubeDNSConfigMap, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(context.TODO(), kubeadmconstants.KubeDNSConfigMap, metav1.GetOptions{})\n\tif err != nil {\n\t\tif apierrors.IsNotFound(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif _, ok := kubeDNSConfigMap.Data[\"federations\"]; ok {\n\t\tklog.V(1).Infoln(\"CoreDNS no longer supports Federation and \" +\n\t\t\t\"hence will not translate the federation data from kube-dns to CoreDNS ConfigMap\")\n\t\treturn errors.New(\"kube-dns Federation data will not be translated\")\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"log\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\ntype FHIRServer struct {\n\tDatabaseHost     string\n\tRouter           *mux.Router\n\tMiddlewareConfig map[string][]negroni.Handler\n}\n\nfunc (f *FHIRServer) AddMiddleware(key string, middleware negroni.Handler) {\n\tf.MiddlewareConfig[key] = append(f.MiddlewareConfig[key], middleware)\n}\n\nfunc (f *FHIRServer) Run() {\n\tvar err error\n\n\t\/\/ Setup the database\n\tif MongoSession, err = mgo.Dial(f.DatabaseHost); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"Connected to mongodb\")\n\tdefer MongoSession.Close()\n\n\tDatabase = MongoSession.DB(\"fhir\")\n\tf.Router = mux.NewRouter()\n\tf.Router.StrictSlash(true)\n\tf.Router.KeepContext = true\n\n\tRegisterRoutes(f.Router, f.MiddlewareConfig)\n\n\tn := negroni.Classic()\n\t\/\/ for _, m := range f.Middleware {\n\t\/\/ \tn.Use(m)\n\t\/\/ }\n\tn.UseHandler(f.Router)\n\tn.Run(\":3001\")\n}\n<commit_msg>Creating a constructor for the FHIRServer<commit_after>package server\n\nimport (\n\t\"log\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\ntype FHIRServer struct {\n\tDatabaseHost     string\n\tRouter           *mux.Router\n\tMiddlewareConfig map[string][]negroni.Handler\n}\n\nfunc (f *FHIRServer) AddMiddleware(key string, middleware negroni.Handler) {\n\tf.MiddlewareConfig[key] = append(f.MiddlewareConfig[key], middleware)\n}\n\nfunc NewServer(databaseHost string) *FHIRServer {\n\tserver := &FHIRServer{DatabaseHost: databaseHost, MiddlewareConfig: make(map[string][]negroni.Handler)}\n\tserver.Router = mux.NewRouter()\n\tserver.Router.StrictSlash(true)\n\tserver.Router.KeepContext = true\n\treturn server\n}\n\nfunc (f *FHIRServer) Run() {\n\tvar err error\n\n\t\/\/ Setup the database\n\tif MongoSession, err = mgo.Dial(f.DatabaseHost); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Println(\"Connected to mongodb\")\n\tdefer MongoSession.Close()\n\n\tDatabase = MongoSession.DB(\"fhir\")\n\n\tRegisterRoutes(f.Router, f.MiddlewareConfig)\n\n\tn := negroni.Classic()\n\t\/\/ for _, m := range f.Middleware {\n\t\/\/ \tn.Use(m)\n\t\/\/ }\n\tn.UseHandler(f.Router)\n\tn.Run(\":3001\")\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\n\/\/ Package app does all of the work necessary to create a Kubernetes\n\/\/ APIServer by binding together the API, master and APIServer infrastructure.\n\/\/ It can be configured and called directly or via the hyperkube cache.\npackage app\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\n\t\"k8s.io\/kubernetes\/federation\/cmd\/federation-apiserver\/app\/options\"\n\t\"k8s.io\/kubernetes\/pkg\/admission\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/apiserver\/authenticator\"\n\tauthorizerunion \"k8s.io\/kubernetes\/pkg\/auth\/authorizer\/union\"\n\t\"k8s.io\/kubernetes\/pkg\/auth\/user\"\n\t\"k8s.io\/kubernetes\/pkg\/controller\/informers\"\n\t\"k8s.io\/kubernetes\/pkg\/generated\/openapi\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\/authorizer\"\n\tgenericvalidation \"k8s.io\/kubernetes\/pkg\/genericapiserver\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/cachesize\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\/registry\"\n\t\"k8s.io\/kubernetes\/pkg\/routes\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n\t\"k8s.io\/kubernetes\/pkg\/version\"\n\tauthenticatorunion \"k8s.io\/kubernetes\/plugin\/pkg\/auth\/authenticator\/request\/union\"\n)\n\n\/\/ NewAPIServerCommand creates a *cobra.Command object with default parameters\nfunc NewAPIServerCommand() *cobra.Command {\n\ts := options.NewServerRunOptions()\n\ts.AddFlags(pflag.CommandLine)\n\tcmd := &cobra.Command{\n\t\tUse: \"federation-apiserver\",\n\t\tLong: `The Kubernetes federation API server validates and configures data\nfor the api objects which include pods, services, replicationcontrollers, and\nothers. The API Server services REST operations and provides the frontend to the\ncluster's shared state through which all other components interact.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t},\n\t}\n\treturn cmd\n}\n\n\/\/ Run runs the specified APIServer.  This should never exit.\nfunc Run(s *options.ServerRunOptions) error {\n\tgenericvalidation.VerifyEtcdServersList(s.ServerRunOptions)\n\tgenericapiserver.DefaultAndValidateRunOptions(s.ServerRunOptions)\n\tgenericConfig := genericapiserver.NewConfig(). \/\/ create the new config\n\t\t\t\t\t\t\tApplyOptions(s.ServerRunOptions). \/\/ apply the options selected\n\t\t\t\t\t\t\tComplete()                        \/\/ set default values based on the known values\n\n\tif err := genericConfig.MaybeGenerateServingCerts(); err != nil {\n\t\tglog.Fatalf(\"Failed to generate service certificate: %v\", err)\n\t}\n\n\t\/\/ TODO: register cluster federation resources here.\n\tresourceConfig := genericapiserver.NewResourceConfig()\n\n\tif s.StorageConfig.DeserializationCacheSize == 0 {\n\t\t\/\/ When size of cache is not explicitly set, set it to 50000\n\t\ts.StorageConfig.DeserializationCacheSize = 50000\n\t}\n\tstorageGroupsToEncodingVersion, err := s.StorageGroupsToEncodingVersion()\n\tif err != nil {\n\t\tglog.Fatalf(\"error generating storage version map: %s\", err)\n\t}\n\tstorageFactory, err := genericapiserver.BuildDefaultStorageFactory(\n\t\ts.StorageConfig, s.DefaultStorageMediaType, api.Codecs,\n\t\tgenericapiserver.NewDefaultResourceEncodingConfig(), storageGroupsToEncodingVersion,\n\t\t[]unversioned.GroupVersionResource{}, resourceConfig, s.RuntimeConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"error in initializing storage factory: %s\", err)\n\t}\n\n\tfor _, override := range s.EtcdServersOverrides {\n\t\ttokens := strings.Split(override, \"#\")\n\t\tif len(tokens) != 2 {\n\t\t\tglog.Errorf(\"invalid value of etcd server overrides: %s\", override)\n\t\t\tcontinue\n\t\t}\n\n\t\tapiresource := strings.Split(tokens[0], \"\/\")\n\t\tif len(apiresource) != 2 {\n\t\t\tglog.Errorf(\"invalid resource definition: %s\", tokens[0])\n\t\t\tcontinue\n\t\t}\n\t\tgroup := apiresource[0]\n\t\tresource := apiresource[1]\n\t\tgroupResource := unversioned.GroupResource{Group: group, Resource: resource}\n\n\t\tservers := strings.Split(tokens[1], \";\")\n\t\tstorageFactory.SetEtcdLocation(groupResource, servers)\n\t}\n\n\tapiAuthenticator, securityDefinitions, err := authenticator.New(authenticator.AuthenticatorConfig{\n\t\tAnonymous:         s.AnonymousAuth,\n\t\tAnyToken:          s.EnableAnyToken,\n\t\tBasicAuthFile:     s.BasicAuthFile,\n\t\tClientCAFile:      s.ClientCAFile,\n\t\tTokenAuthFile:     s.TokenAuthFile,\n\t\tOIDCIssuerURL:     s.OIDCIssuerURL,\n\t\tOIDCClientID:      s.OIDCClientID,\n\t\tOIDCCAFile:        s.OIDCCAFile,\n\t\tOIDCUsernameClaim: s.OIDCUsernameClaim,\n\t\tOIDCGroupsClaim:   s.OIDCGroupsClaim,\n\t\tKeystoneURL:       s.KeystoneURL,\n\t})\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid Authentication Config: %v\", err)\n\t}\n\n\tprivilegedLoopbackToken := uuid.NewRandom().String()\n\tselfClientConfig, err := s.NewSelfClientConfig(privilegedLoopbackToken)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed to create clientset: %v\", err)\n\t}\n\tclient, err := s.NewSelfClient(privilegedLoopbackToken)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create clientset: %v\", err)\n\t}\n\tsharedInformers := informers.NewSharedInformerFactory(client, 10*time.Minute)\n\n\tauthorizationConfig := authorizer.AuthorizationConfig{\n\t\tPolicyFile:                  s.AuthorizationPolicyFile,\n\t\tWebhookConfigFile:           s.AuthorizationWebhookConfigFile,\n\t\tWebhookCacheAuthorizedTTL:   s.AuthorizationWebhookCacheAuthorizedTTL,\n\t\tWebhookCacheUnauthorizedTTL: s.AuthorizationWebhookCacheUnauthorizedTTL,\n\t\tRBACSuperUser:               s.AuthorizationRBACSuperUser,\n\t\tInformerFactory:             sharedInformers,\n\t}\n\tauthorizationModeNames := strings.Split(s.AuthorizationMode, \",\")\n\tapiAuthorizer, err := authorizer.NewAuthorizerFromAuthorizationConfig(authorizationModeNames, authorizationConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid Authorization Config: %v\", err)\n\t}\n\n\tadmissionControlPluginNames := strings.Split(s.AdmissionControl, \",\")\n\n\t\/\/ TODO(dims): We probably need to add an option \"EnableLoopbackToken\"\n\tif apiAuthenticator != nil {\n\t\tvar uid = uuid.NewRandom().String()\n\t\ttokens := make(map[string]*user.DefaultInfo)\n\t\ttokens[privilegedLoopbackToken] = &user.DefaultInfo{\n\t\t\tName:   user.APIServerUser,\n\t\t\tUID:    uid,\n\t\t\tGroups: []string{user.SystemPrivilegedGroup},\n\t\t}\n\n\t\ttokenAuthenticator := authenticator.NewAuthenticatorFromTokens(tokens)\n\t\tapiAuthenticator = authenticatorunion.New(tokenAuthenticator, apiAuthenticator)\n\n\t\ttokenAuthorizer := authorizer.NewPrivilegedGroups(user.SystemPrivilegedGroup)\n\t\tapiAuthorizer = authorizerunion.New(tokenAuthorizer, apiAuthorizer)\n\t}\n\n\tpluginInitializer := admission.NewPluginInitializer(sharedInformers, apiAuthorizer)\n\n\tadmissionController, err := admission.NewFromPlugins(client, admissionControlPluginNames, s.AdmissionControlConfigFile, pluginInitializer)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed to initialize plugins: %v\", err)\n\t}\n\n\tkubeVersion := version.Get()\n\tgenericConfig.Version = &kubeVersion\n\tgenericConfig.LoopbackClientConfig = selfClientConfig\n\tgenericConfig.Authenticator = apiAuthenticator\n\tgenericConfig.SupportsBasicAuth = len(s.BasicAuthFile) > 0\n\tgenericConfig.Authorizer = apiAuthorizer\n\tgenericConfig.AuthorizerRBACSuperUser = s.AuthorizationRBACSuperUser\n\tgenericConfig.AdmissionControl = admissionController\n\tgenericConfig.APIResourceConfigSource = storageFactory.APIResourceConfigSource\n\tgenericConfig.MasterServiceNamespace = s.MasterServiceNamespace\n\tgenericConfig.OpenAPIConfig.Definitions = openapi.OpenAPIDefinitions\n\tgenericConfig.EnableOpenAPISupport = true\n\tgenericConfig.OpenAPIConfig.SecurityDefinitions = securityDefinitions\n\n\t\/\/ TODO: Move this to generic api server (Need to move the command line flag).\n\tif s.EnableWatchCache {\n\t\tcachesize.InitializeWatchCacheSizes(s.TargetRAMMB)\n\t\tcachesize.SetWatchCacheSizes(s.WatchCacheSizes)\n\t}\n\n\tm, err := genericConfig.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troutes.UIRedirect{}.Install(m.HandlerContainer)\n\troutes.Logs{}.Install(m.HandlerContainer)\n\n\trestOptionsFactory := restOptionsFactory{\n\t\tstorageFactory:          storageFactory,\n\t\tdeleteCollectionWorkers: s.DeleteCollectionWorkers,\n\t}\n\tif s.EnableWatchCache {\n\t\trestOptionsFactory.storageDecorator = registry.StorageWithCacher\n\t} else {\n\t\trestOptionsFactory.storageDecorator = generic.UndecoratedStorage\n\t}\n\n\tinstallFederationAPIs(m, restOptionsFactory)\n\tinstallCoreAPIs(s, m, restOptionsFactory)\n\tinstallExtensionsAPIs(m, restOptionsFactory)\n\n\tsharedInformers.Start(wait.NeverStop)\n\tm.PrepareRun().Run()\n\treturn nil\n}\n\ntype restOptionsFactory struct {\n\tstorageFactory          genericapiserver.StorageFactory\n\tstorageDecorator        generic.StorageDecorator\n\tdeleteCollectionWorkers int\n}\n\nfunc (f restOptionsFactory) NewFor(resource unversioned.GroupResource) generic.RESTOptions {\n\tconfig, err := f.storageFactory.NewConfig(resource)\n\tif err != nil {\n\t\tglog.Fatalf(\"Unable to find storage config for %v, due to %v\", resource, err.Error())\n\t}\n\treturn generic.RESTOptions{\n\t\tStorageConfig:           config,\n\t\tDecorator:               f.storageDecorator,\n\t\tDeleteCollectionWorkers: f.deleteCollectionWorkers,\n\t\tResourcePrefix:          f.storageFactory.ResourcePrefix(resource),\n\t}\n}\n<commit_msg>wire up authenticating front proxy:<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\n\/\/ Package app does all of the work necessary to create a Kubernetes\n\/\/ APIServer by binding together the API, master and APIServer infrastructure.\n\/\/ It can be configured and called directly or via the hyperkube cache.\npackage app\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\n\t\"k8s.io\/kubernetes\/federation\/cmd\/federation-apiserver\/app\/options\"\n\t\"k8s.io\/kubernetes\/pkg\/admission\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/apiserver\/authenticator\"\n\tauthorizerunion \"k8s.io\/kubernetes\/pkg\/auth\/authorizer\/union\"\n\t\"k8s.io\/kubernetes\/pkg\/auth\/user\"\n\t\"k8s.io\/kubernetes\/pkg\/controller\/informers\"\n\t\"k8s.io\/kubernetes\/pkg\/generated\/openapi\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\"\n\t\"k8s.io\/kubernetes\/pkg\/genericapiserver\/authorizer\"\n\tgenericvalidation \"k8s.io\/kubernetes\/pkg\/genericapiserver\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/cachesize\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/generic\/registry\"\n\t\"k8s.io\/kubernetes\/pkg\/routes\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n\t\"k8s.io\/kubernetes\/pkg\/version\"\n\tauthenticatorunion \"k8s.io\/kubernetes\/plugin\/pkg\/auth\/authenticator\/request\/union\"\n)\n\n\/\/ NewAPIServerCommand creates a *cobra.Command object with default parameters\nfunc NewAPIServerCommand() *cobra.Command {\n\ts := options.NewServerRunOptions()\n\ts.AddFlags(pflag.CommandLine)\n\tcmd := &cobra.Command{\n\t\tUse: \"federation-apiserver\",\n\t\tLong: `The Kubernetes federation API server validates and configures data\nfor the api objects which include pods, services, replicationcontrollers, and\nothers. The API Server services REST operations and provides the frontend to the\ncluster's shared state through which all other components interact.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t},\n\t}\n\treturn cmd\n}\n\n\/\/ Run runs the specified APIServer.  This should never exit.\nfunc Run(s *options.ServerRunOptions) error {\n\tgenericvalidation.VerifyEtcdServersList(s.ServerRunOptions)\n\tgenericapiserver.DefaultAndValidateRunOptions(s.ServerRunOptions)\n\tgenericConfig := genericapiserver.NewConfig(). \/\/ create the new config\n\t\t\t\t\t\t\tApplyOptions(s.ServerRunOptions). \/\/ apply the options selected\n\t\t\t\t\t\t\tComplete()                        \/\/ set default values based on the known values\n\n\tif err := genericConfig.MaybeGenerateServingCerts(); err != nil {\n\t\tglog.Fatalf(\"Failed to generate service certificate: %v\", err)\n\t}\n\n\t\/\/ TODO: register cluster federation resources here.\n\tresourceConfig := genericapiserver.NewResourceConfig()\n\n\tif s.StorageConfig.DeserializationCacheSize == 0 {\n\t\t\/\/ When size of cache is not explicitly set, set it to 50000\n\t\ts.StorageConfig.DeserializationCacheSize = 50000\n\t}\n\tstorageGroupsToEncodingVersion, err := s.StorageGroupsToEncodingVersion()\n\tif err != nil {\n\t\tglog.Fatalf(\"error generating storage version map: %s\", err)\n\t}\n\tstorageFactory, err := genericapiserver.BuildDefaultStorageFactory(\n\t\ts.StorageConfig, s.DefaultStorageMediaType, api.Codecs,\n\t\tgenericapiserver.NewDefaultResourceEncodingConfig(), storageGroupsToEncodingVersion,\n\t\t[]unversioned.GroupVersionResource{}, resourceConfig, s.RuntimeConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"error in initializing storage factory: %s\", err)\n\t}\n\n\tfor _, override := range s.EtcdServersOverrides {\n\t\ttokens := strings.Split(override, \"#\")\n\t\tif len(tokens) != 2 {\n\t\t\tglog.Errorf(\"invalid value of etcd server overrides: %s\", override)\n\t\t\tcontinue\n\t\t}\n\n\t\tapiresource := strings.Split(tokens[0], \"\/\")\n\t\tif len(apiresource) != 2 {\n\t\t\tglog.Errorf(\"invalid resource definition: %s\", tokens[0])\n\t\t\tcontinue\n\t\t}\n\t\tgroup := apiresource[0]\n\t\tresource := apiresource[1]\n\t\tgroupResource := unversioned.GroupResource{Group: group, Resource: resource}\n\n\t\tservers := strings.Split(tokens[1], \";\")\n\t\tstorageFactory.SetEtcdLocation(groupResource, servers)\n\t}\n\n\tapiAuthenticator, securityDefinitions, err := authenticator.New(authenticator.AuthenticatorConfig{\n\t\tAnonymous:           s.AnonymousAuth,\n\t\tAnyToken:            s.EnableAnyToken,\n\t\tBasicAuthFile:       s.BasicAuthFile,\n\t\tClientCAFile:        s.ClientCAFile,\n\t\tTokenAuthFile:       s.TokenAuthFile,\n\t\tOIDCIssuerURL:       s.OIDCIssuerURL,\n\t\tOIDCClientID:        s.OIDCClientID,\n\t\tOIDCCAFile:          s.OIDCCAFile,\n\t\tOIDCUsernameClaim:   s.OIDCUsernameClaim,\n\t\tOIDCGroupsClaim:     s.OIDCGroupsClaim,\n\t\tKeystoneURL:         s.KeystoneURL,\n\t\tRequestHeaderConfig: s.AuthenticationRequestHeaderConfig(),\n\t})\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid Authentication Config: %v\", err)\n\t}\n\n\tprivilegedLoopbackToken := uuid.NewRandom().String()\n\tselfClientConfig, err := s.NewSelfClientConfig(privilegedLoopbackToken)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed to create clientset: %v\", err)\n\t}\n\tclient, err := s.NewSelfClient(privilegedLoopbackToken)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create clientset: %v\", err)\n\t}\n\tsharedInformers := informers.NewSharedInformerFactory(client, 10*time.Minute)\n\n\tauthorizationConfig := authorizer.AuthorizationConfig{\n\t\tPolicyFile:                  s.AuthorizationPolicyFile,\n\t\tWebhookConfigFile:           s.AuthorizationWebhookConfigFile,\n\t\tWebhookCacheAuthorizedTTL:   s.AuthorizationWebhookCacheAuthorizedTTL,\n\t\tWebhookCacheUnauthorizedTTL: s.AuthorizationWebhookCacheUnauthorizedTTL,\n\t\tRBACSuperUser:               s.AuthorizationRBACSuperUser,\n\t\tInformerFactory:             sharedInformers,\n\t}\n\tauthorizationModeNames := strings.Split(s.AuthorizationMode, \",\")\n\tapiAuthorizer, err := authorizer.NewAuthorizerFromAuthorizationConfig(authorizationModeNames, authorizationConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid Authorization Config: %v\", err)\n\t}\n\n\tadmissionControlPluginNames := strings.Split(s.AdmissionControl, \",\")\n\n\t\/\/ TODO(dims): We probably need to add an option \"EnableLoopbackToken\"\n\tif apiAuthenticator != nil {\n\t\tvar uid = uuid.NewRandom().String()\n\t\ttokens := make(map[string]*user.DefaultInfo)\n\t\ttokens[privilegedLoopbackToken] = &user.DefaultInfo{\n\t\t\tName:   user.APIServerUser,\n\t\t\tUID:    uid,\n\t\t\tGroups: []string{user.SystemPrivilegedGroup},\n\t\t}\n\n\t\ttokenAuthenticator := authenticator.NewAuthenticatorFromTokens(tokens)\n\t\tapiAuthenticator = authenticatorunion.New(tokenAuthenticator, apiAuthenticator)\n\n\t\ttokenAuthorizer := authorizer.NewPrivilegedGroups(user.SystemPrivilegedGroup)\n\t\tapiAuthorizer = authorizerunion.New(tokenAuthorizer, apiAuthorizer)\n\t}\n\n\tpluginInitializer := admission.NewPluginInitializer(sharedInformers, apiAuthorizer)\n\n\tadmissionController, err := admission.NewFromPlugins(client, admissionControlPluginNames, s.AdmissionControlConfigFile, pluginInitializer)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed to initialize plugins: %v\", err)\n\t}\n\n\tkubeVersion := version.Get()\n\tgenericConfig.Version = &kubeVersion\n\tgenericConfig.LoopbackClientConfig = selfClientConfig\n\tgenericConfig.Authenticator = apiAuthenticator\n\tgenericConfig.SupportsBasicAuth = len(s.BasicAuthFile) > 0\n\tgenericConfig.Authorizer = apiAuthorizer\n\tgenericConfig.AuthorizerRBACSuperUser = s.AuthorizationRBACSuperUser\n\tgenericConfig.AdmissionControl = admissionController\n\tgenericConfig.APIResourceConfigSource = storageFactory.APIResourceConfigSource\n\tgenericConfig.MasterServiceNamespace = s.MasterServiceNamespace\n\tgenericConfig.OpenAPIConfig.Definitions = openapi.OpenAPIDefinitions\n\tgenericConfig.EnableOpenAPISupport = true\n\tgenericConfig.OpenAPIConfig.SecurityDefinitions = securityDefinitions\n\n\t\/\/ TODO: Move this to generic api server (Need to move the command line flag).\n\tif s.EnableWatchCache {\n\t\tcachesize.InitializeWatchCacheSizes(s.TargetRAMMB)\n\t\tcachesize.SetWatchCacheSizes(s.WatchCacheSizes)\n\t}\n\n\tm, err := genericConfig.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\troutes.UIRedirect{}.Install(m.HandlerContainer)\n\troutes.Logs{}.Install(m.HandlerContainer)\n\n\trestOptionsFactory := restOptionsFactory{\n\t\tstorageFactory:          storageFactory,\n\t\tdeleteCollectionWorkers: s.DeleteCollectionWorkers,\n\t}\n\tif s.EnableWatchCache {\n\t\trestOptionsFactory.storageDecorator = registry.StorageWithCacher\n\t} else {\n\t\trestOptionsFactory.storageDecorator = generic.UndecoratedStorage\n\t}\n\n\tinstallFederationAPIs(m, restOptionsFactory)\n\tinstallCoreAPIs(s, m, restOptionsFactory)\n\tinstallExtensionsAPIs(m, restOptionsFactory)\n\n\tsharedInformers.Start(wait.NeverStop)\n\tm.PrepareRun().Run()\n\treturn nil\n}\n\ntype restOptionsFactory struct {\n\tstorageFactory          genericapiserver.StorageFactory\n\tstorageDecorator        generic.StorageDecorator\n\tdeleteCollectionWorkers int\n}\n\nfunc (f restOptionsFactory) NewFor(resource unversioned.GroupResource) generic.RESTOptions {\n\tconfig, err := f.storageFactory.NewConfig(resource)\n\tif err != nil {\n\t\tglog.Fatalf(\"Unable to find storage config for %v, due to %v\", resource, err.Error())\n\t}\n\treturn generic.RESTOptions{\n\t\tStorageConfig:           config,\n\t\tDecorator:               f.storageDecorator,\n\t\tDeleteCollectionWorkers: f.deleteCollectionWorkers,\n\t\tResourcePrefix:          f.storageFactory.ResourcePrefix(resource),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/kisielk\/whisper-go\/whisper\"\n\t\"github.com\/raintank\/dur\"\n\t\"github.com\/raintank\/metrictank\/api\"\n\t\"github.com\/raintank\/metrictank\/mdata\"\n\t\"github.com\/raintank\/metrictank\/mdata\/chunk\"\n\t\"github.com\/raintank\/metrictank\/mdata\/chunk\/archive\"\n\t\"gopkg.in\/raintank\/schema.v1\"\n)\n\nvar (\n\texitOnError = flag.Bool(\n\t\t\"exit-on-error\",\n\t\ttrue,\n\t\t\"Exit with a message when there's an error\",\n\t)\n\tverbose = flag.Bool(\n\t\t\"verbose\",\n\t\tfalse,\n\t\t\"Write logs to terminal\",\n\t)\n\thttpEndpoint = flag.String(\n\t\t\"http-endpoint\",\n\t\t\"http:\/\/127.0.0.1:8080\/chunks\",\n\t\t\"The http endpoint to send the data to\",\n\t)\n\tchunkSpanStr = flag.String(\n\t\t\"chunkspans\",\n\t\t\"10min\",\n\t\t\"List of chunk spans separated by ':'. The 1st whisper archive gets the 1st span, 2nd the 2nd, etc\",\n\t)\n\tnamePrefix = flag.String(\n\t\t\"name-prefix\",\n\t\t\"\",\n\t\t\"Prefix to prepend before every metric name, should include the '.' if necessary\",\n\t)\n\tthreads = flag.Int(\n\t\t\"threads\",\n\t\t10,\n\t\t\"Number of workers threads to process .wsp files\",\n\t)\n\tskipUnfinishedChunks = flag.Bool(\n\t\t\"skip-unfinished-chunks\",\n\t\ttrue,\n\t\t\"Chunks that have not completed their chunk span should be skipped\",\n\t)\n\torgId = flag.Int(\n\t\t\"orgid\",\n\t\t1,\n\t\t\"Organization ID the data belongs to \",\n\t)\n\twhisperDirectory = flag.String(\n\t\t\"whisper-directory\",\n\t\t\"\/opt\/graphite\/storage\/whisper\",\n\t\t\"The directory that contains the whisper file structure\",\n\t)\n\treadArchivesStr = flag.String(\n\t\t\"read-archives\",\n\t\t\"*\",\n\t\t\"Comma separated list of positive integers or '*' for all archives\",\n\t)\n\tchunkSpans   []uint32\n\treadArchives map[int]struct{}\n\tprintLock    sync.Mutex\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tfor _, chunkSpanStrSplit := range strings.Split(*chunkSpanStr, \":\") {\n\t\tchunkSpan := dur.MustParseUNsec(\"chunkspan\", chunkSpanStrSplit)\n\n\t\tif (mdata.Month_sec % chunkSpan) != 0 {\n\t\t\tpanic(\"chunkSpan must fit without remainders into month_sec (28*24*60*60)\")\n\t\t}\n\n\t\t_, ok := chunk.RevChunkSpans[chunkSpan]\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"chunkSpan %d is not a valid value (https:\/\/github.com\/raintank\/metrictank\/blob\/master\/docs\/memory-server.md#valid-chunk-spans)\", chunkSpan))\n\t\t}\n\n\t\tchunkSpans = append(chunkSpans, chunkSpan)\n\t}\n\n\tif *readArchivesStr != \"*\" {\n\t\treadArchives = make(map[int]struct{})\n\t\tfor _, archiveIdStr := range strings.Split(*readArchivesStr, \",\") {\n\t\t\tarchiveId, err := strconv.Atoi(archiveIdStr)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Invalid archive id %q: %q\", archiveIdStr, err))\n\t\t\t}\n\t\t\treadArchives[archiveId] = struct{}{}\n\t\t}\n\t}\n\n\tfileChan := make(chan string)\n\n\twg := &sync.WaitGroup{}\n\tfor i := 0; i < *threads; i++ {\n\t\tgo processFromChan(fileChan, wg)\n\t}\n\n\tgetFileListIntoChan(fileChan, wg)\n\twg.Wait()\n}\n\nfunc throwError(msg string) {\n\tmsg = fmt.Sprintf(\"%s\\n\", msg)\n\tif *exitOnError {\n\t\tpanic(msg)\n\t} else {\n\t\tprintLock.Lock()\n\t\tfmt.Fprintln(os.Stderr, msg)\n\t\tprintLock.Unlock()\n\t}\n}\n\nfunc log(msg string) {\n\tif *verbose {\n\t\tprintLock.Lock()\n\t\tfmt.Println(msg)\n\t\tprintLock.Unlock()\n\t}\n}\n\nfunc processFromChan(files chan string, wg *sync.WaitGroup) {\n\tclient := &http.Client{}\n\n\tfor file := range files {\n\t\tfd, err := os.Open(file)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"ERROR: Failed to open whisper file '%q': %q\\n\", file, err))\n\t\t\tcontinue\n\t\t}\n\t\tw, err := whisper.OpenWhisper(fd)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"ERROR: Failed to open whisper file '%q': %q\\n\", file, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tlog(fmt.Sprintf(\"Processing file %q\", file))\n\t\tmet, err := getMetric(w, file)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Failed to get metric: %q\", err))\n\t\t\tcontinue\n\t\t}\n\t\tb, err := met.Encode()\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Failed to encode metric: %q\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\treq, err := http.NewRequest(\"POST\", *httpEndpoint, b)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Cannot construct request to http endpoint %q: %q\", *httpEndpoint, err))\n\t\t}\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\treq.Header.Set(\"Content-Encoding\", \"gzip\")\n\n\t\t_, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Error sending request to http endpoint %q: %q\", *httpEndpoint, err))\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Done()\n\t}\n}\n\n\/\/ generate the metric name based on the file name and given prefix\nfunc getMetricName(file string) string {\n\t\/\/ remove all leading '\/' from file name\n\tfor file[0] == '\/' {\n\t\tfile = file[1:]\n\t}\n\tsplits := strings.Split(file, \"\/\")\n\n\t\/\/ remove the .wsp from the name of the last path element\n\tleafNode := strings.Split(splits[len(splits)-1], \".\")\n\tsplits[len(splits)-1] = strings.Join(leafNode[:len(leafNode)-1], \".\")\n\n\t\/\/ prepend the prefix and concatenate with all the parts of the file name joined by .\n\treturn *namePrefix + strings.Join(splits, \".\")\n}\n\n\/\/ pointSorter sorts points by timestamp\ntype pointSorter []whisper.Point\n\nfunc (a pointSorter) Len() int           { return len(a) }\nfunc (a pointSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a pointSorter) Less(i, j int) bool { return a[i].Timestamp < a[j].Timestamp }\n\n\/\/ the whisper archives are organized like a ringbuffer. since we need to\n\/\/ insert the points into the chunks in order we first need to sort them\nfunc sortPoints(points pointSorter) pointSorter {\n\tsort.Sort(points)\n\treturn points\n}\n\nfunc getMetric(w *whisper.Whisper, file string) (*archive.Metric, error) {\n\tif len(w.Header.Archives) == 0 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Whisper file contains no archives: %q\", file))\n\t}\n\n\tarchives := make([]archive.Archive, 0, len(w.Header.Archives))\n\tvar chunkSpan uint32\n\tvar rowKey string\n\tname := getMetricName(file)\n\n\t\/\/ md gets generated from the first archive in the whisper file\n\tmd := getMetricData(name, int(w.Header.Archives[0].SecondsPerPoint))\n\n\tfor archiveIdx, archiveInfo := range w.Header.Archives {\n\t\tif archiveIdx > 0 {\n\t\t\trowKey = api.AggMetricKey(\n\t\t\t\tmd.Id,\n\t\t\t\tw.Header.Metadata.AggregationMethod.String(),\n\t\t\t\tarchiveInfo.SecondsPerPoint,\n\t\t\t)\n\t\t} else {\n\t\t\trowKey = md.Id\n\t\t}\n\n\t\t\/\/ only read archive if archiveIdx is in readArchives\n\t\tif _, ok := readArchives[archiveIdx]; !ok && len(readArchives) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tencodedChunks := make(archive.ArchiveOfChunks)\n\n\t\tif len(chunkSpans)-1 < archiveIdx {\n\t\t\t\/\/ if we have more archives than chunk spans are specified, we simply use the last one\n\t\t\tchunkSpan = chunkSpans[len(chunkSpans)-1]\n\t\t} else {\n\t\t\tchunkSpan = chunkSpans[archiveIdx]\n\t\t}\n\n\t\tpoints, err := w.DumpArchive(archiveIdx)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Failed to read archive %d in %q, skipping: %q\", archiveIdx, file, err))\n\t\t}\n\n\t\tvar point whisper.Point\n\t\tvar t0, prevT0 uint32\n\t\tvar c *chunk.Chunk\n\n\t\tfor _, point = range sortPoints(points) {\n\t\t\tif point.Timestamp == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tt0 = point.Timestamp - (point.Timestamp % chunkSpan)\n\t\t\tif prevT0 == 0 {\n\t\t\t\tlog(fmt.Sprintf(\"Create new chunk at t0: %d\", t0))\n\t\t\t\tc = chunk.New(t0)\n\t\t\t\tprevT0 = t0\n\t\t\t} else if prevT0 != t0 {\n\t\t\t\tlog(fmt.Sprintf(\"Mark chunk at t0 %d as finished\", prevT0))\n\t\t\t\tc.Finish()\n\n\t\t\t\tencodedChunks[c.T0] = archive.MetricChunk{\n\t\t\t\t\tChunkSpan: chunkSpan,\n\t\t\t\t\tBytes:     c.Series.Bytes(),\n\t\t\t\t}\n\n\t\t\t\tlog(fmt.Sprintf(\"Create new chunk at t0: %d\", t0))\n\t\t\t\tc = chunk.New(t0)\n\t\t\t\tprevT0 = t0\n\t\t\t}\n\n\t\t\terr := c.Push(point.Timestamp, point.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Failed to push value into chunk at t0 %d: %q\", t0, err))\n\t\t\t}\n\t\t}\n\n\t\tif int64(point.Timestamp) > md.Time {\n\t\t\tmd.Time = int64(point.Timestamp)\n\t\t}\n\n\t\t\/\/ if the last written point was also the last one of the current chunk,\n\t\t\/\/ or if skipUnfinishedChunks is on, we close the chunk and\n\t\tif point.Timestamp == t0+chunkSpan-archiveInfo.SecondsPerPoint || !*skipUnfinishedChunks {\n\t\t\tlog(fmt.Sprintf(\"Mark current (last) chunk at t0 %d as finished\", t0))\n\t\t\tc.Finish()\n\t\t\tencodedChunks[c.T0] = archive.MetricChunk{\n\t\t\t\tChunkSpan: chunkSpan,\n\t\t\t\tBytes:     c.Series.Bytes(),\n\t\t\t}\n\t\t}\n\n\t\tlog(fmt.Sprintf(\"Whisper file %q archive %d (%q) gets %d chunks\", file, archiveIdx, name, len(encodedChunks)))\n\t\tarchives = append(archives, archive.Archive{\n\t\t\tArchiveInfo: archiveInfo,\n\t\t\tChunks:      encodedChunks,\n\t\t\tRowKey:      rowKey,\n\t\t})\n\t}\n\n\treturn &archive.Metric{\n\t\tMetadata:   w.Header.Metadata,\n\t\tMetricData: *md,\n\t\tArchives:   archives,\n\t}, nil\n}\n\nfunc getMetricData(name string, interval int) *schema.MetricData {\n\tmd := &schema.MetricData{\n\t\tName:     name,\n\t\tMetric:   name,\n\t\tInterval: interval,\n\t\tValue:    0,\n\t\tUnit:     \"unknown\",\n\t\tTime:     0,\n\t\tMtype:    \"gauge\",\n\t\tTags:     []string{},\n\t\tOrgId:    *orgId,\n\t}\n\tmd.SetId()\n\treturn md\n}\n\n\/\/ scan a directory and feed the list of whisper files relative to base into the given channel\nfunc getFileListIntoChan(fileChan chan string, wg *sync.WaitGroup) {\n\n\tfilepath.Walk(\n\t\t*whisperDirectory,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif path[len(path)-4:] == \".wsp\" {\n\t\t\t\twg.Add(1)\n\t\t\t\tfileChan <- path\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\n\tclose(fileChan)\n}\n<commit_msg>use waitgroup in a better way<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/kisielk\/whisper-go\/whisper\"\n\t\"github.com\/raintank\/dur\"\n\t\"github.com\/raintank\/metrictank\/api\"\n\t\"github.com\/raintank\/metrictank\/mdata\"\n\t\"github.com\/raintank\/metrictank\/mdata\/chunk\"\n\t\"github.com\/raintank\/metrictank\/mdata\/chunk\/archive\"\n\t\"gopkg.in\/raintank\/schema.v1\"\n)\n\nvar (\n\texitOnError = flag.Bool(\n\t\t\"exit-on-error\",\n\t\ttrue,\n\t\t\"Exit with a message when there's an error\",\n\t)\n\tverbose = flag.Bool(\n\t\t\"verbose\",\n\t\tfalse,\n\t\t\"Write logs to terminal\",\n\t)\n\thttpEndpoint = flag.String(\n\t\t\"http-endpoint\",\n\t\t\"http:\/\/127.0.0.1:8080\/chunks\",\n\t\t\"The http endpoint to send the data to\",\n\t)\n\tchunkSpanStr = flag.String(\n\t\t\"chunkspans\",\n\t\t\"10min\",\n\t\t\"List of chunk spans separated by ':'. The 1st whisper archive gets the 1st span, 2nd the 2nd, etc\",\n\t)\n\tnamePrefix = flag.String(\n\t\t\"name-prefix\",\n\t\t\"\",\n\t\t\"Prefix to prepend before every metric name, should include the '.' if necessary\",\n\t)\n\tthreads = flag.Int(\n\t\t\"threads\",\n\t\t10,\n\t\t\"Number of workers threads to process .wsp files\",\n\t)\n\tskipUnfinishedChunks = flag.Bool(\n\t\t\"skip-unfinished-chunks\",\n\t\ttrue,\n\t\t\"Chunks that have not completed their chunk span should be skipped\",\n\t)\n\torgId = flag.Int(\n\t\t\"orgid\",\n\t\t1,\n\t\t\"Organization ID the data belongs to \",\n\t)\n\twhisperDirectory = flag.String(\n\t\t\"whisper-directory\",\n\t\t\"\/opt\/graphite\/storage\/whisper\",\n\t\t\"The directory that contains the whisper file structure\",\n\t)\n\treadArchivesStr = flag.String(\n\t\t\"read-archives\",\n\t\t\"*\",\n\t\t\"Comma separated list of positive integers or '*' for all archives\",\n\t)\n\tchunkSpans   []uint32\n\treadArchives map[int]struct{}\n\tprintLock    sync.Mutex\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tfor _, chunkSpanStrSplit := range strings.Split(*chunkSpanStr, \":\") {\n\t\tchunkSpan := dur.MustParseUNsec(\"chunkspan\", chunkSpanStrSplit)\n\n\t\tif (mdata.Month_sec % chunkSpan) != 0 {\n\t\t\tpanic(\"chunkSpan must fit without remainders into month_sec (28*24*60*60)\")\n\t\t}\n\n\t\t_, ok := chunk.RevChunkSpans[chunkSpan]\n\t\tif !ok {\n\t\t\tpanic(fmt.Sprintf(\"chunkSpan %d is not a valid value (https:\/\/github.com\/raintank\/metrictank\/blob\/master\/docs\/memory-server.md#valid-chunk-spans)\", chunkSpan))\n\t\t}\n\n\t\tchunkSpans = append(chunkSpans, chunkSpan)\n\t}\n\n\tif *readArchivesStr != \"*\" {\n\t\treadArchives = make(map[int]struct{})\n\t\tfor _, archiveIdStr := range strings.Split(*readArchivesStr, \",\") {\n\t\t\tarchiveId, err := strconv.Atoi(archiveIdStr)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Invalid archive id %q: %q\", archiveIdStr, err))\n\t\t\t}\n\t\t\treadArchives[archiveId] = struct{}{}\n\t\t}\n\t}\n\n\tfileChan := make(chan string)\n\n\twg := &sync.WaitGroup{}\n\twg.Add(*threads)\n\tfor i := 0; i < *threads; i++ {\n\t\tgo processFromChan(fileChan, wg)\n\t}\n\n\tgetFileListIntoChan(fileChan)\n\twg.Wait()\n}\n\nfunc throwError(msg string) {\n\tmsg = fmt.Sprintf(\"%s\\n\", msg)\n\tif *exitOnError {\n\t\tpanic(msg)\n\t} else {\n\t\tprintLock.Lock()\n\t\tfmt.Fprintln(os.Stderr, msg)\n\t\tprintLock.Unlock()\n\t}\n}\n\nfunc log(msg string) {\n\tif *verbose {\n\t\tprintLock.Lock()\n\t\tfmt.Println(msg)\n\t\tprintLock.Unlock()\n\t}\n}\n\nfunc processFromChan(files chan string, wg *sync.WaitGroup) {\n\tclient := &http.Client{}\n\n\tfor {\n\t\tfile, more := <-files\n\t\tif !more {\n\t\t\twg.Done()\n\t\t\treturn\n\t\t}\n\n\t\tfd, err := os.Open(file)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"ERROR: Failed to open whisper file '%q': %q\\n\", file, err))\n\t\t\tcontinue\n\t\t}\n\t\tw, err := whisper.OpenWhisper(fd)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"ERROR: Failed to open whisper file '%q': %q\\n\", file, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tlog(fmt.Sprintf(\"Processing file %q\", file))\n\t\tmet, err := getMetric(w, file)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Failed to get metric: %q\", err))\n\t\t\tcontinue\n\t\t}\n\t\tb, err := met.Encode()\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Failed to encode metric: %q\", err))\n\t\t\tcontinue\n\t\t}\n\n\t\treq, err := http.NewRequest(\"POST\", *httpEndpoint, b)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Cannot construct request to http endpoint %q: %q\", *httpEndpoint, err))\n\t\t}\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\treq.Header.Set(\"Content-Encoding\", \"gzip\")\n\n\t\t_, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tthrowError(fmt.Sprintf(\"Error sending request to http endpoint %q: %q\", *httpEndpoint, err))\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\/\/ generate the metric name based on the file name and given prefix\nfunc getMetricName(file string) string {\n\t\/\/ remove all leading '\/' from file name\n\tfor file[0] == '\/' {\n\t\tfile = file[1:]\n\t}\n\tsplits := strings.Split(file, \"\/\")\n\n\t\/\/ remove the .wsp from the name of the last path element\n\tleafNode := strings.Split(splits[len(splits)-1], \".\")\n\tsplits[len(splits)-1] = strings.Join(leafNode[:len(leafNode)-1], \".\")\n\n\t\/\/ prepend the prefix and concatenate with all the parts of the file name joined by .\n\treturn *namePrefix + strings.Join(splits, \".\")\n}\n\n\/\/ pointSorter sorts points by timestamp\ntype pointSorter []whisper.Point\n\nfunc (a pointSorter) Len() int           { return len(a) }\nfunc (a pointSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a pointSorter) Less(i, j int) bool { return a[i].Timestamp < a[j].Timestamp }\n\n\/\/ the whisper archives are organized like a ringbuffer. since we need to\n\/\/ insert the points into the chunks in order we first need to sort them\nfunc sortPoints(points pointSorter) pointSorter {\n\tsort.Sort(points)\n\treturn points\n}\n\nfunc getMetric(w *whisper.Whisper, file string) (*archive.Metric, error) {\n\tif len(w.Header.Archives) == 0 {\n\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Whisper file contains no archives: %q\", file))\n\t}\n\n\tarchives := make([]archive.Archive, 0, len(w.Header.Archives))\n\tvar chunkSpan uint32\n\tvar rowKey string\n\tname := getMetricName(file)\n\n\t\/\/ md gets generated from the first archive in the whisper file\n\tmd := getMetricData(name, int(w.Header.Archives[0].SecondsPerPoint))\n\n\tfor archiveIdx, archiveInfo := range w.Header.Archives {\n\t\tif archiveIdx > 0 {\n\t\t\trowKey = api.AggMetricKey(\n\t\t\t\tmd.Id,\n\t\t\t\tw.Header.Metadata.AggregationMethod.String(),\n\t\t\t\tarchiveInfo.SecondsPerPoint,\n\t\t\t)\n\t\t} else {\n\t\t\trowKey = md.Id\n\t\t}\n\n\t\t\/\/ only read archive if archiveIdx is in readArchives\n\t\tif _, ok := readArchives[archiveIdx]; !ok && len(readArchives) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tencodedChunks := make(archive.ArchiveOfChunks)\n\n\t\tif len(chunkSpans)-1 < archiveIdx {\n\t\t\t\/\/ if we have more archives than chunk spans are specified, we simply use the last one\n\t\t\tchunkSpan = chunkSpans[len(chunkSpans)-1]\n\t\t} else {\n\t\t\tchunkSpan = chunkSpans[archiveIdx]\n\t\t}\n\n\t\tpoints, err := w.DumpArchive(archiveIdx)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Failed to read archive %d in %q, skipping: %q\", archiveIdx, file, err))\n\t\t}\n\n\t\tvar point whisper.Point\n\t\tvar t0, prevT0 uint32\n\t\tvar c *chunk.Chunk\n\n\t\tfor _, point = range sortPoints(points) {\n\t\t\tif point.Timestamp == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tt0 = point.Timestamp - (point.Timestamp % chunkSpan)\n\t\t\tif prevT0 == 0 {\n\t\t\t\tlog(fmt.Sprintf(\"Create new chunk at t0: %d\", t0))\n\t\t\t\tc = chunk.New(t0)\n\t\t\t\tprevT0 = t0\n\t\t\t} else if prevT0 != t0 {\n\t\t\t\tlog(fmt.Sprintf(\"Mark chunk at t0 %d as finished\", prevT0))\n\t\t\t\tc.Finish()\n\n\t\t\t\tencodedChunks[c.T0] = archive.MetricChunk{\n\t\t\t\t\tChunkSpan: chunkSpan,\n\t\t\t\t\tBytes:     c.Series.Bytes(),\n\t\t\t\t}\n\n\t\t\t\tlog(fmt.Sprintf(\"Create new chunk at t0: %d\", t0))\n\t\t\t\tc = chunk.New(t0)\n\t\t\t\tprevT0 = t0\n\t\t\t}\n\n\t\t\terr := c.Push(point.Timestamp, point.Value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"ERROR: Failed to push value into chunk at t0 %d: %q\", t0, err))\n\t\t\t}\n\t\t}\n\n\t\tif int64(point.Timestamp) > md.Time {\n\t\t\tmd.Time = int64(point.Timestamp)\n\t\t}\n\n\t\t\/\/ if the last written point was also the last one of the current chunk,\n\t\t\/\/ or if skipUnfinishedChunks is on, we close the chunk and\n\t\tif point.Timestamp == t0+chunkSpan-archiveInfo.SecondsPerPoint || !*skipUnfinishedChunks {\n\t\t\tlog(fmt.Sprintf(\"Mark current (last) chunk at t0 %d as finished\", t0))\n\t\t\tc.Finish()\n\t\t\tencodedChunks[c.T0] = archive.MetricChunk{\n\t\t\t\tChunkSpan: chunkSpan,\n\t\t\t\tBytes:     c.Series.Bytes(),\n\t\t\t}\n\t\t}\n\n\t\tlog(fmt.Sprintf(\"Whisper file %q archive %d (%q) gets %d chunks\", file, archiveIdx, name, len(encodedChunks)))\n\t\tarchives = append(archives, archive.Archive{\n\t\t\tArchiveInfo: archiveInfo,\n\t\t\tChunks:      encodedChunks,\n\t\t\tRowKey:      rowKey,\n\t\t})\n\t}\n\n\treturn &archive.Metric{\n\t\tMetadata:   w.Header.Metadata,\n\t\tMetricData: *md,\n\t\tArchives:   archives,\n\t}, nil\n}\n\nfunc getMetricData(name string, interval int) *schema.MetricData {\n\tmd := &schema.MetricData{\n\t\tName:     name,\n\t\tMetric:   name,\n\t\tInterval: interval,\n\t\tValue:    0,\n\t\tUnit:     \"unknown\",\n\t\tTime:     0,\n\t\tMtype:    \"gauge\",\n\t\tTags:     []string{},\n\t\tOrgId:    *orgId,\n\t}\n\tmd.SetId()\n\treturn md\n}\n\n\/\/ scan a directory and feed the list of whisper files relative to base into the given channel\nfunc getFileListIntoChan(fileChan chan string) {\n\tfilepath.Walk(\n\t\t*whisperDirectory,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif path[len(path)-4:] == \".wsp\" {\n\t\t\t\tfileChan <- path\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t)\n\n\tclose(fileChan)\n}\n<|endoftext|>"}
{"text":"<commit_before>package env\n\ntype Service struct{}\n\nfunc (Service) Type() string {\n\treturn \"env\"\n}\n\nfunc (Service) Version() string {\n\treturn \"0.5.0\"\n}\n<commit_msg>Bump env version<commit_after>package env\n\ntype Service struct{}\n\nfunc (Service) Type() string {\n\treturn \"env\"\n}\n\nfunc (Service) Version() string {\n\treturn \"0.6.0\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package mangadownloader\n\nimport (\n\t\"net\/url\"\n\t\"testing\"\n)\n\nfunc testCommonServiceManga(t *testing.T, service Service, mangaUrl *url.URL, expectedMangaName string) {\n\t\/\/t.Parallel()\n\n\tobject, err := service.Identify(mangaUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmanga, ok := object.(*Manga)\n\tif !ok {\n\t\tt.Fatal(\"Not a manga\")\n\t}\n\n\tname, err := manga.Name()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != expectedMangaName {\n\t\tt.Fatal(\"Unexpected name\")\n\t}\n\n\tchapters, err := manga.Chapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(chapters) == 0 {\n\t\tt.Fatal(\"No chapter\")\n\t}\n}\n\nfunc testCommonServiceChapter(t *testing.T, service Service, chapterUrl *url.URL, expectedChapterName string) {\n\t\/\/t.Parallel()\n\n\tobject, err := service.Identify(chapterUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tchapter, ok := object.(*Chapter)\n\tif !ok {\n\t\tt.Fatal(\"Not a chapter\")\n\t}\n\n\tname, err := chapter.Name()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != expectedChapterName {\n\t\tt.Fatal(\"Unexpected name\")\n\t}\n\n\tpages, err := chapter.Pages()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(pages) == 0 {\n\t\tt.Fatal(\"No pages\")\n\t}\n\n\tpage := pages[0]\n\t_, err = page.ImageUrl()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n<commit_msg>Enable parallel tests<commit_after>package mangadownloader\n\nimport (\n\t\"net\/url\"\n\t\"testing\"\n)\n\nfunc testCommonServiceManga(t *testing.T, service Service, mangaUrl *url.URL, expectedMangaName string) {\n\tt.Parallel()\n\n\tobject, err := service.Identify(mangaUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmanga, ok := object.(*Manga)\n\tif !ok {\n\t\tt.Fatal(\"Not a manga\")\n\t}\n\n\tname, err := manga.Name()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != expectedMangaName {\n\t\tt.Fatal(\"Unexpected name\")\n\t}\n\n\tchapters, err := manga.Chapters()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(chapters) == 0 {\n\t\tt.Fatal(\"No chapter\")\n\t}\n}\n\nfunc testCommonServiceChapter(t *testing.T, service Service, chapterUrl *url.URL, expectedChapterName string) {\n\tt.Parallel()\n\n\tobject, err := service.Identify(chapterUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tchapter, ok := object.(*Chapter)\n\tif !ok {\n\t\tt.Fatal(\"Not a chapter\")\n\t}\n\n\tname, err := chapter.Name()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif name != expectedChapterName {\n\t\tt.Fatal(\"Unexpected name\")\n\t}\n\n\tpages, err := chapter.Pages()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(pages) == 0 {\n\t\tt.Fatal(\"No pages\")\n\t}\n\n\tpage := pages[0]\n\t_, err = page.ImageUrl()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"github.com\/zenoss\/glog\"\n\t\"github.com\/zenoss\/serviced\/dao\"\n\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\/\/ ServiceAttachConfig is the deserialized object from the command-line\ntype ServiceAttachConfig struct {\n\tServiceSpec string\n\tCommand     []string\n}\n\n\/\/ findServiceStates finds states that match DockerId, ServiceName, or ServiceId\nfunc findServiceStates(a *api, serviceSpecifier string) ([]*dao.ServiceState, map[string]*dao.Service, error) {\n\tvar serviceMap map[string]*dao.Service\n\tvar states []*dao.ServiceState\n\n\t\/\/ make serviceMap\n\tservices, err := a.GetServices()\n\tif err != nil {\n\t\treturn states, serviceMap, err\n\t}\n\n\tserviceMap = make(map[string]*dao.Service)\n\tfor _, service := range services {\n\t\tserviceMap[service.Id] = service\n\n\t\tstatesByServiceID, err := a.GetServiceStatesByServiceID(service.Id)\n\t\tif err != nil {\n\t\t\treturn []*dao.ServiceState{}, map[string]*dao.Service{}, err\n\t\t}\n\n\t\tfor _, state := range statesByServiceID {\n\t\t\tif serviceSpecifier == state.ServiceId ||\n\t\t\t\tserviceSpecifier == serviceMap[state.ServiceId].Name ||\n\t\t\t\tstrings.HasPrefix(state.DockerId, serviceSpecifier) {\n\t\t\t\tstates = append(states, state)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn states, serviceMap, nil\n}\n\n\/\/ findContainerID finds the containerID from either DockerId, ServiceName, or ServiceId\nfunc findContainerID(a *api, serviceSpecifier string) (string, error) {\n\tstates, serviceMap, err := findServiceStates(a, serviceSpecifier)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(states) < 1 {\n\t\treturn \"\", fmt.Errorf(\"did not find any service instances matching specifier:'%s'\", serviceSpecifier)\n\t}\n\tif len(states) > 1 {\n\t\tmessage := fmt.Sprintf(\"%d service instances matched specifier:'%s'\\n\", len(states), serviceSpecifier)\n\t\tmessage += fmt.Sprintf(\"%-16s %-40s %s\\n\", \"NAME\", \"SERVICEID\", \"DOCKERID\")\n\t\tfor _, state := range states {\n\t\t\tmessage += fmt.Sprintf(\"%-16s %-40s %s\\n\",\n\t\t\t\tserviceMap[state.ServiceId].Name, state.ServiceId, state.DockerId)\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"%s\", message)\n\t}\n\n\treturn states[0].DockerId, nil\n}\n\n\/\/ exePaths returns the full path to the given executables in a map\nfunc exePaths(exes []string) (map[string]string, error) {\n\texeMap := map[string]string{}\n\n\tfor _, exe := range exes {\n\t\tpath, err := exec.LookPath(exe)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"exe:'%v' not found error:%v\\n\", exe, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\texeMap[exe] = path\n\t}\n\n\treturn exeMap, nil\n}\n\n\/\/ attachContainerAndExec connects to a container and executes an arbitrary bash command\nfunc attachContainerAndExec(containerId string, cmd []string) error {\n\texeMap, err := exePaths([]string{\"sudo\", \"nsinit\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tNSINIT_ROOT := \"\/var\/lib\/docker\/execdriver\/native\" \/\/ has container.json\n\n\tattachCmd := fmt.Sprintf(\"cd %s\/%s && %s exec %s\", NSINIT_ROOT, containerId,\n\t\texeMap[\"nsinit\"], strings.Join(cmd, \" \"))\n\tfullCmd := []string{exeMap[\"sudo\"], \"--\", \"\/bin\/bash\", \"-c\", attachCmd}\n\tglog.V(1).Infof(\"exec cmd: %v\\n\", fullCmd)\n\treturn syscall.Exec(fullCmd[0], fullCmd[0:], os.Environ())\n}\n\n\/\/ ServiceAttach runs an arbitrary shell command in a running service container\nfunc (a *api) ServiceAttach(config ServiceAttachConfig) error {\n\tif config.ServiceSpec == \"\" {\n\t\treturn fmt.Errorf(\"required ServiceAttachConfig.ServiceSpec is empty\")\n\t}\n\tvar command []string = []string{\"bash\"}\n\tif strings.TrimSpace(strings.Join(config.Command, \"\")) != \"\" {\n\t\tcommand = config.Command\n\t}\n\n\tcontainerID, err := findContainerID(a, config.ServiceSpec)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error looking for DOCKER_ID with specifier:'%v'  error:%v\\n\", config.ServiceSpec, err)\n\t\treturn err\n\t}\n\n\tif err := attachContainerAndExec(containerID, command); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error running bash command:'%v'  error:%v\\n\", command, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>added additional trace logging<commit_after>package api\n\nimport (\n\t\"github.com\/zenoss\/glog\"\n\t\"github.com\/zenoss\/serviced\/dao\"\n\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\/\/ ServiceAttachConfig is the deserialized object from the command-line\ntype ServiceAttachConfig struct {\n\tServiceSpec string\n\tCommand     []string\n}\n\n\/\/ findServiceStates finds states that match DockerId, ServiceName, or ServiceId\nfunc findServiceStates(a *api, serviceSpecifier string) ([]*dao.ServiceState, map[string]*dao.Service, error) {\n\tvar serviceMap map[string]*dao.Service\n\tvar states []*dao.ServiceState\n\n\t\/\/ make serviceMap\n\tservices, err := a.GetServices()\n\tif err != nil {\n\t\treturn states, serviceMap, err\n\t}\n\n\tserviceMap = make(map[string]*dao.Service)\n\tfor _, service := range services {\n\t\tserviceMap[service.Id] = service\n\n\t\tstatesByServiceID, err := a.GetServiceStatesByServiceID(service.Id)\n\t\tif err != nil {\n\t\t\treturn []*dao.ServiceState{}, map[string]*dao.Service{}, err\n\t\t}\n\n\t\tglog.V(2).Infof(\"looking for specifier:%s in service:  ServiceId:%s  ServiceName:%s\\n\",\n\t\t\tserviceSpecifier, service.Id, service.Name)\n\t\tfor _, state := range statesByServiceID {\n\t\t\tglog.V(2).Infof(\"looking for specifier:%s in   state:  ServiceId:%s  ServiceName:%s  DockerId:%s\\n\",\n\t\t\t\tserviceSpecifier, state.ServiceId, serviceMap[state.ServiceId].Name, state.DockerId)\n\t\t\tif serviceSpecifier == state.ServiceId ||\n\t\t\t\tserviceSpecifier == serviceMap[state.ServiceId].Name ||\n\t\t\t\tstrings.HasPrefix(state.DockerId, serviceSpecifier) {\n\t\t\t\tstates = append(states, state)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn states, serviceMap, nil\n}\n\n\/\/ findContainerID finds the containerID from either DockerId, ServiceName, or ServiceId\nfunc findContainerID(a *api, serviceSpecifier string) (string, error) {\n\tstates, serviceMap, err := findServiceStates(a, serviceSpecifier)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(states) < 1 {\n\t\treturn \"\", fmt.Errorf(\"did not find any service instances matching specifier:'%s'\", serviceSpecifier)\n\t}\n\tif len(states) > 1 {\n\t\tmessage := fmt.Sprintf(\"%d service instances matched specifier:'%s'\\n\", len(states), serviceSpecifier)\n\t\tmessage += fmt.Sprintf(\"%-16s %-40s %s\\n\", \"NAME\", \"SERVICEID\", \"DOCKERID\")\n\t\tfor _, state := range states {\n\t\t\tmessage += fmt.Sprintf(\"%-16s %-40s %s\\n\",\n\t\t\t\tserviceMap[state.ServiceId].Name, state.ServiceId, state.DockerId)\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"%s\", message)\n\t}\n\n\treturn states[0].DockerId, nil\n}\n\n\/\/ exePaths returns the full path to the given executables in a map\nfunc exePaths(exes []string) (map[string]string, error) {\n\texeMap := map[string]string{}\n\n\tfor _, exe := range exes {\n\t\tpath, err := exec.LookPath(exe)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"exe:'%v' not found error:%v\\n\", exe, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\texeMap[exe] = path\n\t}\n\n\treturn exeMap, nil\n}\n\n\/\/ attachContainerAndExec connects to a container and executes an arbitrary bash command\nfunc attachContainerAndExec(containerId string, cmd []string) error {\n\texeMap, err := exePaths([]string{\"sudo\", \"nsinit\"})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tNSINIT_ROOT := \"\/var\/lib\/docker\/execdriver\/native\" \/\/ has container.json\n\n\tattachCmd := fmt.Sprintf(\"cd %s\/%s && %s exec %s\", NSINIT_ROOT, containerId,\n\t\texeMap[\"nsinit\"], strings.Join(cmd, \" \"))\n\tfullCmd := []string{exeMap[\"sudo\"], \"--\", \"\/bin\/bash\", \"-c\", attachCmd}\n\tglog.V(1).Infof(\"exec cmd: %v\\n\", fullCmd)\n\treturn syscall.Exec(fullCmd[0], fullCmd[0:], os.Environ())\n}\n\n\/\/ ServiceAttach runs an arbitrary shell command in a running service container\nfunc (a *api) ServiceAttach(config ServiceAttachConfig) error {\n\tif config.ServiceSpec == \"\" {\n\t\treturn fmt.Errorf(\"required ServiceAttachConfig.ServiceSpec is empty\")\n\t}\n\tvar command []string = []string{\"bash\"}\n\tif strings.TrimSpace(strings.Join(config.Command, \"\")) != \"\" {\n\t\tcommand = config.Command\n\t}\n\n\tcontainerID, err := findContainerID(a, config.ServiceSpec)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error looking for DOCKER_ID with specifier:'%v'  error:%v\\n\", config.ServiceSpec, err)\n\t\treturn err\n\t}\n\n\tif err := attachContainerAndExec(containerID, command); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error running bash command:'%v'  error:%v\\n\", command, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package msglog\n\nimport (\n\t\"errors\"\n\t\"github.com\/davyxu\/cellnet\"\n\t\"sync\"\n)\n\nvar (\n\twhiteListByMsgID sync.Map\n\tblackListByMsgID sync.Map\n\tcurrMsgLogMode   = MsgLogMode_ShowAll\n)\n\ntype MsgLogRule int\n\nconst (\n\t\/\/ 显示所有的消息日志\n\tMsgLogRule_None MsgLogRule = iota\n\n\t\/\/ 黑名单内的不显示\n\tMsgLogRule_BlackList\n\n\t\/\/ 只显示白名单的日志\n\tMsgLogRule_WhiteList\n)\n\ntype MsgLogMode int\n\nconst (\n\t\/\/ 显示所有的消息日志\n\tMsgLogMode_ShowAll MsgLogMode = iota\n\n\t\/\/ 禁用所有的消息日志\n\tMsgLogMode_Mute\n\n\t\/\/ 黑名单内的不显示\n\tMsgLogMode_BlackList\n\n\t\/\/ 只显示白名单的日志\n\tMsgLogMode_WhiteList\n)\n\n\/\/ 设置当前的消息日志处理模式\nfunc SetCurrMsgLogMode(mode MsgLogMode) {\n\tcurrMsgLogMode = mode\n}\n\n\/\/ 获取当前的消息日志处理模式\nfunc GetCurrMsgLogMode() MsgLogMode {\n\treturn currMsgLogMode\n}\n\n\/\/ 指定某个消息的处理规则, 消息格式: packageName.MsgName\nfunc SetMsgLogRule(name string, rule MsgLogRule) error {\n\n\tmeta := cellnet.MessageMetaByFullName(name)\n\tif meta == nil {\n\t\treturn errors.New(\"msg not found\")\n\t}\n\n\tswitch rule {\n\tcase MsgLogRule_BlackList:\n\t\tblackListByMsgID.Store(int(meta.ID), meta)\n\tcase MsgLogRule_WhiteList:\n\t\twhiteListByMsgID.Store(int(meta.ID), meta)\n\tcase MsgLogRule_None:\n\t\tblackListByMsgID.Delete(int(meta.ID))\n\t\twhiteListByMsgID.Delete(int(meta.ID))\n\t}\n\n\treturn nil\n}\n\n\/\/ 能否显示消息日志\nfunc IsMsgLogValid(msgid int) bool {\n\tswitch currMsgLogMode {\n\tcase MsgLogMode_BlackList: \/\/ 黑名单里不显示\n\t\tif _, ok := blackListByMsgID.Load(msgid); ok {\n\t\t\treturn false\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\tcase MsgLogMode_WhiteList: \/\/ 只有在白名单里才显示\n\t\tif _, ok := whiteListByMsgID.Load(msgid); ok {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\tcase MsgLogMode_Mute:\n\t\treturn false\n\t}\n\n\t\/\/ MsgLogMode_ShowAll\n\treturn true\n}\n\n\/\/ 遍历消息规则\nfunc VisitMsgLogRule(mode MsgLogMode, callback func(*cellnet.MessageMeta) bool) {\n\n\tswitch mode {\n\tcase MsgLogMode_BlackList:\n\t\tblackListByMsgID.Range(func(key, value interface{}) bool {\n\t\t\tmeta := value.(*cellnet.MessageMeta)\n\n\t\t\treturn callback(meta)\n\t\t})\n\tcase MsgLogMode_WhiteList:\n\t\twhiteListByMsgID.Range(func(key, value interface{}) bool {\n\t\t\tmeta := value.(*cellnet.MessageMeta)\n\n\t\t\treturn callback(meta)\n\t\t})\n\t}\n\n}\n<commit_msg>消息日志默认为黑名单模式<commit_after>package msglog\n\nimport (\n\t\"errors\"\n\t\"github.com\/davyxu\/cellnet\"\n\t\"sync\"\n)\n\nvar (\n\twhiteListByMsgID sync.Map\n\tblackListByMsgID sync.Map\n\tcurrMsgLogMode   = MsgLogMode_BlackList\n)\n\ntype MsgLogRule int\n\nconst (\n\t\/\/ 显示所有的消息日志\n\tMsgLogRule_None MsgLogRule = iota\n\n\t\/\/ 黑名单内的不显示\n\tMsgLogRule_BlackList\n\n\t\/\/ 只显示白名单的日志\n\tMsgLogRule_WhiteList\n)\n\ntype MsgLogMode int\n\nconst (\n\t\/\/ 显示所有的消息日志\n\tMsgLogMode_ShowAll MsgLogMode = iota\n\n\t\/\/ 禁用所有的消息日志\n\tMsgLogMode_Mute\n\n\t\/\/ 黑名单内的不显示\n\tMsgLogMode_BlackList\n\n\t\/\/ 只显示白名单的日志\n\tMsgLogMode_WhiteList\n)\n\n\/\/ 设置当前的消息日志处理模式\nfunc SetCurrMsgLogMode(mode MsgLogMode) {\n\tcurrMsgLogMode = mode\n}\n\n\/\/ 获取当前的消息日志处理模式\nfunc GetCurrMsgLogMode() MsgLogMode {\n\treturn currMsgLogMode\n}\n\n\/\/ 指定某个消息的处理规则, 消息格式: packageName.MsgName\nfunc SetMsgLogRule(name string, rule MsgLogRule) error {\n\n\tmeta := cellnet.MessageMetaByFullName(name)\n\tif meta == nil {\n\t\treturn errors.New(\"msg not found\")\n\t}\n\n\tswitch rule {\n\tcase MsgLogRule_BlackList:\n\t\tblackListByMsgID.Store(int(meta.ID), meta)\n\tcase MsgLogRule_WhiteList:\n\t\twhiteListByMsgID.Store(int(meta.ID), meta)\n\tcase MsgLogRule_None:\n\t\tblackListByMsgID.Delete(int(meta.ID))\n\t\twhiteListByMsgID.Delete(int(meta.ID))\n\t}\n\n\treturn nil\n}\n\n\/\/ 能否显示消息日志\nfunc IsMsgLogValid(msgid int) bool {\n\tswitch currMsgLogMode {\n\tcase MsgLogMode_BlackList: \/\/ 黑名单里不显示\n\t\tif _, ok := blackListByMsgID.Load(msgid); ok {\n\t\t\treturn false\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\tcase MsgLogMode_WhiteList: \/\/ 只有在白名单里才显示\n\t\tif _, ok := whiteListByMsgID.Load(msgid); ok {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\tcase MsgLogMode_Mute:\n\t\treturn false\n\t}\n\n\t\/\/ MsgLogMode_ShowAll\n\treturn true\n}\n\n\/\/ 遍历消息规则\nfunc VisitMsgLogRule(mode MsgLogMode, callback func(*cellnet.MessageMeta) bool) {\n\n\tswitch mode {\n\tcase MsgLogMode_BlackList:\n\t\tblackListByMsgID.Range(func(key, value interface{}) bool {\n\t\t\tmeta := value.(*cellnet.MessageMeta)\n\n\t\t\treturn callback(meta)\n\t\t})\n\tcase MsgLogMode_WhiteList:\n\t\twhiteListByMsgID.Range(func(key, value interface{}) bool {\n\t\t\tmeta := value.(*cellnet.MessageMeta)\n\n\t\t\treturn callback(meta)\n\t\t})\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package mumble\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/TF2Stadium\/fumble\/database\"\n\t\"github.com\/layeh\/gumble\/gumble\"\n)\n\nvar ErrChanNotFound = errors.New(\"channel not found\")\n\nfunc printchannels(c gumble.Channels) {\n\tfor _, channel := range c {\n\t\tlog.Println(channel.Name)\n\t}\n}\n\nfunc AddLobbyChannel(l *Conn, lobbyID uint, maxplayers int) {\n\tname := fmt.Sprintf(\"Lobby #%d\", lobbyID)\n\n\tl.wait.Add(1)\n\tl.client.Do(func() { l.client.Channels[0].Add(name, false) })\n\tl.wait.Wait()\n\n\tlog.Printf(\"#%d: Created root\", lobbyID)\n\n\tl.client.Do(func() {\n\t\tchannel := l.client.Channels[0].Find(name)\n\t\tchannel.SetDescription(\"Mumble channel for TF2Stadium \" + name)\n\t\tchannel.SetMaxUsers(uint32(maxplayers))\n\n\t\tl.wait.Add(2)\n\t\tlog.Printf(\"#%d: Creating RED and BLU\", lobbyID)\n\t\tchannel.Add(\"RED\", false)\n\t\tchannel.Add(\"BLU\", false)\n\t})\n\n\tlog.Printf(\"#%d: Done\", lobbyID)\n\tl.wait.Wait()\n}\n\n\/\/MoveUsersToLobbyRoot moves all users from the RED and BLU channels of the given lobbyID channel\n\/\/to the lobby's root channel\nfunc MoveUsersToLobbyRoot(conn *Conn, lobbyID uint) error {\n\tvar err error\n\tname := fmt.Sprintf(\"Lobby #%d\", lobbyID)\n\n\tconn.client.Do(func() {\n\t\troot := conn.client.Channels[0].Find(name) \/\/ root lobby channel\n\t\tif root == nil {\n\t\t\terr = ErrChanNotFound\n\t\t\treturn\n\t\t}\n\n\t\ttotalUsers := 0\n\t\tfor _, channel := range root.Children {\n\t\t\ttotalUsers += len(channel.Users)\n\n\t\t\tconn.wait.Add(1)\n\t\t\tchannel.Remove()\n\t\t}\n\n\t\tif totalUsers == 0 { \/\/ no users in both channels, remove it entirely\n\t\t\tconn.wait.Add(1)\n\t\t\troot.Remove()\n\t\t}\n\t\treturn\n\t})\n\n\tlog.Printf(\"#%d: Deleted channels\", lobbyID)\n\tconn.wait.Wait()\n\treturn err\n}\n\nfunc getLobbyID(channel *gumble.Channel) uint {\n\tname := channel.Name\n\tif name[0] != 'L' { \/\/ channel name is either \"RED\" or \"BLU\"\n\t\tname = channel.Parent.Name\n\t}\n\n\tid, _ := strconv.ParseUint(name[strings.Index(name, \"#\")+1:], 10, 32)\n\treturn uint(id)\n}\n\nfunc isUserAllowed(user *gumble.User, channel *gumble.Channel) (bool, string) {\n\tif channel.IsRoot() {\n\t\treturn true, \"\"\n\t}\n\n\tlobbyID := getLobbyID(channel)\n\n\treturn database.IsAllowed(user.UserID, lobbyID, channel.Name)\n}\n\nfunc (conn Conn) removeEmptyChannels() {\n\tconn.client.Do(func() {\n\t\tfor _, c := range conn.client.Channels {\n\t\t\tif len(c.Users) == 0 && !database.IsLobbyClosed(getLobbyID(c)) {\n\t\t\t\tconn.wait.Add(1)\n\t\t\t\tc.Remove()\n\t\t\t}\n\t\t}\n\t})\n\n\tconn.wait.Wait()\n}\n<commit_msg>MoveUsersToLobbyRoot: return errors correctly.<commit_after>package mumble\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/TF2Stadium\/fumble\/database\"\n\t\"github.com\/layeh\/gumble\/gumble\"\n)\n\nvar ErrChanNotFound = errors.New(\"channel not found\")\n\nfunc printchannels(c gumble.Channels) {\n\tfor _, channel := range c {\n\t\tlog.Println(channel.Name)\n\t}\n}\n\nfunc AddLobbyChannel(l *Conn, lobbyID uint, maxplayers int) {\n\tname := fmt.Sprintf(\"Lobby #%d\", lobbyID)\n\n\tl.wait.Add(1)\n\tl.client.Do(func() { l.client.Channels[0].Add(name, false) })\n\tl.wait.Wait()\n\n\tlog.Printf(\"#%d: Created root\", lobbyID)\n\n\tl.client.Do(func() {\n\t\tchannel := l.client.Channels[0].Find(name)\n\t\tchannel.SetDescription(\"Mumble channel for TF2Stadium \" + name)\n\t\tchannel.SetMaxUsers(uint32(maxplayers))\n\n\t\tl.wait.Add(2)\n\t\tlog.Printf(\"#%d: Creating RED and BLU\", lobbyID)\n\t\tchannel.Add(\"RED\", false)\n\t\tchannel.Add(\"BLU\", false)\n\t})\n\n\tlog.Printf(\"#%d: Done\", lobbyID)\n\tl.wait.Wait()\n}\n\n\/\/MoveUsersToLobbyRoot moves all users from the RED and BLU channels of the given lobbyID channel\n\/\/to the lobby's root channel\nfunc MoveUsersToLobbyRoot(conn *Conn, lobbyID uint) error {\n\tvar err error\n\tname := fmt.Sprintf(\"Lobby #%d\", lobbyID)\n\n\tconn.client.Do(func() {\n\t\troot := conn.client.Channels[0].Find(name) \/\/ root lobby channel\n\t\tif root == nil {\n\t\t\terr = ErrChanNotFound\n\t\t\treturn\n\t\t}\n\n\t\ttotalUsers := 0\n\t\tfor _, channel := range root.Children {\n\t\t\ttotalUsers += len(channel.Users)\n\n\t\t\tconn.wait.Add(1)\n\t\t\tchannel.Remove()\n\t\t}\n\n\t\tif totalUsers == 0 { \/\/ no users in both channels, remove it entirely\n\t\t\tconn.wait.Add(1)\n\t\t\troot.Remove()\n\t\t}\n\t\treturn\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"#%d: Deleted channels\", lobbyID)\n\tconn.wait.Wait()\n\treturn nil\n}\n\nfunc getLobbyID(channel *gumble.Channel) uint {\n\tname := channel.Name\n\tif name[0] != 'L' { \/\/ channel name is either \"RED\" or \"BLU\"\n\t\tname = channel.Parent.Name\n\t}\n\n\tid, _ := strconv.ParseUint(name[strings.Index(name, \"#\")+1:], 10, 32)\n\treturn uint(id)\n}\n\nfunc isUserAllowed(user *gumble.User, channel *gumble.Channel) (bool, string) {\n\tif channel.IsRoot() {\n\t\treturn true, \"\"\n\t}\n\n\tlobbyID := getLobbyID(channel)\n\n\treturn database.IsAllowed(user.UserID, lobbyID, channel.Name)\n}\n\nfunc (conn Conn) removeEmptyChannels() {\n\tconn.client.Do(func() {\n\t\tfor _, c := range conn.client.Channels {\n\t\t\tif len(c.Users) == 0 && !database.IsLobbyClosed(getLobbyID(c)) {\n\t\t\t\tconn.wait.Add(1)\n\t\t\t\tc.Remove()\n\t\t\t}\n\t\t}\n\t})\n\n\tconn.wait.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build unit\n\n\/\/ Copyright 2016 Mesosphere, 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 framework\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/dcos\/dcos-metrics\/producers\"\n\t\"github.com\/dcos\/dcos-metrics\/schema\/metrics_schema\"\n\t\"github.com\/linkedin\/goavro\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestTransform(t *testing.T) {\n\t\/\/ Create a test record\n\trecDps, err := goavro.NewRecord(datapointNamespace, datapointSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trecDps.Set(\"name\", \"some-name\")\n\trecDps.Set(\"time_ms\", 1000)\n\trecDps.Set(\"value\", 42.0)\n\n\trecTags, err := goavro.NewRecord(tagNamespace, tagSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trecTags.Set(\"key\", \"some-key\")\n\trecTags.Set(\"value\", \"some-val\")\n\n\t\/\/ Run the tests\n\tConvey(\"When transforming an AvroDatum to a MetricsMessage\", t, func() {\n\t\tConvey(\"Should return a proper MetricsMessage without errors if all inputs are correct\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\tpmm, err := a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(pmm, ShouldHaveSameTypeAs, producers.MetricsMessage{})\n\n\t\t\t\/\/ If we could mock the time here, we could do a single assertion\n\t\t\t\/\/ using ShouldResemble (deep equals). However, it isn't easy to\n\t\t\t\/\/ mock the time because it's set by avroRecord.extract(). So we do\n\t\t\t\/\/ the next best thing: ensure we get something besides the zero\n\t\t\t\/\/ value for those fields.\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(pmm.Name, ShouldEqual, \"dcos.metrics.app\")\n\t\t\tSo(pmm.Timestamp, ShouldBeGreaterThan, 0)\n\t\t\tSo(len(pmm.Datapoints), ShouldEqual, 1)\n\t\t\tSo(pmm.Datapoints[0].Name, ShouldEqual, \"some-name\")\n\t\t\tSo(pmm.Datapoints[0].Value, ShouldEqual, 42.0)\n\t\t\tSo(pmm.Datapoints[0].Timestamp, ShouldNotEqual, \"\")\n\t\t\tSo(pmm.Dimensions.MesosID, ShouldEqual, \"some-mesos-id\")\n\t\t\tSo(pmm.Dimensions.ClusterID, ShouldEqual, \"some-cluster-id\")\n\t\t\tSo(pmm.Dimensions.Hostname, ShouldEqual, \"1.2.3.4\")\n\t\t\tSo(pmm.Dimensions.Labels, ShouldResemble, map[string]string{\"some-key\": \"some-val\"})\n\t\t})\n\n\t\tConvey(\"Should return an error if AvroDatum didn't contain a goavro.Record\", func() {\n\t\t\ta := AvroDatum{Record: make(map[string]string), Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"Should return an error if the record didn't contain 'tags'\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"Should return an error if the record didn't contain 'datapoints'\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\t})\n}\n\nfunc TestRunFrameworkTCPListener(t *testing.T) {\n\tConvey(\"When running the framework TCP listener\", t, func() {\n\t\tport, err := getEphemeralPort()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tConvey(\"Should run the listener without errors if valid configuration was given\", func() {\n\t\t\tc := Collector{\n\t\t\t\tlistenEndpointFlag:         net.JoinHostPort(\"localhost\", strconv.Itoa(port)),\n\t\t\t\trecordInputLogFlag:         false,\n\t\t\t\tinputLimitAmountKBytesFlag: 20480,\n\t\t\t\tinputLimitPeriodFlag:       60,\n\t\t\t}\n\t\t\tgo c.RunFrameworkTCPListener(make(chan *AvroDatum))\n\t\t\ttime.Sleep(1 * time.Second) \/\/ brief delay to allow the tcp listener to start\n\n\t\t\t_, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\t})\n}\n\nfunc TestGetTopic(t *testing.T) {\n\tvar (\n\t\tmetricListNamespace = goavro.RecordEnclosingNamespace(metricsSchema.MetricListNamespace)\n\t\tmetricListSchema    = goavro.RecordSchema(metricsSchema.MetricListSchema)\n\t)\n\n\tConvey(\"When extracting the topic value from the provided Avro record\", t, func() {\n\t\tConvey(\"Should return UNKNOWN_RECORD_TYPE if the record wasn't valid\", func() {\n\t\t\tts, ok := GetTopic([]string{\"foo\"})\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_RECORD_TYPE\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return UNKNOWN_TOPIC_VAL if the field 'topic' doesn't exist\", func() {\n\t\t\tr, err := goavro.NewRecord(\n\t\t\t\tmetricListNamespace,\n\t\t\t\tgoavro.RecordSchema(`{\"name\": \"some-schema\", \"fields\": [{\"name\": \"foo\", \"type\": \"string\"}]}`))\n\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_TOPIC_VAL\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return UNKNOWN_TOPIC_TYPE if the topic string wasn't retrievable\", func() {\n\t\t\tr, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tr.Set(\"topic\", nil)\n\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_TOPIC_TYPE\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return the topic string with no errors\", func() {\n\t\t\tr, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tr.Set(\"topic\", \"some-topic\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"some-topic\")\n\t\t\tSo(ok, ShouldBeTrue)\n\t\t})\n\t})\n}\n\nfunc TestHandleConnection(t *testing.T) {\n\tConvey(\"When handling new TCP connections\", t, func() {\n\t\tport, err := getEphemeralPort()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tln, err := net.Listen(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer ln.Close()\n\t\ttime.Sleep(1 * time.Second)\n\n\t\tc := Collector{}\n\t\trecordsChan := make(chan *AvroDatum)\n\n\t\t\/\/ This goroutine runs in the background waiting for a TCP connection\n\t\t\/\/ from the test below. Once the connection has been accepted,\n\t\t\/\/ handleConnection() processes the data and puts it on the recordsChan.\n\t\t\/\/ To avoid a non-deterministic sleep() here, this intentionally blocks\n\t\t\/\/ until the connection is processed, at which point we break out of the\n\t\t\/\/ loop and the goroutine finishes.\n\t\t\/\/\n\t\t\/\/ This works mostly because we only use a single connection in this\n\t\t\/\/ test. If we test with >1 conns in the future, this will need to be\n\t\t\/\/ reworked a bit.\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tconn, err := ln.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tdefer conn.Close()\n\t\t\t\tc.handleConnection(conn, recordsChan) \/\/ blocks\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\n\t\tConvey(\"Should put new records of type AvroDatum on to the channel\", func() {\n\t\t\t\/\/ Create a test record\n\t\t\trecDps, err := goavro.NewRecord(datapointNamespace, datapointSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trecDps.Set(\"name\", \"some-name\")\n\t\t\trecDps.Set(\"time_ms\", int64(1000))\n\t\t\trecDps.Set(\"value\", 42.0)\n\n\t\t\trecTags, err := goavro.NewRecord(tagNamespace, tagSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trecTags.Set(\"key\", \"some-key\")\n\t\t\trecTags.Set(\"value\", \"some-val\")\n\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\t\/\/ Encode and write the record\n\t\t\tconn, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcodec, err := goavro.NewCodec(metricsSchema.MetricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tavroWriter, err := goavro.NewWriter(goavro.ToWriter(conn), goavro.UseCodec(codec))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t\/\/ Test\n\t\t\tavroWriter.Write(rec)\n\t\t\tavroWriter.Close()\n\t\t\trecords := <-recordsChan \/\/ blocks\n\n\t\t\ttags, err := records.Record.(*goavro.Record).Get(\"tags\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdps, err := records.Record.(*goavro.Record).Get(\"datapoints\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tSo(records.ApproxBytes, ShouldBeGreaterThan, 0)\n\t\t\tSo(records.Topic, ShouldEqual, \"some-topic\")\n\t\t\tSo(fmt.Sprintf(\"%+v\", tags), ShouldEqual, \"[{dcos.metrics.Tag: [dcos.metrics.key: some-key, dcos.metrics.value: some-val]}]\")\n\t\t\tSo(fmt.Sprintf(\"%+v\", dps), ShouldEqual, \"[{dcos.metrics.Datapoint: [dcos.metrics.name: some-name, dcos.metrics.time_ms: 1000, dcos.metrics.value: 42]}]\")\n\t\t})\n\t})\n\n}\n\nfunc TestRead(t *testing.T) {\n\tConvey(\"When reading bytes from an io.Reader\", t, func() {\n\t\tConvey(\"Should return accurate byte counts to countingReader\", func() {\n\t\t\tresult := make([]byte, 3)\n\t\t\tcr := countingReader{strings.NewReader(\"foo\"), 0}\n\t\t\tn, err := cr.Read(result)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(cr.inputBytes, ShouldEqual, 3)\n\t\t\tSo(n, ShouldEqual, cr.inputBytes)\n\t\t\tSo(string(result), ShouldEqual, \"foo\")\n\t\t})\n\t})\n}\n\n\/\/ getEphemeralPort returns an available ephemeral port on the system.\nfunc getEphemeralPort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}\n<commit_msg>test new framework collector method<commit_after>\/\/ +build unit\n\n\/\/ Copyright 2016 Mesosphere, 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 framework\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/dcos\/dcos-metrics\/producers\"\n\t\"github.com\/dcos\/dcos-metrics\/schema\/metrics_schema\"\n\t\"github.com\/linkedin\/goavro\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestNew(t *testing.T) {\n\tConvey(\"When creating a new instance of the framework collector\", t, func() {\n\t\tConvey(\"Should return a new Collector with the default config\", func() {\n\t\t\tf := New()\n\t\t\tSo(f, ShouldHaveSameTypeAs, Collector{})\n\t\t\tSo(f, ShouldResemble, Collector{\n\t\t\t\tlistenEndpointFlag:         \"127.0.0.1:8124\",\n\t\t\t\trecordInputLogFlag:         false,\n\t\t\t\tinputLimitAmountKBytesFlag: 20480,\n\t\t\t\tinputLimitPeriodFlag:       60,\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestTransform(t *testing.T) {\n\t\/\/ Create a test record\n\trecDps, err := goavro.NewRecord(datapointNamespace, datapointSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trecDps.Set(\"name\", \"some-name\")\n\trecDps.Set(\"time_ms\", 1000)\n\trecDps.Set(\"value\", 42.0)\n\n\trecTags, err := goavro.NewRecord(tagNamespace, tagSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trecTags.Set(\"key\", \"some-key\")\n\trecTags.Set(\"value\", \"some-val\")\n\n\t\/\/ Run the tests\n\tConvey(\"When transforming an AvroDatum to a MetricsMessage\", t, func() {\n\t\tConvey(\"Should return a proper MetricsMessage without errors if all inputs are correct\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\tpmm, err := a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(pmm, ShouldHaveSameTypeAs, producers.MetricsMessage{})\n\n\t\t\t\/\/ If we could mock the time here, we could do a single assertion\n\t\t\t\/\/ using ShouldResemble (deep equals). However, it isn't easy to\n\t\t\t\/\/ mock the time because it's set by avroRecord.extract(). So we do\n\t\t\t\/\/ the next best thing: ensure we get something besides the zero\n\t\t\t\/\/ value for those fields.\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(pmm.Name, ShouldEqual, \"dcos.metrics.app\")\n\t\t\tSo(pmm.Timestamp, ShouldBeGreaterThan, 0)\n\t\t\tSo(len(pmm.Datapoints), ShouldEqual, 1)\n\t\t\tSo(pmm.Datapoints[0].Name, ShouldEqual, \"some-name\")\n\t\t\tSo(pmm.Datapoints[0].Value, ShouldEqual, 42.0)\n\t\t\tSo(pmm.Datapoints[0].Timestamp, ShouldNotEqual, \"\")\n\t\t\tSo(pmm.Dimensions.MesosID, ShouldEqual, \"some-mesos-id\")\n\t\t\tSo(pmm.Dimensions.ClusterID, ShouldEqual, \"some-cluster-id\")\n\t\t\tSo(pmm.Dimensions.Hostname, ShouldEqual, \"1.2.3.4\")\n\t\t\tSo(pmm.Dimensions.Labels, ShouldResemble, map[string]string{\"some-key\": \"some-val\"})\n\t\t})\n\n\t\tConvey(\"Should return an error if AvroDatum didn't contain a goavro.Record\", func() {\n\t\t\ta := AvroDatum{Record: make(map[string]string), Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"Should return an error if the record didn't contain 'tags'\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"Should return an error if the record didn't contain 'datapoints'\", func() {\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\n\t\t\ta := AvroDatum{Record: rec, Topic: \"some-topic\"}\n\t\t\t_, err = a.Transform(\"some-mesos-id\", \"some-cluster-id\", \"1.2.3.4\")\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t})\n\t})\n}\n\nfunc TestRunFrameworkTCPListener(t *testing.T) {\n\tConvey(\"When running the framework TCP listener\", t, func() {\n\t\tport, err := getEphemeralPort()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tConvey(\"Should run the listener without errors if valid configuration was given\", func() {\n\t\t\tc := Collector{\n\t\t\t\tlistenEndpointFlag:         net.JoinHostPort(\"localhost\", strconv.Itoa(port)),\n\t\t\t\trecordInputLogFlag:         false,\n\t\t\t\tinputLimitAmountKBytesFlag: 20480,\n\t\t\t\tinputLimitPeriodFlag:       60,\n\t\t\t}\n\t\t\tgo c.RunFrameworkTCPListener(make(chan *AvroDatum))\n\t\t\ttime.Sleep(1 * time.Second) \/\/ brief delay to allow the tcp listener to start\n\n\t\t\t_, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\t})\n}\n\nfunc TestGetTopic(t *testing.T) {\n\tvar (\n\t\tmetricListNamespace = goavro.RecordEnclosingNamespace(metricsSchema.MetricListNamespace)\n\t\tmetricListSchema    = goavro.RecordSchema(metricsSchema.MetricListSchema)\n\t)\n\n\tConvey(\"When extracting the topic value from the provided Avro record\", t, func() {\n\t\tConvey(\"Should return UNKNOWN_RECORD_TYPE if the record wasn't valid\", func() {\n\t\t\tts, ok := GetTopic([]string{\"foo\"})\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_RECORD_TYPE\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return UNKNOWN_TOPIC_VAL if the field 'topic' doesn't exist\", func() {\n\t\t\tr, err := goavro.NewRecord(\n\t\t\t\tmetricListNamespace,\n\t\t\t\tgoavro.RecordSchema(`{\"name\": \"some-schema\", \"fields\": [{\"name\": \"foo\", \"type\": \"string\"}]}`))\n\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_TOPIC_VAL\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return UNKNOWN_TOPIC_TYPE if the topic string wasn't retrievable\", func() {\n\t\t\tr, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tr.Set(\"topic\", nil)\n\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"UNKNOWN_TOPIC_TYPE\")\n\t\t\tSo(ok, ShouldBeFalse)\n\t\t})\n\n\t\tConvey(\"Should return the topic string with no errors\", func() {\n\t\t\tr, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tr.Set(\"topic\", \"some-topic\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tts, ok := GetTopic(r)\n\t\t\tSo(ts, ShouldEqual, \"some-topic\")\n\t\t\tSo(ok, ShouldBeTrue)\n\t\t})\n\t})\n}\n\nfunc TestHandleConnection(t *testing.T) {\n\tConvey(\"When handling new TCP connections\", t, func() {\n\t\tport, err := getEphemeralPort()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tln, err := net.Listen(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer ln.Close()\n\t\ttime.Sleep(1 * time.Second)\n\n\t\tc := Collector{}\n\t\trecordsChan := make(chan *AvroDatum)\n\n\t\t\/\/ This goroutine runs in the background waiting for a TCP connection\n\t\t\/\/ from the test below. Once the connection has been accepted,\n\t\t\/\/ handleConnection() processes the data and puts it on the recordsChan.\n\t\t\/\/ To avoid a non-deterministic sleep() here, this intentionally blocks\n\t\t\/\/ until the connection is processed, at which point we break out of the\n\t\t\/\/ loop and the goroutine finishes.\n\t\t\/\/\n\t\t\/\/ This works mostly because we only use a single connection in this\n\t\t\/\/ test. If we test with >1 conns in the future, this will need to be\n\t\t\/\/ reworked a bit.\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tconn, err := ln.Accept()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tdefer conn.Close()\n\t\t\t\tc.handleConnection(conn, recordsChan) \/\/ blocks\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\n\t\tConvey(\"Should put new records of type AvroDatum on to the channel\", func() {\n\t\t\t\/\/ Create a test record\n\t\t\trecDps, err := goavro.NewRecord(datapointNamespace, datapointSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trecDps.Set(\"name\", \"some-name\")\n\t\t\trecDps.Set(\"time_ms\", int64(1000))\n\t\t\trecDps.Set(\"value\", 42.0)\n\n\t\t\trecTags, err := goavro.NewRecord(tagNamespace, tagSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trecTags.Set(\"key\", \"some-key\")\n\t\t\trecTags.Set(\"value\", \"some-val\")\n\n\t\t\trec, err := goavro.NewRecord(metricListNamespace, metricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\trec.Set(\"topic\", \"some-topic\")\n\t\t\trec.Set(\"tags\", []interface{}{recTags})\n\t\t\trec.Set(\"datapoints\", []interface{}{recDps})\n\n\t\t\t\/\/ Encode and write the record\n\t\t\tconn, err := net.Dial(\"tcp\", net.JoinHostPort(\"localhost\", strconv.Itoa(port)))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tcodec, err := goavro.NewCodec(metricsSchema.MetricListSchema)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tavroWriter, err := goavro.NewWriter(goavro.ToWriter(conn), goavro.UseCodec(codec))\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t\/\/ Test\n\t\t\tavroWriter.Write(rec)\n\t\t\tavroWriter.Close()\n\t\t\trecords := <-recordsChan \/\/ blocks\n\n\t\t\ttags, err := records.Record.(*goavro.Record).Get(\"tags\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdps, err := records.Record.(*goavro.Record).Get(\"datapoints\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tSo(records.ApproxBytes, ShouldBeGreaterThan, 0)\n\t\t\tSo(records.Topic, ShouldEqual, \"some-topic\")\n\t\t\tSo(fmt.Sprintf(\"%+v\", tags), ShouldEqual, \"[{dcos.metrics.Tag: [dcos.metrics.key: some-key, dcos.metrics.value: some-val]}]\")\n\t\t\tSo(fmt.Sprintf(\"%+v\", dps), ShouldEqual, \"[{dcos.metrics.Datapoint: [dcos.metrics.name: some-name, dcos.metrics.time_ms: 1000, dcos.metrics.value: 42]}]\")\n\t\t})\n\t})\n\n}\n\nfunc TestRead(t *testing.T) {\n\tConvey(\"When reading bytes from an io.Reader\", t, func() {\n\t\tConvey(\"Should return accurate byte counts to countingReader\", func() {\n\t\t\tresult := make([]byte, 3)\n\t\t\tcr := countingReader{strings.NewReader(\"foo\"), 0}\n\t\t\tn, err := cr.Read(result)\n\n\t\t\tSo(err, ShouldBeNil)\n\t\t\tSo(cr.inputBytes, ShouldEqual, 3)\n\t\t\tSo(n, ShouldEqual, cr.inputBytes)\n\t\t\tSo(string(result), ShouldEqual, \"foo\")\n\t\t})\n\t})\n}\n\n\/\/ getEphemeralPort returns an available ephemeral port on the system.\nfunc getEphemeralPort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hashicorp\/consul\/consul\/structs\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCatalogRegister(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/register\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\targs := &structs.RegisterRequest{\n\t\tNode:    \"foo\",\n\t\tAddress: \"127.0.0.1\",\n\t}\n\treq.Body = encodeReq(args)\n\n\tobj, err := srv.CatalogRegister(nil, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tres := obj.(bool)\n\tif res != true {\n\t\tt.Fatalf(\"bad: %v\", res)\n\t}\n}\n\nfunc TestCatalogDeregister(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/deregister\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\targs := &structs.DeregisterRequest{\n\t\tNode: \"foo\",\n\t}\n\treq.Body = encodeReq(args)\n\n\tobj, err := srv.CatalogDeregister(nil, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tres := obj.(bool)\n\tif res != true {\n\t\tt.Fatalf(\"bad: %v\", res)\n\t}\n}\n\nfunc TestCatalogDatacenters(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for initialization\n\ttime.Sleep(10 * time.Millisecond)\n\n\tobj, err := srv.CatalogDatacenters(nil, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tdcs := obj.([]string)\n\tif len(dcs) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodes(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t}\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/nodes?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Verify an index is set\n\tassertIndex(t, resp)\n\n\tnodes := obj.(structs.Nodes)\n\tif len(nodes) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodes_Blocking(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\targs := &structs.DCSpecificRequest{\n\t\tDatacenter: \"dc1\",\n\t}\n\tvar out structs.IndexedNodes\n\tif err := srv.agent.RPC(\"Catalog.ListNodes\", *args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Do an update in a little while\n\tstart := time.Now()\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\targs := &structs.RegisterRequest{\n\t\t\tDatacenter: \"dc1\",\n\t\t\tNode:       \"foo\",\n\t\t\tAddress:    \"127.0.0.1\",\n\t\t}\n\t\tvar out struct{}\n\t\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\t\tt.Fatalf(\"err: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Do a blocking read\n\treq, err := http.NewRequest(\"GET\",\n\t\tfmt.Sprintf(\"\/v1\/catalog\/nodes?wait=60s&index=%d\", out.Index), nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Should block for a while\n\tif time.Now().Sub(start) < 100*time.Millisecond {\n\t\tt.Fatalf(\"too fast\")\n\t}\n\n\tif idx := getIndex(t, resp); idx <= out.Index {\n\t\tt.Fatalf(\"bad: %v\", idx)\n\t}\n\n\tnodes := obj.(structs.Nodes)\n\tif len(nodes) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogServices(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t},\n\t}\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/services?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogServices(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertIndex(t, resp)\n\n\tservices := obj.(structs.Services)\n\tif len(services) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogServiceNodes(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t\tTags:    []string{\"a\"},\n\t\t},\n\t}\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/service\/api?tag=a\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogServiceNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertIndex(t, resp)\n\n\tnodes := obj.(structs.ServiceNodes)\n\tif len(nodes) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodeServices(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\t\/\/ Wait for a leader\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Register node\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t\tTags:    []string{\"a\"},\n\t\t},\n\t}\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/node\/foo?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodeServices(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tassertIndex(t, resp)\n\n\tservices := obj.(*structs.NodeServices)\n\tif len(services.Services) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n<commit_msg>Remove all sleeps from `catalog_endpoint_test.go`<commit_after>package agent\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hashicorp\/consul\/testutil\"\n\t\"github.com\/hashicorp\/consul\/consul\/structs\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCatalogRegister(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/register\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\treq.Body = encodeReq(args)\n\n\tobj, err := srv.CatalogRegister(nil, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tres := obj.(bool)\n\tif res != true {\n\t\tt.Fatalf(\"bad: %v\", res)\n\t}\n}\n\nfunc TestCatalogDeregister(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.DeregisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/deregister\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\treq.Body = encodeReq(args)\n\n\tobj, err := srv.CatalogDeregister(nil, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tres := obj.(bool)\n\tif res != true {\n\t\tt.Fatalf(\"bad: %v\", res)\n\t}\n}\n\nfunc TestCatalogDatacenters(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\tobj, err := srv.CatalogDatacenters(nil, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tdcs := obj.([]string)\n\tif len(dcs) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodes(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/nodes?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Verify an index is set\n\tassertIndex(t, resp)\n\n\tnodes := obj.(structs.Nodes)\n\tif len(nodes) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodes_Blocking(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.DCSpecificRequest{\n\t\tDatacenter: \"dc1\",\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\tvar out structs.IndexedNodes\n\tif err := srv.agent.RPC(\"Catalog.ListNodes\", *args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Do an update in a little while\n\tstart := time.Now()\n\tgo func() {\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\targs := &structs.RegisterRequest{\n\t\t\tDatacenter: \"dc1\",\n\t\t\tNode:       \"foo\",\n\t\t\tAddress:    \"127.0.0.1\",\n\t\t}\n\t\tvar out struct{}\n\t\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\t\tt.Fatalf(\"err: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Do a blocking read\n\treq, err := http.NewRequest(\"GET\",\n\t\tfmt.Sprintf(\"\/v1\/catalog\/nodes?wait=60s&index=%d\", out.Index), nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\t\/\/ Should block for a while\n\tif time.Now().Sub(start) < 50 * time.Millisecond {\n\t\tt.Fatalf(\"too fast\")\n\t}\n\n\tif idx := getIndex(t, resp); idx <= out.Index {\n\t\tt.Fatalf(\"bad: %v\", idx)\n\t}\n\n\tnodes := obj.(structs.Nodes)\n\tif len(nodes) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogServices(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t},\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/services?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogServices(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertIndex(t, resp)\n\n\tservices := obj.(structs.Services)\n\tif len(services) != 2 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogServiceNodes(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t\tTags:    []string{\"a\"},\n\t\t},\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/service\/api?tag=a\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogServiceNodes(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tassertIndex(t, resp)\n\n\tnodes := obj.(structs.ServiceNodes)\n\tif len(nodes) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\n\t}\n}\n\nfunc TestCatalogNodeServices(t *testing.T) {\n\tdir, srv := makeHTTPServer(t)\n\tdefer os.RemoveAll(dir)\n\tdefer srv.Shutdown()\n\tdefer srv.agent.Shutdown()\n\n\targs := &structs.RegisterRequest{\n\t\tDatacenter: \"dc1\",\n\t\tNode:       \"foo\",\n\t\tAddress:    \"127.0.0.1\",\n\t\tService: &structs.NodeService{\n\t\t\tService: \"api\",\n\t\t\tTags:    []string{\"a\"},\n\t\t},\n\t}\n\n\ttestutil.WaitForLeader(t, srv.agent.RPC, args)\n\n\t\/\/ Register node\n\tvar out struct{}\n\tif err := srv.agent.RPC(\"Catalog.Register\", args, &out); err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", \"\/v1\/catalog\/node\/foo?dc=dc1\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\n\tresp := httptest.NewRecorder()\n\tobj, err := srv.CatalogNodeServices(resp, req)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %v\", err)\n\t}\n\tassertIndex(t, resp)\n\n\tservices := obj.(*structs.NodeServices)\n\tif len(services.Services) != 1 {\n\t\tt.Fatalf(\"bad: %v\", obj)\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 gcpcredential\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"k8s.io\/cloud-provider\/credentialconfig\"\n\t\"k8s.io\/klog\/v2\"\n)\n\nconst (\n\tmetadataURL        = \"http:\/\/metadata.google.internal.\/computeMetadata\/v1\/\"\n\tmetadataAttributes = metadataURL + \"instance\/attributes\/\"\n\t\/\/ DockerConfigKey is the URL of the dockercfg metadata key used by DockerConfigKeyProvider.\n\tDockerConfigKey = metadataAttributes + \"google-dockercfg\"\n\t\/\/ DockerConfigURLKey is the URL of the dockercfg metadata key used by DockerConfigURLKeyProvider.\n\tDockerConfigURLKey = metadataAttributes + \"google-dockercfg-url\"\n\tserviceAccounts    = metadataURL + \"instance\/service-accounts\/\"\n\tmetadataScopes     = metadataURL + \"instance\/service-accounts\/default\/scopes\"\n\tmetadataToken      = metadataURL + \"instance\/service-accounts\/default\/token\"\n\tmetadataEmail      = metadataURL + \"instance\/service-accounts\/default\/email\"\n\t\/\/ StorageScopePrefix is the prefix checked by ContainerRegistryProvider.Enabled.\n\tStorageScopePrefix       = \"https:\/\/www.googleapis.com\/auth\/devstorage\"\n\tcloudPlatformScopePrefix = \"https:\/\/www.googleapis.com\/auth\/cloud-platform\"\n\tdefaultServiceAccount    = \"default\/\"\n)\n\n\/\/ GCEProductNameFile is the product file path that contains the cloud service name.\n\/\/ This is a variable instead of a const to enable testing.\nvar GCEProductNameFile = \"\/sys\/class\/dmi\/id\/product_name\"\n\n\/\/ For these urls, the parts of the host name can be glob, for example '*.gcr.io\" will match\n\/\/ \"foo.gcr.io\" and \"bar.gcr.io\".\nvar containerRegistryUrls = []string{\"container.cloud.google.com\", \"gcr.io\", \"*.gcr.io\", \"*.pkg.dev\"}\n\nvar metadataHeader = &http.Header{\n\t\"Metadata-Flavor\": []string{\"Google\"},\n}\n\n\/\/ ProvideConfigKey implements a dockercfg-based authentication flow.\nfunc ProvideConfigKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t\/\/ Read the contents of the google-dockercfg metadata key and\n\t\/\/ parse them as an alternate .dockercfg\n\tif cfg, err := ReadDockerConfigFileFromURL(DockerConfigKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg' metadata: %v\", err)\n\t} else {\n\t\treturn cfg\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}\n\n\/\/ ProvideURLKey implements a dockercfg-url-based authentication flow.\nfunc ProvideURLKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t\/\/ Read the contents of the google-dockercfg-url key and load a .dockercfg from there\n\tif url, err := ReadURL(DockerConfigURLKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg-url' metadata: %v\", err)\n\t} else {\n\t\tif strings.HasPrefix(string(url), \"http\") {\n\t\t\tif cfg, err := ReadDockerConfigFileFromURL(string(url), client, nil); err != nil {\n\t\t\t\tklog.Errorf(\"while reading 'google-dockercfg-url'-specified url: %s, %v\", string(url), err)\n\t\t\t} else {\n\t\t\t\treturn cfg\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ TODO(mattmoor): support reading alternate scheme URLs (e.g. gs:\/\/ or s3:\/\/)\n\t\t\tklog.Errorf(\"Unsupported URL scheme: %s\", string(url))\n\t\t}\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}\n\n\/\/ TokenBlob is used to decode the JSON blob containing an access token\n\/\/ that is returned by GCE metadata.\ntype TokenBlob struct {\n\tAccessToken string `json:\"access_token\"`\n}\n\n\/\/ ProvideContainerRegistry implements a gcr.io-based authentication flow.\nfunc ProvideContainerRegistry(client *http.Client, image string) credentialconfig.RegistryConfig {\n\tcfg := credentialconfig.RegistryConfig{}\n\n\ttokenJSONBlob, err := ReadURL(metadataToken, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading access token endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\temail, err := ReadURL(metadataEmail, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading email endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\tvar parsedBlob TokenBlob\n\tif err := json.Unmarshal([]byte(tokenJSONBlob), &parsedBlob); err != nil {\n\t\tklog.Errorf(\"while parsing json blob %s: %v\", tokenJSONBlob, err)\n\t\treturn cfg\n\t}\n\n\tentry := credentialconfig.RegistryConfigEntry{\n\t\tUsername: \"_token\",\n\t\tPassword: parsedBlob.AccessToken,\n\t\tEmail:    string(email),\n\t}\n\n\t\/\/ Add our entry for each of the supported container registry URLs\n\tfor _, k := range containerRegistryUrls {\n\t\tcfg[k] = entry\n\t}\n\treturn cfg\n}\n<commit_msg>Avoid logging JSON blob on error.<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 gcpcredential\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"k8s.io\/cloud-provider\/credentialconfig\"\n\t\"k8s.io\/klog\/v2\"\n)\n\nconst (\n\tmetadataURL        = \"http:\/\/metadata.google.internal.\/computeMetadata\/v1\/\"\n\tmetadataAttributes = metadataURL + \"instance\/attributes\/\"\n\t\/\/ DockerConfigKey is the URL of the dockercfg metadata key used by DockerConfigKeyProvider.\n\tDockerConfigKey = metadataAttributes + \"google-dockercfg\"\n\t\/\/ DockerConfigURLKey is the URL of the dockercfg metadata key used by DockerConfigURLKeyProvider.\n\tDockerConfigURLKey = metadataAttributes + \"google-dockercfg-url\"\n\tserviceAccounts    = metadataURL + \"instance\/service-accounts\/\"\n\tmetadataScopes     = metadataURL + \"instance\/service-accounts\/default\/scopes\"\n\tmetadataToken      = metadataURL + \"instance\/service-accounts\/default\/token\"\n\tmetadataEmail      = metadataURL + \"instance\/service-accounts\/default\/email\"\n\t\/\/ StorageScopePrefix is the prefix checked by ContainerRegistryProvider.Enabled.\n\tStorageScopePrefix       = \"https:\/\/www.googleapis.com\/auth\/devstorage\"\n\tcloudPlatformScopePrefix = \"https:\/\/www.googleapis.com\/auth\/cloud-platform\"\n\tdefaultServiceAccount    = \"default\/\"\n)\n\n\/\/ GCEProductNameFile is the product file path that contains the cloud service name.\n\/\/ This is a variable instead of a const to enable testing.\nvar GCEProductNameFile = \"\/sys\/class\/dmi\/id\/product_name\"\n\n\/\/ For these urls, the parts of the host name can be glob, for example '*.gcr.io\" will match\n\/\/ \"foo.gcr.io\" and \"bar.gcr.io\".\nvar containerRegistryUrls = []string{\"container.cloud.google.com\", \"gcr.io\", \"*.gcr.io\", \"*.pkg.dev\"}\n\nvar metadataHeader = &http.Header{\n\t\"Metadata-Flavor\": []string{\"Google\"},\n}\n\n\/\/ ProvideConfigKey implements a dockercfg-based authentication flow.\nfunc ProvideConfigKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t\/\/ Read the contents of the google-dockercfg metadata key and\n\t\/\/ parse them as an alternate .dockercfg\n\tif cfg, err := ReadDockerConfigFileFromURL(DockerConfigKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg' metadata: %v\", err)\n\t} else {\n\t\treturn cfg\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}\n\n\/\/ ProvideURLKey implements a dockercfg-url-based authentication flow.\nfunc ProvideURLKey(client *http.Client, image string) credentialconfig.RegistryConfig {\n\t\/\/ Read the contents of the google-dockercfg-url key and load a .dockercfg from there\n\tif url, err := ReadURL(DockerConfigURLKey, client, metadataHeader); err != nil {\n\t\tklog.Errorf(\"while reading 'google-dockercfg-url' metadata: %v\", err)\n\t} else {\n\t\tif strings.HasPrefix(string(url), \"http\") {\n\t\t\tif cfg, err := ReadDockerConfigFileFromURL(string(url), client, nil); err != nil {\n\t\t\t\tklog.Errorf(\"while reading 'google-dockercfg-url'-specified url: %s, %v\", string(url), err)\n\t\t\t} else {\n\t\t\t\treturn cfg\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ TODO(mattmoor): support reading alternate scheme URLs (e.g. gs:\/\/ or s3:\/\/)\n\t\t\tklog.Errorf(\"Unsupported URL scheme: %s\", string(url))\n\t\t}\n\t}\n\n\treturn credentialconfig.RegistryConfig{}\n}\n\n\/\/ TokenBlob is used to decode the JSON blob containing an access token\n\/\/ that is returned by GCE metadata.\ntype TokenBlob struct {\n\tAccessToken string `json:\"access_token\"`\n}\n\n\/\/ ProvideContainerRegistry implements a gcr.io-based authentication flow.\nfunc ProvideContainerRegistry(client *http.Client, image string) credentialconfig.RegistryConfig {\n\tcfg := credentialconfig.RegistryConfig{}\n\n\ttokenJSONBlob, err := ReadURL(metadataToken, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading access token endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\temail, err := ReadURL(metadataEmail, client, metadataHeader)\n\tif err != nil {\n\t\tklog.Errorf(\"while reading email endpoint: %v\", err)\n\t\treturn cfg\n\t}\n\n\tvar parsedBlob TokenBlob\n\tif err := json.Unmarshal([]byte(tokenJSONBlob), &parsedBlob); err != nil {\n\t\tklog.Errorf(\"error while parsing json blob of length %d\", len(tokenJSONBlob))\n\t\treturn cfg\n\t}\n\n\tentry := credentialconfig.RegistryConfigEntry{\n\t\tUsername: \"_token\",\n\t\tPassword: parsedBlob.AccessToken,\n\t\tEmail:    string(email),\n\t}\n\n\t\/\/ Add our entry for each of the supported container registry URLs\n\tfor _, k := range containerRegistryUrls {\n\t\tcfg[k] = entry\n\t}\n\treturn cfg\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 common\n\nimport (\n\t\"github.com\/admpub\/tail\"\n\t\"github.com\/webx-top\/echo\"\n)\n\n\/\/ LogParsers 日志格式解析器\nvar LogParsers = map[string]func(line *tail.Line) (interface{}, error){}\n\n\/\/ LogShow 获取日志内容用于显示\nfunc LogShow(ctx echo.Context, logFile string, extensions ...echo.H) error {\n\tdata := ctx.Data()\n\tvar result echo.H\n\tif len(extensions) > 0 {\n\t\tresult = extensions[0]\n\t}\n\tif result == nil {\n\t\tresult = echo.H{}\n\t}\n\tif len(logFile) == 0 {\n\t\tresult.Set(`content`, ctx.T(`没有日志文件`))\n\t\tdata.SetData(result)\n\t\treturn ctx.JSON(data)\n\t}\n\tlastLines := ctx.Formx(`lastLines`).Int()\n\tconfig := tail.Config{\n\t\tMustExist: true,\n\t\tLastLines: 50,\n\t}\n\tif lastLines > 0 {\n\t\tconfig.LastLines = lastLines\n\t}\n\tobj, err := tail.TailFile(logFile, config)\n\tif err != nil {\n\t\tdata.SetError(err)\n\t} else {\n\t\tpipe := ctx.Query(`pipe`)\n\t\tif len(pipe) > 0 {\n\t\t\tparser, ok := LogParsers[pipe]\n\t\t\tif !ok {\n\t\t\t\treturn ctx.JSON(data.SetInfo(ctx.T(`Invalid pipe: %s`, pipe), 0))\n\t\t\t}\n\t\t\trows := []interface{}{}\n\t\t\tfor line := range obj.Lines {\n\t\t\t\trow, err := parser(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn ctx.JSON(data.SetError(err))\n\t\t\t\t}\n\t\t\t\tif row == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trows = append(rows, row)\n\t\t\t}\n\t\t\tresult.Set(`list`, rows)\n\t\t\tdata.SetData(result)\n\t\t\treturn ctx.JSON(data)\n\t\t}\n\t\tvar content string\n\t\tfor line := range obj.Lines {\n\t\t\tcontent += line.Text + \"\\n\"\n\t\t}\n\t\tresult.Set(`content`, content)\n\t\tdata.SetData(result)\n\t}\n\treturn ctx.JSON(data)\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 common\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/admpub\/tail\"\n\t\"github.com\/webx-top\/echo\"\n)\n\n\/\/ LogParsers 日志格式解析器\nvar LogParsers = map[string]func(line *tail.Line) (interface{}, error){}\n\n\/\/ LogShow 获取日志内容用于显示\nfunc LogShow(ctx echo.Context, logFile string, extensions ...echo.H) error {\n\tdata := ctx.Data()\n\tvar result echo.H\n\tif len(extensions) > 0 {\n\t\tresult = extensions[0]\n\t}\n\tif result == nil {\n\t\tresult = echo.H{}\n\t}\n\tif len(logFile) == 0 {\n\t\tresult.Set(`content`, ctx.T(`没有日志文件`))\n\t\tdata.SetData(result)\n\t\treturn ctx.JSON(data)\n\t}\n\tlastLines := ctx.Formx(`lastLines`).Int()\n\tconfig := tail.Config{\n\t\tMustExist: true,\n\t\tLastLines: 50,\n\t}\n\tif lastLines > 0 {\n\t\tconfig.LastLines = lastLines\n\t}\n\tobj, err := tail.TailFile(logFile, config)\n\tif err != nil {\n\t\tdata.SetError(fmt.Errorf(`%w: %s`, err, logFile))\n\t} else {\n\t\tpipe := ctx.Query(`pipe`)\n\t\tif len(pipe) > 0 {\n\t\t\tparser, ok := LogParsers[pipe]\n\t\t\tif !ok {\n\t\t\t\treturn ctx.JSON(data.SetInfo(ctx.T(`Invalid pipe: %s`, pipe), 0))\n\t\t\t}\n\t\t\trows := []interface{}{}\n\t\t\tfor line := range obj.Lines {\n\t\t\t\trow, err := parser(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn ctx.JSON(data.SetError(err))\n\t\t\t\t}\n\t\t\t\tif row == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trows = append(rows, row)\n\t\t\t}\n\t\t\tresult.Set(`list`, rows)\n\t\t\tdata.SetData(result)\n\t\t\treturn ctx.JSON(data)\n\t\t}\n\t\tvar content string\n\t\tfor line := range obj.Lines {\n\t\t\tcontent += line.Text + \"\\n\"\n\t\t}\n\t\tresult.Set(`content`, content)\n\t\tdata.SetData(result)\n\t}\n\treturn ctx.JSON(data)\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 gcscaching\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n)\n\n\/\/ Create a bucket that caches object records returned by the supplied wrapped\n\/\/ bucket. Records are invalidated when modifications are made through this\n\/\/ bucket, and after the supplied TTL.\nfunc NewFastStatBucket(\n\tttl time.Duration,\n\tcache StatCache,\n\tclock timeutil.Clock,\n\twrapped gcs.Bucket) (b gcs.Bucket) {\n\tfsb := &fastStatBucket{\n\t\tcache:   cache,\n\t\tclock:   clock,\n\t\twrapped: wrapped,\n\t\tttl:     ttl,\n\t}\n\n\tb = fsb\n\treturn\n}\n\ntype fastStatBucket struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ GUARDED_BY(mu)\n\tcache StatCache\n\n\tclock   timeutil.Clock\n\twrapped gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tttl time.Duration\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insert(o *gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.cache.Insert(o, b.clock.Now().Add(b.ttl))\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) invalidate(name string) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.cache.Erase(name)\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) lookUp(name string) (o *gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\to = b.cache.LookUp(name, b.clock.Now())\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Bucket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (b *fastStatBucket) Name() string {\n\treturn b.wrapped.Name()\n}\n\nfunc (b *fastStatBucket) NewReader(\n\tctx context.Context,\n\treq *gcs.ReadObjectRequest) (rc io.ReadCloser, err error) {\n\trc, err = b.wrapped.NewReader(ctx, req)\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) CreateObject(\n\tctx context.Context,\n\treq *gcs.CreateObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Throw away any existing record for this object.\n\tb.invalidate(req.Name)\n\n\t\/\/ Create the new object.\n\to, err = b.wrapped.CreateObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Record the new object.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) StatObject(\n\tctx context.Context,\n\treq *gcs.StatObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Do we already have an entry in the cache?\n\to = b.lookUp(req.Name)\n\tif o != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ask the wrapped bucket.\n\to, err = b.wrapped.StatObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Update the cache.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) ListObjects(\n\tctx context.Context,\n\treq *gcs.ListObjectsRequest) (listing *gcs.Listing, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) UpdateObject(\n\tctx context.Context,\n\treq *gcs.UpdateObjectRequest) (o *gcs.Object, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) DeleteObject(\n\tctx context.Context,\n\tname string) (err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<commit_msg>fastStatBucket.ListObjects<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 gcscaching\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n)\n\n\/\/ Create a bucket that caches object records returned by the supplied wrapped\n\/\/ bucket. Records are invalidated when modifications are made through this\n\/\/ bucket, and after the supplied TTL.\nfunc NewFastStatBucket(\n\tttl time.Duration,\n\tcache StatCache,\n\tclock timeutil.Clock,\n\twrapped gcs.Bucket) (b gcs.Bucket) {\n\tfsb := &fastStatBucket{\n\t\tcache:   cache,\n\t\tclock:   clock,\n\t\twrapped: wrapped,\n\t\tttl:     ttl,\n\t}\n\n\tb = fsb\n\treturn\n}\n\ntype fastStatBucket struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ GUARDED_BY(mu)\n\tcache StatCache\n\n\tclock   timeutil.Clock\n\twrapped gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tttl time.Duration\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insertMultiple(objs []*gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\texpiration := b.clock.Now().Add(b.ttl)\n\tfor _, o := range objs {\n\t\tb.cache.Insert(o, expiration)\n\t}\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insert(o *gcs.Object) {\n\tb.insertMultiple([]*gcs.Object{o})\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) invalidate(name string) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.cache.Erase(name)\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) lookUp(name string) (o *gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\to = b.cache.LookUp(name, b.clock.Now())\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Bucket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (b *fastStatBucket) Name() string {\n\treturn b.wrapped.Name()\n}\n\nfunc (b *fastStatBucket) NewReader(\n\tctx context.Context,\n\treq *gcs.ReadObjectRequest) (rc io.ReadCloser, err error) {\n\trc, err = b.wrapped.NewReader(ctx, req)\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) CreateObject(\n\tctx context.Context,\n\treq *gcs.CreateObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Throw away any existing record for this object.\n\tb.invalidate(req.Name)\n\n\t\/\/ Create the new object.\n\to, err = b.wrapped.CreateObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Record the new object.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) StatObject(\n\tctx context.Context,\n\treq *gcs.StatObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Do we already have an entry in the cache?\n\to = b.lookUp(req.Name)\n\tif o != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ask the wrapped bucket.\n\to, err = b.wrapped.StatObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Update the cache.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) ListObjects(\n\tctx context.Context,\n\treq *gcs.ListObjectsRequest) (listing *gcs.Listing, err error) {\n\t\/\/ Fetch the listing.\n\tlisting, err = b.wrapped.ListObjects(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Note anything we found.\n\tb.insertMultiple(listing.Objects)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) UpdateObject(\n\tctx context.Context,\n\treq *gcs.UpdateObjectRequest) (o *gcs.Object, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) DeleteObject(\n\tctx context.Context,\n\tname string) (err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nconst (\n\tnamespace = \"mysql\"\n)\n\nvar (\n\tlistenAddress = flag.String(\"web.listen-address\", \":9104\", \"Address to listen on for web interface and telemetry.\")\n\tmetricPath    = flag.String(\"web.telemetry-path\", \"\/metrics\", \"Path under which to expose metrics.\")\n)\n\ntype Exporter struct {\n\tdsn                        string\n\tmutex                      sync.RWMutex\n\tduration                   prometheus.Gauge\n\ttotalScrapes, errorScrapes prometheus.Counter\n\tmetrics                    map[string]prometheus.Gauge\n}\n\n\/\/ return new empty exporter\nfunc NewMySQLExporter(dsn string) *Exporter {\n\treturn &Exporter{\n\t\tdsn: dsn,\n\t\tduration: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_last_scrape_duration_seconds\",\n\t\t\tHelp:      \"The last scrape duration.\",\n\t\t}),\n\t\ttotalScrapes: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_scrapes_total\",\n\t\t\tHelp:      \"Current total mysqld scrapes.\",\n\t\t}),\n\t\terrorScrapes: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_scrape_errors_total\",\n\t\t\tHelp:      \"Error mysqld scrapes.\",\n\t\t}),\n\t\tmetrics: map[string]prometheus.Gauge{},\n\t}\n}\n\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range e.metrics {\n\t\tm.Describe(ch)\n\t}\n\n\tch <- e.duration.Desc()\n\tch <- e.totalScrapes.Desc()\n\tch <- e.errorScrapes.Desc()\n}\n\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tscrapes := make(chan []string)\n\n\tgo e.scrape(scrapes)\n\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.setMetrics(scrapes)\n\tch <- e.duration\n\tch <- e.totalScrapes\n\tch <- e.errorScrapes\n\te.collectMetrics(ch)\n}\n\nfunc (e *Exporter) scrape(scrapes chan<- []string) {\n\tdefer close(scrapes)\n\n\tnow := time.Now().UnixNano()\n\n\te.totalScrapes.Inc()\n\n\tdb, err := sql.Open(\"mysql\", e.dsn)\n\tif err != nil {\n\t\tlog.Printf(\"error opening connection to database: \", err)\n\t\te.errorScrapes = 1\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\t\/\/ fetch database status\n\trows, err := db.Query(\"SHOW GLOBAL STATUS\")\n\tif err != nil {\n\t\tlog.Println(\"error running status query on database: \", err)\n\t\te.errorScrapes = 1\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tvar key, val []byte\n\tfor rows.Next() {\n\t\t\/\/ get RawBytes from data\n\t\terr = rows.Scan(&key, &val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting result set: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar res []string = make([]string, 2)\n\t\tres[0] = string(key)\n\t\tres[1] = string(val)\n\n\t\tscrapes <- res\n\t}\n\n\t\/\/ fetch slave status\n\trows, err = db.Query(\"SHOW SLAVE STATUS\")\n\tif err != nil {\n\t\tlog.Println(\"error running show slave query on database: \", err)\n\t\te.errorScrapes = 1\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\t\/\/ get RawBytes from data\n\t\terr = rows.Scan(&key, &val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting result set: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar res []string = make([]string, 2)\n\t\tres[0] = string(key)\n\t\tif (string(key) == \"Slave_IO_State\") {\n\t\t\tif (strings.HasPrefix(string(val), \"Waiting\")) {\n\t\t\t\tres[1] = \"1\"\n\t\t\t} else {\n\t\t\t\tres[1] = \"0\"\n\t\t\t}\n\t\t} else {\n\t\t\tif (string(val) == \"Yes\") {\n\t\t\t\tres[1] = \"1\"\n\t\t\t} else if (string(val) == \"No\") {\n\t\t\t\tres[1] = \"0\"\n\t\t\t} else {\n\t\t\t\tres[1] = string(val)\n\t\t\t}\n\t\t}\n\n\t\tscrapes <- res\n\t}\n\t\n\te.errorScrapes = 0\n\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n}\n\nfunc (e *Exporter) setMetrics(scrapes <-chan []string) {\n\tfor row := range scrapes {\n\n\t\tname := strings.ToLower(row[0])\n\t\tvalue, err := strconv.ParseInt(row[1], 10, 64)\n\t\tif err != nil {\n\t\t\t\/\/ convert\/serve text values here ?\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := e.metrics[name]; !ok {\n\t\t\te.metrics[name] = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      name,\n\t\t\t})\n\t\t}\n\n\t\te.metrics[name].Set(float64(value))\n\t}\n}\n\nfunc (e *Exporter) collectMetrics(metrics chan<- prometheus.Metric) {\n\tfor _, m := range e.metrics {\n\t\tm.Collect(metrics)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tdsn := os.Getenv(\"DATA_SOURCE_NAME\")\n\tif len(dsn) == 0 {\n\t\tlog.Fatal(\"couldn't find environment variable DATA_SOURCE_NAME\")\n\t}\n\n\texporter := NewMySQLExporter(dsn)\n\tprometheus.MustRegister(exporter)\n\thttp.Handle(*metricPath, prometheus.Handler())\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<html>\n<head><title>MySQLd exporter<\/title><\/head>\n<body>\n<h1>MySQLd exporter<\/h1>\n<p><a href='` + *metricPath + `'>Metrics<\/a><\/p>\n<\/body>\n<\/html>\n`))\n\t})\n\n\tlog.Fatal(http.ListenAndServe(*listenAddress, nil))\n}\n<commit_msg>fix error gauge<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nconst (\n\tnamespace = \"mysql\"\n)\n\nvar (\n\tlistenAddress = flag.String(\"web.listen-address\", \":9104\", \"Address to listen on for web interface and telemetry.\")\n\tmetricPath    = flag.String(\"web.telemetry-path\", \"\/metrics\", \"Path under which to expose metrics.\")\n)\n\ntype Exporter struct {\n\tdsn                string\n\tmutex              sync.RWMutex\n\tduration,error     prometheus.Gauge\n\ttotalScrapes       prometheus.Counter\n\tmetrics            map[string]prometheus.Gauge\n}\n\n\/\/ return new empty exporter\nfunc NewMySQLExporter(dsn string) *Exporter {\n\treturn &Exporter{\n\t\tdsn: dsn,\n\t\tduration: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_last_scrape_duration_seconds\",\n\t\t\tHelp:      \"The last scrape duration.\",\n\t\t}),\n\t\ttotalScrapes: prometheus.NewCounter(prometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_scrapes_total\",\n\t\t\tHelp:      \"Current total mysqld scrapes.\",\n\t\t}),\n\t\terror: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"exporter_last_scrape_error\",\n\t\t\tHelp:      \"The last scrape error status.\",\n\t\t}),\n\t\tmetrics: map[string]prometheus.Gauge{},\n\t}\n}\n\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range e.metrics {\n\t\tm.Describe(ch)\n\t}\n\n\tch <- e.duration.Desc()\n\tch <- e.totalScrapes.Desc()\n\tch <- e.error.Desc()\n}\n\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tscrapes := make(chan []string)\n\n\tgo e.scrape(scrapes)\n\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.setMetrics(scrapes)\n\tch <- e.duration\n\tch <- e.totalScrapes\n\tch <- e.error\n\te.collectMetrics(ch)\n}\n\nfunc (e *Exporter) scrape(scrapes chan<- []string) {\n\tdefer close(scrapes)\n\n\tnow := time.Now().UnixNano()\n\n\te.totalScrapes.Inc()\n\n\tdb, err := sql.Open(\"mysql\", e.dsn)\n\tif err != nil {\n\t\tlog.Printf(\"error opening connection to database: \", err)\n\t\te.error.Set(1)\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\t\/\/ fetch database status\n\trows, err := db.Query(\"SHOW GLOBAL STATUS\")\n\tif err != nil {\n\t\tlog.Println(\"error running status query on database: \", err)\n\t\te.error.Set(1)\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tvar key, val []byte\n\tfor rows.Next() {\n\t\t\/\/ get RawBytes from data\n\t\terr = rows.Scan(&key, &val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting result set: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar res []string = make([]string, 2)\n\t\tres[0] = string(key)\n\t\tres[1] = string(val)\n\n\t\tscrapes <- res\n\t}\n\n\t\/\/ fetch slave status\n\trows, err = db.Query(\"SHOW SLAVE STATUS\")\n\tif err != nil {\n\t\tlog.Println(\"error running show slave query on database: \", err)\n\t\te.error.Set(1)\n\t\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\t\/\/ get RawBytes from data\n\t\terr = rows.Scan(&key, &val)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error getting result set: \", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar res []string = make([]string, 2)\n\t\tres[0] = string(key)\n\t\tif (string(key) == \"Slave_IO_State\") {\n\t\t\tif (strings.HasPrefix(string(val), \"Waiting\")) {\n\t\t\t\tres[1] = \"1\"\n\t\t\t} else {\n\t\t\t\tres[1] = \"0\"\n\t\t\t}\n\t\t} else {\n\t\t\tif (string(val) == \"Yes\") {\n\t\t\t\tres[1] = \"1\"\n\t\t\t} else if (string(val) == \"No\") {\n\t\t\t\tres[1] = \"0\"\n\t\t\t} else {\n\t\t\t\tres[1] = string(val)\n\t\t\t}\n\t\t}\n\n\t\tscrapes <- res\n\t}\n\t\n\te.error.Set(0)\n\te.duration.Set(float64(time.Now().UnixNano() - now) \/ 1000000000)\n}\n\nfunc (e *Exporter) setMetrics(scrapes <-chan []string) {\n\tfor row := range scrapes {\n\n\t\tname := strings.ToLower(row[0])\n\t\tvalue, err := strconv.ParseInt(row[1], 10, 64)\n\t\tif err != nil {\n\t\t\t\/\/ convert\/serve text values here ?\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := e.metrics[name]; !ok {\n\t\t\te.metrics[name] = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      name,\n\t\t\t})\n\t\t}\n\n\t\te.metrics[name].Set(float64(value))\n\t}\n}\n\nfunc (e *Exporter) collectMetrics(metrics chan<- prometheus.Metric) {\n\tfor _, m := range e.metrics {\n\t\tm.Collect(metrics)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tdsn := os.Getenv(\"DATA_SOURCE_NAME\")\n\tif len(dsn) == 0 {\n\t\tlog.Fatal(\"couldn't find environment variable DATA_SOURCE_NAME\")\n\t}\n\n\texporter := NewMySQLExporter(dsn)\n\tprometheus.MustRegister(exporter)\n\thttp.Handle(*metricPath, prometheus.Handler())\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<html>\n<head><title>MySQLd exporter<\/title><\/head>\n<body>\n<h1>MySQLd exporter<\/h1>\n<p><a href='` + *metricPath + `'>Metrics<\/a><\/p>\n<\/body>\n<\/html>\n`))\n\t})\n\n\tlog.Fatal(http.ListenAndServe(*listenAddress, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\tlog \"github.com\/cihub\/seelog\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar Configuration Settings\n\nfunc main() {\n\tinitLog()\n\n\tfmt.Println(\"Starting...\")\n\tlog.Info(\"Starting...\")\n\n\tConfiguration = LoadSettings()\n\n\tloop := make(chan bool)\n\tgo dns_loop(loop)\n\n\tret := <-loop\n\n\tif !ret {\n\t\tfmt.Println(\"Dns loop exited...\")\n\t\tlog.Error(\"Dns loop exited...\")\n\t\tclose(loop)\n\n\t\tos.Exit(1)\n\t}\n}\n\nfunc dns_loop(loop chan bool) {\n\n\tfor {\n\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\tlog.Info(\"Stack trace:\\n\" + string(debug.Stack()))\n\t\t\t}\n\t\t}()\n\n\t\tdomain_id := get_domain(Configuration.Domain)\n\n\t\tif domain_id == -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrentIP, err := get_currentIP(Configuration.IP_Url)\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsub_domain_id, ip := get_subdomain(domain_id, Configuration.Sub_domain)\n\n\t\tif sub_domain_id == \"\" || ip == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"currentIp is:%s\\n\", currentIP)\n\t\tlog.Infof(\"currentIp is:%s\\n\", currentIP)\n\n\t\t\/\/Continue to check the IP of sub-domain\n\t\tif len(ip) > 0 && !strings.Contains(currentIP, ip) {\n\n\t\t\tfmt.Println(\"Start to update record IP...\")\n\t\t\tlog.Info(\"Start to update record IP...\")\n\t\t\tupdate_ip(domain_id, sub_domain_id, Configuration.Sub_domain, currentIP)\n\n\t\t} else {\n\t\t\tfmt.Println(\"Current IP is same as domain IP, no need to update...\")\n\t\t\tlog.Info(\"Current IP is same as domain IP, no need to update...\")\n\t\t}\n\n\t\t\/\/Interval is 5 minutes\n\t\ttime.Sleep(time.Second * 60 * 5)\n\t}\n\n\tlog.Info(\"Loop exited...\")\n\tloop <- false\n}\n<commit_msg>bug fix<commit_after>package main\n\nimport (\n\t\"fmt\"\n\tlog \"github.com\/cihub\/seelog\"\n\t\"os\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar Configuration Settings\n\nfunc main() {\n\tinitLog()\n\n\tfmt.Println(\"Starting...\")\n\tlog.Info(\"Starting...\")\n\n\tConfiguration = LoadSettings()\n\n\tloop := make(chan bool)\n\tgo dns_loop(loop)\n\n\tret := <-loop\n\n\tif !ret {\n\t\tfmt.Println(\"Dns loop exited...\")\n\t\tlog.Error(\"Dns loop exited...\")\n\t\tclose(loop)\n\n\t\tos.Exit(1)\n\t}\n}\n\nfunc dns_loop(loop chan bool) {\n\n\tfor {\n\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\tlog.Info(\"Stack trace:\\n\" + string(debug.Stack()))\n\t\t\t\tlog.Info(\"Got panic in goroutine, will start a new one...\")\n\t\t\t\tgo dns_loop(loop)\n\t\t\t}\n\t\t}()\n\n\t\tdomain_id := get_domain(Configuration.Domain)\n\n\t\tif domain_id == -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrentIP, err := get_currentIP(Configuration.IP_Url)\n\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsub_domain_id, ip := get_subdomain(domain_id, Configuration.Sub_domain)\n\n\t\tif sub_domain_id == \"\" || ip == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"currentIp is:%s\\n\", currentIP)\n\t\tlog.Infof(\"currentIp is:%s\\n\", currentIP)\n\n\t\t\/\/Continue to check the IP of sub-domain\n\t\tif len(ip) > 0 && !strings.Contains(currentIP, ip) {\n\n\t\t\tfmt.Println(\"Start to update record IP...\")\n\t\t\tlog.Info(\"Start to update record IP...\")\n\t\t\tupdate_ip(domain_id, sub_domain_id, Configuration.Sub_domain, currentIP)\n\n\t\t} else {\n\t\t\tfmt.Println(\"Current IP is same as domain IP, no need to update...\")\n\t\t\tlog.Info(\"Current IP is same as domain IP, no need to update...\")\n\t\t}\n\n\t\t\/\/Interval is 5 minutes\n\t\ttime.Sleep(time.Second * 60 * 5)\n\t}\n\n\tlog.Info(\"Loop exited...\")\n\tloop <- false\n}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/tidwall\/gjson\"\n)\n\nfunc issuesToBlocksGraph(issues []issue) map[string][]string {\n\tblocksGraph := map[string][]string{}\n\tfor _, iss := range issues {\n\t\tfor _, blockedBy := range iss.blockedByKeys {\n\t\t\tblocksGraph[blockedBy] = append(blocksGraph[blockedBy], iss.Key)\n\t\t}\n\n\t\t_, exists := blocksGraph[iss.Key]\n\t\tif !exists {\n\t\t\tblocksGraph[iss.Key] = []string{}\n\t\t}\n\t}\n\treturn blocksGraph\n}\n\ntype errBadStatus struct {\n\tstatusCode int\n}\n\nfunc (e errBadStatus) Error() string {\n\treturn fmt.Sprintf(\"code: %d\", e.statusCode)\n}\n\nfunc getSingleIssue(jc jiraClient, key string) (issue, error) {\n\tq := url.Values{\"fields\": jc.getRequestFields()}\n\tresp, err := jc.Get(fmt.Sprintf(\"\/rest\/api\/2\/issue\/%s\", key), q)\n\tif err != nil {\n\t\treturn issue{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn issue{}, errBadStatus{resp.StatusCode}\n\t}\n\n\tresultBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn issue{}, err\n\t}\n\tparsed := gjson.ParseBytes(resultBytes)\n\tissue := jc.unmarshallIssue(parsed)\n\n\tif issue.Type == \"Epic\" {\n\t\tcolorCode, err := getEpicColorCode(jc, key)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to get epic color code: %v\", err)\n\t\t}\n\t\tissue.Color = colorCode\n\t}\n\n\treturn issue, nil\n}\n\nfunc getEpicColorCode(jc jiraClient, key string) (string, error) {\n\tresp, err := jc.Get(fmt.Sprintf(\"\/rest\/agile\/1.0\/epic\/%s\", key), url.Values{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tresultBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tparsed := gjson.ParseBytes(resultBytes)\n\n\tcolor := parsed.Get(\"color.key\").String()\n\treturn color, nil\n}\n\nfunc getIssues(jc jiraClient, epicKey string) ([]issue, error) {\n\tjql := fmt.Sprintf(`\"Epic Link\" = %s`, epicKey)\n\n\tresult := []issue{}\n\tfor {\n\t\tb, err := jc.Search(jql, jc.getRequestFields(), len(result))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparsed := gjson.ParseBytes(b)\n\n\t\tfor _, parsedIssue := range parsed.Get(\"issues\").Array() {\n\t\t\tiss := jc.unmarshallIssue(parsedIssue)\n\n\t\t\tparsedBlocks := parsedIssue.Get(`fields.issuelinks.#[type.name==\"Blocks\"]#.inwardIssue.key`).Array()\n\t\t\tiss.blockedByKeys = make([]string, len(parsedBlocks))\n\t\t\tfor i := range parsedBlocks {\n\t\t\t\tiss.blockedByKeys[i] = parsedBlocks[i].String()\n\t\t\t}\n\n\t\t\tresult = append(result, iss)\n\t\t}\n\n\t\ttotal := parsed.Get(\"total\").Int()\n\t\tif len(result) >= int(total) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn result, nil\n}\n<commit_msg>Support resolving issues from multiple epics<commit_after>package graph\n\nimport (\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\t\"github.com\/tidwall\/gjson\"\n)\n\nfunc issuesToBlocksGraph(issues []issue) map[string][]string {\n\tblocksGraph := map[string][]string{}\n\tfor _, iss := range issues {\n\t\tfor _, blockedBy := range iss.blockedByKeys {\n\t\t\tblocksGraph[blockedBy] = append(blocksGraph[blockedBy], iss.Key)\n\t\t}\n\n\t\t_, exists := blocksGraph[iss.Key]\n\t\tif !exists {\n\t\t\tblocksGraph[iss.Key] = []string{}\n\t\t}\n\t}\n\treturn blocksGraph\n}\n\ntype errBadStatus struct {\n\tstatusCode int\n}\n\nfunc (e errBadStatus) Error() string {\n\treturn fmt.Sprintf(\"code: %d\", e.statusCode)\n}\n\nfunc getSingleIssue(jc jiraClient, key string) (issue, error) {\n\tq := url.Values{\"fields\": jc.getRequestFields()}\n\tresp, err := jc.Get(fmt.Sprintf(\"\/rest\/api\/2\/issue\/%s\", key), q)\n\tif err != nil {\n\t\treturn issue{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn issue{}, errBadStatus{resp.StatusCode}\n\t}\n\n\tresultBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn issue{}, err\n\t}\n\tparsed := gjson.ParseBytes(resultBytes)\n\tissue := jc.unmarshallIssue(parsed)\n\n\tif issue.Type == \"Epic\" {\n\t\tcolorCode, err := getEpicColorCode(jc, key)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to get epic color code: %v\", err)\n\t\t}\n\t\tissue.Color = colorCode\n\t}\n\n\treturn issue, nil\n}\n\nfunc getEpicColorCode(jc jiraClient, key string) (string, error) {\n\tresp, err := jc.Get(fmt.Sprintf(\"\/rest\/agile\/1.0\/epic\/%s\", key), url.Values{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\tresultBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tparsed := gjson.ParseBytes(resultBytes)\n\n\tcolor := parsed.Get(\"color.key\").String()\n\treturn color, nil\n}\n\nfunc getIssues(jc jiraClient, epicKeys ...string) ([]issue, error) {\n\tif len(epicKeys) == 0 {\n\t\treturn nil, errors.New(\"at least one epic key is required\")\n\t}\n\tjql := fmt.Sprintf(`\"Epic Link\" IN (%s)`, strings.Join(epicKeys, \",\"))\n\n\tresult := []issue{}\n\tfor {\n\t\tb, err := jc.Search(jql, jc.getRequestFields(), len(result))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparsed := gjson.ParseBytes(b)\n\n\t\tfor _, parsedIssue := range parsed.Get(\"issues\").Array() {\n\t\t\tiss := jc.unmarshallIssue(parsedIssue)\n\n\t\t\tparsedBlocks := parsedIssue.Get(`fields.issuelinks.#[type.name==\"Blocks\"]#.inwardIssue.key`).Array()\n\t\t\tiss.blockedByKeys = make([]string, len(parsedBlocks))\n\t\t\tfor i := range parsedBlocks {\n\t\t\t\tiss.blockedByKeys[i] = parsedBlocks[i].String()\n\t\t\t}\n\n\t\t\tresult = append(result, iss)\n\t\t}\n\n\t\ttotal := parsed.Get(\"total\").Int()\n\t\tif len(result) >= int(total) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\/\/\"log\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\/\/\"github.com\/gonum\/matrix\/mat64\"\n\t\"github.com\/gonum\/stat\"\n)\n\nvar (\n\tcolors = []string{\n\t\t\"rgba(31,119,180,1)\",\n\t\t\"rgba(255,127,14,1)\",\n\t\t\"rgba(44,160,44,1)\",\n\t\t\"rgba(214,39,40,1)\",\n\t\t\"rgba(148,103,189,1)\",\n\t\t\"rgba(140,86,75,1)\",\n\t\t\"rgba(227,119,194,1)\",\n\t}\n)\n\nconst (\n\tmaxBallNum       = 59\n\tballs            = 7\n\tavgMarkerSize    = 8\n\tregressionLinear = \"linear\"\n\tregressionPoly   = \"polynomial\"\n\tgraphTypeScatter = \"scatter\"\n\tgraphTypeBar     = \"bar\"\n\tgraphTypeLine    = \"line\"\n)\n\ntype dataset struct {\n\tX           []string `json:\"x\"`\n\tY           []string `json:\"y\"`\n\tZ           []string `json:\"z\"`\n\tName        string   `json:\"name\"`\n\tMode        string   `json:\"mode\"`\n\tType        string   `json:\"type\"`\n\tLine        line     `json:\"line\"`\n\tMarker      marker   `json:\"marker\"`\n\tConnectGaps bool     `json:\"connectgaps\"`\n}\n\ntype datasetB struct {\n\tX           []string `json:\"x\"`\n\tY           []string `json:\"y\"`\n\tZ           []string `json:\"z\"`\n\tName        string   `json:\"name\"`\n\tMode        string   `json:\"mode\"`\n\tType        string   `json:\"type\"`\n\tLine        line     `json:\"line\"`\n\tMarker      markerB  `json:\"marker\"`\n\tConnectGaps bool     `json:\"connectgaps\"`\n}\n\ntype marker struct {\n\tColour  string  `json:\"color\"`\n\tSize    float64 `json:\"size\"`\n\tLine    line    `json:\"line\"`\n\tOpacity float64 `json:\"opacity\"`\n\tSymbol  string  `json:\"symbol\"`\n}\n\ntype markerB struct {\n\tColour   string    `json:\"color\"`\n\tSize     []float64 `json:\"size\"`\n\tSizeMode string    `json:\"sizemode\"`\n\tSizeRef  float64   `json:\"sizeref\"`\n\tLine     line      `json:\"line\"`\n\tOpacity  float64   `json:\"opacity\"`\n\tSymbol   string    `json:\"symbol\"`\n}\n\ntype line struct {\n\tWidth   float64 `json:\"width\"`\n\tColour  string  `json:\"color\"`\n\tShape   string  `json:\"shape\"`\n\tDash    string  `json:\"dash\"`\n\tOpacity float64 `json:\"opacity\"`\n}\n\nfunc graphResultsTimeSeries(records <-chan dbRow, bestFit bool, t string) []dataset {\n\tdata := make([]dataset, balls)\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\n\t\t\t\tswitch t {\n\t\t\t\tcase graphTypeScatter:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\t\tColour:  colors[ball],\n\t\t\t\t\t\t\tSize:    avgMarkerSize,\n\t\t\t\t\t\t\tOpacity: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\n\t\t\t\tcase graphTypeLine:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"lines\",\n\t\t\t\t\t\tLine: line{\n\t\t\t\t\t\t\tWidth: 1,\n\t\t\t\t\t\t\tShape: \"spline\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t} \/\/ END SWITCH\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\t\t\tdata[ball].X = append(data[ball].X, fmt.Sprintf(\"%s:%d:%s\", row.Date.Format(formatYYYYMMDD), row.Set, row.Machine))\n\t\t\tdata[ball].Y = append(data[ball].Y, strconv.Itoa(row.Num[ball]))\n\t\t}\n\n\t\ti++\n\t}\n\n\tif bestFit && t == graphTypeScatter {\n\t\tdata = append(data, regressionSet(data, regressionLinear)...)\n\t}\n\n\treturn data\n}\n\nfunc graphResultsFreqDist(records <-chan dbRow, bestFit bool, t string) []dataset {\n\tdata := make([]dataset, balls)\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\n\t\t\t\tswitch t {\n\t\t\t\tcase graphTypeScatter:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\t\tColour:  colors[ball],\n\t\t\t\t\t\t\tSize:    avgMarkerSize,\n\t\t\t\t\t\t\tOpacity: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tX: freqDistXLabels(),\n\t\t\t\t\t\tY: make([]string, maxBallNum),\n\t\t\t\t\t}\n\n\t\t\t\tcase graphTypeBar:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tType: graphTypeBar,\n\t\t\t\t\t\tX:    freqDistXLabels(),\n\t\t\t\t\t\tY:    make([]string, maxBallNum),\n\t\t\t\t\t}\n\n\t\t\t\t} \/\/ END SWITCH\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\n\t\t\tn, _ := strconv.Atoi(data[ball].Y[row.Num[ball]-1])\n\t\t\tdata[ball].Y[row.Num[ball]-1] = strconv.Itoa(n + 1)\n\t\t}\n\t\ti++\n\t}\n\n\t\/*\n\t\tif bestFit && t != graphTypeBar {\n\t\t\tdata = append(data, regressionSet(data, regressionPoly)...)\n\t\t}\n\t*\/\n\n\treturn data\n}\n\nfunc graphResultsRawScatter3D(records <-chan dbRow) []dataset {\n\tdata := make([]dataset, balls)\n\n\t\/\/ x: machine\n\t\/\/ y: set\n\t\/\/ z: ball result\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\tType: \"scatter3d\",\n\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\tSize:    avgMarkerSize \/ 2,\n\t\t\t\t\t\tOpacity: 0.9,\n\t\t\t\t\t\tLine:    line{Width: 0.1},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\t\t\tdata[ball].X = append(data[ball].X, row.Machine)\n\t\t\tdata[ball].Y = append(data[ball].Y, strconv.Itoa(row.Set))\n\t\t\tdata[ball].Z = append(data[ball].Z, strconv.Itoa(row.Num[ball]))\n\t\t}\n\t\ti++\n\t}\n\n\treturn data\n}\n\nfunc graphMSFreqDistScatter3D(m map[string]int) []dataset {\n\tdata := dataset{\n\t\tType: \"scatter3d\",\n\t\tMode: \"markers\",\n\t\tMarker: marker{\n\t\t\tSize:    avgMarkerSize,\n\t\t\tOpacity: 0.9,\n\t\t\tLine: line{\n\t\t\t\tWidth: 0.1,\n\t\t\t},\n\t\t},\n\t}\n\n\tl := []string{}\n\tfor k := range m {\n\t\tl = append(l, k)\n\t}\n\tsort.Strings(l)\n\n\tfor _, k := range l {\n\t\ts := strings.Split(k, \":\")\n\t\ty, _ := strconv.Atoi(s[1])\n\n\t\tdata.X = append(data.X, s[0])               \/\/ Machine\n\t\tdata.Y = append(data.Y, strconv.Itoa(y))    \/\/ Set\n\t\tdata.Z = append(data.Z, strconv.Itoa(m[k])) \/\/ Frequency\n\t}\n\n\treturn []dataset{data}\n}\n\nfunc graphMSFreqDistBubble(m map[string]int) []datasetB {\n\tdata := datasetB{\n\t\tType: \"scatter\",\n\t\tMode: \"markers\",\n\t\tMarker: markerB{\n\t\t\tOpacity: 0.8,\n\t\t\tLine:    line{Width: 0.1},\n\t\t},\n\t}\n\n\tl := []string{}\n\tfor k := range m {\n\t\tl = append(l, k)\n\t}\n\tsort.Strings(l)\n\n\tfor _, k := range l {\n\t\ts := strings.Split(k, \":\")\n\t\tz, _ := strconv.Atoi(s[1])\n\n\t\tdata.X = append(data.X, s[0])\n\t\tdata.Y = append(data.Y, strconv.Itoa(z))\n\t\tdata.Marker.Size = append(data.Marker.Size, float64(m[k])*2)\n\t}\n\n\treturn []datasetB{data}\n}\n\nfunc regressionSet(data []dataset, t string) []dataset {\n\t\/\/ Calculate and append regressionLinear regressions for each set\n\tr, rX := make([]dataset, balls), make([]float64, len(data[0].Y))\n\n\t\/\/ Generate numerical X axis data\n\tfor i := range rX {\n\t\trX[i] = float64(i) + 1\n\t}\n\n\t\/\/ Iterate existing sets and create new regression sets\n\tfor i, set := range data {\n\t\tr[i] = dataset{\n\t\t\tName: set.Name,\n\t\t\tMode: \"lines\",\n\t\t\tLine: line{\n\t\t\t\tDash:   \"dot\",\n\t\t\t\tWidth:  2,\n\t\t\t\tColour: colors[i],\n\t\t\t},\n\t\t\tConnectGaps: true,\n\t\t\tX:           set.X,\n\t\t}\n\n\t\t\/\/ Translate Y axis to numerical data\n\t\trY := make([]float64, len(data[0].Y))\n\t\tfor j := range rY {\n\t\t\trY[j], _ = strconv.ParseFloat(data[i].Y[j], 64)\n\t\t}\n\t\tswitch t {\n\t\tcase regressionLinear:\n\t\t\tr[i].Y = linRegYData(rX, rY, false)\n\t\t\t\/*\n\t\t\t\tcase regressionPoly:\n\t\t\t\t\tr[i].Y = polRegYData(rX, set.Y, false) \/\/ Not currently working because I suck at maths\n\t\t\t*\/\n\t\t}\n\t}\n\n\treturn r\n}\n\nfunc polRegYData(prX, prY []float64, subzero bool) []float64 {\n\t\/\/ @TODO: polynomial regression sets for non-linear best fits\n\ty := make([]float64, len(prX))\n\t\/\/a, b := stat.LinearRegression(prX, prY, nil, false)\n\t\/\/r2 := stat.RSquared(prX, prY, nil, a, b)\n\t\/\/log.Println(r2)\n\n\treturn y\n}\n\nfunc linRegYData(lrX, lrY []float64, subzero bool) []string {\n\ta, b := stat.LinearRegression(lrX, lrY, nil, false)\n\n\ty := make([]string, len(lrX))\n\tfor idx, x := range lrX {\n\t\tn := a + (b * x)\n\t\tf := strconv.FormatFloat(n, 'f', -1, 64)\n\t\tif subzero {\n\t\t\ty[idx] = f\n\t\t} else if n < 0 {\n\t\t\ty[idx] = \"0\"\n\t\t} else {\n\t\t\ty[idx] = f\n\t\t}\n\n\t}\n\treturn y\n}\n\nfunc freqDistXLabels() []string {\n\tvar x []string\n\tfor i := 0; i < maxBallNum; i++ {\n\t\tx = append(x, strconv.Itoa(i+1))\n\t}\n\treturn x\n}\n\nfunc label(ball int) string {\n\tif ball < 6 {\n\t\treturn fmt.Sprintf(\"Ball %d\", ball+1)\n\t}\n\n\treturn \"Bonus\"\n}\n<commit_msg>all string conversions done using strconv<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\/\/\"log\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\/\/\"github.com\/gonum\/matrix\/mat64\"\n\t\"github.com\/gonum\/stat\"\n)\n\nvar (\n\tcolors = []string{\n\t\t\"rgba(31,119,180,1)\",\n\t\t\"rgba(255,127,14,1)\",\n\t\t\"rgba(44,160,44,1)\",\n\t\t\"rgba(214,39,40,1)\",\n\t\t\"rgba(148,103,189,1)\",\n\t\t\"rgba(140,86,75,1)\",\n\t\t\"rgba(227,119,194,1)\",\n\t}\n)\n\nconst (\n\tmaxBallNum       = 59\n\tballs            = 7\n\tavgMarkerSize    = 8\n\tregressionLinear = \"linear\"\n\tregressionPoly   = \"polynomial\"\n\tgraphTypeScatter = \"scatter\"\n\tgraphTypeBar     = \"bar\"\n\tgraphTypeLine    = \"line\"\n)\n\ntype dataset struct {\n\tX           []string `json:\"x\"`\n\tY           []string `json:\"y\"`\n\tZ           []string `json:\"z\"`\n\tName        string   `json:\"name\"`\n\tMode        string   `json:\"mode\"`\n\tType        string   `json:\"type\"`\n\tLine        line     `json:\"line\"`\n\tMarker      marker   `json:\"marker\"`\n\tConnectGaps bool     `json:\"connectgaps\"`\n}\n\ntype datasetB struct {\n\tX           []string `json:\"x\"`\n\tY           []string `json:\"y\"`\n\tZ           []string `json:\"z\"`\n\tName        string   `json:\"name\"`\n\tMode        string   `json:\"mode\"`\n\tType        string   `json:\"type\"`\n\tLine        line     `json:\"line\"`\n\tMarker      markerB  `json:\"marker\"`\n\tConnectGaps bool     `json:\"connectgaps\"`\n}\n\ntype marker struct {\n\tColour  string  `json:\"color\"`\n\tSize    float64 `json:\"size\"`\n\tLine    line    `json:\"line\"`\n\tOpacity float64 `json:\"opacity\"`\n\tSymbol  string  `json:\"symbol\"`\n}\n\ntype markerB struct {\n\tColour   string    `json:\"color\"`\n\tSize     []float64 `json:\"size\"`\n\tSizeMode string    `json:\"sizemode\"`\n\tSizeRef  float64   `json:\"sizeref\"`\n\tLine     line      `json:\"line\"`\n\tOpacity  float64   `json:\"opacity\"`\n\tSymbol   string    `json:\"symbol\"`\n}\n\ntype line struct {\n\tWidth   float64 `json:\"width\"`\n\tColour  string  `json:\"color\"`\n\tShape   string  `json:\"shape\"`\n\tDash    string  `json:\"dash\"`\n\tOpacity float64 `json:\"opacity\"`\n}\n\nfunc graphResultsTimeSeries(records <-chan dbRow, bestFit bool, t string) []dataset {\n\tdata := make([]dataset, balls)\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\n\t\t\t\tswitch t {\n\t\t\t\tcase graphTypeScatter:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\t\tColour:  colors[ball],\n\t\t\t\t\t\t\tSize:    avgMarkerSize,\n\t\t\t\t\t\t\tOpacity: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\n\t\t\t\tcase graphTypeLine:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"lines\",\n\t\t\t\t\t\tLine: line{\n\t\t\t\t\t\t\tWidth: 1,\n\t\t\t\t\t\t\tShape: \"spline\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t} \/\/ END SWITCH\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\t\t\tdata[ball].X = append(data[ball].X, fmt.Sprintf(\"%s:%d:%s\", row.Date.Format(formatYYYYMMDD), row.Set, row.Machine))\n\t\t\tdata[ball].Y = append(data[ball].Y, strconv.Itoa(row.Num[ball]))\n\t\t}\n\n\t\ti++\n\t}\n\n\tif bestFit && t == graphTypeScatter {\n\t\tdata = append(data, regressionSet(data, regressionLinear)...)\n\t}\n\n\treturn data\n}\n\nfunc graphResultsFreqDist(records <-chan dbRow, bestFit bool, t string) []dataset {\n\tdata := make([]dataset, balls)\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\n\t\t\t\tswitch t {\n\t\t\t\tcase graphTypeScatter:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\t\tColour:  colors[ball],\n\t\t\t\t\t\t\tSize:    avgMarkerSize,\n\t\t\t\t\t\t\tOpacity: 1,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tX: freqDistXLabels(),\n\t\t\t\t\t\tY: make([]string, maxBallNum),\n\t\t\t\t\t}\n\n\t\t\t\tcase graphTypeBar:\n\t\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\t\tType: graphTypeBar,\n\t\t\t\t\t\tX:    freqDistXLabels(),\n\t\t\t\t\t\tY:    make([]string, maxBallNum),\n\t\t\t\t\t}\n\n\t\t\t\t} \/\/ END SWITCH\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\n\t\t\tn, _ := strconv.Atoi(data[ball].Y[row.Num[ball]-1])\n\t\t\tdata[ball].Y[row.Num[ball]-1] = strconv.Itoa(n + 1)\n\t\t}\n\t\ti++\n\t}\n\n\t\/*\n\t\tif bestFit && t != graphTypeBar {\n\t\t\tdata = append(data, regressionSet(data, regressionPoly)...)\n\t\t}\n\t*\/\n\n\treturn data\n}\n\nfunc graphResultsRawScatter3D(records <-chan dbRow) []dataset {\n\tdata := make([]dataset, balls)\n\n\t\/\/ x: machine\n\t\/\/ y: set\n\t\/\/ z: ball result\n\n\ti := 0\n\tfor row := range records {\n\t\tfor ball := 0; ball < balls; ball++ {\n\t\t\tif i == 0 {\n\t\t\t\tdata[ball] = dataset{\n\t\t\t\t\tMode: \"markers\",\n\t\t\t\t\tType: \"scatter3d\",\n\t\t\t\t\tMarker: marker{\n\t\t\t\t\t\tSize:    avgMarkerSize \/ 2,\n\t\t\t\t\t\tOpacity: 0.9,\n\t\t\t\t\t\tLine:    line{Width: 0.1},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tdata[ball].Name = label(ball)\n\t\t\t}\n\t\t\tdata[ball].X = append(data[ball].X, row.Machine)\n\t\t\tdata[ball].Y = append(data[ball].Y, strconv.Itoa(row.Set))\n\t\t\tdata[ball].Z = append(data[ball].Z, strconv.Itoa(row.Num[ball]))\n\t\t}\n\t\ti++\n\t}\n\n\treturn data\n}\n\nfunc graphMSFreqDistScatter3D(m map[string]int) []dataset {\n\tdata := dataset{\n\t\tType: \"scatter3d\",\n\t\tMode: \"markers\",\n\t\tMarker: marker{\n\t\t\tSize:    avgMarkerSize,\n\t\t\tOpacity: 0.9,\n\t\t\tLine: line{\n\t\t\t\tWidth: 0.1,\n\t\t\t},\n\t\t},\n\t}\n\n\tl := []string{}\n\tfor k := range m {\n\t\tl = append(l, k)\n\t}\n\tsort.Strings(l)\n\n\tfor _, k := range l {\n\t\ts := strings.Split(k, \":\")\n\t\ty, _ := strconv.Atoi(s[1])\n\n\t\tdata.X = append(data.X, s[0])               \/\/ Machine\n\t\tdata.Y = append(data.Y, strconv.Itoa(y))    \/\/ Set\n\t\tdata.Z = append(data.Z, strconv.Itoa(m[k])) \/\/ Frequency\n\t}\n\n\treturn []dataset{data}\n}\n\nfunc graphMSFreqDistBubble(m map[string]int) []datasetB {\n\tdata := datasetB{\n\t\tType: \"scatter\",\n\t\tMode: \"markers\",\n\t\tMarker: markerB{\n\t\t\tOpacity: 0.8,\n\t\t\tLine:    line{Width: 0.1},\n\t\t},\n\t}\n\n\tl := []string{}\n\tfor k := range m {\n\t\tl = append(l, k)\n\t}\n\tsort.Strings(l)\n\n\tfor _, k := range l {\n\t\ts := strings.Split(k, \":\")\n\t\tz, _ := strconv.Atoi(s[1])\n\n\t\tdata.X = append(data.X, s[0])\n\t\tdata.Y = append(data.Y, strconv.Itoa(z))\n\t\tdata.Marker.Size = append(data.Marker.Size, float64(m[k])*2)\n\t}\n\n\treturn []datasetB{data}\n}\n\nfunc regressionSet(data []dataset, t string) []dataset {\n\t\/\/ Calculate and append regressionLinear regressions for each set\n\tr, rX := make([]dataset, balls), make([]float64, len(data[0].Y))\n\n\t\/\/ Generate numerical X axis data\n\tfor i := range rX {\n\t\trX[i] = float64(i) + 1\n\t}\n\n\t\/\/ Iterate existing sets and create new regression sets\n\tfor i, set := range data {\n\t\tr[i] = dataset{\n\t\t\tName: set.Name,\n\t\t\tMode: \"lines\",\n\t\t\tLine: line{\n\t\t\t\tDash:   \"dot\",\n\t\t\t\tWidth:  2,\n\t\t\t\tColour: colors[i],\n\t\t\t},\n\t\t\tConnectGaps: true,\n\t\t\tX:           set.X,\n\t\t}\n\n\t\t\/\/ Translate Y axis to numerical data\n\t\trY := make([]float64, len(data[0].Y))\n\t\tfor j := range rY {\n\t\t\trY[j], _ = strconv.ParseFloat(data[i].Y[j], 64)\n\t\t}\n\t\tswitch t {\n\t\tcase regressionLinear:\n\t\t\tr[i].Y = linRegYData(rX, rY, false)\n\n\t\tcase regressionPoly:\n\t\t\tr[i].Y = polRegYData(rX, rY, false) \/\/ Not currently working because I suck at maths\n\n\t\t}\n\t}\n\n\treturn r\n}\n\nfunc polRegYData(prX, prY []float64, subzero bool) []string {\n\t\/\/ @TODO: polynomial regression sets for non-linear best fits\n\ty := make([]string, len(prX))\n\t\/\/a, b := stat.LinearRegression(prX, prY, nil, false)\n\t\/\/r2 := stat.RSquared(prX, prY, nil, a, b)\n\t\/\/log.Println(r2)\n\n\treturn y\n}\n\nfunc linRegYData(lrX, lrY []float64, subzero bool) []string {\n\ta, b := stat.LinearRegression(lrX, lrY, nil, false)\n\n\ty := make([]string, len(lrX))\n\tfor idx, x := range lrX {\n\t\tn := a + (b * x)\n\t\tf := strconv.FormatFloat(n, 'f', -1, 64)\n\t\tif subzero {\n\t\t\ty[idx] = f\n\t\t} else if n < 0 {\n\t\t\ty[idx] = \"0\"\n\t\t} else {\n\t\t\ty[idx] = f\n\t\t}\n\n\t}\n\treturn y\n}\n\nfunc freqDistXLabels() []string {\n\tvar x []string\n\tfor i := 0; i < maxBallNum; i++ {\n\t\tx = append(x, strconv.Itoa(i+1))\n\t}\n\treturn x\n}\n\nfunc label(ball int) string {\n\tif ball < 6 {\n\t\treturn fmt.Sprintf(\"Ball %d\", ball+1)\n\t}\n\n\treturn \"Bonus\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package gogl\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\/* Vertex structures *\/\n\n\/\/ As a rule, gogl tries to place as low a requirement on its vertices as\n\/\/ possible. This is because, from a purely graph theoretic perspective,\n\/\/ vertices are inert. Boring, even. Graphs are more about the topology, the\n\/\/ characteristics of the edges connecting the points than the points\n\/\/ themselves. Your use case cares about the content of your vertices, but gogl\n\/\/ does not.  Consequently, anything can act as a vertex.\ntype Vertex interface{}\ntype VertexList []Vertex\n\n\/\/ VertexSet uses maps to express a value-less (empty struct), indexed\n\/\/ unordered list. See\n\/\/ https:\/\/groups.google.com\/forum\/#!searchin\/golang-nuts\/map\/golang-nuts\/H2cXpwisEUE\/1X2FV-rODfIJ\ntype VertexSet map[Vertex]struct{}\n\n\/\/ However, as a practical, internal matter, some approaches to representing\n\/\/ graphs may benefit significantly (in terms of memory use) from having a uint\n\/\/ that uniquely identifies each vertex. This is essentially an implementation\n\/\/ detail, but if your use case merits it (large graph processing is busting\n\/\/ memory), you can trade off a bit of speed for potentially nontrivial memory\n\/\/ savings.\n\/\/ TODO implement a datastructure that does this, and test these outlandish claims!\ntype IdentifiableVertex interface {\n\tid() uint64\n}\n\n\/* Edge structures *\/\n\n\/\/ A graph's behaviors is primarily a product of the constraints and\n\/\/ capabilities it places on its edges. These constraints and capabilities\n\/\/ determine whether certain types of operations are possible on the graph, as\n\/\/ well as the efficiencies for various operations.\n\n\/\/ gogl aims to provide a diverse range of graph implementations that can meet\n\/\/ the varying constraints and implementation needs, but still achieve optimal\n\/\/ performance given those constraints.\n\n\/\/ TODO totally unclear whether or not defining capabilities in a bitfield like\n\/\/ this will actually help us achieve the goal\nconst (\n\tE_DIRECTED, EM_DIRECTED = 1 << iota, 1<<iota - 1\n\tE_UNDIRECTED, EM_UNDIRECTED\n\tE_WEIGHTED, EM_WEIGHTED\n\tE_TYPED, EM_TYPED\n\tE_SIGNED, EM_SIGNED\n\tE_LOOPS, EM_LOOPS\n\tE_MULTIGRAPH, EM_MULTIGRAPH\n)\n\ntype Edge interface {\n\tSource() Vertex\n\tTarget() Vertex\n\tBoth() (Vertex, Vertex)\n}\n\ntype WeightedEdge interface {\n\tEdge\n\tWeight() int\n}\n\ntype Path []Edge\n\n\/\/ BaseEdge is a struct used internally to represent edges and meet the Edge\n\/\/ interface requirements. It uses the standard notation, (u,v), for vertex\n\/\/ pairs in an edge.\ntype BaseEdge struct {\n\tU Vertex\n\tV Vertex\n}\n\nfunc (e BaseEdge) Source() Vertex {\n\treturn e.U\n}\n\nfunc (e BaseEdge) Target() Vertex {\n\treturn e.V\n}\n\nfunc (e BaseEdge) Both() (Vertex, Vertex) {\n\treturn e.U, e.V\n}\n\ntype BaseWeightedEdge struct {\n\tBaseEdge\n\tW int\n}\n\nfunc (e BaseWeightedEdge) Weight() int {\n\treturn e.W\n}\n\n\/* Graph structures *\/\n\ntype Graph interface {\n\tEachVertex(f func(vertex Vertex))\n\tEachEdge(f func(edge Edge))\n\tEachAdjacent(vertex Vertex, f func(adjacent Vertex))\n\tHasVertex(vertex Vertex) bool\n\tOrder() int\n\tSize() int\n\tInDegree(vertex Vertex) (int, bool)\n\tOutDegree(vertex Vertex) (int, bool)\n}\n\ntype MutableGraph interface {\n\tGraph\n\tEnsureVertex(vertices ...Vertex)\n\tRemoveVertex(vertices ...Vertex)\n\tAddEdges(edges ...Edge)\n\tRemoveEdges(edges ...Edge)\n}\n\n\/\/ A simple graph is in opposition to a multigraph: it disallows loops and\n\/\/ parallel edges.\ntype SimpleGraph interface {\n\tGraph\n\tDensity() float64\n}\n\ntype DirectedGraph interface {\n\tGraph\n\tTranspose() DirectedGraph\n\tIsAcyclic() bool\n\tGetCycles() [][]Vertex\n}\n\ntype WeightedGraph interface {\n\tGraph\n\tEachWeightedEdge(f func(edge WeightedEdge))\n}\n\ntype MutableWeightedGraph interface {\n\tWeightedGraph\n\tEnsureVertex(vertices ...Vertex)\n\tRemoveVertex(vertices ...Vertex)\n\tAddEdges(edges ...WeightedEdge)\n\tRemoveEdges(edges ...WeightedEdge)\n}\n\n\/* Initialization for immutable graphs *\/\n\ntype IGInitializer interface {\n\tEnsureVertex(vertex ...Vertex)\n\tAddEdges(edges ...Edge) bool\n\tGetGraph() Graph\n}\n\ntype ImmutableGraph interface {\n\tGraph\n\tEnsureVertex(vertex ...Vertex)\n\tAddEdges(edges ...Edge)\n}\n\nvar immutableGraphs map[string]ImmutableGraph\n\nfunc CreateImmutableGraph(name string) (*ImmutableGraphInitializer, error) {\n\ttemplate := immutableGraphs[name]\n\tif template == nil {\n\t\treturn nil, fmt.Errorf(\"gogl: Unregistered graph type %s\", name)\n\t}\n\n\t\/\/ Use reflection to make a copy of the graph template\n\tv := reflect.New(reflect.Indirect(reflect.ValueOf(template)).Type()).Interface()\n\tgraph, ok := v.(ImmutableGraph)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"gogl: Unable to copy graph template: %s (%v)\", name, reflect.ValueOf(v).Kind().String()))\n\t}\n\n\tinitializer := &ImmutableGraphInitializer{\n\t\tGraph: graph,\n\t}\n\n\treturn initializer, nil\n}\n\n\/\/ A ImmutableGraphInitializer provides write-only methods to populate an\n\/\/ immutable graph.\ntype ImmutableGraphInitializer struct {\n\tGraph ImmutableGraph\n}\n\nfunc (gi *ImmutableGraphInitializer) EnsureVertex(vertices ...Vertex) {\n\tgi.Graph.EnsureVertex(vertices...)\n}\n\nfunc (gi *ImmutableGraphInitializer) AddEdges(edges ...Edge) {\n\tgi.Graph.AddEdges(edges...)\n}\n\nfunc (gi *ImmutableGraphInitializer) GetGraph() Graph {\n\tdefer func() { gi.Graph = nil }()\n\treturn gi.Graph\n}\n\nfunc init() {\n\timmutableGraphs = map[string]ImmutableGraph{\n\t\t\"ual\": NewUndirected(),\n\t}\n}\n<commit_msg>Remove detritus that was offering no benefit.<commit_after>package gogl\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\/* Vertex structures *\/\n\n\/\/ As a rule, gogl tries to place as low a requirement on its vertices as\n\/\/ possible. This is because, from a purely graph theoretic perspective,\n\/\/ vertices are inert. Boring, even. Graphs are more about the topology, the\n\/\/ characteristics of the edges connecting the points than the points\n\/\/ themselves. Your use case cares about the content of your vertices, but gogl\n\/\/ does not.  Consequently, anything can act as a vertex.\ntype Vertex interface{}\n\n\/* Edge structures *\/\n\n\/\/ A graph's behaviors is primarily a product of the constraints and\n\/\/ capabilities it places on its edges. These constraints and capabilities\n\/\/ determine whether certain types of operations are possible on the graph, as\n\/\/ well as the efficiencies for various operations.\n\n\/\/ gogl aims to provide a diverse range of graph implementations that can meet\n\/\/ the varying constraints and implementation needs, but still achieve optimal\n\/\/ performance given those constraints.\n\ntype Edge interface {\n\tSource() Vertex\n\tTarget() Vertex\n\tBoth() (Vertex, Vertex)\n}\n\ntype WeightedEdge interface {\n\tEdge\n\tWeight() int\n}\n\n\/\/ BaseEdge is a struct used internally to represent edges and meet the Edge\n\/\/ interface requirements. It uses the standard notation, (u,v), for vertex\n\/\/ pairs in an edge.\ntype BaseEdge struct {\n\tU Vertex\n\tV Vertex\n}\n\nfunc (e BaseEdge) Source() Vertex {\n\treturn e.U\n}\n\nfunc (e BaseEdge) Target() Vertex {\n\treturn e.V\n}\n\nfunc (e BaseEdge) Both() (Vertex, Vertex) {\n\treturn e.U, e.V\n}\n\ntype BaseWeightedEdge struct {\n\tBaseEdge\n\tW int\n}\n\nfunc (e BaseWeightedEdge) Weight() int {\n\treturn e.W\n}\n\n\/* Graph structures *\/\n\ntype Graph interface {\n\tEachVertex(f func(vertex Vertex))\n\tEachEdge(f func(edge Edge))\n\tEachAdjacent(vertex Vertex, f func(adjacent Vertex))\n\tHasVertex(vertex Vertex) bool\n\tOrder() int\n\tSize() int\n\tInDegree(vertex Vertex) (int, bool)\n\tOutDegree(vertex Vertex) (int, bool)\n}\n\ntype MutableGraph interface {\n\tGraph\n\tEnsureVertex(vertices ...Vertex)\n\tRemoveVertex(vertices ...Vertex)\n\tAddEdges(edges ...Edge)\n\tRemoveEdges(edges ...Edge)\n}\n\n\/\/ A simple graph is in opposition to a multigraph: it disallows loops and\n\/\/ parallel edges.\ntype SimpleGraph interface {\n\tGraph\n\tDensity() float64\n}\n\ntype DirectedGraph interface {\n\tGraph\n\tTranspose() DirectedGraph\n\tIsAcyclic() bool\n\tGetCycles() [][]Vertex\n}\n\ntype WeightedGraph interface {\n\tGraph\n\tEachWeightedEdge(f func(edge WeightedEdge))\n}\n\ntype MutableWeightedGraph interface {\n\tWeightedGraph\n\tEnsureVertex(vertices ...Vertex)\n\tRemoveVertex(vertices ...Vertex)\n\tAddEdges(edges ...WeightedEdge)\n\tRemoveEdges(edges ...WeightedEdge)\n}\n\n\/* Initialization for immutable graphs *\/\n\ntype IGInitializer interface {\n\tEnsureVertex(vertex ...Vertex)\n\tAddEdges(edges ...Edge) bool\n\tGetGraph() Graph\n}\n\ntype ImmutableGraph interface {\n\tGraph\n\tEnsureVertex(vertex ...Vertex)\n\tAddEdges(edges ...Edge)\n}\n\nvar immutableGraphs map[string]ImmutableGraph\n\nfunc CreateImmutableGraph(name string) (*ImmutableGraphInitializer, error) {\n\ttemplate := immutableGraphs[name]\n\tif template == nil {\n\t\treturn nil, fmt.Errorf(\"gogl: Unregistered graph type %s\", name)\n\t}\n\n\t\/\/ Use reflection to make a copy of the graph template\n\tv := reflect.New(reflect.Indirect(reflect.ValueOf(template)).Type()).Interface()\n\tgraph, ok := v.(ImmutableGraph)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"gogl: Unable to copy graph template: %s (%v)\", name, reflect.ValueOf(v).Kind().String()))\n\t}\n\n\tinitializer := &ImmutableGraphInitializer{\n\t\tGraph: graph,\n\t}\n\n\treturn initializer, nil\n}\n\n\/\/ A ImmutableGraphInitializer provides write-only methods to populate an\n\/\/ immutable graph.\ntype ImmutableGraphInitializer struct {\n\tGraph ImmutableGraph\n}\n\nfunc (gi *ImmutableGraphInitializer) EnsureVertex(vertices ...Vertex) {\n\tgi.Graph.EnsureVertex(vertices...)\n}\n\nfunc (gi *ImmutableGraphInitializer) AddEdges(edges ...Edge) {\n\tgi.Graph.AddEdges(edges...)\n}\n\nfunc (gi *ImmutableGraphInitializer) GetGraph() Graph {\n\tdefer func() { gi.Graph = nil }()\n\treturn gi.Graph\n}\n\nfunc init() {\n\timmutableGraphs = map[string]ImmutableGraph{\n\t\t\"ual\": NewUndirected(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package newznab\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"time\"\n)\n\n\/\/ NZB represents an NZB found on the index\ntype NZB struct {\n\tID          string    `json:\"id,omitempty\"`\n\tTitle       string    `json:\"title,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSize        int64     `json:\"size,omitempty\"`\n\tAirDate     time.Time `json:\"air_date,omitempty\"`\n\tPubDate     time.Time `json:\"pub_date,omitempty\"`\n\tUsenetDate  time.Time `json:\"usenet_date,omitempty\"`\n\tNumGrabs    int       `json:\"num_grabs,omitempty\"`\n\tNumComments int       `json:\"num_comments,omitempty\"`\n\tComments    []Comment `json:\"comments,omitempty\"`\n\n\tSourceEndpoint string `json:\"source_endpoint\"`\n\tSourceAPIKey   string `json:\"source_apikey\"`\n\n\tCategory []string `json:\"category,omitempty\"`\n\tInfo     string   `json:\"info,omitempty\"`\n\tGenre    string   `json:\"genre,omitempty\"`\n\n\t\/\/ TV Specific stuff\n\tTVDBID   string `json:\"genre,omitempty\"`\n\tTVRageID string `json:\"genre,omitempty\"`\n\tSeason   string `json:\"season,omitempty\"`\n\tEpisode  string `json:\"episode,omitempty\"`\n\tTVTitle  string `json:\"tvtitle,omitempty\"`\n\tRating   int    `json:\"tvtitle,omitempty\"`\n\n\t\/\/ Movie Specific stuff\n\tIMDBID    string  `json:\"imdb,omitempty\"`\n\tIMDBTitle string  `json:\"imdbtitle,omitempty\"`\n\tIMDBYear  int     `json:\"imdbyear,omitempty\"`\n\tIMDBScore float32 `json:\"imdbscore,omitempty\"`\n\tCoverURL  string  `json:\"coverurl,omitempty\"`\n\n\t\/\/ Torznab specific stuff\n\tSeeders     int    `json:\"seeders,omitempty\"`\n\tPeers       int    `json:\"peers,omitempty\"`\n\tInfoHash    string `json:\"infohash,omitempty\"`\n\tDownloadURL string `json:\"download_url,omitempty\"`\n\tIsTorrent   bool   `json:\"is_torrent,omitempty\"`\n}\n\n\/\/ Comment represents a user comment left on an NZB record\ntype Comment struct {\n\tTitle   string    `json:\"title,omitempty\"`\n\tContent string    `json:\"content,omitempty\"`\n\tPubDate time.Time `json:\"pub_date,omitempty\"`\n}\n\n\/\/ JSONString returns a JSON string representation of this NZB\nfunc (n NZB) JSONString() string {\n\tjsonString, _ := json.MarshalIndent(n, \"\", \"  \")\n\treturn string(jsonString)\n}\n\n\/\/ JSONString returns a JSON string representation of this Comment\nfunc (c Comment) JSONString() string {\n\tjsonString, _ := json.MarshalIndent(c, \"\", \"  \")\n\treturn string(jsonString)\n}\n\n\/\/ SearchResponse is a RSS version of the response.\ntype SearchResponse struct {\n\tVersion   string `xml:\"version,attr\"`\n\tErrorCode int    `xml:\"code,attr\"`\n\tErrorDesc string `xml:\"description,attr\"`\n\tChannel   struct {\n\t\tTitle string `xml:\"title\"`\n\t\tLink  struct {\n\t\t\tHref string `xml:\"href,attr\"`\n\t\t\tRel  string `xml:\"rel,attr\"`\n\t\t\tType string `xml:\"type,attr\"`\n\t\t} `xml:\"http:\/\/www.w3.org\/2005\/Atom link\"`\n\t\tDescription string `xml:\"description\"`\n\t\tLanguage    string `xml:\"language,omitempty\"`\n\t\tWebmaster   string `xml:\"webmaster,omitempty\"`\n\t\tCategory    string `xml:\"category,omitempty\"`\n\t\tImage       struct {\n\t\t\tURL         string `xml:\"url\"`\n\t\t\tTitle       string `xml:\"title\"`\n\t\t\tLink        string `xml:\"link\"`\n\t\t\tDescription string `xml:\"description,omitempty\"`\n\t\t\tWidth       int    `xml:\"width,omitempty\"`\n\t\t\tHeight      int    `xml:\"height,omitempty\"`\n\t\t} `xml:\"image\"`\n\n\t\tResponse struct {\n\t\t\tOffset int `xml:\"offset,attr\"`\n\t\t\tTotal  int `xml:\"total,attr\"`\n\t\t} `xml:\"http:\/\/www.newznab.com\/DTD\/2010\/feeds\/attributes\/ response\"`\n\n\t\t\/\/ All NZBs that match the search query, up to the response limit.\n\t\tNZBs []RawNZB `xml:\"item\"`\n\t} `xml:\"channel\"`\n}\n\n\/\/ RawNZB represents a single NZB item in search results.\ntype RawNZB struct {\n\tTitle    string `xml:\"title,omitempty\"`\n\tLink     string `xml:\"link,omitempty\"`\n\tSize     int64  `xml:\"size,omitempty\"`\n\tCategory struct {\n\t\tDomain string `xml:\"domain,attr\"`\n\t\tValue  string `xml:\",chardata\"`\n\t} `xml:\"category,omitempty\"`\n\n\tGUID struct {\n\t\tGUID        string `xml:\",chardata\"`\n\t\tIsPermaLink bool   `xml:\"isPermaLink,attr\"`\n\t} `xml:\"guid,omitempty\"`\n\n\tComments    string `xml:\"comments\"`\n\tDescription string `xml:\"description\"`\n\tAuthor      string `xml:\"author,omitempty\"`\n\n\tSource struct {\n\t\tURL   string `xml:\"url,attr\"`\n\t\tValue string `xml:\",chardata\"`\n\t} `xml:\"source,omitempty\"`\n\n\tDate Time `xml:\"pubDate,omitempty\"`\n\n\tEnclosure struct {\n\t\tURL    string `xml:\"url,attr\"`\n\t\tLength string `xml:\"length,attr\"`\n\t\tType   string `xml:\"type,attr\"`\n\t} `xml:\"enclosure,omitempty\"`\n\n\tAttributes []struct {\n\t\tXMLName xml.Name\n\t\tName    string `xml:\"name,attr\"`\n\t\tValue   string `xml:\"value,attr\"`\n\t} `xml:\"attr\"`\n}\n\ntype Time struct {\n\ttime.Time\n}\n\nfunc (t *Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\te.EncodeToken(start)\n\te.EncodeToken(xml.CharData([]byte(t.UTC().Format(time.RFC822))))\n\te.EncodeToken(xml.EndElement{start.Name})\n\treturn nil\n}\n\nfunc (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar raw string\n\n\terr := d.DecodeElement(&raw, &start)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdate, err := time.Parse(time.RFC1123Z, raw)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*t = Time{date}\n\treturn nil\n\n}\n<commit_msg>symmetric marshalling of date<commit_after>package newznab\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"time\"\n)\n\n\/\/ NZB represents an NZB found on the index\ntype NZB struct {\n\tID          string    `json:\"id,omitempty\"`\n\tTitle       string    `json:\"title,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSize        int64     `json:\"size,omitempty\"`\n\tAirDate     time.Time `json:\"air_date,omitempty\"`\n\tPubDate     time.Time `json:\"pub_date,omitempty\"`\n\tUsenetDate  time.Time `json:\"usenet_date,omitempty\"`\n\tNumGrabs    int       `json:\"num_grabs,omitempty\"`\n\tNumComments int       `json:\"num_comments,omitempty\"`\n\tComments    []Comment `json:\"comments,omitempty\"`\n\n\tSourceEndpoint string `json:\"source_endpoint\"`\n\tSourceAPIKey   string `json:\"source_apikey\"`\n\n\tCategory []string `json:\"category,omitempty\"`\n\tInfo     string   `json:\"info,omitempty\"`\n\tGenre    string   `json:\"genre,omitempty\"`\n\n\t\/\/ TV Specific stuff\n\tTVDBID   string `json:\"genre,omitempty\"`\n\tTVRageID string `json:\"genre,omitempty\"`\n\tSeason   string `json:\"season,omitempty\"`\n\tEpisode  string `json:\"episode,omitempty\"`\n\tTVTitle  string `json:\"tvtitle,omitempty\"`\n\tRating   int    `json:\"tvtitle,omitempty\"`\n\n\t\/\/ Movie Specific stuff\n\tIMDBID    string  `json:\"imdb,omitempty\"`\n\tIMDBTitle string  `json:\"imdbtitle,omitempty\"`\n\tIMDBYear  int     `json:\"imdbyear,omitempty\"`\n\tIMDBScore float32 `json:\"imdbscore,omitempty\"`\n\tCoverURL  string  `json:\"coverurl,omitempty\"`\n\n\t\/\/ Torznab specific stuff\n\tSeeders     int    `json:\"seeders,omitempty\"`\n\tPeers       int    `json:\"peers,omitempty\"`\n\tInfoHash    string `json:\"infohash,omitempty\"`\n\tDownloadURL string `json:\"download_url,omitempty\"`\n\tIsTorrent   bool   `json:\"is_torrent,omitempty\"`\n}\n\n\/\/ Comment represents a user comment left on an NZB record\ntype Comment struct {\n\tTitle   string    `json:\"title,omitempty\"`\n\tContent string    `json:\"content,omitempty\"`\n\tPubDate time.Time `json:\"pub_date,omitempty\"`\n}\n\n\/\/ JSONString returns a JSON string representation of this NZB\nfunc (n NZB) JSONString() string {\n\tjsonString, _ := json.MarshalIndent(n, \"\", \"  \")\n\treturn string(jsonString)\n}\n\n\/\/ JSONString returns a JSON string representation of this Comment\nfunc (c Comment) JSONString() string {\n\tjsonString, _ := json.MarshalIndent(c, \"\", \"  \")\n\treturn string(jsonString)\n}\n\n\/\/ SearchResponse is a RSS version of the response.\ntype SearchResponse struct {\n\tVersion   string `xml:\"version,attr\"`\n\tErrorCode int    `xml:\"code,attr\"`\n\tErrorDesc string `xml:\"description,attr\"`\n\tChannel   struct {\n\t\tTitle string `xml:\"title\"`\n\t\tLink  struct {\n\t\t\tHref string `xml:\"href,attr\"`\n\t\t\tRel  string `xml:\"rel,attr\"`\n\t\t\tType string `xml:\"type,attr\"`\n\t\t} `xml:\"http:\/\/www.w3.org\/2005\/Atom link\"`\n\t\tDescription string `xml:\"description\"`\n\t\tLanguage    string `xml:\"language,omitempty\"`\n\t\tWebmaster   string `xml:\"webmaster,omitempty\"`\n\t\tCategory    string `xml:\"category,omitempty\"`\n\t\tImage       struct {\n\t\t\tURL         string `xml:\"url\"`\n\t\t\tTitle       string `xml:\"title\"`\n\t\t\tLink        string `xml:\"link\"`\n\t\t\tDescription string `xml:\"description,omitempty\"`\n\t\t\tWidth       int    `xml:\"width,omitempty\"`\n\t\t\tHeight      int    `xml:\"height,omitempty\"`\n\t\t} `xml:\"image\"`\n\n\t\tResponse struct {\n\t\t\tOffset int `xml:\"offset,attr\"`\n\t\t\tTotal  int `xml:\"total,attr\"`\n\t\t} `xml:\"http:\/\/www.newznab.com\/DTD\/2010\/feeds\/attributes\/ response\"`\n\n\t\t\/\/ All NZBs that match the search query, up to the response limit.\n\t\tNZBs []RawNZB `xml:\"item\"`\n\t} `xml:\"channel\"`\n}\n\n\/\/ RawNZB represents a single NZB item in search results.\ntype RawNZB struct {\n\tTitle    string `xml:\"title,omitempty\"`\n\tLink     string `xml:\"link,omitempty\"`\n\tSize     int64  `xml:\"size,omitempty\"`\n\tCategory struct {\n\t\tDomain string `xml:\"domain,attr\"`\n\t\tValue  string `xml:\",chardata\"`\n\t} `xml:\"category,omitempty\"`\n\n\tGUID struct {\n\t\tGUID        string `xml:\",chardata\"`\n\t\tIsPermaLink bool   `xml:\"isPermaLink,attr\"`\n\t} `xml:\"guid,omitempty\"`\n\n\tComments    string `xml:\"comments\"`\n\tDescription string `xml:\"description\"`\n\tAuthor      string `xml:\"author,omitempty\"`\n\n\tSource struct {\n\t\tURL   string `xml:\"url,attr\"`\n\t\tValue string `xml:\",chardata\"`\n\t} `xml:\"source,omitempty\"`\n\n\tDate Time `xml:\"pubDate,omitempty\"`\n\n\tEnclosure struct {\n\t\tURL    string `xml:\"url,attr\"`\n\t\tLength string `xml:\"length,attr\"`\n\t\tType   string `xml:\"type,attr\"`\n\t} `xml:\"enclosure,omitempty\"`\n\n\tAttributes []struct {\n\t\tXMLName xml.Name\n\t\tName    string `xml:\"name,attr\"`\n\t\tValue   string `xml:\"value,attr\"`\n\t} `xml:\"attr\"`\n}\n\ntype Time struct {\n\ttime.Time\n}\n\nfunc (t *Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\te.EncodeToken(start)\n\te.EncodeToken(xml.CharData([]byte(t.UTC().Format(time.RFC1123Z))))\n\te.EncodeToken(xml.EndElement{start.Name})\n\treturn nil\n}\n\nfunc (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar raw string\n\n\terr := d.DecodeElement(&raw, &start)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdate, err := time.Parse(time.RFC1123Z, raw)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*t = Time{date}\n\treturn nil\n\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\"flag\"\n\t\"strings\"\n\t\"time\"\n\n\texpect \"github.com\/google\/goexpect\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\tk8sv1 \"k8s.io\/api\/core\/v1\"\n\n\t\"kubevirt.io\/kubevirt\/pkg\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/pkg\/log\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n)\n\nvar _ = Describe(\"Slirp\", func() {\n\n\tflag.Parse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tvar genericVmi *v1.VirtualMachineInstance\n\tvar deadbeafVmi *v1.VirtualMachineInstance\n\tvar container k8sv1.Container\n\n\ttests.BeforeAll(func() {\n\t\tports := []v1.Port{{Name: \"http\", Port: 80}}\n\t\tgenericVmi = tests.NewRandomVMIWithSlirpInterfaceEphemeralDiskAndUserdata(tests.RegistryDiskFor(tests.RegistryDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\", ports)\n\t\tdeadbeafVmi = tests.NewRandomVMIWithSlirpInterfaceEphemeralDiskAndUserdata(tests.RegistryDiskFor(tests.RegistryDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\", ports)\n\t\tdeadbeafVmi.Spec.Domain.Devices.Interfaces[0].MacAddress = \"de:ad:00:00:be:af\"\n\n\t\tfor _, vmi := range []*v1.VirtualMachineInstance{genericVmi, deadbeafVmi} {\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\t\t\tgenerateHelloWorldServer(vmi, virtClient, 80, \"tcp\")\n\t\t}\n\t})\n\n\ttable.DescribeTable(\"should be able to\", func(vmiRef **v1.VirtualMachineInstance) {\n\t\tBy(\"have containerPort in the pod manifest\")\n\t\tvmi := *vmiRef\n\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\tfor _, containerSpec := range vmiPod.Spec.Containers {\n\t\t\tif containerSpec.Name == \"compute\" {\n\t\t\t\tcontainer = containerSpec\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tExpect(container.Name).ToNot(Equal(\"\"))\n\t\tExpect(container.Ports).ToNot(Equal(nil))\n\t\tExpect(container.Ports[0].Name).To(Equal(\"http\"))\n\t\tExpect(container.Ports[0].Protocol).To(Equal(k8sv1.Protocol(\"TCP\")))\n\t\tExpect(container.Ports[0].ContainerPort).To(Equal(int32(80)))\n\n\t\tBy(\"start the virtual machine with slirp interface\")\n\t\toutput, err := tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"netstat\", \"-tnlp\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(strings.Contains(output, \"0.0.0.0:80\")).To(BeTrue())\n\n\t\tBy(\"return \\\"Hello World!\\\" when connecting to localhost on port 80\")\n\t\toutput, err = tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"curl\", \"-s\", \"--retry\", \"30\", \"--retry-delay\", \"30\", \"127.0.0.1\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(strings.Contains(output, \"Hello World!\")).To(BeTrue())\n\n\t\tBy(\"reject connecting to localhost and port different than 80\")\n\t\toutput, err = tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"curl\", \"127.0.0.1:9080\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).To(HaveOccurred())\n\n\t\tBy(\"communicate with the outside world\")\n\t\texpecter, _, err := tests.NewConsoleExpecter(virtClient, vmi, 10*time.Second)\n\t\tdefer expecter.Close()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tout, err := expecter.ExpectBatch([]expect.Batcher{\n\t\t\t&expect.BSnd{S: \"\\n\"},\n\t\t\t&expect.BExp{R: \"\\\\$ \"},\n\t\t\t&expect.BSnd{S: \"curl -o \/dev\/null -s -w \\\"%{http_code}\\\\n\\\" -k https:\/\/google.com\\n\"},\n\t\t\t&expect.BExp{R: \"301\"},\n\t\t}, 180*time.Second)\n\t\tlog.Log.Infof(\"%v\", out)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t},\n\t\ttable.Entry(\"VirtualMachineInstance with slirp interface\", &genericVmi),\n\t\ttable.Entry(\"VirtualMachineInstance with slirp interface with custom MAC address\", &deadbeafVmi),\n\t)\n})\n<commit_msg>Use \"\/proc\/net\/tcp instead of netstat in slirp tests<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\"flag\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/google\/goexpect\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\tk8sv1 \"k8s.io\/api\/core\/v1\"\n\n\t\"kubevirt.io\/kubevirt\/pkg\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/pkg\/log\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n)\n\nvar _ = Describe(\"Slirp\", func() {\n\n\tflag.Parse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tvar genericVmi *v1.VirtualMachineInstance\n\tvar deadbeafVmi *v1.VirtualMachineInstance\n\tvar container k8sv1.Container\n\n\ttests.BeforeAll(func() {\n\t\tports := []v1.Port{{Name: \"http\", Port: 80}}\n\t\tgenericVmi = tests.NewRandomVMIWithSlirpInterfaceEphemeralDiskAndUserdata(tests.RegistryDiskFor(tests.RegistryDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\", ports)\n\t\tdeadbeafVmi = tests.NewRandomVMIWithSlirpInterfaceEphemeralDiskAndUserdata(tests.RegistryDiskFor(tests.RegistryDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\", ports)\n\t\tdeadbeafVmi.Spec.Domain.Devices.Interfaces[0].MacAddress = \"de:ad:00:00:be:af\"\n\n\t\tfor _, vmi := range []*v1.VirtualMachineInstance{genericVmi, deadbeafVmi} {\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\t\t\tgenerateHelloWorldServer(vmi, virtClient, 80, \"tcp\")\n\t\t}\n\t})\n\n\ttable.DescribeTable(\"should be able to\", func(vmiRef **v1.VirtualMachineInstance) {\n\t\tBy(\"have containerPort in the pod manifest\")\n\t\tvmi := *vmiRef\n\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\tfor _, containerSpec := range vmiPod.Spec.Containers {\n\t\t\tif containerSpec.Name == \"compute\" {\n\t\t\t\tcontainer = containerSpec\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tExpect(container.Name).ToNot(Equal(\"\"))\n\t\tExpect(container.Ports).ToNot(Equal(nil))\n\t\tExpect(container.Ports[0].Name).To(Equal(\"http\"))\n\t\tExpect(container.Ports[0].Protocol).To(Equal(k8sv1.Protocol(\"TCP\")))\n\t\tExpect(container.Ports[0].ContainerPort).To(Equal(int32(80)))\n\n\t\tBy(\"start the virtual machine with slirp interface\")\n\t\toutput, err := tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"cat\", \"\/proc\/net\/tcp\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\/\/ :0050 is port 80, 0A is listening\n\t\tExpect(strings.Contains(output, \"0: 00000000:0050 00000000:0000 0A\")).To(BeTrue())\n\n\t\tBy(\"return \\\"Hello World!\\\" when connecting to localhost on port 80\")\n\t\toutput, err = tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"curl\", \"-s\", \"--retry\", \"30\", \"--retry-delay\", \"30\", \"127.0.0.1\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(strings.Contains(output, \"Hello World!\")).To(BeTrue())\n\n\t\tBy(\"reject connecting to localhost and port different than 80\")\n\t\toutput, err = tests.ExecuteCommandOnPod(\n\t\t\tvirtClient,\n\t\t\tvmiPod,\n\t\t\tvmiPod.Spec.Containers[1].Name,\n\t\t\t[]string{\"curl\", \"127.0.0.1:9080\"},\n\t\t)\n\t\tlog.Log.Infof(\"%v\", output)\n\t\tExpect(err).To(HaveOccurred())\n\n\t\tBy(\"communicate with the outside world\")\n\t\texpecter, _, err := tests.NewConsoleExpecter(virtClient, vmi, 10*time.Second)\n\t\tdefer expecter.Close()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tout, err := expecter.ExpectBatch([]expect.Batcher{\n\t\t\t&expect.BSnd{S: \"\\n\"},\n\t\t\t&expect.BExp{R: \"\\\\$ \"},\n\t\t\t&expect.BSnd{S: \"curl -o \/dev\/null -s -w \\\"%{http_code}\\\\n\\\" -k https:\/\/google.com\\n\"},\n\t\t\t&expect.BExp{R: \"301\"},\n\t\t}, 180*time.Second)\n\t\tlog.Log.Infof(\"%v\", out)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t},\n\t\ttable.Entry(\"VirtualMachineInstance with slirp interface\", &genericVmi),\n\t\ttable.Entry(\"VirtualMachineInstance with slirp interface with custom MAC address\", &deadbeafVmi),\n\t)\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 thrift\n\nimport (\n\t\"errors\"\n\t\"io\"\n)\n\nvar errTransportInterrupted = errors.New(\"Transport Interrupted\")\n\ntype Flusher interface {\n\tFlush() (err error)\n}\n\ntype ReadSizeProvider interface {\n\tRemainingBytes() (num_bytes uint64)\n}\n\n\n\/\/ Encapsulates the I\/O layer\ntype Transport interface {\n\tio.ReadWriteCloser\n\tFlusher\n\tReadSizeProvider\n\n\t\/\/ Opens the transport for communication\n\tOpen() error\n\n\t\/\/ Returns true if the transport is open\n\tIsOpen() bool\n}\n\ntype stringWriter interface {\n\tWriteString(s string) (n int, err error)\n}\n\n\n\/\/ This is \"enchanced\" transport with extra capabilities. You need to use one of these\n\/\/ to construct protocol.\n\/\/ Notably, Socket does not implement this interface, and it is always a mistake to use\n\/\/ Socket directly in protocol.\ntype RichTransport interface {\n\tio.ReadWriter\n\tio.ByteReader\n\tio.ByteWriter\n\tstringWriter\n\tFlusher\n\tReadSizeProvider\n}\n\n<commit_msg>clean up thrift\/transport.go<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 thrift\n\nimport (\n\t\"errors\"\n\t\"io\"\n)\n\nvar errTransportInterrupted = errors.New(\"Transport Interrupted\")\n\n\/\/ Flusher is the interface that wraps the basic Flush method\ntype Flusher interface {\n\tFlush() (err error)\n}\n\n\/\/ ReadSizeProvider is the interface that wraps the basic RemainingBytes method\ntype ReadSizeProvider interface {\n\tRemainingBytes() (numBytes uint64)\n}\n\n\/\/ Transport is an encapsulation of the I\/O layer\ntype Transport interface {\n\tio.ReadWriteCloser\n\tFlusher\n\tReadSizeProvider\n\n\t\/\/ Opens the transport for communication\n\tOpen() error\n\n\t\/\/ Returns true if the transport is open\n\tIsOpen() bool\n}\n\ntype stringWriter interface {\n\tWriteString(s string) (n int, err error)\n}\n\n\/\/ RichTransport is an \"enhanced\" transport with extra capabilities.\n\/\/ You need to use one of these to construct protocol.\n\/\/ Notably, Socket does not implement this interface, and it is always a mistake to use\n\/\/ Socket directly in protocol.\ntype RichTransport interface {\n\tio.ReadWriter\n\tio.ByteReader\n\tio.ByteWriter\n\tstringWriter\n\tFlusher\n\tReadSizeProvider\n}\n<|endoftext|>"}
{"text":"<commit_before>package operation\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"fmt\"\n\t\"github.com\/stormcat24\/ecs-formation\/aws\"\n\t\"github.com\/stormcat24\/ecs-formation\/service\"\n\t\"github.com\/stormcat24\/ecs-formation\/task\"\n\t\"strings\"\n\t\"github.com\/str1ngs\/ansi\/color\"\n\t\"github.com\/stormcat24\/ecs-formation\/plan\"\n\t\"github.com\/stormcat24\/ecs-formation\/util\"\n\t\"github.com\/stormcat24\/ecs-formation\/bluegreen\"\n\t\"github.com\/stormcat24\/ecs-formation\/logger\"\n)\n\nvar Commands = []cli.Command{\n\tcommandService,\n\tcommandTask,\n\tcommandBluegreen,\n}\n\nvar commandService = cli.Command{\n\tName: \"service\",\n\tUsage: \"Manage ECS services on cluster\",\n\tDescription: `\n\tManage services on ECS cluster.\n`,\n\tAction: doService,\n}\n\nvar commandTask = cli.Command{\n\tName: \"task\",\n\tUsage: \"Manage ECS Task Definitions\",\n\tDescription: `\n\tManage ECS Task Definitions.\n`,\n\tAction: doTask,\n}\n\nvar commandBluegreen = cli.Command{\n\tName: \"bluegreen\",\n\tUsage: \"Manage bluegreen deployment on ECS\",\n\tDescription: `\n\tManage bluegreen deployment on ECS.\n`,\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"nodeploy, nd\",\n\t\t\tUsage: \"bbb\",\n\t\t},\n\t},\n\tAction: doBluegreen,\n}\n\nfunc debug(v ...interface{}) {\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tlog.Println(v...)\n\t}\n}\n\nfunc assert(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc doService(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tclusterController, err := service.NewServiceController(ecsManager, projectDir, operation.TargetResource)\n\n\tplans, err := createClusterPlans(clusterController, projectDir)\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tif (operation.SubCommand == \"apply\") {\n\t\tclusterController.ApplyServicePlans(plans)\n\t}\n}\n\nfunc doTask(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\ttaskController, err := task.NewTaskDefinitionController(ecsManager, projectDir, operation.TargetResource)\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tplans := createTaskPlans(taskController, projectDir)\n\n\tif (operation.SubCommand == \"apply\") {\n\t\tresults, errapp := taskController.ApplyTaskDefinitionPlans(plans)\n\n\t\tif errapp != nil {\n\t\t\tlogger.Main.Error(color.Red(errapp.Error()))\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfor _, output := range results {\n\t\t\tlogger.Main.Infof(\"Registered Task Definition '%s'\", *output.TaskDefinition.Family)\n\t\t\tlogger.Main.Info(color.Cyan(util.StringValueWithIndent(output.TaskDefinition, 1)))\n\t\t}\n\t}\n}\n\nfunc doBluegreen(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tbgController, errbgc := bluegreen.NewBlueGreenController(ecsManager, projectDir, operation.TargetResource)\n\tif errbgc != nil {\n\t\tlogger.Main.Error(color.Red(errbgc.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tbgPlans, err := createBlueGreenPlans(bgController)\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ cluster check\n\n\tif (operation.SubCommand == \"apply\") {\n\n\t\tnodeploy := c.Bool(\"nodeploy\")\n\n\t\tif len(bgPlans) > 0 {\n\t\t\terrbg := bgController.ApplyBlueGreenDeploys(bgPlans, nodeploy)\n\t\t\tif errbg != nil {\n\t\t\t\tlogger.Main.Error(color.Red(errbg.Error()))\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Main.Infof(\"Not found Blue Green Definition\")\n\n\t\t\tif len(operation.TargetResource) > 0 {\n\t\t\t\tlogger.Main.Infof(\"Try to update service '%s'\", operation.TargetResource)\n\t\t\t\tdoService(c)\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nfunc createClusterPlans(controller *service.ServiceController, projectDir string) ([]*plan.ServiceUpdatePlan, error) {\n\n\tlogger.Main.Infoln(\"Checking services on clusters...\")\n\tplans, err := controller.CreateServiceUpdatePlans()\n\n\tif err != nil {\n\t\treturn []*plan.ServiceUpdatePlan{}, err\n\t}\n\n\tfor _, plan := range plans {\n\n\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"Current status of ECS Cluster '%s':\", plan.Name)))\n\n\t\tif len(plan.CurrentServices) > 0 {\n\t\t\tfmt.Println(color.Yellow(\"    Services as follows:\"))\n\t\t} else {\n\t\t\tfmt.Println(color.Yellow(\"    No services are deployed.\"))\n\t\t}\n\n\t\tfor _, cs := range plan.CurrentServices {\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ServiceName = %s\", *cs.ServiceName)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ServiceARN = %s\", *cs.ServiceARN)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        TaskDefinition = %s\", *cs.TaskDefinition)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        DesiredCount = %d\", *cs.DesiredCount)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        PendingCount = %d\", *cs.PendingCount)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        RunningCount = %d\", *cs.RunningCount)))\n\t\t\tfor _, lb := range cs.LoadBalancers {\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ELB = %s:\", *lb.LoadBalancerName)))\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"            ContainerName = %s\", *lb.ContainerName)))\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"            ContainerName = %d\", *lb.ContainerPort)))\n\t\t\t}\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        STATUS = %s\", *cs.Status)))\n\t\t}\n\n\t\tfor _, add := range plan.NewServices {\n\t\t\tfor _, lb := range add.LoadBalancers {\n\t\t\t\tlogger.Main.Info(color.Cyan(fmt.Sprintf(\"            ELB:%s\", lb.Name)))\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn plans, nil\n}\n\nfunc createTaskPlans(controller *task.TaskDefinitionController, projectDir string) []*plan.TaskUpdatePlan {\n\n\ttaskDefs := controller.GetTaskDefinitionMap()\n\tplans := controller.CreateTaskUpdatePlans(taskDefs)\n\n\tfor _, plan := range plans {\n\t\tlogger.Main.Infof(\"Task Definition '%s'\", plan.Name)\n\n\t\tfor _, add := range plan.NewContainers {\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"    (+) %s\", add.Name)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      image: %s\", add.Image)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      ports: %s\", add.Ports)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      environment:\\n%s\", util.StringValueWithIndent(add.Environment, 4))))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      links: %s\", add.Links)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      volumes: %s\", add.Volumes)))\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn plans\n}\n\nfunc createBlueGreenPlans(controller *bluegreen.BlueGreenController) ([]*plan.BlueGreenPlan, error) {\n\n\tbgmap := controller.GetBlueGreenMap()\n\n\tcplans, errcp := controller.ClusterController.CreateServiceUpdatePlans()\n\tif errcp != nil {\n\t\treturn []*plan.BlueGreenPlan{}, errcp\n\t}\n\n\tbgplans, errbgp := controller.CreateBlueGreenPlans(bgmap, cplans)\n\tif errbgp != nil {\n\t\treturn bgplans, errbgp\n\t}\n\n\tfor _, bgplan := range bgplans {\n\t\tfmt.Println(color.Cyan(\"    Blue:\"))\n\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"        Cluster = %s\", bgplan.Blue.NewService.Cluster)))\n\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"        AutoScalingGroupARN = %s\", *bgplan.Blue.AutoScalingGroup.AutoScalingGroupARN)))\n\t\tfmt.Println(color.Cyan(\"        Current services as follows:\"))\n\t\tfor _, bcs := range bgplan.Blue.ClusterUpdatePlan.CurrentServices {\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"            %s:\", *bcs.ServiceName)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                ServiceARN = %s\", *bcs.ServiceARN)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                TaskDefinition = %s\", *bcs.TaskDefinition)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                DesiredCount = %d\", *bcs.DesiredCount)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                PendingCount = %d\", *bcs.PendingCount)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                RunningCount = %d\", *bcs.RunningCount)))\n\t\t}\n\n\t\tfmt.Println(color.Green(\"    Green:\"))\n\t\tfmt.Println(color.Green(fmt.Sprintf(\"        Cluster = %s\", bgplan.Green.NewService.Cluster)))\n\t\tfmt.Println(color.Green(fmt.Sprintf(\"        AutoScalingGroupARN = %s\", *bgplan.Green.AutoScalingGroup.AutoScalingGroupARN)))\n\t\tfmt.Println(color.Green(\"        Current services as follows:\"))\n\t\tfor _, gcs := range bgplan.Green.ClusterUpdatePlan.CurrentServices {\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"            %s:\", *gcs.ServiceName)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                ServiceARN = %s\", *gcs.ServiceARN)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                TaskDefinition = %s\", *gcs.TaskDefinition)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                DesiredCount = %d\", *gcs.DesiredCount)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                PendingCount = %d\", *gcs.PendingCount)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                RunningCount = %d\", *gcs.RunningCount)))\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn bgplans, nil\n}\n\nfunc buildECSManager() (*aws.ECSManager, error) {\n\n\taccessKey := strings.Trim(os.Getenv(\"AWS_ACCESS_KEY\"), \" \")\n\taccessSecretKey := strings.Trim(os.Getenv(\"AWS_SECRET_ACCESS_KEY\"), \" \")\n\tregion := strings.Trim(os.Getenv(\"AWS_REGION\"), \" \")\n\n\tif len(accessKey) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_ACCESS_KEY' is not specified.\")\n\t}\n\n\tif len(accessSecretKey) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_SECRET_ACCESS_KEY' is not specified.\")\n\t}\n\n\tif len(region) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_REGION' is not specified.\")\n\t}\n\n\treturn aws.NewECSManager(accessKey, accessSecretKey, region), nil\n}\n\nfunc createOperation(args cli.Args) (Operation, error) {\n\n\tif len(args) == 0 {\n\t\treturn Operation{}, fmt.Errorf(\"subcommand is not specified.\")\n\t}\n\n\tsub := args[0]\n\tif sub == \"plan\" || sub == \"apply\" {\n\n\t\tvar targetResource string\n\t\tif len(args) > 1 {\n\t\t\ttargetResource = args[1]\n\t\t}\n\n\t\treturn Operation{\n\t\t\tSubCommand: sub,\n\t\t\tTargetResource: targetResource,\n\t\t}, nil\n\t} else {\n\t\treturn Operation{}, fmt.Errorf(\"'%s' is invalid subcommand.\", sub)\n\t}\n}\n\ntype Operation struct {\n\tSubCommand     string\n\tTargetResource string\n}\n<commit_msg>:bug: bugfix<commit_after>package operation\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"fmt\"\n\t\"github.com\/stormcat24\/ecs-formation\/aws\"\n\t\"github.com\/stormcat24\/ecs-formation\/service\"\n\t\"github.com\/stormcat24\/ecs-formation\/task\"\n\t\"strings\"\n\t\"github.com\/str1ngs\/ansi\/color\"\n\t\"github.com\/stormcat24\/ecs-formation\/plan\"\n\t\"github.com\/stormcat24\/ecs-formation\/util\"\n\t\"github.com\/stormcat24\/ecs-formation\/bluegreen\"\n\t\"github.com\/stormcat24\/ecs-formation\/logger\"\n)\n\nvar Commands = []cli.Command{\n\tcommandService,\n\tcommandTask,\n\tcommandBluegreen,\n}\n\nvar commandService = cli.Command{\n\tName: \"service\",\n\tUsage: \"Manage ECS services on cluster\",\n\tDescription: `\n\tManage services on ECS cluster.\n`,\n\tAction: doService,\n}\n\nvar commandTask = cli.Command{\n\tName: \"task\",\n\tUsage: \"Manage ECS Task Definitions\",\n\tDescription: `\n\tManage ECS Task Definitions.\n`,\n\tAction: doTask,\n}\n\nvar commandBluegreen = cli.Command{\n\tName: \"bluegreen\",\n\tUsage: \"Manage bluegreen deployment on ECS\",\n\tDescription: `\n\tManage bluegreen deployment on ECS.\n`,\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"nodeploy, nd\",\n\t\t\tUsage: \"bbb\",\n\t\t},\n\t},\n\tAction: doBluegreen,\n}\n\nfunc debug(v ...interface{}) {\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tlog.Println(v...)\n\t}\n}\n\nfunc assert(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc doService(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tclusterController, err := service.NewServiceController(ecsManager, projectDir, operation.TargetResource)\n\n\tplans, err := createClusterPlans(clusterController, projectDir)\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tif (operation.SubCommand == \"apply\") {\n\t\tclusterController.ApplyServicePlans(plans)\n\t}\n}\n\nfunc doTask(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\ttaskController, err := task.NewTaskDefinitionController(ecsManager, projectDir, operation.TargetResource)\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tplans := createTaskPlans(taskController, projectDir)\n\n\tif (operation.SubCommand == \"apply\") {\n\t\tresults, errapp := taskController.ApplyTaskDefinitionPlans(plans)\n\n\t\tif errapp != nil {\n\t\t\tlogger.Main.Error(color.Red(errapp.Error()))\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfor _, output := range results {\n\t\t\tlogger.Main.Infof(\"Registered Task Definition '%s'\", *output.TaskDefinition.Family)\n\t\t\tlogger.Main.Info(color.Cyan(util.StringValueWithIndent(output.TaskDefinition, 1)))\n\t\t}\n\t}\n}\n\nfunc doBluegreen(c *cli.Context) {\n\n\tecsManager, err := buildECSManager()\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\toperation, errSubCommand := createOperation(c.Args())\n\n\tif errSubCommand != nil {\n\t\tlogger.Main.Error(color.Red(errSubCommand.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tprojectDir, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tbgController, errbgc := bluegreen.NewBlueGreenController(ecsManager, projectDir, operation.TargetResource)\n\tif errbgc != nil {\n\t\tlogger.Main.Error(color.Red(errbgc.Error()))\n\t\tos.Exit(1)\n\t}\n\n\tbgPlans, err := createBlueGreenPlans(bgController)\n\n\tif err != nil {\n\t\tlogger.Main.Error(color.Red(err.Error()))\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ cluster check\n\n\tif (operation.SubCommand == \"apply\") {\n\n\t\tnodeploy := c.Bool(\"nodeploy\")\n\n\t\tif len(bgPlans) > 0 {\n\t\t\terrbg := bgController.ApplyBlueGreenDeploys(bgPlans, nodeploy)\n\t\t\tif errbg != nil {\n\t\t\t\tlogger.Main.Error(color.Red(errbg.Error()))\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Main.Infof(\"Not found Blue Green Definition\")\n\n\t\t\tif len(operation.TargetResource) > 0 && !nodeploy {\n\t\t\t\tlogger.Main.Infof(\"Try to update service '%s'\", operation.TargetResource)\n\t\t\t\tdoService(c)\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nfunc createClusterPlans(controller *service.ServiceController, projectDir string) ([]*plan.ServiceUpdatePlan, error) {\n\n\tlogger.Main.Infoln(\"Checking services on clusters...\")\n\tplans, err := controller.CreateServiceUpdatePlans()\n\n\tif err != nil {\n\t\treturn []*plan.ServiceUpdatePlan{}, err\n\t}\n\n\tfor _, plan := range plans {\n\n\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"Current status of ECS Cluster '%s':\", plan.Name)))\n\n\t\tif len(plan.CurrentServices) > 0 {\n\t\t\tfmt.Println(color.Yellow(\"    Services as follows:\"))\n\t\t} else {\n\t\t\tfmt.Println(color.Yellow(\"    No services are deployed.\"))\n\t\t}\n\n\t\tfor _, cs := range plan.CurrentServices {\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ServiceName = %s\", *cs.ServiceName)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ServiceARN = %s\", *cs.ServiceARN)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        TaskDefinition = %s\", *cs.TaskDefinition)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        DesiredCount = %d\", *cs.DesiredCount)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        PendingCount = %d\", *cs.PendingCount)))\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        RunningCount = %d\", *cs.RunningCount)))\n\t\t\tfor _, lb := range cs.LoadBalancers {\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        ELB = %s:\", *lb.LoadBalancerName)))\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"            ContainerName = %s\", *lb.ContainerName)))\n\t\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"            ContainerName = %d\", *lb.ContainerPort)))\n\t\t\t}\n\t\t\tfmt.Println(color.Yellow(fmt.Sprintf(\"        STATUS = %s\", *cs.Status)))\n\t\t}\n\n\t\tfor _, add := range plan.NewServices {\n\t\t\tfor _, lb := range add.LoadBalancers {\n\t\t\t\tlogger.Main.Info(color.Cyan(fmt.Sprintf(\"            ELB:%s\", lb.Name)))\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn plans, nil\n}\n\nfunc createTaskPlans(controller *task.TaskDefinitionController, projectDir string) []*plan.TaskUpdatePlan {\n\n\ttaskDefs := controller.GetTaskDefinitionMap()\n\tplans := controller.CreateTaskUpdatePlans(taskDefs)\n\n\tfor _, plan := range plans {\n\t\tlogger.Main.Infof(\"Task Definition '%s'\", plan.Name)\n\n\t\tfor _, add := range plan.NewContainers {\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"    (+) %s\", add.Name)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      image: %s\", add.Image)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      ports: %s\", add.Ports)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      environment:\\n%s\", util.StringValueWithIndent(add.Environment, 4))))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      links: %s\", add.Links)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"      volumes: %s\", add.Volumes)))\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn plans\n}\n\nfunc createBlueGreenPlans(controller *bluegreen.BlueGreenController) ([]*plan.BlueGreenPlan, error) {\n\n\tbgmap := controller.GetBlueGreenMap()\n\n\tcplans, errcp := controller.ClusterController.CreateServiceUpdatePlans()\n\tif errcp != nil {\n\t\treturn []*plan.BlueGreenPlan{}, errcp\n\t}\n\n\tbgplans, errbgp := controller.CreateBlueGreenPlans(bgmap, cplans)\n\tif errbgp != nil {\n\t\treturn bgplans, errbgp\n\t}\n\n\tfor _, bgplan := range bgplans {\n\t\tfmt.Println(color.Cyan(\"    Blue:\"))\n\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"        Cluster = %s\", bgplan.Blue.NewService.Cluster)))\n\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"        AutoScalingGroupARN = %s\", *bgplan.Blue.AutoScalingGroup.AutoScalingGroupARN)))\n\t\tfmt.Println(color.Cyan(\"        Current services as follows:\"))\n\t\tfor _, bcs := range bgplan.Blue.ClusterUpdatePlan.CurrentServices {\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"            %s:\", *bcs.ServiceName)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                ServiceARN = %s\", *bcs.ServiceARN)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                TaskDefinition = %s\", *bcs.TaskDefinition)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                DesiredCount = %d\", *bcs.DesiredCount)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                PendingCount = %d\", *bcs.PendingCount)))\n\t\t\tfmt.Println(color.Cyan(fmt.Sprintf(\"                RunningCount = %d\", *bcs.RunningCount)))\n\t\t}\n\n\t\tfmt.Println(color.Green(\"    Green:\"))\n\t\tfmt.Println(color.Green(fmt.Sprintf(\"        Cluster = %s\", bgplan.Green.NewService.Cluster)))\n\t\tfmt.Println(color.Green(fmt.Sprintf(\"        AutoScalingGroupARN = %s\", *bgplan.Green.AutoScalingGroup.AutoScalingGroupARN)))\n\t\tfmt.Println(color.Green(\"        Current services as follows:\"))\n\t\tfor _, gcs := range bgplan.Green.ClusterUpdatePlan.CurrentServices {\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"            %s:\", *gcs.ServiceName)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                ServiceARN = %s\", *gcs.ServiceARN)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                TaskDefinition = %s\", *gcs.TaskDefinition)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                DesiredCount = %d\", *gcs.DesiredCount)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                PendingCount = %d\", *gcs.PendingCount)))\n\t\t\tfmt.Println(color.Green(fmt.Sprintf(\"                RunningCount = %d\", *gcs.RunningCount)))\n\t\t}\n\n\t\tfmt.Println()\n\t}\n\n\treturn bgplans, nil\n}\n\nfunc buildECSManager() (*aws.ECSManager, error) {\n\n\taccessKey := strings.Trim(os.Getenv(\"AWS_ACCESS_KEY\"), \" \")\n\taccessSecretKey := strings.Trim(os.Getenv(\"AWS_SECRET_ACCESS_KEY\"), \" \")\n\tregion := strings.Trim(os.Getenv(\"AWS_REGION\"), \" \")\n\n\tif len(accessKey) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_ACCESS_KEY' is not specified.\")\n\t}\n\n\tif len(accessSecretKey) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_SECRET_ACCESS_KEY' is not specified.\")\n\t}\n\n\tif len(region) == 0 {\n\t\treturn nil, fmt.Errorf(\"'AWS_REGION' is not specified.\")\n\t}\n\n\treturn aws.NewECSManager(accessKey, accessSecretKey, region), nil\n}\n\nfunc createOperation(args cli.Args) (Operation, error) {\n\n\tif len(args) == 0 {\n\t\treturn Operation{}, fmt.Errorf(\"subcommand is not specified.\")\n\t}\n\n\tsub := args[0]\n\tif sub == \"plan\" || sub == \"apply\" {\n\n\t\tvar targetResource string\n\t\tif len(args) > 1 {\n\t\t\ttargetResource = args[1]\n\t\t}\n\n\t\treturn Operation{\n\t\t\tSubCommand: sub,\n\t\t\tTargetResource: targetResource,\n\t\t}, nil\n\t} else {\n\t\treturn Operation{}, fmt.Errorf(\"'%s' is invalid subcommand.\", sub)\n\t}\n}\n\ntype Operation struct {\n\tSubCommand     string\n\tTargetResource string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package hierr provides a simple way to return and display hierarchical\n\/\/ errors.\n\/\/\n\/\/ Transforms:\n\/\/\n\/\/         can't pull remote 'origin': can't run git fetch 'origin' 'refs\/tokens\/*:refs\/tokens\/*': exit status 128\n\/\/\n\/\/ Into:\n\/\/\n\/\/         can't pull remote 'origin'\n\/\/         └─ can't run git fetch 'origin' 'refs\/tokens\/*:refs\/tokens\/*'\n\/\/            └─ exit status 128\npackage hierr\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst (\n\t\/\/ BranchDelimiterASCII represents a simple ASCII delimiter for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchDelimiter = hierr.BranchDelimiterASCII\n\tBranchDelimiterASCII = `\\_ `\n\n\t\/\/ BranchDelimiterBox represents UTF8 delimiter for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchDelimiter = hierr.BranchDelimiterBox\n\tBranchDelimiterBox = `└─ `\n\n\t\/\/ BranchChainerASCII represents a simple ASCII chainer for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchChainer = hierr.BranchChainerASCII\n\tBranchChainerASCII = `| `\n\n\t\/\/ BranchChainerBox represents UTF8 chainer for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchChainer = hierr.BranchChainerBox\n\tBranchChainerBox = `│ `\n\n\t\/\/ BranchSplitterASCII represents a simple ASCII splitter for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchSplitter = hierr.BranchSplitterASCII\n\tBranchSplitterASCII = `+ `\n\n\t\/\/ BranchSplitterBox represents UTF8 splitter for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchSplitter = hierr.BranchSplitterBox\n\tBranchSplitterBox = `├─ `\n)\n\nvar (\n\t\/\/ BranchDelimiter set delimiter each nested error text will be started\n\t\/\/ from.\n\tBranchDelimiter = BranchDelimiterBox\n\n\t\/\/ BranchChainer set chainer each nested error tree text will be started\n\t\/\/ from.\n\tBranchChainer = BranchChainerBox\n\n\t\/\/ BranchSplitter set splitter each nested errors splitted by.\n\tBranchSplitter = BranchSplitterBox\n\n\t\/\/ BranchIndent set number of spaces each nested error will be indented by.\n\tBranchIndent = 3\n)\n\n\/\/ Error represents hierarchy error, linked with nested error.\ntype Error struct {\n\t\/\/ Message is formatter error message, which will be reported when Error()\n\t\/\/ will be invoked.\n\tMessage string\n\n\t\/\/ Nested error, which can be hierr.Error as well.\n\tNested interface{}\n}\n\n\/\/ HierarchicalError represents interface, which methods will be used instead\n\/\/ of calling String() and Error() methods.\ntype HierarchicalError interface {\n\t\/\/ HierarchicalError returns hierarhical string representation.\n\tHierarchicalError() string\n\n\t\/\/ GetNested returns slice of nested errors.\n\tGetNested() []NestedError\n\n\t\/\/ GetMessage returns top-level error message.\n\tGetMessage() string\n}\n\nvar (\n\texiter = os.Exit\n)\n\n\/\/ NestedError is either `error` or string.\ntype NestedError interface{}\n\n\/\/ Errorf creates new hierarchy error.\n\/\/\n\/\/ With nestedError == nil call will be equal to `fmt.Errorf()`.\nfunc Errorf(\n\tnestedError NestedError,\n\tmessage string,\n\targs ...interface{},\n) error {\n\treturn Error{\n\t\tMessage: fmt.Sprintf(message, args...),\n\t\tNested:  nestedError,\n\t}\n}\n\n\/\/ Fatalf creates new hierarchy error, prints to stderr and exit 1\n\/\/\n\/\/ Have same semantics as `hierr.Errorf()`.\nfunc Fatalf(\n\tnestedError NestedError,\n\tmessage string,\n\targs ...interface{},\n) {\n\tfmt.Fprintln(os.Stderr, Errorf(nestedError, message, args...))\n\texiter(1)\n}\n\n\/\/ Error returns string representation of hierarchical error. If no nested\n\/\/ error was specified, then only current error message will be returned.\nfunc (err Error) Error() string {\n\tswitch children := err.Nested.(type) {\n\tcase nil:\n\t\treturn err.Message\n\n\tcase []NestedError:\n\t\treturn formatNestedError(err, children)\n\n\tdefault:\n\t\treturn err.Message + \"\\n\" +\n\t\t\tBranchDelimiter +\n\t\t\tstrings.Replace(\n\t\t\t\tString(err.Nested),\n\t\t\t\t\"\\n\",\n\t\t\t\t\"\\n\"+strings.Repeat(\" \", BranchIndent),\n\t\t\t\t-1,\n\t\t\t)\n\t}\n}\n\n\/\/ GetNested returns nested errors, embedded into error.\nfunc (err Error) GetNested() []NestedError {\n\tchildren, ok := err.Nested.([]NestedError)\n\tif !ok {\n\t\tchildren = []NestedError{}\n\t\tif err.Nested != nil {\n\t\t\tchildren = append(children, err.Nested)\n\t\t}\n\t}\n\n\treturn children\n}\n\n\/\/ GetMessage returns top-level error message.\nfunc (err Error) GetMessage() string {\n\treturn err.Message\n}\n\n\/\/ HierarchicalError returns pretty hierarchical rendering.\nfunc (err Error) HierarchicalError() string {\n\treturn err.Error()\n}\n\n\/\/ Push creates new hierarchy error with multiple branches separated by\n\/\/ separator, delimited by delimiter and prolongated by prolongator.\nfunc Push(topError NestedError, childError ...NestedError) error {\n\tparent, ok := topError.(Error)\n\tif !ok {\n\t\tparent = Error{\n\t\t\tMessage: String(topError),\n\t\t}\n\t}\n\n\tchildren := parent.GetNested()\n\n\tchildren = append(children, childError...)\n\n\treturn Error{\n\t\tMessage: parent.Message,\n\t\tNested:  children,\n\t}\n}\n\n\/\/ String returns string representation of given object, if object implements\n\/\/ HierarchicalError then will be returned result of calling\n\/\/ object.HierarchicalError().\nfunc String(object interface{}) string {\n\tif hierr, ok := object.(HierarchicalError); ok {\n\t\treturn hierr.HierarchicalError()\n\t}\n\n\tif err, ok := object.(error); ok {\n\t\treturn err.Error()\n\t}\n\n\treturn fmt.Sprintf(\"%s\", object)\n}\n\nfunc formatNestedError(err Error, children []NestedError) string {\n\tmessage := err.Message\n\n\tprolongate := false\n\tfor _, child := range children {\n\t\tif childError, ok := child.(HierarchicalError); ok {\n\t\t\terrs := childError.GetNested()\n\t\t\tif len(errs) > 0 {\n\t\t\t\tprolongate = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfor index, child := range children {\n\t\tvar (\n\t\t\tsplitter      = BranchSplitter\n\t\t\tchainer       = BranchChainer\n\t\t\tchainerLength = len([]rune(BranchChainer))\n\t\t)\n\n\t\tif index == len(children)-1 {\n\t\t\tsplitter = BranchDelimiter\n\t\t\tchainer = strings.Repeat(\" \", chainerLength)\n\t\t}\n\n\t\tindentation := chainer\n\t\tif BranchIndent >= chainerLength {\n\t\t\tindentation += strings.Repeat(\" \", BranchIndent-chainerLength)\n\t\t}\n\n\t\tprolongator := \"\"\n\t\tif prolongate && index < len(children)-1 {\n\t\t\tprolongator = \"\\n\" + strings.TrimRightFunc(\n\t\t\t\tchainer, unicode.IsSpace,\n\t\t\t)\n\t\t}\n\n\t\tmessage = message + \"\\n\" +\n\t\t\tsplitter +\n\t\t\tstrings.Replace(\n\t\t\t\tString(child),\n\t\t\t\t\"\\n\",\n\t\t\t\t\"\\n\"+indentation,\n\t\t\t\t-1,\n\t\t\t) +\n\t\t\tprolongator\n\t}\n\n\treturn message\n}\n<commit_msg>deprecate old import path<commit_after>\/\/ Package hierr provides a simple way to return and display hierarchical\n\/\/ errors.\n\/\/\n\/\/ Transforms:\n\/\/\n\/\/         can't pull remote 'origin': can't run git fetch 'origin' 'refs\/tokens\/*:refs\/tokens\/*': exit status 128\n\/\/\n\/\/ Into:\n\/\/\n\/\/         can't pull remote 'origin'\n\/\/         └─ can't run git fetch 'origin' 'refs\/tokens\/*:refs\/tokens\/*'\n\/\/            └─ exit status 128\npackage hierr \/\/ import \"github.com\/reconquest\/hierr-go\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst (\n\t\/\/ BranchDelimiterASCII represents a simple ASCII delimiter for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchDelimiter = hierr.BranchDelimiterASCII\n\tBranchDelimiterASCII = `\\_ `\n\n\t\/\/ BranchDelimiterBox represents UTF8 delimiter for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchDelimiter = hierr.BranchDelimiterBox\n\tBranchDelimiterBox = `└─ `\n\n\t\/\/ BranchChainerASCII represents a simple ASCII chainer for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchChainer = hierr.BranchChainerASCII\n\tBranchChainerASCII = `| `\n\n\t\/\/ BranchChainerBox represents UTF8 chainer for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchChainer = hierr.BranchChainerBox\n\tBranchChainerBox = `│ `\n\n\t\/\/ BranchSplitterASCII represents a simple ASCII splitter for hierarchy\n\t\/\/ branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchSplitter = hierr.BranchSplitterASCII\n\tBranchSplitterASCII = `+ `\n\n\t\/\/ BranchSplitterBox represents UTF8 splitter for hierarchy branches.\n\t\/\/\n\t\/\/ Use: hierr.BranchSplitter = hierr.BranchSplitterBox\n\tBranchSplitterBox = `├─ `\n)\n\nvar (\n\t\/\/ BranchDelimiter set delimiter each nested error text will be started\n\t\/\/ from.\n\tBranchDelimiter = BranchDelimiterBox\n\n\t\/\/ BranchChainer set chainer each nested error tree text will be started\n\t\/\/ from.\n\tBranchChainer = BranchChainerBox\n\n\t\/\/ BranchSplitter set splitter each nested errors splitted by.\n\tBranchSplitter = BranchSplitterBox\n\n\t\/\/ BranchIndent set number of spaces each nested error will be indented by.\n\tBranchIndent = 3\n)\n\n\/\/ Error represents hierarchy error, linked with nested error.\ntype Error struct {\n\t\/\/ Message is formatter error message, which will be reported when Error()\n\t\/\/ will be invoked.\n\tMessage string\n\n\t\/\/ Nested error, which can be hierr.Error as well.\n\tNested interface{}\n}\n\n\/\/ HierarchicalError represents interface, which methods will be used instead\n\/\/ of calling String() and Error() methods.\ntype HierarchicalError interface {\n\t\/\/ HierarchicalError returns hierarhical string representation.\n\tHierarchicalError() string\n\n\t\/\/ GetNested returns slice of nested errors.\n\tGetNested() []NestedError\n\n\t\/\/ GetMessage returns top-level error message.\n\tGetMessage() string\n}\n\nvar (\n\texiter = os.Exit\n)\n\n\/\/ NestedError is either `error` or string.\ntype NestedError interface{}\n\n\/\/ Errorf creates new hierarchy error.\n\/\/\n\/\/ With nestedError == nil call will be equal to `fmt.Errorf()`.\nfunc Errorf(\n\tnestedError NestedError,\n\tmessage string,\n\targs ...interface{},\n) error {\n\treturn Error{\n\t\tMessage: fmt.Sprintf(message, args...),\n\t\tNested:  nestedError,\n\t}\n}\n\n\/\/ Fatalf creates new hierarchy error, prints to stderr and exit 1\n\/\/\n\/\/ Have same semantics as `hierr.Errorf()`.\nfunc Fatalf(\n\tnestedError NestedError,\n\tmessage string,\n\targs ...interface{},\n) {\n\tfmt.Fprintln(os.Stderr, Errorf(nestedError, message, args...))\n\texiter(1)\n}\n\n\/\/ Error returns string representation of hierarchical error. If no nested\n\/\/ error was specified, then only current error message will be returned.\nfunc (err Error) Error() string {\n\tswitch children := err.Nested.(type) {\n\tcase nil:\n\t\treturn err.Message\n\n\tcase []NestedError:\n\t\treturn formatNestedError(err, children)\n\n\tdefault:\n\t\treturn err.Message + \"\\n\" +\n\t\t\tBranchDelimiter +\n\t\t\tstrings.Replace(\n\t\t\t\tString(err.Nested),\n\t\t\t\t\"\\n\",\n\t\t\t\t\"\\n\"+strings.Repeat(\" \", BranchIndent),\n\t\t\t\t-1,\n\t\t\t)\n\t}\n}\n\n\/\/ GetNested returns nested errors, embedded into error.\nfunc (err Error) GetNested() []NestedError {\n\tchildren, ok := err.Nested.([]NestedError)\n\tif !ok {\n\t\tchildren = []NestedError{}\n\t\tif err.Nested != nil {\n\t\t\tchildren = append(children, err.Nested)\n\t\t}\n\t}\n\n\treturn children\n}\n\n\/\/ GetMessage returns top-level error message.\nfunc (err Error) GetMessage() string {\n\treturn err.Message\n}\n\n\/\/ HierarchicalError returns pretty hierarchical rendering.\nfunc (err Error) HierarchicalError() string {\n\treturn err.Error()\n}\n\n\/\/ Push creates new hierarchy error with multiple branches separated by\n\/\/ separator, delimited by delimiter and prolongated by prolongator.\nfunc Push(topError NestedError, childError ...NestedError) error {\n\tparent, ok := topError.(Error)\n\tif !ok {\n\t\tparent = Error{\n\t\t\tMessage: String(topError),\n\t\t}\n\t}\n\n\tchildren := parent.GetNested()\n\n\tchildren = append(children, childError...)\n\n\treturn Error{\n\t\tMessage: parent.Message,\n\t\tNested:  children,\n\t}\n}\n\n\/\/ String returns string representation of given object, if object implements\n\/\/ HierarchicalError then will be returned result of calling\n\/\/ object.HierarchicalError().\nfunc String(object interface{}) string {\n\tif hierr, ok := object.(HierarchicalError); ok {\n\t\treturn hierr.HierarchicalError()\n\t}\n\n\tif err, ok := object.(error); ok {\n\t\treturn err.Error()\n\t}\n\n\treturn fmt.Sprintf(\"%s\", object)\n}\n\nfunc formatNestedError(err Error, children []NestedError) string {\n\tmessage := err.Message\n\n\tprolongate := false\n\tfor _, child := range children {\n\t\tif childError, ok := child.(HierarchicalError); ok {\n\t\t\terrs := childError.GetNested()\n\t\t\tif len(errs) > 0 {\n\t\t\t\tprolongate = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tfor index, child := range children {\n\t\tvar (\n\t\t\tsplitter      = BranchSplitter\n\t\t\tchainer       = BranchChainer\n\t\t\tchainerLength = len([]rune(BranchChainer))\n\t\t)\n\n\t\tif index == len(children)-1 {\n\t\t\tsplitter = BranchDelimiter\n\t\t\tchainer = strings.Repeat(\" \", chainerLength)\n\t\t}\n\n\t\tindentation := chainer\n\t\tif BranchIndent >= chainerLength {\n\t\t\tindentation += strings.Repeat(\" \", BranchIndent-chainerLength)\n\t\t}\n\n\t\tprolongator := \"\"\n\t\tif prolongate && index < len(children)-1 {\n\t\t\tprolongator = \"\\n\" + strings.TrimRightFunc(\n\t\t\t\tchainer, unicode.IsSpace,\n\t\t\t)\n\t\t}\n\n\t\tmessage = message + \"\\n\" +\n\t\t\tsplitter +\n\t\t\tstrings.Replace(\n\t\t\t\tString(child),\n\t\t\t\t\"\\n\",\n\t\t\t\t\"\\n\"+indentation,\n\t\t\t\t-1,\n\t\t\t) +\n\t\t\tprolongator\n\t}\n\n\treturn message\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport \"github.com\/subgraph\/oz\/ipc\"\n\nconst SocketName = \"@oz-control\"\n\ntype OkMsg struct {\n\t_ string \"Ok\"\n}\n\ntype ErrorMsg struct {\n\tMsg string \"Error\"\n}\n\ntype PingMsg struct {\n\tData string \"Ping\"\n}\n\ntype GetConfigMsg struct {\n\tData string \"GetConfig\"\n}\n\ntype ListProfilesMsg struct {\n\t_ string \"ListProfiles\"\n}\n\ntype Profile struct {\n\tIndex int\n\tName  string\n\tPath  string\n}\n\ntype ListProfilesResp struct {\n\tProfiles []Profile \"ListProfilesResp\"\n}\n\ntype LaunchMsg struct {\n\tIndex  int \"Launch\"\n\tPath   string\n\tName   string\n\tPwd    string\n\tGids   []uint32\n\tArgs   []string\n\tEnv    []string\n\tNoexec bool\n}\n\ntype ListSandboxesMsg struct {\n\t_ string \"ListSandboxes\"\n}\n\ntype SandboxInfo struct {\n\tId      int\n\tAddress string\n\tProfile string\n\tMounts  []string\n}\n\ntype ListSandboxesResp struct {\n\tSandboxes []SandboxInfo \"ListSandboxesResp\"\n}\n\ntype KillSandboxMsg struct {\n\tId int \"KillSandbox\"\n}\n\ntype RelaunchXpraClientMsg struct {\n\tId int \"RelaunchXpraClient\"\n}\n\ntype MountFilesMsg struct {\n\tId       int \"MountFiles\"\n\tFiles    []string\n\tReadOnly bool\n}\n\ntype UnmountFileMsg struct {\n\tId   int \"UnmountFile\"\n\tFile string\n}\n\ntype LogsMsg struct {\n\tCount  int \"Logs\"\n\tFollow bool\n}\n\ntype LogData struct {\n\tLines []string \"LogData\"\n}\n\nvar messageFactory = ipc.NewMsgFactory(\n\tnew(PingMsg),\n\tnew(OkMsg),\n\tnew(ErrorMsg),\n\tnew(GetConfigMsg),\n\tnew(ListProfilesMsg),\n\tnew(ListProfilesResp),\n\tnew(LaunchMsg),\n\tnew(ListSandboxesMsg),\n\tnew(ListSandboxesResp),\n\tnew(KillSandboxMsg),\n\tnew(RelaunchXpraClientMsg),\n\tnew(MountFilesMsg),\n\tnew(UnmountFileMsg),\n\tnew(LogsMsg),\n\tnew(LogData),\n)\n<commit_msg>Backport forwarder protocol implementation<commit_after>package daemon\n\nimport \"github.com\/subgraph\/oz\/ipc\"\n\nconst SocketName = \"@oz-control\"\n\ntype OkMsg struct {\n\t_ string \"Ok\"\n}\n\ntype ErrorMsg struct {\n\tMsg string \"Error\"\n}\n\ntype PingMsg struct {\n\tData string \"Ping\"\n}\n\ntype GetConfigMsg struct {\n\tData string \"GetConfig\"\n}\n\ntype ListProfilesMsg struct {\n\t_ string \"ListProfiles\"\n}\n\ntype Profile struct {\n\tIndex int\n\tName  string\n\tPath  string\n}\n\ntype ListProfilesResp struct {\n\tProfiles []Profile \"ListProfilesResp\"\n}\n\ntype ListForwardersResp struct {\n\tName string \"ListForwardersResp\"\n\tForwarders []Forwarder \"ListForwardersResp\"\n}\n\ntype LaunchMsg struct {\n\tIndex  int \"Launch\"\n\tPath   string\n\tName   string\n\tPwd    string\n\tGids   []uint32\n\tArgs   []string\n\tEnv    []string\n\tNoexec bool\n}\n\ntype ListSandboxesMsg struct {\n\t_ string \"ListSandboxes\"\n}\n\ntype SandboxInfo struct {\n\tId      int\n\tAddress string\n\tProfile string\n\tMounts  []string\n}\n\ntype ListSandboxesResp struct {\n\tSandboxes []SandboxInfo \"ListSandboxesResp\"\n}\n\ntype KillSandboxMsg struct {\n\tId int \"KillSandbox\"\n}\n\ntype RelaunchXpraClientMsg struct {\n\tId int \"RelaunchXpraClient\"\n}\n\ntype MountFilesMsg struct {\n\tId       int \"MountFiles\"\n\tFiles    []string\n\tReadOnly bool\n}\n\ntype UnmountFileMsg struct {\n\tId   int \"UnmountFile\"\n\tFile string\n}\n\ntype LogsMsg struct {\n\tCount  int \"Logs\"\n\tFollow bool\n}\n\ntype LogData struct {\n\tLines []string \"LogData\"\n}\n\ntype ListForwardersMsg struct {\n\tId int \"ListForwarders\"\n}\n\ntype AskForwarderMsg struct {\n\tId int \"AskForwarder\"\n\tName string\n\tAddr string\n\tPort string\n}\n\ntype Forwarder struct {\n\tName string \"Forwarder\"\n\tDesc string\n\tTarget string\n}\n\ntype ForwarderSuccessMsg struct {\n        Proto string \"ForwarderSuccess\"\n        Addr string\n\tPort string\n}\n\nvar messageFactory = ipc.NewMsgFactory(\n\tnew(PingMsg),\n\tnew(OkMsg),\n\tnew(ErrorMsg),\n\tnew(GetConfigMsg),\n\tnew(ListProfilesMsg),\n\tnew(ListProfilesResp),\n\tnew(LaunchMsg),\n\tnew(ListSandboxesMsg),\n\tnew(ListSandboxesResp),\n\tnew(KillSandboxMsg),\n\tnew(RelaunchXpraClientMsg),\n\tnew(MountFilesMsg),\n\tnew(UnmountFileMsg),\n\tnew(LogsMsg),\n\tnew(LogData),\n\tnew(AskForwarderMsg),\n\tnew(ForwarderSuccessMsg),\n\tnew(ListForwardersMsg),\n\tnew(ListForwardersResp),\n)\n<|endoftext|>"}
{"text":"<commit_before>package parsesearch\n\nimport (\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/tmc\/parse\"\n)\n\n\/\/ RegisterHooks auto-registers the search service with a Parse Application.\nfunc (i *Indexer) RegisterHooks(prefix string, className string) error {\n\tc, err := parse.NewClient(i.appID, \"\")\n\tc.TraceOn(log.New(os.Stderr, \"[parse api] \", log.LstdFlags))\n\tif err != nil {\n\t\treturn err\n\t}\n\tc = c.WithMasterKey(i.masterKey)\n\n\terr = c.CreateHookFunction(&parse.HookFunction{\n\t\tFunctionName: prefix + \"search\",\n\t\tURL:          os.Getenv(\"URL\") + \"\/search\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.CreateTriggerFunction(&parse.TriggerFunction{\n\t\tClassName:    className,\n\t\tFunctionName: \"afterSave\",\n\t\tURL:          os.Getenv(\"URL\") + \"\/index\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Fix trigger creation<commit_after>package parsesearch\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/tmc\/parse\"\n)\n\nfunc squelchAlreadyExists(err error) error {\n\tif err, ok := err.(*parse.Error); ok {\n\t\tif strings.Contains(err.Message, \"already exists\") {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ RegisterHooks auto-registers the search service with a Parse Application.\nfunc (i *Indexer) RegisterHooks(prefix string, className string) error {\n\tc, err := parse.NewClient(i.appID, \"\")\n\tc.TraceOn(log.New(os.Stderr, \"[parse api] \", log.LstdFlags))\n\tif err != nil {\n\t\treturn err\n\t}\n\tc = c.WithMasterKey(i.masterKey)\n\n\terr = c.CreateHookFunction(&parse.HookFunction{\n\t\tFunctionName: prefix + \"search\",\n\t\tURL:          os.Getenv(\"URL\") + \"\/search\",\n\t})\n\terr = squelchAlreadyExists(err)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = c.CreateTriggerFunction(&parse.TriggerFunction{\n\t\tClassName:   className,\n\t\tTriggerName: \"afterSave\",\n\t\tURL:         os.Getenv(\"URL\") + \"\/index\",\n\t})\n\terr = squelchAlreadyExists(err)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aimg\n\nimport (\n\t\"bytes\"\n\t\"image\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\/\/ supporting these files types\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\n\t\"github.com\/stroborobo\/ansirgb\"\n)\n\nvar (\n\tisUTF8 = false\n)\n\nfunc init() {\n\tisUTF8 = strings.Contains(os.Getenv(\"LC_ALL\"), \"UTF-8\") ||\n\t\tstrings.Contains(os.Getenv(\"LANG\"), \"UTF-8\")\n}\n\n\/\/ Image represents an ANSI color code \"image\"\ntype Image struct {\n\tim image.Image\n\n\t\/\/ actual size\n\twidth  int\n\theight int\n\n\t\/\/ display size\n\tcols int\n\trows int\n\n\tratio float64\n\n\treadIndex int\n}\n\n\/\/ NewImage returns an Image that will parse and print for a given width of\n\/\/ columns.\nfunc NewImage(cols int) *Image {\n\treturn &Image{\n\t\tcols: cols,\n\t}\n}\n\n\/\/ Size returns the resulting size in columns and rows.\nfunc (im *Image) Size() (rows, cols int) {\n\treturn im.cols, im.rows \/ 2\n}\n\n\/\/ ActualSize returns the size of the underlying image.\nfunc (im *Image) ActualSize() (height, width int) {\n\treturn im.width, im.height\n}\n\n\/\/ ParseFile is a shorthand for os.Open() and ParseReader().\nfunc (im *Image) ParseFile(fpath string) error {\n\tfh, err := os.Open(fpath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\treturn im.ParseReader(fh)\n}\n\n\/\/ ParseReader reads image data from the reader.\nfunc (im *Image) ParseReader(rd io.Reader) error {\n\tif img, _, err := image.Decode(rd); err != nil {\n\t\treturn err\n\t} else {\n\t\tim.im = img\n\t}\n\n\tim.width = im.im.Bounds().Dx()\n\tim.height = im.im.Bounds().Dy()\n\n\tif im.width < im.cols {\n\t\tim.cols = im.width\n\t}\n\n\tim.ratio = float64(im.width) \/ float64(im.cols)\n\tim.rows = int(float64(im.height) \/ im.ratio)\n\n\treturn nil\n}\n\n\/\/ Blank returns a string containing as many newlines as needed to display the\n\/\/ image.\nfunc (im *Image) Blank() string {\n\treturn strings.Repeat(\"\\n\", im.rows\/2)\n}\n\n\/\/ BlankReset returns a string like Blank() but with an escape code to set the\n\/\/ cursor to the first of the previous newlines.\nfunc (im *Image) BlankReset() string {\n\tret := im.Blank()\n\treturn ret + cursorUp(len(ret))\n}\n\n\/\/ WriteTo writes the image data to wr.\nfunc (im *Image) WriteTo(wr io.Writer) (int, error) {\n\twritten := 0\n\tfor r := 1; r < im.rows; r += 2 {\n\t\tvar before *Block\n\t\tfor c := 1; c < im.cols; c++ {\n\t\t\tx := int(im.ratio * float64(c))\n\t\t\tyt := int(im.ratio * float64(r-1))\n\t\t\tyb := int(im.ratio * float64(r))\n\n\t\t\tb := &Block{\n\t\t\t\tTop:    im.getColor(x, yt),\n\t\t\t\tBottom: im.getColor(x, yb),\n\t\t\t}\n\n\t\t\tif before != nil {\n\t\t\t\tb.nocolor = b.equals(before)\n\t\t\t}\n\t\t\tbefore = b\n\n\t\t\tn, err := io.WriteString(wr, b.String())\n\t\t\twritten += n\n\t\t\tif err != nil {\n\t\t\t\treturn written, err\n\t\t\t}\n\t\t}\n\t\tn, err := io.WriteString(wr, newLine())\n\t\twritten += n\n\t\tif err != nil {\n\t\t\treturn written, err\n\t\t}\n\t}\n\treturn written, nil\n}\n\nfunc (im *Image) getColor(x, y int) *ansirgb.Color {\n\tc := im.im.At(x, y)\n\tif _, _, _, a := c.RGBA(); a < 1<<14-1 {\n\t\treturn &ansirgb.Color{c, -1} \/\/ default\/transparent color\n\t}\n\treturn ansirgb.Convert(c)\n}\n\n\/\/ String returns the Image's string representation. It's a shorthand to\n\/\/ WriteTo() using a bytes.Buffer and buf.String().\nfunc (im *Image) String() string {\n\tbuf := &bytes.Buffer{}\n\tim.WriteTo(buf)\n\treturn buf.String()\n}\n\n\/\/ Block represents two pixels or a character in a string. It contains a\n\/\/ Unicode LOWER\/UPPER HALF BLOCK, so the top or bottom \"pixel\" is the\n\/\/ foreground color and the other one is the background color.\n\/\/ The character used might change if transparency is needed, which is only\n\/\/ possible by using the default background color.\ntype Block struct {\n\tnocolor bool\n\tTop     *ansirgb.Color\n\tBottom  *ansirgb.Color\n}\n\n\/\/ String returns the string representation of the block. If aimg can't\n\/\/ determine whether this is a UTF-8 environment, String will use a '#' instead\n\/\/ of the LOWER\/UPPER HALF BLOCK. If the block's color is equal to the one\n\/\/ before, it'll just return a string containing a single space.\nfunc (b *Block) String() string {\n\tif b.nocolor {\n\t\treturn \" \"\n\t}\n\n\t\/\/ By default top is background, bottom foreground, using\n\t\/\/ LOWER HALF BLOCK.\n\tfirst := b.Top\n\tsecond := b.Bottom\n\tblock := \"\\u2584\"\n\n\t\/\/ If the bottom is transparent however switch them all\n\t\/\/ since transparency can only be archieved by using the default\n\t\/\/ background color.\n\tif b.Bottom.IsTransparent() {\n\t\tfirst, second = second, first\n\t\tblock = \"\\u2580\"\n\t}\n\n\tret := first.Bg()\n\n\t\/\/ Foreground colors are lighter in some terminals. Also \"transparent\"\n\t\/\/ foreground is not a thing.  Ignore it if it's the same color anyway.\n\tif !first.Equals(second) {\n\t\tret += second.Fg()\n\t\t\/\/ If it's not a UTF-8 terminal, fall back to '#'\n\t\tif isUTF8 {\n\t\t\tret += block\n\t\t} else {\n\t\t\tret += \"#\"\n\t\t}\n\t} else {\n\t\tret += \" \"\n\t}\n\n\treturn ret\n}\n\nfunc (b *Block) equals(b2 *Block) bool {\n\treturn b.Bottom.Code == b2.Bottom.Code && b.Top.Code == b2.Top.Code\n}\n<commit_msg>fix idiotic errors<commit_after>package aimg\n\nimport (\n\t\"bytes\"\n\t\"image\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\/\/ supporting these files types\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\n\t\"github.com\/stroborobo\/ansirgb\"\n)\n\nvar (\n\tisUTF8 = false\n)\n\nfunc init() {\n\tisUTF8 = strings.Contains(os.Getenv(\"LC_ALL\"), \"UTF-8\") ||\n\t\tstrings.Contains(os.Getenv(\"LANG\"), \"UTF-8\")\n}\n\n\/\/ Image represents an ANSI color code \"image\"\ntype Image struct {\n\tim image.Image\n\n\t\/\/ actual size\n\twidth  int\n\theight int\n\n\t\/\/ display size\n\tcols int\n\trows int\n\n\tratio float64\n\n\treadIndex int\n}\n\n\/\/ NewImage returns an Image that will parse and print for a given width of\n\/\/ columns.\nfunc NewImage(cols int) *Image {\n\treturn &Image{\n\t\tcols: cols,\n\t}\n}\n\n\/\/ Size returns the resulting size in columns and rows.\nfunc (im *Image) Size() (rows, cols int) {\n\treturn im.cols, im.rows \/ 2\n}\n\n\/\/ ActualSize returns the size of the underlying image.\nfunc (im *Image) ActualSize() (height, width int) {\n\treturn im.width, im.height\n}\n\n\/\/ ParseFile is a shorthand for os.Open() and ParseReader().\nfunc (im *Image) ParseFile(fpath string) error {\n\tfh, err := os.Open(fpath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\treturn im.ParseReader(fh)\n}\n\n\/\/ ParseReader reads image data from the reader.\nfunc (im *Image) ParseReader(rd io.Reader) error {\n\tif img, _, err := image.Decode(rd); err != nil {\n\t\treturn err\n\t} else {\n\t\tim.im = img\n\t}\n\n\tim.width = im.im.Bounds().Dx()\n\tim.height = im.im.Bounds().Dy()\n\n\tif im.width < im.cols {\n\t\tim.cols = im.width\n\t}\n\n\tim.ratio = float64(im.width) \/ float64(im.cols)\n\tim.rows = int(float64(im.height) \/ im.ratio)\n\n\treturn nil\n}\n\n\/\/ Blank returns a string containing as many newlines as needed to display the\n\/\/ image.\nfunc (im *Image) Blank() string {\n\treturn strings.Repeat(\"\\n\", im.rows\/2)\n}\n\n\/\/ BlankReset returns a string like Blank() but with an escape code to set the\n\/\/ cursor to the first of the previous newlines.\nfunc (im *Image) BlankReset() string {\n\tret := im.Blank()\n\treturn ret + cursorUp(len(ret))\n}\n\n\/\/ WriteTo writes the image data to wr.\nfunc (im *Image) WriteTo(wr io.Writer) (int, error) {\n\twritten := 0\n\tfor r := 0; r < im.rows; r += 2 {\n\t\tvar before *Block\n\t\tfor c := 0; c < im.cols; c++ {\n\t\t\tx := int(im.ratio * float64(c))\n\t\t\tyt := int(im.ratio * float64(r))\n\t\t\tyb := int(im.ratio * float64(r+1))\n\n\t\t\tb := &Block{\n\t\t\t\tTop:    im.getColor(x, yt),\n\t\t\t\tBottom: im.getColor(x, yb),\n\t\t\t}\n\n\t\t\tif before != nil {\n\t\t\t\tb.nocolor = b.equals(before)\n\t\t\t}\n\t\t\tbefore = b\n\n\t\t\tn, err := io.WriteString(wr, b.String())\n\t\t\twritten += n\n\t\t\tif err != nil {\n\t\t\t\treturn written, err\n\t\t\t}\n\t\t}\n\t\tn, err := io.WriteString(wr, newLine())\n\t\twritten += n\n\t\tif err != nil {\n\t\t\treturn written, err\n\t\t}\n\t}\n\treturn written, nil\n}\n\nfunc (im *Image) getColor(x, y int) *ansirgb.Color {\n\tc := im.im.At(x, y)\n\tif _, _, _, a := c.RGBA(); a < 1<<14-1 {\n\t\treturn &ansirgb.Color{c, -1} \/\/ default\/transparent color\n\t}\n\treturn ansirgb.Convert(c)\n}\n\n\/\/ String returns the Image's string representation. It's a shorthand to\n\/\/ WriteTo() using a bytes.Buffer and buf.String().\nfunc (im *Image) String() string {\n\tbuf := &bytes.Buffer{}\n\tim.WriteTo(buf)\n\treturn buf.String()\n}\n\n\/\/ Block represents two pixels or a character in a string. It contains a\n\/\/ Unicode LOWER\/UPPER HALF BLOCK, so the top or bottom \"pixel\" is the\n\/\/ foreground color and the other one is the background color.\n\/\/ The character used might change if transparency is needed, which is only\n\/\/ possible by using the default background color.\ntype Block struct {\n\tnocolor bool\n\tTop     *ansirgb.Color\n\tBottom  *ansirgb.Color\n}\n\n\/\/ String returns the string representation of the block. If aimg can't\n\/\/ determine whether this is a UTF-8 environment, String will use a '#' instead\n\/\/ of the LOWER\/UPPER HALF BLOCK. If the block's color is equal to the one\n\/\/ before, it'll just return a string containing a single space.\nfunc (b *Block) String() string {\n\t\/\/ By default top is background, bottom foreground, using\n\t\/\/ LOWER HALF BLOCK.\n\tfirst := b.Top\n\tsecond := b.Bottom\n\tblock := \"\\u2584\"\n\n\t\/\/ If the bottom is transparent however switch them all\n\t\/\/ since transparency can only be archieved by using the default\n\t\/\/ background color.\n\tif b.Bottom.IsTransparent() {\n\t\tfirst, second = second, first\n\t\tblock = \"\\u2580\"\n\t}\n\n\tret := \"\"\n\tif !b.nocolor {\n\t\tret += first.Bg()\n\t}\n\n\t\/\/ Foreground colors are lighter in some terminals. Also \"transparent\"\n\t\/\/ foreground is not a thing.  Ignore it if it's the same color anyway.\n\tif !first.Equals(second) {\n\t\tif !b.nocolor {\n\t\t\tret += second.Fg()\n\t\t}\n\t\t\/\/ If it's not a UTF-8 terminal, fall back to '#'\n\t\tif isUTF8 {\n\t\t\tret += block\n\t\t} else {\n\t\t\tret += \"#\"\n\t\t}\n\t} else {\n\t\tret += \" \"\n\t}\n\n\treturn ret\n}\n\nfunc (b *Block) equals(b2 *Block) bool {\n\treturn b.Bottom.Code == b2.Bottom.Code && b.Top.Code == b2.Top.Code\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ DISCLAIMER\n\/\/\n\/\/ Copyright 2017 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\/\/ Author Ewout Prangsma\n\/\/\n\npackage driver\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n)\n\n\/\/ ArangoError is a Go error with arangodb specific error information.\ntype ArangoError struct {\n\tHasError     bool   `json:\"error\"`\n\tCode         int    `json:\"code\"`\n\tErrorNum     int    `json:\"errorNum\"`\n\tErrorMessage string `json:\"errorMessage\"`\n}\n\n\/\/ Error returns the error message of an ArangoError.\nfunc (ae ArangoError) Error() string {\n\treturn ae.ErrorMessage\n}\n\n\/\/ newArangoError creates a new ArangoError with given values.\nfunc newArangoError(code, errorNum int, errorMessage string) error {\n\treturn ArangoError{\n\t\tHasError:     true,\n\t\tCode:         code,\n\t\tErrorNum:     errorNum,\n\t\tErrorMessage: errorMessage,\n\t}\n}\n\n\/\/ IsArangoError returns true when the given error is an ArangoError.\nfunc IsArangoError(err error) bool {\n\tae, ok := Cause(err).(ArangoError)\n\treturn ok && ae.HasError\n}\n\n\/\/ IsArangoErrorWithCode returns true when the given error is an ArangoError and its Code field is equal to the given code.\nfunc IsArangoErrorWithCode(err error, code int) bool {\n\tae, ok := Cause(err).(ArangoError)\n\treturn ok && ae.Code == code\n}\n\n\/\/ IsArangoErrorWithErrorNum returns true when the given error is an ArangoError and its ErrorNum field is equal to one of the given numbers.\nfunc IsArangoErrorWithErrorNum(err error, errorNum ...int) bool {\n\tae, ok := Cause(err).(ArangoError)\n\tif !ok {\n\t\treturn false\n\t}\n\tfor _, x := range errorNum {\n\t\tif ae.ErrorNum == x {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsInvalidRequest returns true if the given error is an ArangoError with code 400, indicating an invalid request.\nfunc IsInvalidRequest(err error) bool {\n\treturn IsArangoErrorWithCode(err, 400)\n}\n\n\/\/ IsUnauthorized returns true if the given error is an ArangoError with code 401, indicating an unauthorized request.\nfunc IsUnauthorized(err error) bool {\n\treturn IsArangoErrorWithCode(err, 401)\n}\n\n\/\/ IsForbidden returns true if the given error is an ArangoError with code 403, indicating a forbidden request.\nfunc IsForbidden(err error) bool {\n\treturn IsArangoErrorWithCode(err, 403)\n}\n\n\/\/ IsNotFound returns true if the given error is an ArangoError with code 404, indicating a object not found.\nfunc IsNotFound(err error) bool {\n\treturn IsArangoErrorWithCode(err, 404) || IsArangoErrorWithErrorNum(err, 1202, 1203)\n}\n\n\/\/ IsConflict returns true if the given error is an ArangoError with code 409, indicating a conflict.\nfunc IsConflict(err error) bool {\n\treturn IsArangoErrorWithCode(err, 409) || IsArangoErrorWithErrorNum(err, 1702)\n}\n\n\/\/ IsPreconditionFailed returns true if the given error is an ArangoError with code 412, indicating a failed precondition.\nfunc IsPreconditionFailed(err error) bool {\n\treturn IsArangoErrorWithCode(err, 412) || IsArangoErrorWithErrorNum(err, 1200, 1210)\n}\n\n\/\/ InvalidArgumentError is returned when a go function argument is invalid.\ntype InvalidArgumentError struct {\n\tMessage string\n}\n\n\/\/ Error implements the error interface for InvalidArgumentError.\nfunc (e InvalidArgumentError) Error() string {\n\treturn e.Message\n}\n\n\/\/ IsInvalidArgument returns true if the given error is an InvalidArgumentError.\nfunc IsInvalidArgument(err error) bool {\n\t_, ok := Cause(err).(InvalidArgumentError)\n\treturn ok\n}\n\n\/\/ NoMoreDocumentsError is returned by Cursor's, when an attempt is made to read documents when there are no more.\ntype NoMoreDocumentsError struct{}\n\n\/\/ Error implements the error interface for NoMoreDocumentsError.\nfunc (e NoMoreDocumentsError) Error() string {\n\treturn \"no more documents\"\n}\n\n\/\/ IsNoMoreDocuments returns true if the given error is an NoMoreDocumentsError.\nfunc IsNoMoreDocuments(err error) bool {\n\t_, ok := Cause(err).(NoMoreDocumentsError)\n\treturn ok\n}\n\n\/\/ A ResponseError is returned when a request was completely written to a server, but\n\/\/ the server did not respond, or some kind of network error occurred during the response.\ntype ResponseError struct {\n\tErr error\n}\n\n\/\/ Error returns the Error() result of the underlying error.\nfunc (e *ResponseError) Error() string {\n\treturn e.Err.Error()\n}\n\n\/\/ IsResponse returns true if the given error is (or is caused by) a ResponseError.\nfunc IsResponse(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { _, ok := e.(*ResponseError); return ok })\n}\n\n\/\/ IsCanceled returns true if the given error is the result on a cancelled context.\nfunc IsCanceled(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { return e == context.Canceled })\n}\n\n\/\/ IsTimeout returns true if the given error is the result on a deadline that has been exceeded.\nfunc IsTimeout(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { return e == context.DeadlineExceeded })\n}\n\n\/\/ isCausedBy returns true if the given error returns true on the given predicate,\n\/\/ unwrapping various standard library error wrappers.\nfunc isCausedBy(err error, p func(error) bool) bool {\n\tif p(err) {\n\t\treturn true\n\t}\n\terr = Cause(err)\n\tfor {\n\t\tif p(err) {\n\t\t\treturn true\n\t\t} else if err == nil {\n\t\t\treturn false\n\t\t}\n\t\tif xerr, ok := err.(*ResponseError); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*url.Error); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*net.OpError); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*os.SyscallError); ok {\n\t\t\terr = xerr.Err\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\nvar (\n\t\/\/ WithStack is called on every return of an error to add stacktrace information to the error.\n\t\/\/ When setting this function, also set the Cause function.\n\t\/\/ The interface of this function is compatible with functions in github.com\/pkg\/errors.\n\tWithStack = func(err error) error { return err }\n\t\/\/ Cause is used to get the root cause of the given error.\n\t\/\/ The interface of this function is compatible with functions in github.com\/pkg\/errors.\n\tCause = func(err error) error { return err }\n)\n\n\/\/ ErrorSlice is a slice of errors\ntype ErrorSlice []error\n\n\/\/ FirstNonNil returns the first error in the slice that is not nil.\n\/\/ If all errors in the slice are nil, nil is returned.\nfunc (l ErrorSlice) FirstNonNil() error {\n\tfor _, e := range l {\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Adding technical error message when `ErrorMessage` is empty<commit_after>\/\/\n\/\/ DISCLAIMER\n\/\/\n\/\/ Copyright 2017 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\/\/ Author Ewout Prangsma\n\/\/\n\npackage driver\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n)\n\n\/\/ ArangoError is a Go error with arangodb specific error information.\ntype ArangoError struct {\n\tHasError     bool   `json:\"error\"`\n\tCode         int    `json:\"code\"`\n\tErrorNum     int    `json:\"errorNum\"`\n\tErrorMessage string `json:\"errorMessage\"`\n}\n\n\/\/ Error returns the error message of an ArangoError.\nfunc (ae ArangoError) Error() string {\n\tif ae.ErrorMessage != \"\" {\n\t\treturn ae.ErrorMessage\n\t}\n\treturn fmt.Sprintf(\"ArangoError: Code %d, ErrorNum %d\", ae.Code, ae.ErrorNum)\n}\n\n\/\/ newArangoError creates a new ArangoError with given values.\nfunc newArangoError(code, errorNum int, errorMessage string) error {\n\treturn ArangoError{\n\t\tHasError:     true,\n\t\tCode:         code,\n\t\tErrorNum:     errorNum,\n\t\tErrorMessage: errorMessage,\n\t}\n}\n\n\/\/ IsArangoError returns true when the given error is an ArangoError.\nfunc IsArangoError(err error) bool {\n\tae, ok := Cause(err).(ArangoError)\n\treturn ok && ae.HasError\n}\n\n\/\/ IsArangoErrorWithCode returns true when the given error is an ArangoError and its Code field is equal to the given code.\nfunc IsArangoErrorWithCode(err error, code int) bool {\n\tae, ok := Cause(err).(ArangoError)\n\treturn ok && ae.Code == code\n}\n\n\/\/ IsArangoErrorWithErrorNum returns true when the given error is an ArangoError and its ErrorNum field is equal to one of the given numbers.\nfunc IsArangoErrorWithErrorNum(err error, errorNum ...int) bool {\n\tae, ok := Cause(err).(ArangoError)\n\tif !ok {\n\t\treturn false\n\t}\n\tfor _, x := range errorNum {\n\t\tif ae.ErrorNum == x {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsInvalidRequest returns true if the given error is an ArangoError with code 400, indicating an invalid request.\nfunc IsInvalidRequest(err error) bool {\n\treturn IsArangoErrorWithCode(err, 400)\n}\n\n\/\/ IsUnauthorized returns true if the given error is an ArangoError with code 401, indicating an unauthorized request.\nfunc IsUnauthorized(err error) bool {\n\treturn IsArangoErrorWithCode(err, 401)\n}\n\n\/\/ IsForbidden returns true if the given error is an ArangoError with code 403, indicating a forbidden request.\nfunc IsForbidden(err error) bool {\n\treturn IsArangoErrorWithCode(err, 403)\n}\n\n\/\/ IsNotFound returns true if the given error is an ArangoError with code 404, indicating a object not found.\nfunc IsNotFound(err error) bool {\n\treturn IsArangoErrorWithCode(err, 404) || IsArangoErrorWithErrorNum(err, 1202, 1203)\n}\n\n\/\/ IsConflict returns true if the given error is an ArangoError with code 409, indicating a conflict.\nfunc IsConflict(err error) bool {\n\treturn IsArangoErrorWithCode(err, 409) || IsArangoErrorWithErrorNum(err, 1702)\n}\n\n\/\/ IsPreconditionFailed returns true if the given error is an ArangoError with code 412, indicating a failed precondition.\nfunc IsPreconditionFailed(err error) bool {\n\treturn IsArangoErrorWithCode(err, 412) || IsArangoErrorWithErrorNum(err, 1200, 1210)\n}\n\n\/\/ InvalidArgumentError is returned when a go function argument is invalid.\ntype InvalidArgumentError struct {\n\tMessage string\n}\n\n\/\/ Error implements the error interface for InvalidArgumentError.\nfunc (e InvalidArgumentError) Error() string {\n\treturn e.Message\n}\n\n\/\/ IsInvalidArgument returns true if the given error is an InvalidArgumentError.\nfunc IsInvalidArgument(err error) bool {\n\t_, ok := Cause(err).(InvalidArgumentError)\n\treturn ok\n}\n\n\/\/ NoMoreDocumentsError is returned by Cursor's, when an attempt is made to read documents when there are no more.\ntype NoMoreDocumentsError struct{}\n\n\/\/ Error implements the error interface for NoMoreDocumentsError.\nfunc (e NoMoreDocumentsError) Error() string {\n\treturn \"no more documents\"\n}\n\n\/\/ IsNoMoreDocuments returns true if the given error is an NoMoreDocumentsError.\nfunc IsNoMoreDocuments(err error) bool {\n\t_, ok := Cause(err).(NoMoreDocumentsError)\n\treturn ok\n}\n\n\/\/ A ResponseError is returned when a request was completely written to a server, but\n\/\/ the server did not respond, or some kind of network error occurred during the response.\ntype ResponseError struct {\n\tErr error\n}\n\n\/\/ Error returns the Error() result of the underlying error.\nfunc (e *ResponseError) Error() string {\n\treturn e.Err.Error()\n}\n\n\/\/ IsResponse returns true if the given error is (or is caused by) a ResponseError.\nfunc IsResponse(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { _, ok := e.(*ResponseError); return ok })\n}\n\n\/\/ IsCanceled returns true if the given error is the result on a cancelled context.\nfunc IsCanceled(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { return e == context.Canceled })\n}\n\n\/\/ IsTimeout returns true if the given error is the result on a deadline that has been exceeded.\nfunc IsTimeout(err error) bool {\n\treturn isCausedBy(err, func(e error) bool { return e == context.DeadlineExceeded })\n}\n\n\/\/ isCausedBy returns true if the given error returns true on the given predicate,\n\/\/ unwrapping various standard library error wrappers.\nfunc isCausedBy(err error, p func(error) bool) bool {\n\tif p(err) {\n\t\treturn true\n\t}\n\terr = Cause(err)\n\tfor {\n\t\tif p(err) {\n\t\t\treturn true\n\t\t} else if err == nil {\n\t\t\treturn false\n\t\t}\n\t\tif xerr, ok := err.(*ResponseError); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*url.Error); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*net.OpError); ok {\n\t\t\terr = xerr.Err\n\t\t} else if xerr, ok := err.(*os.SyscallError); ok {\n\t\t\terr = xerr.Err\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n}\n\nvar (\n\t\/\/ WithStack is called on every return of an error to add stacktrace information to the error.\n\t\/\/ When setting this function, also set the Cause function.\n\t\/\/ The interface of this function is compatible with functions in github.com\/pkg\/errors.\n\tWithStack = func(err error) error { return err }\n\t\/\/ Cause is used to get the root cause of the given error.\n\t\/\/ The interface of this function is compatible with functions in github.com\/pkg\/errors.\n\tCause = func(err error) error { return err }\n)\n\n\/\/ ErrorSlice is a slice of errors\ntype ErrorSlice []error\n\n\/\/ FirstNonNil returns the first error in the slice that is not nil.\n\/\/ If all errors in the slice are nil, nil is returned.\nfunc (l ErrorSlice) FirstNonNil() error {\n\tfor _, e := range l {\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cask\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\/\/ Errors represents a group of errors and its context.\ntype Errors struct {\n\t\/\/ context specifies the errors context.\n\tcontext string\n\n\t\/\/ errors specify a group of errors represented as an array.\n\terrors []error\n}\n\n\/\/ An unexpectedTokenError represents the error that occurs when an the expected\n\/\/ tokens doesn't match the actual ones.\ntype unexpectedTokenError struct {\n\t\/\/ expectedTokens specify a group of expected token types.\n\texpectedTokens []TokenType\n\n\t\/\/ actualToken specifies the actual token type.\n\tactualToken TokenType\n}\n\n\/\/ NewErrors creates a new Errors instance and returns its pointer. Requires\n\/\/ both Errors.context and Errors.errors to be passed as arguments.\nfunc NewErrors(context string, errors ...error) *Errors {\n\treturn &Errors{context, errors}\n}\n\n\/\/ Error returns all error messages represented as a single string. All errors\n\/\/ include trailing newlines and prepended context.\nfunc (e *Errors) Error() string {\n\tvar buffer bytes.Buffer\n\n\tfmt.Fprintf(&buffer, \"%s:\\n\", e.context)\n\tfor _, err := range e.errors {\n\t\tfmt.Fprintf(&buffer, \"%s\\n\", err.Error())\n\t}\n\n\treturn buffer.String()\n}\n\n\/\/ Error returns a string representation of the unexpectedTokenError.\nfunc (u *unexpectedTokenError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"expected next token to be of type %s, got %s instead\",\n\t\tu.expectedTokens,\n\t\tu.actualToken,\n\t)\n}\n<commit_msg>Use \"%v\" in unexpectedTokenError.Error()<commit_after>package cask\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\n\/\/ Errors represents a group of errors and its context.\ntype Errors struct {\n\t\/\/ context specifies the errors context.\n\tcontext string\n\n\t\/\/ errors specify a group of errors represented as an array.\n\terrors []error\n}\n\n\/\/ An unexpectedTokenError represents the error that occurs when an the expected\n\/\/ tokens doesn't match the actual ones.\ntype unexpectedTokenError struct {\n\t\/\/ expectedTokens specify a group of expected token types.\n\texpectedTokens []TokenType\n\n\t\/\/ actualToken specifies the actual token type.\n\tactualToken TokenType\n}\n\n\/\/ NewErrors creates a new Errors instance and returns its pointer. Requires\n\/\/ both Errors.context and Errors.errors to be passed as arguments.\nfunc NewErrors(context string, errors ...error) *Errors {\n\treturn &Errors{context, errors}\n}\n\n\/\/ Error returns all error messages represented as a single string. All errors\n\/\/ include trailing newlines and prepended context.\nfunc (e *Errors) Error() string {\n\tvar buffer bytes.Buffer\n\n\tfmt.Fprintf(&buffer, \"%s:\\n\", e.context)\n\tfor _, err := range e.errors {\n\t\tfmt.Fprintf(&buffer, \"%s\\n\", err.Error())\n\t}\n\n\treturn buffer.String()\n}\n\n\/\/ Error returns a string representation of the unexpectedTokenError.\nfunc (u *unexpectedTokenError) Error() string {\n\treturn fmt.Sprintf(\n\t\t\"expected next token to be of type %v, got %s instead\",\n\t\tu.expectedTokens,\n\t\tu.actualToken,\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"github.com\/jangler\/edit\"\n\t\"github.com\/veandco\/go-sdl2\/sdl\"\n\t\"github.com\/veandco\/go-sdl2\/sdl_ttf\"\n)\n\nvar (\n\tspaceRegexp = regexp.MustCompile(`\\s`) \/\/ matches whitespace characters\n\twordRegexp  = regexp.MustCompile(`\\w`) \/\/ matches word characters\n)\n\n\/\/ focusedPane returns the focused pane index out of a slice of panes.\nfunc focusedPane(panes []Pane) int {\n\tfor i, pane := range panes {\n\t\tif pane.Focused {\n\t\t\treturn i\n\t\t}\n\t}\n\tlog.Fatal(\"No focused pane\")\n\treturn 0 \/\/ unreachable\n}\n\n\/\/ change pane focus based on mouse position\nfunc refocus(panes []Pane, win *sdl.Window, font *ttf.Font, x, y int) {\n\t_, height := win.GetSize()\n\tps := paneSpace(height, len(panes), font)\n\ti := y \/ ps\n\tif i < len(panes) {\n\t\tfor j := range panes {\n\t\t\tpanes[j].Focused = false\n\t\t}\n\t\tpanes[i].Focused = true\n\t}\n}\n\n\/\/ singleClick processes a single left mouse click at the given coordinates.\nfunc singleClick(panes []Pane, win *sdl.Window, font *ttf.Font, x, y int) {\n\t_, height := win.GetSize()\n\tps := paneSpace(height, len(panes), font)\n\ti := y \/ ps                        \/\/ clicked pane index\n\ty = y%ps - font.Height() - padPx*3 \/\/ subtract pane header\n\tx -= padPx - fontWidth\/2\n\ty \/= font.Height()\n\tx \/= fontWidth\n\tif i < len(panes) {\n\t\tpanes[i].Mark(panes[i].IndexFromCoords(x, y), insertMark)\n\t}\n}\n\n\/\/ textInput inserts text into the focus, or performs another action depending\n\/\/ on the contents of the string.\nfunc textInput(buf *edit.Buffer, s string) {\n\tindex, _ := buf.IndexFromMark(insertMark)\n\tbuf.Insert(index, s)\n}\n\n\/\/ resize resizes the panes in the display and requests a render.\nfunc resize(panes []Pane, font *ttf.Font, width, height int) {\n\tcols, rows := bufSize(width, height, len(panes), font)\n\tfor i := range panes {\n\t\tpanes[i].Cols, panes[i].Rows = cols, rows\n\t\tpanes[i].SetSize(cols, rows)\n\t}\n\trender <- 1\n}\n\n\/\/ ShiftIndexByWord returns the given index shifted forward by n words. A\n\/\/ negative value for n will shift backwards.\nfunc (p *Pane) ShiftIndexByWord(index edit.Index, n int) edit.Index {\n\tfor n > 0 {\n\t\t\/\/ TODO\n\t\tn--\n\t}\n\tfor n < 0 {\n\t\tif index.Char == 0 {\n\t\t\tindex = p.ShiftIndex(index, -1)\n\t\t} else {\n\t\t\ttext := []rune(p.Get(edit.Index{index.Line, 0}, index))\n\t\t\ti := len(text) - 1\n\t\t\tfor i >= 0 && spaceRegexp.MatchString(string(text[i])) {\n\t\t\t\ti--\n\t\t\t}\n\t\t\tif i >= 0 && wordRegexp.MatchString(string(text[i])) {\n\t\t\t\tfor i >= 0 && wordRegexp.MatchString(string(text[i])) {\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor i >= 0 && !wordRegexp.MatchString(string(text[i])) &&\n\t\t\t\t\t!spaceRegexp.MatchString(string(text[i])) {\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t\tindex.Char = i + 1\n\t\t}\n\t\tn++\n\t}\n\treturn index\n}\n\n\/\/ eventLoop handles SDL events until quit is requested.\nfunc eventLoop(panes []Pane, font *ttf.Font, win *sdl.Window) {\n\tpane := panes[focusedPane(panes)]\n\tfor {\n\t\tswitch event := sdl.WaitEvent().(type) {\n\t\tcase *sdl.KeyDownEvent:\n\t\t\tswitch event.Keysym.Sym {\n\t\t\tcase sdl.K_BACKSPACE:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Delete(pane.ShiftIndex(index, -1), index)\n\t\t\tcase sdl.K_DELETE:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Delete(index, pane.ShiftIndex(index, 1))\n\t\t\tcase sdl.K_DOWN:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row+1), insertMark)\n\t\t\tcase sdl.K_END:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(edit.Index{index.Line, 0xffff}, insertMark)\n\t\t\tcase sdl.K_LEFT:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(pane.ShiftIndex(index, -1), insertMark)\n\t\t\tcase sdl.K_HOME:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(edit.Index{index.Line, 0}, insertMark)\n\t\t\tcase sdl.K_PAGEDOWN:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row+pane.Rows), insertMark)\n\t\t\tcase sdl.K_PAGEUP:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row-pane.Rows), insertMark)\n\t\t\tcase sdl.K_RETURN:\n\t\t\t\ttextInput(pane.Buffer, \"\\n\")\n\t\t\tcase sdl.K_RIGHT:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(pane.ShiftIndex(index, 1), insertMark)\n\t\t\tcase sdl.K_TAB:\n\t\t\t\ttextInput(pane.Buffer, \"\\t\")\n\t\t\tcase sdl.K_UP:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row-1), insertMark)\n\t\t\tcase sdl.K_a:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Mark(edit.Index{index.Line, 0}, insertMark)\n\t\t\t\t}\n\t\t\tcase sdl.K_e:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Mark(edit.Index{index.Line, 0xffff}, insertMark)\n\t\t\t\t}\n\t\t\tcase sdl.K_h:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Delete(pane.ShiftIndex(index, -1), index)\n\t\t\t\t}\n\t\t\tcase sdl.K_q:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase sdl.K_u:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Delete(edit.Index{index.Line, 0}, index)\n\t\t\t\t}\n\t\t\tcase sdl.K_w:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tend, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tbegin := pane.ShiftIndexByWord(end, -1)\n\t\t\t\t\tpane.Delete(begin, end)\n\t\t\t\t}\n\t\t\t}\n\t\t\tpane.See(insertMark)\n\t\t\trender <- 1\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\tif event.Type == sdl.MOUSEBUTTONDOWN &&\n\t\t\t\tevent.Button == sdl.BUTTON_LEFT {\n\t\t\t\tsingleClick(panes, win, font, int(event.X), int(event.Y))\n\t\t\t\tpane = panes[focusedPane(panes)]\n\t\t\t\tpaneSet <- panes\n\t\t\t}\n\t\tcase *sdl.MouseMotionEvent:\n\t\t\trefocus(panes, win, font, int(event.X), int(event.Y))\n\t\t\tpane = panes[focusedPane(panes)]\n\t\t\tpaneSet <- panes\n\t\tcase *sdl.MouseWheelEvent:\n\t\t\tpane.Scroll(int(event.Y) * -3)\n\t\t\trender <- 1\n\t\tcase *sdl.QuitEvent:\n\t\t\treturn\n\t\tcase *sdl.TextInputEvent:\n\t\t\tif n := bytes.Index(event.Text[:], []byte{0}); n > 0 {\n\t\t\t\ttextInput(pane.Buffer, string(event.Text[:n]))\n\t\t\t\trender <- 1\n\t\t\t}\n\t\tcase *sdl.WindowEvent:\n\t\t\tswitch event.Event {\n\t\t\tcase sdl.WINDOWEVENT_EXPOSED:\n\t\t\t\twin.UpdateSurface()\n\t\t\tcase sdl.WINDOWEVENT_RESIZED:\n\t\t\t\tresize(panes, font, int(event.Data1), int(event.Data2))\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Implement autoindent<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"github.com\/jangler\/edit\"\n\t\"github.com\/veandco\/go-sdl2\/sdl\"\n\t\"github.com\/veandco\/go-sdl2\/sdl_ttf\"\n)\n\nvar (\n\tspaceRegexp = regexp.MustCompile(`\\s`) \/\/ matches whitespace characters\n\twordRegexp  = regexp.MustCompile(`\\w`) \/\/ matches word characters\n)\n\n\/\/ focusedPane returns the focused pane index out of a slice of panes.\nfunc focusedPane(panes []Pane) int {\n\tfor i, pane := range panes {\n\t\tif pane.Focused {\n\t\t\treturn i\n\t\t}\n\t}\n\tlog.Fatal(\"No focused pane\")\n\treturn 0 \/\/ unreachable\n}\n\n\/\/ change pane focus based on mouse position\nfunc refocus(panes []Pane, win *sdl.Window, font *ttf.Font, x, y int) {\n\t_, height := win.GetSize()\n\tps := paneSpace(height, len(panes), font)\n\ti := y \/ ps\n\tif i < len(panes) {\n\t\tfor j := range panes {\n\t\t\tpanes[j].Focused = false\n\t\t}\n\t\tpanes[i].Focused = true\n\t}\n}\n\n\/\/ singleClick processes a single left mouse click at the given coordinates.\nfunc singleClick(panes []Pane, win *sdl.Window, font *ttf.Font, x, y int) {\n\t_, height := win.GetSize()\n\tps := paneSpace(height, len(panes), font)\n\ti := y \/ ps                        \/\/ clicked pane index\n\ty = y%ps - font.Height() - padPx*3 \/\/ subtract pane header\n\tx -= padPx - fontWidth\/2\n\ty \/= font.Height()\n\tx \/= fontWidth\n\tif i < len(panes) {\n\t\tpanes[i].Mark(panes[i].IndexFromCoords(x, y), insertMark)\n\t}\n}\n\n\/\/ textInput inserts text into the focus, or performs another action depending\n\/\/ on the contents of the string.\nfunc textInput(buf *edit.Buffer, s string) {\n\tindex, _ := buf.IndexFromMark(insertMark)\n\tif s == \"\\n\" {\n\t\t\/\/ autoindent\n\t\tindent := buf.Get(edit.Index{index.Line, 0},\n\t\t\tedit.Index{index.Line, 0xffff})\n\t\ti := 0\n\t\tfor i < len(indent) && (indent[i] == ' ' || indent[i] == '\\t') {\n\t\t\ti++\n\t\t}\n\t\tif i <= index.Char {\n\t\t\ts += indent[:i]\n\n\t\t\t\/\/ delete lines containing only whitespace\n\t\t\tif i == len(indent) {\n\t\t\t\tbuf.Delete(edit.Index{index.Line, 0}, index)\n\t\t\t\tindex.Char = 0\n\t\t\t}\n\t\t}\n\t}\n\tbuf.Insert(index, s)\n}\n\n\/\/ resize resizes the panes in the display and requests a render.\nfunc resize(panes []Pane, font *ttf.Font, width, height int) {\n\tcols, rows := bufSize(width, height, len(panes), font)\n\tfor i := range panes {\n\t\tpanes[i].Cols, panes[i].Rows = cols, rows\n\t\tpanes[i].SetSize(cols, rows)\n\t}\n\trender <- 1\n}\n\n\/\/ ShiftIndexByWord returns the given index shifted forward by n words. A\n\/\/ negative value for n will shift backwards.\nfunc (p *Pane) ShiftIndexByWord(index edit.Index, n int) edit.Index {\n\tfor n > 0 {\n\t\t\/\/ TODO\n\t\tn--\n\t}\n\tfor n < 0 {\n\t\tif index.Char == 0 {\n\t\t\tindex = p.ShiftIndex(index, -1)\n\t\t} else {\n\t\t\ttext := []rune(p.Get(edit.Index{index.Line, 0}, index))\n\t\t\ti := len(text) - 1\n\t\t\tfor i >= 0 && spaceRegexp.MatchString(string(text[i])) {\n\t\t\t\ti--\n\t\t\t}\n\t\t\tif i >= 0 && wordRegexp.MatchString(string(text[i])) {\n\t\t\t\tfor i >= 0 && wordRegexp.MatchString(string(text[i])) {\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor i >= 0 && !wordRegexp.MatchString(string(text[i])) &&\n\t\t\t\t\t!spaceRegexp.MatchString(string(text[i])) {\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t\tindex.Char = i + 1\n\t\t}\n\t\tn++\n\t}\n\treturn index\n}\n\n\/\/ eventLoop handles SDL events until quit is requested.\nfunc eventLoop(panes []Pane, font *ttf.Font, win *sdl.Window) {\n\tpane := panes[focusedPane(panes)]\n\tfor {\n\t\tswitch event := sdl.WaitEvent().(type) {\n\t\tcase *sdl.KeyDownEvent:\n\t\t\tswitch event.Keysym.Sym {\n\t\t\tcase sdl.K_BACKSPACE:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Delete(pane.ShiftIndex(index, -1), index)\n\t\t\tcase sdl.K_DELETE:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Delete(index, pane.ShiftIndex(index, 1))\n\t\t\tcase sdl.K_DOWN:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row+1), insertMark)\n\t\t\tcase sdl.K_END:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(edit.Index{index.Line, 0xffff}, insertMark)\n\t\t\tcase sdl.K_LEFT:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(pane.ShiftIndex(index, -1), insertMark)\n\t\t\tcase sdl.K_HOME:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(edit.Index{index.Line, 0}, insertMark)\n\t\t\tcase sdl.K_PAGEDOWN:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row+pane.Rows), insertMark)\n\t\t\tcase sdl.K_PAGEUP:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row-pane.Rows), insertMark)\n\t\t\tcase sdl.K_RETURN:\n\t\t\t\ttextInput(pane.Buffer, \"\\n\")\n\t\t\tcase sdl.K_RIGHT:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tpane.Mark(pane.ShiftIndex(index, 1), insertMark)\n\t\t\tcase sdl.K_TAB:\n\t\t\t\ttextInput(pane.Buffer, \"\\t\")\n\t\t\tcase sdl.K_UP:\n\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\tcol, row := pane.CoordsFromIndex(index)\n\t\t\t\tpane.Mark(pane.IndexFromCoords(col, row-1), insertMark)\n\t\t\tcase sdl.K_a:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Mark(edit.Index{index.Line, 0}, insertMark)\n\t\t\t\t}\n\t\t\tcase sdl.K_e:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Mark(edit.Index{index.Line, 0xffff}, insertMark)\n\t\t\t\t}\n\t\t\tcase sdl.K_h:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Delete(pane.ShiftIndex(index, -1), index)\n\t\t\t\t}\n\t\t\tcase sdl.K_q:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase sdl.K_u:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tindex, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tpane.Delete(edit.Index{index.Line, 0}, index)\n\t\t\t\t}\n\t\t\tcase sdl.K_w:\n\t\t\t\tif event.Keysym.Mod&sdl.KMOD_CTRL != 0 {\n\t\t\t\t\tend, _ := pane.IndexFromMark(insertMark)\n\t\t\t\t\tbegin := pane.ShiftIndexByWord(end, -1)\n\t\t\t\t\tpane.Delete(begin, end)\n\t\t\t\t}\n\t\t\t}\n\t\t\tpane.See(insertMark)\n\t\t\trender <- 1\n\t\tcase *sdl.MouseButtonEvent:\n\t\t\tif event.Type == sdl.MOUSEBUTTONDOWN &&\n\t\t\t\tevent.Button == sdl.BUTTON_LEFT {\n\t\t\t\tsingleClick(panes, win, font, int(event.X), int(event.Y))\n\t\t\t\tpane = panes[focusedPane(panes)]\n\t\t\t\tpaneSet <- panes\n\t\t\t}\n\t\tcase *sdl.MouseMotionEvent:\n\t\t\trefocus(panes, win, font, int(event.X), int(event.Y))\n\t\t\tpane = panes[focusedPane(panes)]\n\t\t\tpaneSet <- panes\n\t\tcase *sdl.MouseWheelEvent:\n\t\t\tpane.Scroll(int(event.Y) * -3)\n\t\t\trender <- 1\n\t\tcase *sdl.QuitEvent:\n\t\t\treturn\n\t\tcase *sdl.TextInputEvent:\n\t\t\tif n := bytes.Index(event.Text[:], []byte{0}); n > 0 {\n\t\t\t\ttextInput(pane.Buffer, string(event.Text[:n]))\n\t\t\t\trender <- 1\n\t\t\t}\n\t\tcase *sdl.WindowEvent:\n\t\t\tswitch event.Event {\n\t\t\tcase sdl.WINDOWEVENT_EXPOSED:\n\t\t\t\twin.UpdateSurface()\n\t\t\tcase sdl.WINDOWEVENT_RESIZED:\n\t\t\t\tresize(panes, font, int(event.Data1), int(event.Data2))\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kocha\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\n\t\"github.com\/naoina\/kocha\/event\"\n)\n\n\/\/ EventHandlerMap represents a map of event handlers.\ntype EventHandlerMap map[event.Queue]map[string]func(app *Application, args ...interface{}) error\n\n\/\/ Evevnt represents the event.\ntype Event struct {\n\t\/\/ HandlerMap is a map of queue\/handlers.\n\tHandlerMap EventHandlerMap\n\n\t\/\/ WorkersPerQueue is a number of workers per queue.\n\t\/\/ The default value is taken from GOMAXPROCS.\n\t\/\/ If value of GOMAXPROCS is invalid, set to 1.\n\tWorkersPerQueue int\n\n\t\/\/ ErrorHandler is the handler for error.\n\t\/\/ If you want to use your own error handler, please set to ErrorHandler.\n\tErrorHandler func(err interface{})\n\n\te   *event.Event\n\tapp *Application\n}\n\n\/\/ Trigger emits the event.\n\/\/ The name is an event name that is defined in e.HandlerMap.\n\/\/ If args given, they will be passed to event handler that is defined in e.HandlerMap.\nfunc (e *Event) Trigger(name string, args ...interface{}) error {\n\treturn e.e.Trigger(name, args...)\n}\n\nfunc (e *Event) addHandler(name string, queueName string, handler func(app *Application, args ...interface{}) error) error {\n\treturn e.e.AddHandler(name, queueName, func(args ...interface{}) error {\n\t\treturn handler(e.app, args...)\n\t})\n}\n\nfunc (e *Event) build(app *Application) (*Event, error) {\n\tif e == nil {\n\t\te = &Event{}\n\t}\n\te.e = event.New()\n\tfor queue, handlerMap := range e.HandlerMap {\n\t\tqueueName := reflect.TypeOf(queue).Name()\n\t\tif err := e.e.RegisterQueue(queueName, queue); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor name, handler := range handlerMap {\n\t\t\tif err := e.addHandler(name, queueName, handler); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tn := e.WorkersPerQueue\n\tif n < 1 {\n\t\tif n, _ = strconv.Atoi(os.Getenv(\"GOMAXPROCS\")); n < 1 {\n\t\t\tn = 1\n\t\t}\n\t}\n\te.e.SetWorkersPerQueue(n)\n\te.e.ErrorHandler = e.ErrorHandler\n\treturn e, nil\n}\n\nfunc (e *Event) start() {\n\te.e.Start()\n}\n\nfunc (e *Event) stop() {\n\te.e.Stop()\n}\n<commit_msg>event: Fix the issue that a queue name is always empty string<commit_after>package kocha\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\n\t\"github.com\/naoina\/kocha\/event\"\n)\n\n\/\/ EventHandlerMap represents a map of event handlers.\ntype EventHandlerMap map[event.Queue]map[string]func(app *Application, args ...interface{}) error\n\n\/\/ Evevnt represents the event.\ntype Event struct {\n\t\/\/ HandlerMap is a map of queue\/handlers.\n\tHandlerMap EventHandlerMap\n\n\t\/\/ WorkersPerQueue is a number of workers per queue.\n\t\/\/ The default value is taken from GOMAXPROCS.\n\t\/\/ If value of GOMAXPROCS is invalid, set to 1.\n\tWorkersPerQueue int\n\n\t\/\/ ErrorHandler is the handler for error.\n\t\/\/ If you want to use your own error handler, please set to ErrorHandler.\n\tErrorHandler func(err interface{})\n\n\te   *event.Event\n\tapp *Application\n}\n\n\/\/ Trigger emits the event.\n\/\/ The name is an event name that is defined in e.HandlerMap.\n\/\/ If args given, they will be passed to event handler that is defined in e.HandlerMap.\nfunc (e *Event) Trigger(name string, args ...interface{}) error {\n\treturn e.e.Trigger(name, args...)\n}\n\nfunc (e *Event) addHandler(name string, queueName string, handler func(app *Application, args ...interface{}) error) error {\n\treturn e.e.AddHandler(name, queueName, func(args ...interface{}) error {\n\t\treturn handler(e.app, args...)\n\t})\n}\n\nfunc (e *Event) build(app *Application) (*Event, error) {\n\tif e == nil {\n\t\te = &Event{}\n\t}\n\te.e = event.New()\n\tfor queue, handlerMap := range e.HandlerMap {\n\t\tqueueName := reflect.TypeOf(queue).String()\n\t\tif err := e.e.RegisterQueue(queueName, queue); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor name, handler := range handlerMap {\n\t\t\tif err := e.addHandler(name, queueName, handler); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tn := e.WorkersPerQueue\n\tif n < 1 {\n\t\tif n, _ = strconv.Atoi(os.Getenv(\"GOMAXPROCS\")); n < 1 {\n\t\t\tn = 1\n\t\t}\n\t}\n\te.e.SetWorkersPerQueue(n)\n\te.e.ErrorHandler = e.ErrorHandler\n\treturn e, nil\n}\n\nfunc (e *Event) start() {\n\te.e.Start()\n}\n\nfunc (e *Event) stop() {\n\te.e.Stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package filu\n\nimport \"time\"\n\n\/\/ An Event is an immutable fact that happened at a single moment in time.\ntype Event interface {\n\tHappenedAt() time.Time\n}\n\n\/\/ A Time is a single moment in time. It is used by Implementors\n\/\/ of the Event interface to avoid reimplementation of the HappenedAt()\n\/\/ method.\ntype Time struct {\n\tmoment time.Time\n}\n\nfunc (e Time) HappenedAt() time.Time {\n\treturn e.moment\n}\n<commit_msg>[filu] Add function to produce time.Now() as filu.Time<commit_after>package filu\n\nimport \"time\"\n\n\/\/ An Event is an immutable fact that happened at a single moment in time.\ntype Event interface {\n\tHappenedAt() time.Time\n}\n\n\/\/ A Time is a single moment in time. It is used by Implementors\n\/\/ of the Event interface to avoid reimplementation of the HappenedAt()\n\/\/ method.\ntype Time struct {\n\tmoment time.Time\n}\n\nfunc Now() Time {\n\treturn Time{time.Now()}\n}\n\nfunc (e Time) HappenedAt() time.Time {\n\treturn e.moment\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ History: Oct 07 14 tcolar Creation\n\npackage main\n\nimport \"github.com\/tcolar\/termbox-go\"\n\nfunc (e *Editor) EventLoop() {\n\n\ttermbox.SetInputMode(termbox.InputEsc | termbox.InputMouse)\n\n\tfor {\n\t\tev := termbox.PollEvent()\n\t\tswitch ev.Type {\n\t\tcase termbox.EventResize:\n\t\t\te.Render()\n\t\tcase termbox.EventKey:\n\t\t\tswitch ev.Key {\n\t\t\tcase termbox.KeyEsc:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tif e.CurView != nil {\n\t\t\t\t\te.CurView.Event(&ev)\n\t\t\t\t}\n\t\t\t}\n\t\tcase termbox.EventMouse:\n\t\t\tw := e.WidgetAt(ev.MouseX, ev.MouseY)\n\t\t\tif w != nil {\n\t\t\t\tw.Event(&ev)\n\t\t\t}\n\t\t}\n\t\te.Render()\n\t}\n}\n\n\/\/ Event handler for Menubar\nfunc (m *Menubar) Event(ev *termbox.Event) {\n\t\/\/ TBD\n}\n\n\/\/ Event handler for Statusbar\nfunc (s *Statusbar) Event(ev *termbox.Event) {\n\t\/\/ TBD\n}\n\n\/\/ Event handler for View\nfunc (v *View) Event(ev *termbox.Event) {\n\tswitch ev.Type {\n\tcase termbox.EventKey:\n\t\tswitch ev.Key {\n\t\tcase termbox.KeyArrowRight:\n\t\t\tv.MoveCursor(1, 0)\n\t\tcase termbox.KeyArrowLeft:\n\t\t\tv.MoveCursor(-1, 0)\n\t\tcase termbox.KeyArrowUp:\n\t\t\tv.MoveCursor(0, -1)\n\t\tcase termbox.KeyArrowDown:\n\t\t\tv.MoveCursor(0, 1)\n\t\tcase termbox.KeyPgdn:\n\t\t\tdist := v.LastViewLine() + 1\n\t\t\tif len(v.Buffer)-v.CurLine() < dist {\n\t\t\t\tdist = len(v.Buffer) - v.CurLine() - 1\n\t\t\t}\n\t\t\tv.MoveCursor(0, dist)\n\t\tcase termbox.KeyPgup:\n\t\t\tdist := v.LastViewLine() + 1\n\t\t\tif dist > v.CurLine() {\n\t\t\t\tdist = v.CurLine()\n\t\t\t}\n\t\t\tv.MoveCursor(0, -dist)\n\t\tcase termbox.KeyEsc:\n\t\t\treturn\n\t\t}\n\tcase termbox.EventMouse:\n\t\tswitch ev.Key {\n\t\tcase termbox.MouseLeft:\n\t\t\t\/\/ MoveCursor use text coordinates which starts at offset 2,2\n\t\t\tv.MoveCursor(ev.MouseX-v.x1-2-v.CursorX, ev.MouseY-v.y1-2-v.CursorY)\n\t\t\t\/\/ Make the clicked view active\n\t\t\tEd.CurView = v\n\t\t}\n\t}\n}\n<commit_msg>Home\/End keys.<commit_after>\/\/ History: Oct 07 14 tcolar Creation\n\npackage main\n\nimport \"github.com\/tcolar\/termbox-go\"\n\nfunc (e *Editor) EventLoop() {\n\n\ttermbox.SetInputMode(termbox.InputEsc | termbox.InputMouse)\n\n\tfor {\n\t\tev := termbox.PollEvent()\n\t\tswitch ev.Type {\n\t\tcase termbox.EventResize:\n\t\t\te.Render()\n\t\tcase termbox.EventKey:\n\t\t\tswitch ev.Key {\n\t\t\tcase termbox.KeyEsc:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tif e.CurView != nil {\n\t\t\t\t\te.CurView.Event(&ev)\n\t\t\t\t}\n\t\t\t}\n\t\tcase termbox.EventMouse:\n\t\t\tw := e.WidgetAt(ev.MouseX, ev.MouseY)\n\t\t\tif w != nil {\n\t\t\t\tw.Event(&ev)\n\t\t\t}\n\t\t}\n\t\te.Render()\n\t}\n}\n\n\/\/ Event handler for Menubar\nfunc (m *Menubar) Event(ev *termbox.Event) {\n\t\/\/ TBD\n}\n\n\/\/ Event handler for Statusbar\nfunc (s *Statusbar) Event(ev *termbox.Event) {\n\t\/\/ TBD\n}\n\n\/\/ Event handler for View\nfunc (v *View) Event(ev *termbox.Event) {\n\tswitch ev.Type {\n\tcase termbox.EventKey:\n\t\tswitch ev.Key {\n\t\tcase termbox.KeyArrowRight:\n\t\t\tv.MoveCursor(1, 0)\n\t\tcase termbox.KeyArrowLeft:\n\t\t\tv.MoveCursor(-1, 0)\n\t\tcase termbox.KeyArrowUp:\n\t\t\tv.MoveCursor(0, -1)\n\t\tcase termbox.KeyArrowDown:\n\t\t\tv.MoveCursor(0, 1)\n\t\tcase termbox.KeyPgdn:\n\t\t\tdist := v.LastViewLine() + 1\n\t\t\tif len(v.Buffer)-v.CurLine() < dist {\n\t\t\t\tdist = len(v.Buffer) - v.CurLine() - 1\n\t\t\t}\n\t\t\tv.MoveCursor(0, dist)\n\t\tcase termbox.KeyPgup:\n\t\t\tdist := v.LastViewLine() + 1\n\t\t\tif dist > v.CurLine() {\n\t\t\t\tdist = v.CurLine()\n\t\t\t}\n\t\t\tv.MoveCursor(0, -dist)\n\t\tcase termbox.KeyEnd:\n\t\t\tv.MoveCursor(v.lineLn(v.CurLine())-v.CurCol(), 0)\n\t\tcase termbox.KeyHome:\n\t\t\tv.MoveCursor(-v.CurCol(), 0)\n\t\tcase termbox.KeyEsc:\n\t\t\treturn\n\t\t}\n\tcase termbox.EventMouse:\n\t\tswitch ev.Key {\n\t\tcase termbox.MouseLeft:\n\t\t\t\/\/ MoveCursor use text coordinates which starts at offset 2,2\n\t\t\tv.MoveCursor(ev.MouseX-v.x1-2-v.CursorX, ev.MouseY-v.y1-2-v.CursorY)\n\t\t\t\/\/ Make the clicked view active\n\t\t\tEd.CurView = v\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package grpc_opentracing\n\nimport (\n\t\"strings\"\n\n\tgrpc_ctxtags \"github.com\/grpc-ecosystem\/go-grpc-middleware\/tags\"\n\topentracing \"github.com\/opentracing\/opentracing-go\"\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\nconst (\n\tTagTraceId           = \"trace.traceid\"\n\tTagSpanId            = \"trace.spanid\"\n\tTagSampled           = \"trace.sampled\"\n\tjaegerNotSampledFlag = \"0\"\n)\n\n\/\/ injectOpentracingIdsToTags writes trace data to ctxtags.\n\/\/ This is done in an incredibly hacky way, because the public-facing interface of opentracing doesn't give access to\n\/\/ the TraceId and SpanId of the SpanContext. Only the Tracer's Inject\/Extract methods know what these are.\n\/\/ Most tracers have them encoded as keys with 'traceid' and 'spanid':\n\/\/ https:\/\/github.com\/openzipkin\/zipkin-go-opentracing\/blob\/594640b9ef7e5c994e8d9499359d693c032d738c\/propagation_ot.go#L29\n\/\/ https:\/\/github.com\/opentracing\/basictracer-go\/blob\/1b32af207119a14b1b231d451df3ed04a72efebf\/propagation_ot.go#L26\n\/\/ Jaeger from Uber use one-key schema with next format '{trace-id}:{span-id}:{parent-span-id}:{flags}'\n\/\/ https:\/\/www.jaegertracing.io\/docs\/client-libraries\/#trace-span-identity\nfunc injectOpentracingIdsToTags(span opentracing.Span, tags grpc_ctxtags.Tags) {\n\tif err := span.Tracer().Inject(span.Context(), opentracing.HTTPHeaders, &tagsCarrier{tags}); err != nil {\n\t\tgrpclog.Infof(\"grpc_opentracing: failed extracting trace info into ctx %v\", err)\n\t}\n}\n\n\/\/ tagsCarrier is a really hacky way of\ntype tagsCarrier struct {\n\tgrpc_ctxtags.Tags\n}\n\nfunc (t *tagsCarrier) Set(key, val string) {\n\tkey = strings.ToLower(key)\n\tif strings.Contains(key, \"traceid\") {\n\t\tt.Tags.Set(TagTraceId, val) \/\/ this will most likely be base-16 (hex) encoded\n\t}\n\n\tif strings.Contains(key, \"spanid\") && !strings.Contains(strings.ToLower(key), \"parent\") {\n\t\tt.Tags.Set(TagSpanId, val) \/\/ this will most likely be base-16 (hex) encoded\n\t}\n\n\tif strings.Contains(key, \"sampled\") {\n\t\tswitch val {\n\t\tcase \"true\", \"false\":\n\t\t\tt.Tags.Set(TagSampled, val)\n\t\t}\n\t}\n\n\tif key == \"uber-trace-id\" {\n\t\tparts := strings.Split(val, \":\")\n\t\tif len(parts) == 4 {\n\t\t\tt.Tags.Set(TagTraceId, parts[0])\n\t\t\tt.Tags.Set(TagSpanId, parts[1])\n\n\t\t\tif parts[3] != jaegerNotSampledFlag {\n\t\t\t\tt.Tags.Set(TagSampled, \"true\")\n\t\t\t} else {\n\t\t\t\tt.Tags.Set(TagSampled, \"false\")\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>feature(tracing): Add datadog support to injectOpenTracingIdsToTags<commit_after>package grpc_opentracing\n\nimport (\n\t\"strings\"\n\n\tgrpc_ctxtags \"github.com\/grpc-ecosystem\/go-grpc-middleware\/tags\"\n\topentracing \"github.com\/opentracing\/opentracing-go\"\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\nconst (\n\tTagTraceId           = \"trace.traceid\"\n\tTagSpanId            = \"trace.spanid\"\n\tTagSampled           = \"trace.sampled\"\n\tjaegerNotSampledFlag = \"0\"\n)\n\n\/\/ injectOpentracingIdsToTags writes trace data to ctxtags.\n\/\/ This is done in an incredibly hacky way, because the public-facing interface of opentracing doesn't give access to\n\/\/ the TraceId and SpanId of the SpanContext. Only the Tracer's Inject\/Extract methods know what these are.\n\/\/ Most tracers have them encoded as keys with 'traceid' and 'spanid':\n\/\/ https:\/\/github.com\/openzipkin\/zipkin-go-opentracing\/blob\/594640b9ef7e5c994e8d9499359d693c032d738c\/propagation_ot.go#L29\n\/\/ https:\/\/github.com\/opentracing\/basictracer-go\/blob\/1b32af207119a14b1b231d451df3ed04a72efebf\/propagation_ot.go#L26\n\/\/ Jaeger from Uber use one-key schema with next format '{trace-id}:{span-id}:{parent-span-id}:{flags}'\n\/\/ https:\/\/www.jaegertracing.io\/docs\/client-libraries\/#trace-span-identity\n\/\/ Datadog uses keys ending with 'trace-id' and 'parent-id' (for span) by default:\n\/\/ https:\/\/github.com\/DataDog\/dd-trace-go\/blob\/v1\/ddtrace\/tracer\/textmap.go#L77\nfunc injectOpentracingIdsToTags(span opentracing.Span, tags grpc_ctxtags.Tags) {\n\tif err := span.Tracer().Inject(span.Context(), opentracing.HTTPHeaders, &tagsCarrier{tags}); err != nil {\n\t\tgrpclog.Infof(\"grpc_opentracing: failed extracting trace info into ctx %v\", err)\n\t}\n}\n\n\/\/ tagsCarrier is a really hacky way of\ntype tagsCarrier struct {\n\tgrpc_ctxtags.Tags\n}\n\nfunc (t *tagsCarrier) Set(key, val string) {\n\tkey = strings.ToLower(key)\n\tif strings.Contains(key, \"traceid\") {\n\t\tt.Tags.Set(TagTraceId, val) \/\/ this will most likely be base-16 (hex) encoded\n\t}\n\n\tif strings.Contains(key, \"spanid\") && !strings.Contains(strings.ToLower(key), \"parent\") {\n\t\tt.Tags.Set(TagSpanId, val) \/\/ this will most likely be base-16 (hex) encoded\n\t}\n\n\tif strings.Contains(key, \"sampled\") {\n\t\tswitch val {\n\t\tcase \"true\", \"false\":\n\t\t\tt.Tags.Set(TagSampled, val)\n\t\t}\n\t}\n\n\tif key == \"uber-trace-id\" {\n\t\tparts := strings.Split(val, \":\")\n\t\tif len(parts) == 4 {\n\t\t\tt.Tags.Set(TagTraceId, parts[0])\n\t\t\tt.Tags.Set(TagSpanId, parts[1])\n\n\t\t\tif parts[3] != jaegerNotSampledFlag {\n\t\t\t\tt.Tags.Set(TagSampled, \"true\")\n\t\t\t} else {\n\t\t\t\tt.Tags.Set(TagSampled, \"false\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif strings.HasSuffix(key, \"trace-id\") {\n\t\tt.Tags.Set(TagTraceId, val)\n\t}\n\n\tif strings.HasSuffix(key, \"parent-id\") {\n\t\tt.Tags.Set(TagSpanId, val)\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\/\/ The vector package implements an efficient container for managing\n\/\/ linear arrays of elements.  Unlike arrays, vectors can change size dynamically.\npackage vector\n\n\/\/ Element is an empty-interface object representing the contents of\n\/\/ a cell in the vector.\ntype Element interface {}\n\n\n\/\/ Vector is the container itself.\ntype Vector struct {\n\ta []Element\n}\n\n\nfunc copy(dst, src []Element) {\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = src[i]\n\t}\n}\n\n\n\/\/ Insert n elements at position i.\nfunc expand(a []Element, i, n int) []Element {\n\t\/\/ make sure we have enough space\n\tlen0 := len(a);\n\tlen1 := len0 + n;\n\tif len1 < cap(a) {\n\t\t\/\/ enough space - just expand\n\t\ta = a[0 : len1]\n\t} else {\n\t\t\/\/ not enough space - double capacity\n\t\tcapb := cap(a)*2;\n\t\tif capb < len1 {\n\t\t\t\/\/ still not enough - use required length\n\t\t\tcapb = len1\n\t\t}\n\t\t\/\/ capb >= len1\n\t\tb := make([]Element, len1, capb);\n\t\tcopy(b, a);\n\t\ta = b\n\t}\n\n\t\/\/ make a hole\n\tfor j := len0-1; j >= i ; j-- {\n\t\ta[j+n] = a[j]\n\t}\n\treturn a\n}\n\n\n\/\/ Init initializes a new or resized vector.  The initial_len may be <= 0 to\n\/\/ request a default length.  If initial_len is shorter than the current\n\/\/ length of the Vector, trailing elements of the Vector will be cleared.\nfunc (p *Vector) Init(initial_len int) *Vector {\n\ta := p.a;\n\n\tif cap(a) == 0 || cap(a) < initial_len {\n\t\tn := 8;  \/\/ initial capacity\n\t\tif initial_len > n {\n\t\t\tn = initial_len\n\t\t}\n\t\ta = make([]Element, n);\n\t} else {\n\t\t\/\/ nil out entries\n\t\tfor j := len(a) - 1; j >= 0; j-- {\n\t\t\ta[j] = nil\n\t\t}\n\t}\n\n\tp.a = a[0 : initial_len];\n\treturn p\n}\n\n\n\/\/ New returns an initialized new Vector with length at least len.\nfunc New(len int) *Vector {\n\treturn new(Vector).Init(len)\n}\n\n\n\/\/ Len returns the number of elements in the vector.\nfunc (p *Vector) Len() int {\n\treturn len(p.a)\n}\n\n\n\/\/ At returns the i'th element of the vector.\nfunc (p *Vector) At(i int) Element {\n\treturn p.a[i]\n}\n\n\n\/\/ Set sets the i'th element of the vector to value x.\nfunc (p *Vector) Set(i int, x Element) {\n\tp.a[i] = x\n}\n\n\n\/\/ Last returns the element in the vector of highest index.\nfunc (p *Vector) Last() Element {\n\treturn p.a[len(p.a) - 1]\n}\n\n\n\/\/ Insert inserts into the vector an element of value x before\n\/\/ the current element at index i.\nfunc (p *Vector) Insert(i int, x Element) {\n\tp.a = expand(p.a, i, 1);\n\tp.a[i] = x;\n}\n\n\n\/\/ Delete deletes the i'th element of the vector.  The gap is closed so the old\n\/\/ element at index i+1 has index i afterwards.\nfunc (p *Vector) Delete(i int) Element {\n\ta := p.a;\n\tn := len(a);\n\n\tx := a[i];\n\tcopy(a[i : n-1], a[i+1 : n]);\n\ta[n-1] = nil;  \/\/ support GC, nil out entry\n\tp.a = a[0 : n-1];\n\n\treturn x\n}\n\n\n\/\/ InsertVector inserts into the vector the contents of the Vector\n\/\/ x such that the 0th element of x appears at index i after insertion.\nfunc (p *Vector) InsertVector(i int, x *Vector) {\n\tp.a = expand(p.a, i, len(x.a));\n\tcopy(p.a[i : i + len(x.a)], x.a);\n}\n\n\n\/\/ Cut deletes elements i through j-1, inclusive.\nfunc (p *Vector) Cut(i, j int) {\n\ta := p.a;\n\tn := len(a);\n\tm := n - (j - i);\n\n\tcopy(a[i : m], a[j : n]);\n\tfor k := m; k < n; k++ {\n\t\ta[k] = nil  \/\/ support GC, nil out entries\n\t}\n\n\tp.a = a[0 : m];\n}\n\n\n\/\/ Slice returns a new Vector by slicing the old one to extract slice [i:j].\n\/\/ The elements are copied. The original vector is unchanged.\nfunc (p *Vector) Slice(i, j int) *Vector {\n\ts := New(j - i);  \/\/ will fail in Init() if j < j\n\tcopy(s.a, p.a[i : j]);\n\treturn s;\n}\n\n\n\/\/ Do calls function f for each element of the vector, in order.\n\/\/ The function should not change the indexing of the vector underfoot.\nfunc (p *Vector) Do(f func(elem Element)) {\n\tfor i := 0; i < len(p.a); i++ {\n\t\tf(p.a[i])\t\/\/ not too safe if f changes the Vector\n\t}\n}\n\n\n\/\/ Convenience wrappers\n\n\/\/ Push appends x to the end of the vector.\nfunc (p *Vector) Push(x Element) {\n\tp.Insert(len(p.a), x)\n}\n\n\n\/\/ Push deletes the last element of the vector.\nfunc (p *Vector) Pop() Element {\n\treturn p.Delete(len(p.a) - 1)\n}\n\n\n\/\/ AppendVector appends the entire Vector x to the end of this vector.\nfunc (p *Vector) AppendVector(x *Vector) {\n\tp.InsertVector(len(p.a), x);\n}\n\n\n\/\/ Partial SortInterface support\n\n\/\/ LessInterface provides partial support of the SortInterface.\ntype LessInterface interface {\n\tLess(y Element) bool\n}\n\n\n\/\/ Less returns a boolean denoting whether the i'th element is less than the j'th element.\nfunc (p *Vector) Less(i, j int) bool {\n\treturn p.a[i].(LessInterface).Less(p.a[j])\n}\n\n\n\/\/ Swap exchanges the elements at indexes i and j.\nfunc (p *Vector) Swap(i, j int) {\n\ta := p.a;\n\ta[i], a[j] = a[j], a[i]\n}\n\n\n\/\/ Iterate over all elements; driver for range\nfunc (p *Vector) iterate(c chan Element) {\n\tfor i := 0; i < len(p.a); i++ {\n\t\tc <- p.a[i]\n\t}\n\tclose(c);\n}\n\n\/\/ Channel iterator for range.\nfunc (p *Vector) Iter() chan Element {\n\tc := make(chan Element);\n\tgo p.iterate(c);\n\treturn c;\n}\n<commit_msg>use range in vector iterator<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\/\/ The vector package implements an efficient container for managing\n\/\/ linear arrays of elements.  Unlike arrays, vectors can change size dynamically.\npackage vector\n\n\/\/ Element is an empty-interface object representing the contents of\n\/\/ a cell in the vector.\ntype Element interface {}\n\n\n\/\/ Vector is the container itself.\ntype Vector struct {\n\ta []Element\n}\n\n\nfunc copy(dst, src []Element) {\n\tfor i := 0; i < len(src); i++ {\n\t\tdst[i] = src[i]\n\t}\n}\n\n\n\/\/ Insert n elements at position i.\nfunc expand(a []Element, i, n int) []Element {\n\t\/\/ make sure we have enough space\n\tlen0 := len(a);\n\tlen1 := len0 + n;\n\tif len1 < cap(a) {\n\t\t\/\/ enough space - just expand\n\t\ta = a[0 : len1]\n\t} else {\n\t\t\/\/ not enough space - double capacity\n\t\tcapb := cap(a)*2;\n\t\tif capb < len1 {\n\t\t\t\/\/ still not enough - use required length\n\t\t\tcapb = len1\n\t\t}\n\t\t\/\/ capb >= len1\n\t\tb := make([]Element, len1, capb);\n\t\tcopy(b, a);\n\t\ta = b\n\t}\n\n\t\/\/ make a hole\n\tfor j := len0-1; j >= i ; j-- {\n\t\ta[j+n] = a[j]\n\t}\n\treturn a\n}\n\n\n\/\/ Init initializes a new or resized vector.  The initial_len may be <= 0 to\n\/\/ request a default length.  If initial_len is shorter than the current\n\/\/ length of the Vector, trailing elements of the Vector will be cleared.\nfunc (p *Vector) Init(initial_len int) *Vector {\n\ta := p.a;\n\n\tif cap(a) == 0 || cap(a) < initial_len {\n\t\tn := 8;  \/\/ initial capacity\n\t\tif initial_len > n {\n\t\t\tn = initial_len\n\t\t}\n\t\ta = make([]Element, n);\n\t} else {\n\t\t\/\/ nil out entries\n\t\tfor j := len(a) - 1; j >= 0; j-- {\n\t\t\ta[j] = nil\n\t\t}\n\t}\n\n\tp.a = a[0 : initial_len];\n\treturn p\n}\n\n\n\/\/ New returns an initialized new Vector with length at least len.\nfunc New(len int) *Vector {\n\treturn new(Vector).Init(len)\n}\n\n\n\/\/ Len returns the number of elements in the vector.\nfunc (p *Vector) Len() int {\n\treturn len(p.a)\n}\n\n\n\/\/ At returns the i'th element of the vector.\nfunc (p *Vector) At(i int) Element {\n\treturn p.a[i]\n}\n\n\n\/\/ Set sets the i'th element of the vector to value x.\nfunc (p *Vector) Set(i int, x Element) {\n\tp.a[i] = x\n}\n\n\n\/\/ Last returns the element in the vector of highest index.\nfunc (p *Vector) Last() Element {\n\treturn p.a[len(p.a) - 1]\n}\n\n\n\/\/ Insert inserts into the vector an element of value x before\n\/\/ the current element at index i.\nfunc (p *Vector) Insert(i int, x Element) {\n\tp.a = expand(p.a, i, 1);\n\tp.a[i] = x;\n}\n\n\n\/\/ Delete deletes the i'th element of the vector.  The gap is closed so the old\n\/\/ element at index i+1 has index i afterwards.\nfunc (p *Vector) Delete(i int) Element {\n\ta := p.a;\n\tn := len(a);\n\n\tx := a[i];\n\tcopy(a[i : n-1], a[i+1 : n]);\n\ta[n-1] = nil;  \/\/ support GC, nil out entry\n\tp.a = a[0 : n-1];\n\n\treturn x\n}\n\n\n\/\/ InsertVector inserts into the vector the contents of the Vector\n\/\/ x such that the 0th element of x appears at index i after insertion.\nfunc (p *Vector) InsertVector(i int, x *Vector) {\n\tp.a = expand(p.a, i, len(x.a));\n\tcopy(p.a[i : i + len(x.a)], x.a);\n}\n\n\n\/\/ Cut deletes elements i through j-1, inclusive.\nfunc (p *Vector) Cut(i, j int) {\n\ta := p.a;\n\tn := len(a);\n\tm := n - (j - i);\n\n\tcopy(a[i : m], a[j : n]);\n\tfor k := m; k < n; k++ {\n\t\ta[k] = nil  \/\/ support GC, nil out entries\n\t}\n\n\tp.a = a[0 : m];\n}\n\n\n\/\/ Slice returns a new Vector by slicing the old one to extract slice [i:j].\n\/\/ The elements are copied. The original vector is unchanged.\nfunc (p *Vector) Slice(i, j int) *Vector {\n\ts := New(j - i);  \/\/ will fail in Init() if j < j\n\tcopy(s.a, p.a[i : j]);\n\treturn s;\n}\n\n\n\/\/ Do calls function f for each element of the vector, in order.\n\/\/ The function should not change the indexing of the vector underfoot.\nfunc (p *Vector) Do(f func(elem Element)) {\n\tfor i := 0; i < len(p.a); i++ {\n\t\tf(p.a[i])\t\/\/ not too safe if f changes the Vector\n\t}\n}\n\n\n\/\/ Convenience wrappers\n\n\/\/ Push appends x to the end of the vector.\nfunc (p *Vector) Push(x Element) {\n\tp.Insert(len(p.a), x)\n}\n\n\n\/\/ Push deletes the last element of the vector.\nfunc (p *Vector) Pop() Element {\n\treturn p.Delete(len(p.a) - 1)\n}\n\n\n\/\/ AppendVector appends the entire Vector x to the end of this vector.\nfunc (p *Vector) AppendVector(x *Vector) {\n\tp.InsertVector(len(p.a), x);\n}\n\n\n\/\/ Partial SortInterface support\n\n\/\/ LessInterface provides partial support of the SortInterface.\ntype LessInterface interface {\n\tLess(y Element) bool\n}\n\n\n\/\/ Less returns a boolean denoting whether the i'th element is less than the j'th element.\nfunc (p *Vector) Less(i, j int) bool {\n\treturn p.a[i].(LessInterface).Less(p.a[j])\n}\n\n\n\/\/ Swap exchanges the elements at indexes i and j.\nfunc (p *Vector) Swap(i, j int) {\n\ta := p.a;\n\ta[i], a[j] = a[j], a[i]\n}\n\n\n\/\/ Iterate over all elements; driver for range\nfunc (p *Vector) iterate(c chan Element) {\n\tfor i, v := range p.a {\n\t\tc <- v\n\t}\n\tclose(c);\n}\n\n\/\/ Channel iterator for range.\nfunc (p *Vector) Iter() chan Element {\n\tc := make(chan Element);\n\tgo p.iterate(c);\n\treturn c;\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ StringsUnique returns true if all strings in the list are unique,\n\/\/ false otherwise.\nfunc StringsUnique(s []string) bool {\n\tsort.Strings(s)\n\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tif s[i] == s[i+1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ StringsHasPrefix returns true if all of the strings have the given prefix,\n\/\/ false otherwise.\nfunc StringsHasPrefix(s []string, p string) bool {\n\tfor _, x := range s {\n\t\tif !strings.HasPrefix(x, p) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ StringsSharePrefix returns true if any of the strings are prefixes of another,\n\/\/ false otherwise.\nfunc StringsSharePrefix(s []string) bool {\n\tsort.Strings(s)\n\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tif strings.HasPrefix(s[i+1], s[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ StringsCountMoreThan returns true if any of the strings in s\n\/\/ contain more than n occurences of c, false otherwise.\nfunc StringsCountMoreThan(s []string, c string, n int) bool {\n\tfor _, x := range s {\n\t\tif strings.Count(x, c) > n {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ StringsHaveOrNot returns true if all strings in s either have an occurence of c,\n\/\/ or do not have any occurence of c.\n\/\/ In another way, it returns false if only some strings in s have an occurence of c.\nfunc StringsHaveOrNot(s []string, c string) bool {\n\tnumStringsWithOccurence := 0\n\n\tfor _, x := range s {\n\t\tif strings.Contains(x, c) {\n\t\t\tnumStringsWithOccurence++\n\t\t}\n\t}\n\n\treturn !(numStringsWithOccurence > 0 && numStringsWithOccurence < len(s))\n}\n\n\/\/ ValidateSubmitRequest validates that the given request contains no SliceIDs.\n\/\/ Otherwise it is identical to ValidateRequest().\nfunc ValidateSubmitRequest(request Request) (bool, error) {\n\tif len(request.SliceIDs) != 0 {\n\t\treturn false, maskAny(invalidSubmitRequestSlicesGivenError)\n\t}\n\n\treturn ValidateRequest(request)\n}\n\n\/\/ ValidateRequest takes a Request, and returns whether it is valid or not.\n\/\/ If the request is not valid, the error provides more details.\nfunc ValidateRequest(request Request) (bool, error) {\n\tvar error ValidationError\n\t\/\/ Check there are units in the group.\n\tif len(request.Units) == 0 {\n\t\terror.causingErrors = append(error.causingErrors, noUnitsInGroupError)\n\t}\n\n\t\/\/ Check that there are not any @ symbols in the group name.\n\tif strings.Contains(request.Group, \"@\") {\n\t\terror.causingErrors = append(error.causingErrors, atInGroupNameError)\n\t}\n\n\tunitNames := []string{}\n\tfor _, unit := range request.Units {\n\t\tunitNames = append(unitNames, unit.Name)\n\t}\n\n\t\/\/ Check that we're not mixing units with @ and units without @.\n\tif !StringsHaveOrNot(unitNames, \"@.\") {\n\t\terror.causingErrors = append(error.causingErrors, mixedSliceInstanceError)\n\t}\n\n\t\/\/ Check that all unit names are prefixed by the group name.\n\tif !StringsHasPrefix(unitNames, request.Group) {\n\t\terror.causingErrors = append(error.causingErrors, badUnitPrefixError)\n\t}\n\n\t\/\/ Check that @ only occurences at most once per unit name.\n\tif StringsCountMoreThan(unitNames, \"@\", 1) {\n\t\terror.causingErrors = append(error.causingErrors, multipleAtInUnitNameError)\n\t}\n\n\t\/\/ Check that all unit names are unique.\n\tif !StringsUnique(unitNames) {\n\t\terror.causingErrors = append(error.causingErrors, unitsSameNameError)\n\t}\n\n\tif len(error.causingErrors) != 0 {\n\t\treturn false, error\n\t}\n\treturn true, nil\n}\n\n\/\/ ValidateMultipleRequest takes a list of Requests, and returns whether\n\/\/ they are valid together or not.\n\/\/ If the requests are not valid, the error returned provides more details.\nfunc ValidateMultipleRequest(requests []Request) (bool, error) {\n\tgroupNames := []string{}\n\tvar error ValidationError\n\n\tfor _, request := range requests {\n\t\tgroupNames = append(groupNames, request.Group)\n\t}\n\n\t\/\/ Check that all group names are unique.\n\tif !StringsUnique(groupNames) {\n\t\terror.causingErrors = append(error.causingErrors, groupsSameNameError)\n\t}\n\n\t\/\/ Check that group names are not prefixes of each other.\n\tif StringsSharePrefix(groupNames) {\n\t\terror.causingErrors = append(error.causingErrors, groupsArePrefixError)\n\t}\n\n\tif len(error.causingErrors) != 0 {\n\t\treturn false, error\n\t}\n\treturn true, nil\n}\n<commit_msg>rename error to ValidationError<commit_after>package controller\n\nimport (\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ StringsUnique returns true if all strings in the list are unique,\n\/\/ false otherwise.\nfunc StringsUnique(s []string) bool {\n\tsort.Strings(s)\n\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tif s[i] == s[i+1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ StringsHasPrefix returns true if all of the strings have the given prefix,\n\/\/ false otherwise.\nfunc StringsHasPrefix(s []string, p string) bool {\n\tfor _, x := range s {\n\t\tif !strings.HasPrefix(x, p) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ StringsSharePrefix returns true if any of the strings are prefixes of another,\n\/\/ false otherwise.\nfunc StringsSharePrefix(s []string) bool {\n\tsort.Strings(s)\n\n\tfor i := 0; i < len(s)-1; i++ {\n\t\tif strings.HasPrefix(s[i+1], s[i]) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ StringsCountMoreThan returns true if any of the strings in s\n\/\/ contain more than n occurences of c, false otherwise.\nfunc StringsCountMoreThan(s []string, c string, n int) bool {\n\tfor _, x := range s {\n\t\tif strings.Count(x, c) > n {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ StringsHaveOrNot returns true if all strings in s either have an occurence of c,\n\/\/ or do not have any occurence of c.\n\/\/ In another way, it returns false if only some strings in s have an occurence of c.\nfunc StringsHaveOrNot(s []string, c string) bool {\n\tnumStringsWithOccurence := 0\n\n\tfor _, x := range s {\n\t\tif strings.Contains(x, c) {\n\t\t\tnumStringsWithOccurence++\n\t\t}\n\t}\n\n\treturn !(numStringsWithOccurence > 0 && numStringsWithOccurence < len(s))\n}\n\n\/\/ ValidateSubmitRequest validates that the given request contains no SliceIDs.\n\/\/ Otherwise it is identical to ValidateRequest().\nfunc ValidateSubmitRequest(request Request) (bool, error) {\n\tif len(request.SliceIDs) != 0 {\n\t\treturn false, maskAny(invalidSubmitRequestSlicesGivenError)\n\t}\n\n\treturn ValidateRequest(request)\n}\n\n\/\/ ValidateRequest takes a Request, and returns whether it is valid or not.\n\/\/ If the request is not valid, the error provides more details.\nfunc ValidateRequest(request Request) (bool, error) {\n\tvar validationError ValidationError\n\t\/\/ Check there are units in the group.\n\tif len(request.Units) == 0 {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, noUnitsInGroupError)\n\t}\n\n\t\/\/ Check that there are not any @ symbols in the group name.\n\tif strings.Contains(request.Group, \"@\") {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, atInGroupNameError)\n\t}\n\n\tunitNames := []string{}\n\tfor _, unit := range request.Units {\n\t\tunitNames = append(unitNames, unit.Name)\n\t}\n\n\t\/\/ Check that we're not mixing units with @ and units without @.\n\tif !StringsHaveOrNot(unitNames, \"@.\") {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, mixedSliceInstanceError)\n\t}\n\n\t\/\/ Check that all unit names are prefixed by the group name.\n\tif !StringsHasPrefix(unitNames, request.Group) {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, badUnitPrefixError)\n\t}\n\n\t\/\/ Check that @ only occurences at most once per unit name.\n\tif StringsCountMoreThan(unitNames, \"@\", 1) {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, multipleAtInUnitNameError)\n\t}\n\n\t\/\/ Check that all unit names are unique.\n\tif !StringsUnique(unitNames) {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, unitsSameNameError)\n\t}\n\n\tif len(validationError.causingErrors) != 0 {\n\t\treturn false, validationError\n\t}\n\treturn true, nil\n}\n\n\/\/ ValidateMultipleRequest takes a list of Requests, and returns whether\n\/\/ they are valid together or not.\n\/\/ If the requests are not valid, the error returned provides more details.\nfunc ValidateMultipleRequest(requests []Request) (bool, error) {\n\tgroupNames := []string{}\n\tvar validationError ValidationError\n\n\tfor _, request := range requests {\n\t\tgroupNames = append(groupNames, request.Group)\n\t}\n\n\t\/\/ Check that all group names are unique.\n\tif !StringsUnique(groupNames) {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, groupsSameNameError)\n\t}\n\n\t\/\/ Check that group names are not prefixes of each other.\n\tif StringsSharePrefix(groupNames) {\n\t\tvalidationError.causingErrors = append(validationError.causingErrors, groupsArePrefixError)\n\t}\n\n\tif len(validationError.causingErrors) != 0 {\n\t\treturn false, validationError\n\t}\n\treturn true, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014, Surul Software Labs GmbH\n\/\/ All rights reserved.\n\n\/*\nPackage fault provides utilities to help with package internal error handling.\n\nIt supports a simple idiom for reducing the amount of package internal error\nhandling. It allows you to panic with a Fault instance in package internal code.\nThis is then recovered using a defer for a all exported methods, which then return\nan error extracted from the fault. As an example, if you were to be reading data\nfrom a file and then writing it you could use\n\n\timport (\n\t\t\"github.com\/surullabs\/fault\"\n\t)\n\n\tvar check = fault.NewChecker()\n\n\tfunc ExportedMethod() (err error) {\n\t\t\/\/ Set up the recovery. err will be automatically populated and all\n\t\t\/\/ non-fault panics will be propogated.\n\t\tdefer check.Recover(&err)\n\n\t\t\/\/ If there is an error in ReadFile the method will automatically return\n\t\t\/\/ the error.\n\t\tdata := check.Return(ioutil.ReadFile(\"filename\")).([]byte)\n\t\t\/\/ If yourFn returns false the function will return an error\n\t\t\/\/ formatted as \"condition is not true: yourData\"\n\t\tcheck.Truef(yourFn(data), \"condition is not true: %s\", string(data))\n\t}\n\nIt also provides access to an ErrorChain class which can be used to chain errors together.\nErrors can be transparently checked for existence in a chain by calling the Contains method.\n\nPlease look at the tests for more sample usage.\n*\/\npackage fault\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ ErrorChain is a list of errors and can be used to chain errors together.\ntype ErrorChain struct {\n\tchain []error\n}\n\n\/\/ AsError returns an error if any are present in the chain or nil if not\nfunc (c *ErrorChain) AsError() error {\n\tif c == nil || len(c.chain) == 0 {\n\t\treturn nil\n\t}\n\treturn c\n}\n\n\/\/ String returns the same value as Error()\nfunc (c *ErrorChain) String() string { return c.Error() }\n\n\/\/ Errors returns all errors in the chain\nfunc (c *ErrorChain) Errors() []error { return c.chain }\n\n\/\/ Error will return a string representation of all errors.\nfunc (c *ErrorChain) Error() string {\n\terrors := make([]string, len(c.chain))\n\tfor i, err := range c.chain {\n\t\terrors[i] = err.Error()\n\t}\n\treturn strings.Join(errors, \"; \")\n}\n\n\/\/ Chain appends the error provided to the current chain. If the\n\/\/ err is a chain then all errors in the chain are appended.\nfunc (c *ErrorChain) Chain(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tif c.chain == nil {\n\t\tc.chain = make([]error, 0)\n\t}\n\n\tswitch e := err.(type) {\n\tcase *ErrorChain:\n\t\tif e.chain != nil {\n\t\t\tc.chain = append(c.chain, e.chain...)\n\t\t}\n\tdefault:\n\t\tc.chain = append(c.chain, e)\n\t}\n}\n\n\/\/ Chain will chain a list of errors passed in. The errors can\n\/\/ be of type *ErrorChain in which case their chains will be appended.\nfunc Chain(errs ...error) error {\n\tchain := &ErrorChain{}\n\tfor _, err := range errs {\n\t\tchain.Chain(err)\n\t}\n\treturn chain.AsError()\n}\n\n\/\/ Contains will return true in the following cases:\n\/\/\n\/\/ \t* chain.Error() == target.Error()\n\/\/ \t* chain is an ErrorChain and one of the errors is target\n\/\/ \t* Contains(target, chain) returns true\nfunc Contains(chain, target error) bool {\n\tif chain == nil || target == nil {\n\t\treturn false\n\t}\n\tif chain.Error() == target.Error() {\n\t\treturn true\n\t}\n\tif chainErr, isChain := chain.(*ErrorChain); isChain {\n\t\tfor _, err := range chainErr.chain {\n\t\t\tif err.Error() == target.Error() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tif chainErr, isChain := target.(*ErrorChain); isChain {\n\t\tfor _, err := range chainErr.chain {\n\t\t\tif err.Error() == chain.Error() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Fault is an interface for representing a package internal fault.\ntype Fault interface {\n\t\/\/ Fault returns the error tied to this fault\n\tFault() error\n}\n\n\/\/ Faulter is an interface used to generate faults from errors\ntype Faulter interface {\n\tNew(err error) Fault\n}\n\n\/\/ FaultCheck is an interface providing functionality to check for faults and recover from them.\ntype FaultCheck interface {\n\t\/\/ Recover is used to recover from faults that were expressed through panics.\n\t\/\/ It will call recover() internally and the error variable pointed to by the argument will be populated with the fault information.\n\tRecover(*error)\n\t\/\/ RecoverPanic works exactly like recover with the exception that the second argument\n\t\/\/ must be the result of a call to recover()\n\tRecoverPanic(*error, interface{})\n\t\/\/ True will panic with a fault if the condition provided is false\n\t\/\/ The fault error string will be the second argument\n\tTrue(bool, string)\n\t\/\/ Truef behaves like Check with the error string as the result of a call to fmt.Errorf(format, args...)\n\tTruef(bool, string, ...interface{})\n\t\/\/ Return will panic if the error provided is not nil. It will return the first argument if not\n\tReturn(interface{}, error) interface{}\n\t\/\/ Error is equivalent to a call to Return(nil, err)\n\tError(error)\n\t\/\/ Output functions exactly as Return, with the only difference being that the output is included in the error message.\n\t\/\/ If the output is a byte array it is converted to a string.\n\t\/\/ This can be useful when debugging use of os\/exec package for instance.\n\tOutput(interface{}, error) interface{}\n}\n\n\/\/ Checker provides a default implementation of FaultCheck\ntype Checker struct {\n\tfaulter Faulter\n}\n\nfunc NewChecker() *Checker { return &Checker{faulter: ErrorFaulter{}} }\n\nfunc (c *Checker) SetFaulter(f Faulter) *Checker {\n\tc.faulter = f\n\treturn c\n}\n\n\/\/ RecoverPanic implements FaultCheck.RecoverPanic\nfunc (c *Checker) RecoverPanic(errPtr *error, panicked interface{}) {\n\tif panicked == nil {\n\t\treturn\n\t} else if fault, faulty := panicked.(Fault); faulty {\n\t\t*errPtr = Chain(fault.Fault(), *errPtr)\n\t\treturn\n\t} else {\n\t\tpanic(panicked)\n\t}\n}\n\n\/\/ Recover implements FaultCheck.Recover\nfunc (c *Checker) Recover(errPtr *error) {\n\tc.RecoverPanic(errPtr, recover())\n}\n\ntype ErrorFaulter struct{}\n\nfunc (ErrorFaulter) New(err error) Fault { return &errorFault{err: err} }\n\ntype errorFault struct {\n\terr error\n}\n\nfunc (e *errorFault) Fault() error { return e.err }\n\nfunc (e *errorFault) String() string {\n\tif e.err == nil {\n\t\treturn \"\"\n\t}\n\treturn e.err.Error()\n\n}\n\nfunc (c *Checker) True(condition bool, errStr string) {\n\tif !condition {\n\t\tpanic(c.faulter.New(errors.New(errStr)))\n\t}\n}\n\n\/\/ True implements FaultCheck.True\nfunc (c *Checker) Truef(condition bool, format string, args ...interface{}) {\n\tif !condition {\n\t\tpanic(c.faulter.New(fmt.Errorf(format, args...)))\n\t}\n}\n\n\/\/ Return implements FaultCheck.Return\nfunc (c *Checker) Return(i interface{}, err error) interface{} {\n\tif err != nil {\n\t\tpanic(c.faulter.New(err))\n\t}\n\treturn i\n}\n\n\/\/ Error implements FaultCheck.Error\nfunc (c *Checker) Error(err error) {\n\tif err != nil {\n\t\tpanic(c.faulter.New(err))\n\t}\n}\n\n\/\/ Output implements FaultCheck.Output\nfunc (c *Checker) Output(i interface{}, err error) interface{} {\n\tif err != nil {\n\t\tvar out string\n\t\tif bytes, isByteArray := i.([]byte); isByteArray {\n\t\t\tout = string(bytes)\n\t\t} else {\n\t\t\tout = fmt.Sprintf(\"%v\", i)\n\t\t}\n\t\tpanic(c.faulter.New(&ErrorChain{chain: []error{err, fmt.Errorf(\"output: %s\", out)}}))\n\t}\n\treturn i\n}\n\n\/\/ Call provides information about a function call.\ntype Call struct {\n\tFile string \/\/ File provides the file of the caller\n\tLine int    \/\/ Line provides the line number\n\tName string \/\/ Name is the name of the calling function\n}\n\nfunc (c *Call) String() string { return fmt.Sprintf(\"%s:%d:%s\", filepath.Base(c.File), c.Line, c.Name) }\n\nfunc (c *Call) Equal(c2 *Call) bool {\n\tif c == nil {\n\t\treturn c2 == nil\n\t} else if c2 == nil {\n\t\treturn false\n\t}\n\treturn c.File == c2.File && c.Line == c2.Line && c.Name == c2.Name\n}\n\ntype debugFault struct {\n\terr   error\n\ttrace []Call\n}\n\nfunc GetTrace(err error) (trace []Call) {\n\tif chain, isChain := err.(*ErrorChain); isChain {\n\t\tif fault, isFault := chain.Errors()[0].(*debugFault); isFault {\n\t\t\treturn fault.trace\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc StartSite(trace []Call) (call *Call) {\n\tif len(trace) == 0 {\n\t\tcall = &Call{\"?\", -1, \"?\"}\n\t} else {\n\t\tcall = &trace[0]\n\t}\n\treturn\n}\n\nfunc (d *debugFault) Error() string {\n\treturn fmt.Sprintf(\"%v: %s\", StartSite(d.trace), d.err.Error())\n}\n\nfunc (d *debugFault) Fault() error { return d }\n\ntype DebugFaulter struct{}\n\nvar checkerPrefix = TypePrefix(&Checker{})\n\nfunc TypePrefix(i interface{}) string {\n\tval := reflect.ValueOf(i)\n\tif val.Kind() == reflect.Ptr {\n\t\ttypeVal := val.Elem().Type()\n\t\treturn fmt.Sprintf(\"%s.(*%s)\", typeVal.PkgPath(), typeVal.Name())\n\t} else {\n\t\treturn fmt.Sprintf(\"%s.(%s)\", val.Type().PkgPath(), val.Type().Name())\n\t}\n}\n\n\/\/ ReadStack reads returns the stack after ignoring all calls up to the\n\/\/ function which has the first parameter as a prefix . An empty string returns\n\/\/ the entire stack.\nfunc ReadStack(prefix string) (trace []Call) {\n\ttrace = make([]Call, 0)\n\tvar (\n\t\tpc uintptr\n\t\tfn *runtime.Func\n\t)\n\tappendTo := false\n\tfor skip, ok := 0, true; ok; skip++ {\n\t\tcall := Call{Name: \"?\"}\n\t\tif pc, call.File, call.Line, ok = runtime.Caller(skip); !ok {\n\t\t\tbreak\n\t\t}\n\t\tif fn = runtime.FuncForPC(pc); fn != nil {\n\t\t\tcall.Name = fn.Name()\n\t\t}\n\n\t\tif appendTo {\n\t\t\ttrace = append(trace, call)\n\t\t}\n\t\tif strings.HasPrefix(call.Name, prefix) {\n\t\t\tappendTo = true\n\t\t}\n\t}\n\treturn\n}\n\nfunc (DebugFaulter) New(err error) Fault {\n\treturn &debugFault{err: err, trace: ReadStack(checkerPrefix)}\n}\n<commit_msg>Utilities to add stacktraces to errors.<commit_after>\/\/ Copyright 2014, Surul Software Labs GmbH\n\/\/ All rights reserved.\n\n\/*\nPackage fault provides utilities to help with package internal error handling.\n\nIt supports a simple idiom for reducing the amount of package internal error\nhandling. It allows you to panic with a Fault instance in package internal code.\nThis is then recovered using a defer for a all exported methods, which then return\nan error extracted from the fault. As an example, if you were to be reading data\nfrom a file and then writing it you could use\n\n\timport (\n\t\t\"github.com\/surullabs\/fault\"\n\t)\n\n\tvar check = fault.NewChecker()\n\n\tfunc ExportedMethod() (err error) {\n\t\t\/\/ Set up the recovery. err will be automatically populated and all\n\t\t\/\/ non-fault panics will be propogated.\n\t\tdefer check.Recover(&err)\n\n\t\t\/\/ If there is an error in ReadFile the method will automatically return\n\t\t\/\/ the error.\n\t\tdata := check.Return(ioutil.ReadFile(\"filename\")).([]byte)\n\t\t\/\/ If yourFn returns false the function will return an error\n\t\t\/\/ formatted as \"condition is not true: yourData\"\n\t\tcheck.Truef(yourFn(data), \"condition is not true: %s\", string(data))\n\t}\n\nIt also provides access to an ErrorChain class which can be used to chain errors together.\nErrors can be transparently checked for existence in a chain by calling the Contains method.\n\nPlease look at the tests for more sample usage.\n*\/\npackage fault\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ ErrorChain is a list of errors and can be used to chain errors together.\ntype ErrorChain struct {\n\tchain []error\n}\n\n\/\/ AsError returns an error if any are present in the chain or nil if not\nfunc (c *ErrorChain) AsError() error {\n\tif c == nil || len(c.chain) == 0 {\n\t\treturn nil\n\t}\n\treturn c\n}\n\n\/\/ String returns the same value as Error()\nfunc (c *ErrorChain) String() string { return c.Error() }\n\n\/\/ Errors returns all errors in the chain\nfunc (c *ErrorChain) Errors() []error { return c.chain }\n\n\/\/ Error will return a string representation of all errors.\nfunc (c *ErrorChain) Error() string {\n\terrors := make([]string, len(c.chain))\n\tfor i, err := range c.chain {\n\t\terrors[i] = err.Error()\n\t}\n\treturn strings.Join(errors, \"; \")\n}\n\n\/\/ Chain appends the error provided to the current chain. If the\n\/\/ err is a chain then all errors in the chain are appended.\nfunc (c *ErrorChain) Chain(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tif c.chain == nil {\n\t\tc.chain = make([]error, 0)\n\t}\n\n\tswitch e := err.(type) {\n\tcase *ErrorChain:\n\t\tif e.chain != nil {\n\t\t\tc.chain = append(c.chain, e.chain...)\n\t\t}\n\tdefault:\n\t\tc.chain = append(c.chain, e)\n\t}\n}\n\n\/\/ Chain will chain a list of errors passed in. The errors can\n\/\/ be of type *ErrorChain in which case their chains will be appended.\nfunc Chain(errs ...error) error {\n\tchain := &ErrorChain{}\n\tfor _, err := range errs {\n\t\tchain.Chain(err)\n\t}\n\treturn chain.AsError()\n}\n\n\/\/ Contains will return true in the following cases:\n\/\/\n\/\/ \t* chain.Error() == target.Error()\n\/\/ \t* chain is an ErrorChain and one of the errors is target\n\/\/ \t* Contains(target, chain) returns true\nfunc Contains(chain, target error) bool {\n\tif chain == nil || target == nil {\n\t\treturn false\n\t}\n\tif chain.Error() == target.Error() {\n\t\treturn true\n\t}\n\tif chainErr, isChain := chain.(*ErrorChain); isChain {\n\t\tfor _, err := range chainErr.chain {\n\t\t\tif err.Error() == target.Error() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tif chainErr, isChain := target.(*ErrorChain); isChain {\n\t\tfor _, err := range chainErr.chain {\n\t\t\tif err.Error() == chain.Error() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Fault is an interface for representing a package internal fault.\ntype Fault interface {\n\t\/\/ Cause returns the error tied to this fault\n\tCause() error\n\t\/\/ Error returns the result of a call to Cause().Error()\n\tError() string\n}\n\n\/\/ Faulter is an interface used to generate faults from errors\ntype Faulter interface {\n\tNew(err error) Fault\n}\n\n\/\/ FaultCheck is an interface providing functionality to check for faults and recover from them.\ntype FaultCheck interface {\n\t\/\/ Recover is used to recover from faults that were expressed through panics.\n\t\/\/ It will call recover() internally and the error variable pointed to by the argument will be populated with the fault information.\n\tRecover(*error)\n\t\/\/ RecoverPanic works exactly like recover with the exception that the second argument\n\t\/\/ must be the result of a call to recover()\n\tRecoverPanic(*error, interface{})\n\t\/\/ True will panic with a fault if the condition provided is false\n\t\/\/ The fault error string will be the second argument\n\tTrue(bool, string)\n\t\/\/ Truef behaves like Check with the error string as the result of a call to fmt.Errorf(format, args...)\n\tTruef(bool, string, ...interface{})\n\t\/\/ Return will panic if the error provided is not nil. It will return the first argument if not\n\tReturn(interface{}, error) interface{}\n\t\/\/ Error is equivalent to a call to Return(nil, err)\n\tError(error)\n\t\/\/ Output functions exactly as Return, with the only difference being that the output is included in the error message.\n\t\/\/ If the output is a byte array it is converted to a string.\n\t\/\/ This can be useful when debugging use of os\/exec package for instance.\n\tOutput(interface{}, error) interface{}\n}\n\n\/\/ Checker provides a default implementation of FaultCheck\ntype Checker struct {\n\tfaulter Faulter\n}\n\nfunc NewChecker() *Checker { return &Checker{faulter: ErrorFaulter{}} }\n\nfunc (c *Checker) SetFaulter(f Faulter) *Checker {\n\tc.faulter = f\n\treturn c\n}\n\n\/\/ RecoverPanic implements FaultCheck.RecoverPanic\nfunc (c *Checker) RecoverPanic(errPtr *error, panicked interface{}) {\n\tif panicked == nil {\n\t\treturn\n\t} else if fault, faulty := panicked.(Fault); faulty {\n\t\t*errPtr = Chain(fault.Cause(), *errPtr)\n\t\treturn\n\t} else {\n\t\tpanic(panicked)\n\t}\n}\n\n\/\/ Recover implements FaultCheck.Recover\nfunc (c *Checker) Recover(errPtr *error) {\n\tc.RecoverPanic(errPtr, recover())\n}\n\ntype ErrorFaulter struct{}\n\nfunc (ErrorFaulter) New(err error) Fault { return &errorFault{err: err} }\n\ntype errorFault struct {\n\terr error\n}\n\nfunc (e *errorFault) Error() string { return e.err.Error() }\nfunc (e *errorFault) Cause() error  { return e.err }\n\nfunc (e *errorFault) String() string {\n\tif e.err == nil {\n\t\treturn \"\"\n\t}\n\treturn e.err.Error()\n\n}\n\nfunc (c *Checker) True(condition bool, errStr string) {\n\tif !condition {\n\t\tpanic(c.faulter.New(errors.New(errStr)))\n\t}\n}\n\n\/\/ True implements FaultCheck.True\nfunc (c *Checker) Truef(condition bool, format string, args ...interface{}) {\n\tif !condition {\n\t\tpanic(c.faulter.New(fmt.Errorf(format, args...)))\n\t}\n}\n\n\/\/ Return implements FaultCheck.Return\nfunc (c *Checker) Return(i interface{}, err error) interface{} {\n\tif err != nil {\n\t\tpanic(c.faulter.New(err))\n\t}\n\treturn i\n}\n\n\/\/ Error implements FaultCheck.Error\nfunc (c *Checker) Error(err error) {\n\tif err != nil {\n\t\tpanic(c.faulter.New(err))\n\t}\n}\n\n\/\/ Output implements FaultCheck.Output\nfunc (c *Checker) Output(i interface{}, err error) interface{} {\n\tif err != nil {\n\t\tvar out string\n\t\tif bytes, isByteArray := i.([]byte); isByteArray {\n\t\t\tout = string(bytes)\n\t\t} else {\n\t\t\tout = fmt.Sprintf(\"%v\", i)\n\t\t}\n\t\tpanic(c.faulter.New(&ErrorChain{chain: []error{err, fmt.Errorf(\"output: %s\", out)}}))\n\t}\n\treturn i\n}\n\n\/\/ Call provides information about a function call.\ntype Call struct {\n\tFile string \/\/ File provides the file of the caller\n\tLine int    \/\/ Line provides the line number\n\tName string \/\/ Name is the name of the calling function\n}\n\nfunc (c *Call) String() string { return fmt.Sprintf(\"%s:%d:%s\", filepath.Base(c.File), c.Line, c.Name) }\n\nfunc (c *Call) Equal(c2 *Call) bool {\n\tif c == nil {\n\t\treturn c2 == nil\n\t} else if c2 == nil {\n\t\treturn false\n\t}\n\treturn c.File == c2.File && c.Line == c2.Line && c.Name == c2.Name\n}\n\ntype debugFault struct {\n\terr   error\n\ttrace []Call\n}\n\nfunc GetTrace(err error) (trace []Call) {\n\tif chain, isChain := err.(*ErrorChain); isChain && len(chain.Errors()) == 1 {\n\t\terr = chain.Errors()[0]\n\t}\n\tif fault, isFault := err.(*debugFault); isFault {\n\t\treturn fault.trace\n\t}\n\treturn nil\n}\n\nfunc StartSite(trace []Call) (call *Call) {\n\tif len(trace) == 0 {\n\t\tcall = &Call{\"?\", -1, \"?\"}\n\t} else {\n\t\tcall = &trace[0]\n\t}\n\treturn\n}\n\nfunc (d *debugFault) Error() string {\n\treturn fmt.Sprintf(\"%v: %s\", StartSite(d.trace), d.err.Error())\n}\n\nfunc (d *debugFault) Cause() error { return d }\n\ntype DebugFaulter struct{}\n\nvar checkerPrefix = TypePrefix(&Checker{})\n\nfunc TypePrefix(i interface{}) string {\n\tval := reflect.ValueOf(i)\n\tif val.Kind() == reflect.Ptr {\n\t\ttypeVal := val.Elem().Type()\n\t\treturn fmt.Sprintf(\"%s.(*%s)\", typeVal.PkgPath(), typeVal.Name())\n\t} else {\n\t\treturn fmt.Sprintf(\"%s.(%s)\", val.Type().PkgPath(), val.Type().Name())\n\t}\n}\n\n\/\/ ReadStack reads returns the stack after ignoring all calls up to the\n\/\/ function which has the first parameter as a prefix . An empty string returns\n\/\/ the entire stack.\nfunc ReadStack(prefix string) (trace []Call) {\n\ttrace = make([]Call, 0)\n\tvar (\n\t\tpc uintptr\n\t\tfn *runtime.Func\n\t)\n\tappendTo := false\n\tfor skip, ok := 0, true; ok; skip++ {\n\t\tcall := Call{Name: \"?\"}\n\t\tif pc, call.File, call.Line, ok = runtime.Caller(skip); !ok {\n\t\t\tbreak\n\t\t}\n\t\tif fn = runtime.FuncForPC(pc); fn != nil {\n\t\t\tcall.Name = fn.Name()\n\t\t}\n\n\t\tif appendTo {\n\t\t\ttrace = append(trace, call)\n\t\t}\n\t\tif strings.HasPrefix(call.Name, prefix) {\n\t\t\tappendTo = true\n\t\t}\n\t}\n\treturn\n}\n\nfunc (DebugFaulter) New(err error) Fault {\n\treturn &debugFault{err: err, trace: ReadStack(checkerPrefix)}\n}\n\n\/\/ Traced returns an error with the entire stack trace\nfunc Traced(err error) error {\n\tif chain, isChain := err.(*ErrorChain); isChain && len(chain.Errors()) == 1 {\n\t\terr = chain.Errors()[0]\n\t}\n\tif _, ok := err.(*debugFault); ok {\n\t\treturn err\n\t}\n\ttrace := ReadStack(\"\")\n\treturn &debugFault{err: err, trace: trace[1:]}\n}\n\nfunc VerboseTrace(err error) string {\n\ttrace := GetTrace(err)\n\tif trace == nil {\n\t\treturn err.Error()\n\t}\n\n\tparts := make([]string, len(trace))\n\tfor i := range trace {\n\t\tparts[i] = trace[i].String()\n\t}\n\tparts[0] = err.Error()\n\treturn strings.Join(parts, \"\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package userstored\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\n\t\"github.com\/rancher\/norman\/store\/subtype\"\n\t\"github.com\/rancher\/norman\/types\"\n\tnamespacecustom \"github.com\/rancher\/rancher\/pkg\/api\/customization\/namespace\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/customization\/yaml\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/cert\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/ingress\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/namespace\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/pod\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/projectsetter\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/secret\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/service\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/workload\"\n\t\"github.com\/rancher\/rancher\/pkg\/clustermanager\"\n\tclusterschema \"github.com\/rancher\/types\/apis\/cluster.cattle.io\/v3\/schema\"\n\t\"github.com\/rancher\/types\/apis\/project.cattle.io\/v3\/schema\"\n\tclusterClient \"github.com\/rancher\/types\/client\/cluster\/v3\"\n\t\"github.com\/rancher\/types\/client\/project\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n)\n\nfunc Setup(ctx context.Context, mgmt *config.ScaledContext, clusterManager *clustermanager.Manager, k8sProxy http.Handler) error {\n\t\/\/ Here we setup all types that will be stored in the User cluster\n\n\tschemas := mgmt.Schemas\n\n\taddProxyStore(ctx, schemas, mgmt, client.ConfigMapType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, client.CronJobType, \"batch\/v1beta1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.DaemonSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.DeploymentType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.IngressType, \"extensions\/v1beta1\", ingress.Wrap)\n\taddProxyStore(ctx, schemas, mgmt, client.JobType, \"batch\/v1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.PersistentVolumeClaimType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, client.PodType, \"v1\", func(store types.Store) types.Store {\n\t\treturn pod.New(store, clusterManager, mgmt)\n\t})\n\taddProxyStore(ctx, schemas, mgmt, client.ReplicaSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.ReplicationControllerType, \"v1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.ServiceType, \"v1\", service.New)\n\taddProxyStore(ctx, schemas, mgmt, client.StatefulSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.NamespaceType, \"v1\", namespace.New)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.PersistentVolumeType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.StorageClassType, \"storage.k8s.io\/v1\", nil)\n\n\tSecret(ctx, mgmt, schemas)\n\tService(schemas)\n\tWorkload(schemas, clusterManager)\n\tNamespace(schemas, clusterManager)\n\n\tSetProjectID(schemas, clusterManager, k8sProxy)\n\n\treturn nil\n}\n\nfunc SetProjectID(schemas *types.Schemas, clusterManager *clustermanager.Manager, k8sProxy http.Handler) {\n\tfor _, schema := range schemas.SchemasForVersion(schema.Version) {\n\t\tif schema.Store == nil || schema.Store.Context() != config.UserStorageContext {\n\t\t\tcontinue\n\t\t}\n\n\t\tif schema.CanList(nil) != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := schema.ResourceFields[\"namespaceId\"]; !ok {\n\t\t\tpanic(schema.ID + \" does not have namespaceId\")\n\t\t}\n\n\t\tif _, ok := schema.ResourceFields[\"projectId\"]; !ok {\n\t\t\tpanic(schema.ID + \" does not have projectId\")\n\t\t}\n\n\t\tschema.Store = projectsetter.New(schema.Store, clusterManager)\n\t\tschema.Formatter = yaml.NewFormatter(schema.Formatter)\n\t\tschema.LinkHandler = yaml.NewLinkHandler(k8sProxy, clusterManager, schema.LinkHandler)\n\t}\n}\n\nfunc Namespace(schemas *types.Schemas, manager *clustermanager.Manager) {\n\tnamespaceSchema := schemas.Schema(&clusterschema.Version, \"namespace\")\n\tnamespaceSchema.LinkHandler = namespacecustom.NewLinkHandler(namespaceSchema.LinkHandler, manager)\n\tnamespaceSchema.Formatter = yaml.NewFormatter(namespaceSchema.Formatter)\n}\n\nfunc Workload(schemas *types.Schemas, clusterManager *clustermanager.Manager) {\n\tworkload.NewWorkloadAggregateStore(schemas, clusterManager)\n}\n\nfunc Service(schemas *types.Schemas) {\n\tserviceSchema := schemas.Schema(&schema.Version, \"service\")\n\tdnsSchema := schemas.Schema(&schema.Version, \"dnsRecord\")\n\tdnsSchema.Store = struct {\n\t\ttypes.Store\n\t}{\n\t\tserviceSchema.Store,\n\t}\n}\n\nfunc Secret(ctx context.Context, management *config.ScaledContext, schemas *types.Schemas) {\n\tschema := schemas.Schema(&schema.Version, \"namespacedSecret\")\n\tschema.Store = secret.NewNamespacedSecretStore(ctx, management.ClientGetter)\n\n\tfor _, subSchema := range schemas.Schemas() {\n\t\tif subSchema.BaseType == schema.ID && subSchema.ID != schema.ID {\n\t\t\tsubSchema.Store = subtype.NewSubTypeStore(subSchema.ID, schema.Store)\n\t\t}\n\t}\n\n\tschema = schemas.Schema(&schema.Version, \"namespacedCertificate\")\n\tschema.Store = cert.Wrap(schema.Store)\n}\n<commit_msg>Should Not Use the Same Store Instance for DNSRecord and Service<commit_after>package userstored\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\n\t\"github.com\/rancher\/norman\/store\/subtype\"\n\t\"github.com\/rancher\/norman\/types\"\n\tnamespacecustom \"github.com\/rancher\/rancher\/pkg\/api\/customization\/namespace\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/customization\/yaml\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/cert\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/ingress\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/namespace\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/pod\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/projectsetter\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/secret\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/service\"\n\t\"github.com\/rancher\/rancher\/pkg\/api\/store\/workload\"\n\t\"github.com\/rancher\/rancher\/pkg\/clustermanager\"\n\tclusterschema \"github.com\/rancher\/types\/apis\/cluster.cattle.io\/v3\/schema\"\n\t\"github.com\/rancher\/types\/apis\/project.cattle.io\/v3\/schema\"\n\tclusterClient \"github.com\/rancher\/types\/client\/cluster\/v3\"\n\t\"github.com\/rancher\/types\/client\/project\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n)\n\nfunc Setup(ctx context.Context, mgmt *config.ScaledContext, clusterManager *clustermanager.Manager, k8sProxy http.Handler) error {\n\t\/\/ Here we setup all types that will be stored in the User cluster\n\n\tschemas := mgmt.Schemas\n\n\taddProxyStore(ctx, schemas, mgmt, client.ConfigMapType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, client.CronJobType, \"batch\/v1beta1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.DaemonSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.DeploymentType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.IngressType, \"extensions\/v1beta1\", ingress.Wrap)\n\taddProxyStore(ctx, schemas, mgmt, client.JobType, \"batch\/v1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.PersistentVolumeClaimType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, client.PodType, \"v1\", func(store types.Store) types.Store {\n\t\treturn pod.New(store, clusterManager, mgmt)\n\t})\n\taddProxyStore(ctx, schemas, mgmt, client.ReplicaSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.ReplicationControllerType, \"v1\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, client.ServiceType, \"v1\", service.New)\n\taddProxyStore(ctx, schemas, mgmt, client.StatefulSetType, \"apps\/v1beta2\", workload.NewCustomizeStore)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.NamespaceType, \"v1\", namespace.New)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.PersistentVolumeType, \"v1\", nil)\n\taddProxyStore(ctx, schemas, mgmt, clusterClient.StorageClassType, \"storage.k8s.io\/v1\", nil)\n\n\tSecret(ctx, mgmt, schemas)\n\tService(ctx, schemas, mgmt)\n\tWorkload(schemas, clusterManager)\n\tNamespace(schemas, clusterManager)\n\n\tSetProjectID(schemas, clusterManager, k8sProxy)\n\n\treturn nil\n}\n\nfunc SetProjectID(schemas *types.Schemas, clusterManager *clustermanager.Manager, k8sProxy http.Handler) {\n\tfor _, schema := range schemas.SchemasForVersion(schema.Version) {\n\t\tif schema.Store == nil || schema.Store.Context() != config.UserStorageContext {\n\t\t\tcontinue\n\t\t}\n\n\t\tif schema.CanList(nil) != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := schema.ResourceFields[\"namespaceId\"]; !ok {\n\t\t\tpanic(schema.ID + \" does not have namespaceId\")\n\t\t}\n\n\t\tif _, ok := schema.ResourceFields[\"projectId\"]; !ok {\n\t\t\tpanic(schema.ID + \" does not have projectId\")\n\t\t}\n\n\t\tschema.Store = projectsetter.New(schema.Store, clusterManager)\n\t\tschema.Formatter = yaml.NewFormatter(schema.Formatter)\n\t\tschema.LinkHandler = yaml.NewLinkHandler(k8sProxy, clusterManager, schema.LinkHandler)\n\t}\n}\n\nfunc Namespace(schemas *types.Schemas, manager *clustermanager.Manager) {\n\tnamespaceSchema := schemas.Schema(&clusterschema.Version, \"namespace\")\n\tnamespaceSchema.LinkHandler = namespacecustom.NewLinkHandler(namespaceSchema.LinkHandler, manager)\n\tnamespaceSchema.Formatter = yaml.NewFormatter(namespaceSchema.Formatter)\n}\n\nfunc Workload(schemas *types.Schemas, clusterManager *clustermanager.Manager) {\n\tworkload.NewWorkloadAggregateStore(schemas, clusterManager)\n}\n\nfunc Service(ctx context.Context, schemas *types.Schemas, mgmt *config.ScaledContext) {\n\tserviceSchema := schemas.Schema(&schema.Version, \"service\")\n\tdnsSchema := schemas.Schema(&schema.Version, \"dnsRecord\")\n\t\/\/ Move service store to DNSRecord and create new store on service, so they are then\n\t\/\/ same store but two different instances\n\tdnsSchema.Store = serviceSchema.Store\n\taddProxyStore(ctx, schemas, mgmt, client.ServiceType, \"v1\", service.New)\n}\n\nfunc Secret(ctx context.Context, management *config.ScaledContext, schemas *types.Schemas) {\n\tschema := schemas.Schema(&schema.Version, \"namespacedSecret\")\n\tschema.Store = secret.NewNamespacedSecretStore(ctx, management.ClientGetter)\n\n\tfor _, subSchema := range schemas.Schemas() {\n\t\tif subSchema.BaseType == schema.ID && subSchema.ID != schema.ID {\n\t\t\tsubSchema.Store = subtype.NewSubTypeStore(subSchema.ID, schema.Store)\n\t\t}\n\t}\n\n\tschema = schemas.Schema(&schema.Version, \"namespacedCertificate\")\n\tschema.Store = cert.Wrap(schema.Store)\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 config\n\nimport (\n\t\"context\"\n\n\t\"knative.dev\/pkg\/configmap\"\n)\n\ntype channelCfgKey struct{}\n\n\/\/ Config holds the collection of configurations that we attach to contexts.\n\/\/ +k8s:deepcopy-gen=false\ntype Config struct {\n\tChannelDefaults *ChannelDefaults\n}\n\n\/\/ FromContext extracts a Config from the provided context.\nfunc FromContext(ctx context.Context) *Config {\n\tx, ok := ctx.Value(channelCfgKey{}).(*Config)\n\tif ok {\n\t\treturn x\n\t}\n\treturn nil\n}\n\n\/\/ FromContextOrDefaults is like FromContext, but when no Config is attached it\n\/\/ returns a Config populated with the defaults for each of the Config fields.\nfunc FromContextOrDefaults(ctx context.Context) *Config {\n\tif cfg := FromContext(ctx); cfg != nil {\n\t\treturn cfg\n\t}\n\tchannelDefaults, _ := NewChannelDefaultsConfigFromMap(map[string]string{})\n\treturn &Config{\n\t\tChannelDefaults: channelDefaults,\n\t}\n}\n\n\/\/ ToContext attaches the provided Config to the provided context, returning the\n\/\/ new context with the Config attached.\nfunc ToContext(ctx context.Context, c *Config) context.Context {\n\treturn context.WithValue(ctx, channelCfgKey{}, c)\n}\n\n\/\/ Store is a typed wrapper around configmap.Untyped store to handle our configmaps.\n\/\/ +k8s:deepcopy-gen=false\ntype Store struct {\n\t*configmap.UntypedStore\n}\n\n\/\/ NewStore creates a new store of Configs and optionally calls functions when ConfigMaps are updated.\nfunc NewStore(logger configmap.Logger, onAfterStore ...func(name string, value interface{})) *Store {\n\tstore := &Store{\n\t\tUntypedStore: configmap.NewUntypedStore(\n\t\t\t\"chnaneldefaults\",\n\t\t\tlogger,\n\t\t\tconfigmap.Constructors{\n\t\t\t\tChannelDefaultsConfigName: NewChannelDefaultsConfigFromConfigMap,\n\t\t\t},\n\t\t\tonAfterStore...,\n\t\t),\n\t}\n\n\treturn store\n}\n\n\/\/ ToContext attaches the current Config state to the provided context.\nfunc (s *Store) ToContext(ctx context.Context) context.Context {\n\treturn ToContext(ctx, s.Load())\n}\n\n\/\/ Load creates a Config from the current config state of the Store.\nfunc (s *Store) Load() *Config {\n\treturn &Config{\n\t\tChannelDefaults: s.UntypedLoad(ChannelDefaultsConfigName).(*ChannelDefaults).DeepCopy(),\n\t}\n}\n<commit_msg>Fix typo 'chnanel' -> 'channel'. (#3237)<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 config\n\nimport (\n\t\"context\"\n\n\t\"knative.dev\/pkg\/configmap\"\n)\n\ntype channelCfgKey struct{}\n\n\/\/ Config holds the collection of configurations that we attach to contexts.\n\/\/ +k8s:deepcopy-gen=false\ntype Config struct {\n\tChannelDefaults *ChannelDefaults\n}\n\n\/\/ FromContext extracts a Config from the provided context.\nfunc FromContext(ctx context.Context) *Config {\n\tx, ok := ctx.Value(channelCfgKey{}).(*Config)\n\tif ok {\n\t\treturn x\n\t}\n\treturn nil\n}\n\n\/\/ FromContextOrDefaults is like FromContext, but when no Config is attached it\n\/\/ returns a Config populated with the defaults for each of the Config fields.\nfunc FromContextOrDefaults(ctx context.Context) *Config {\n\tif cfg := FromContext(ctx); cfg != nil {\n\t\treturn cfg\n\t}\n\tchannelDefaults, _ := NewChannelDefaultsConfigFromMap(map[string]string{})\n\treturn &Config{\n\t\tChannelDefaults: channelDefaults,\n\t}\n}\n\n\/\/ ToContext attaches the provided Config to the provided context, returning the\n\/\/ new context with the Config attached.\nfunc ToContext(ctx context.Context, c *Config) context.Context {\n\treturn context.WithValue(ctx, channelCfgKey{}, c)\n}\n\n\/\/ Store is a typed wrapper around configmap.Untyped store to handle our configmaps.\n\/\/ +k8s:deepcopy-gen=false\ntype Store struct {\n\t*configmap.UntypedStore\n}\n\n\/\/ NewStore creates a new store of Configs and optionally calls functions when ConfigMaps are updated.\nfunc NewStore(logger configmap.Logger, onAfterStore ...func(name string, value interface{})) *Store {\n\tstore := &Store{\n\t\tUntypedStore: configmap.NewUntypedStore(\n\t\t\t\"channeldefaults\",\n\t\t\tlogger,\n\t\t\tconfigmap.Constructors{\n\t\t\t\tChannelDefaultsConfigName: NewChannelDefaultsConfigFromConfigMap,\n\t\t\t},\n\t\t\tonAfterStore...,\n\t\t),\n\t}\n\n\treturn store\n}\n\n\/\/ ToContext attaches the current Config state to the provided context.\nfunc (s *Store) ToContext(ctx context.Context) context.Context {\n\treturn ToContext(ctx, s.Load())\n}\n\n\/\/ Load creates a Config from the current config state of the Store.\nfunc (s *Store) Load() *Config {\n\treturn &Config{\n\t\tChannelDefaults: s.UntypedLoad(ChannelDefaultsConfigName).(*ChannelDefaults).DeepCopy(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package metricsstore\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n)\n\n\/\/ FamilyStringer represents a metric family that can be converted to its string\n\/\/ representation.\ntype FamilyStringer interface {\n\tString() string\n}\n\n\/\/ MetricsStore implements the k8s.io\/kubernetes\/client-go\/tools\/cache.Store\n\/\/ interface. Instead of storing entire Kubernetes objects, it stores metrics\n\/\/ generated based on those objects.\ntype MetricsStore struct {\n\t\/\/ Protects metrics\n\tmutex sync.RWMutex\n\t\/\/ metrics is a map indexed by Kubernetes object id, containing a slice of\n\t\/\/ metric families, containing a slice of metrics. We need to keep metrics\n\t\/\/ grouped by metric families in order to zip families with their help text in\n\t\/\/ MetricsStore.WriteAll().\n\tmetrics map[types.UID][]string\n\t\/\/ headers contains the header (TYPE and HELP) of each metric family. It is\n\t\/\/ later on zipped with with their corresponding metric families in\n\t\/\/ MetricStore.WriteAll().\n\theaders []string\n\n\t\/\/ generateMetricsFunc generates metrics based on a given Kubernetes object\n\t\/\/ and returns them grouped by metric family.\n\tgenerateMetricsFunc func(interface{}) []FamilyStringer\n}\n\n\/\/ NewMetricsStore returns a new MetricsStore\nfunc NewMetricsStore(headers []string, generateFunc func(interface{}) []FamilyStringer) *MetricsStore {\n\treturn &MetricsStore{\n\t\tgenerateMetricsFunc: generateFunc,\n\t\theaders:             headers,\n\t\tmetrics:             map[types.UID][]string{},\n\t}\n}\n\n\/\/ Implementing k8s.io\/kubernetes\/client-go\/tools\/cache.Store interface\n\n\/\/ TODO: Proper comments on all functions below.\nfunc (s *MetricsStore) Add(obj interface{}) error {\n\to, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tfamilies := s.generateMetricsFunc(obj)\n\tfamilyStrings := make([]string, len(families))\n\n\tfor i, f := range families {\n\t\tfamilyStrings[i] = f.String()\n\t}\n\n\ts.metrics[o.GetUID()] = familyStrings\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) Update(obj interface{}) error {\n\t\/\/ For now, just call Add, in the future one could check if the resource\n\t\/\/ version changed?\n\treturn s.Add(obj)\n}\n\nfunc (s *MetricsStore) Delete(obj interface{}) error {\n\n\to, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tdelete(s.metrics, o.GetUID())\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) List() []interface{} {\n\treturn nil\n}\n\nfunc (s *MetricsStore) ListKeys() []string {\n\treturn nil\n}\n\nfunc (s *MetricsStore) Get(obj interface{}) (item interface{}, exists bool, err error) {\n\treturn nil, false, nil\n}\n\nfunc (s *MetricsStore) GetByKey(key string) (item interface{}, exists bool, err error) {\n\treturn nil, false, nil\n}\n\n\/\/ Replace will delete the contents of the store, using instead the\n\/\/ given list.\nfunc (s *MetricsStore) Replace(list []interface{}, _ string) error {\n\ts.mutex.Lock()\n\ts.metrics = map[types.UID][]string{}\n\ts.mutex.Unlock()\n\n\tfor _, o := range list {\n\t\terr := s.Add(o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) Resync() error {\n\treturn nil\n}\n\n\/\/ WriteAll writes all metrics of the store into the given writer, zipped with the\n\/\/ help text of each metric family.\nfunc (s *MetricsStore) WriteAll(w io.Writer) {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\n\tfor i, help := range s.headers {\n\t\tw.Write([]byte(help))\n\t\tw.Write([]byte{'\\n'})\n\t\tfor _, metricFamilies := range s.metrics {\n\t\t\tw.Write([]byte(metricFamilies[i]))\n\t\t}\n\t}\n}\n<commit_msg>clarify the import location of Store interface in comments<commit_after>package metricsstore\n\nimport (\n\t\"io\"\n\t\"sync\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n)\n\n\/\/ FamilyStringer represents a metric family that can be converted to its string\n\/\/ representation.\ntype FamilyStringer interface {\n\tString() string\n}\n\n\/\/ MetricsStore implements the k8s.io\/client-go\/tools\/cache.Store\n\/\/ interface. Instead of storing entire Kubernetes objects, it stores metrics\n\/\/ generated based on those objects.\ntype MetricsStore struct {\n\t\/\/ Protects metrics\n\tmutex sync.RWMutex\n\t\/\/ metrics is a map indexed by Kubernetes object id, containing a slice of\n\t\/\/ metric families, containing a slice of metrics. We need to keep metrics\n\t\/\/ grouped by metric families in order to zip families with their help text in\n\t\/\/ MetricsStore.WriteAll().\n\tmetrics map[types.UID][]string\n\t\/\/ headers contains the header (TYPE and HELP) of each metric family. It is\n\t\/\/ later on zipped with with their corresponding metric families in\n\t\/\/ MetricStore.WriteAll().\n\theaders []string\n\n\t\/\/ generateMetricsFunc generates metrics based on a given Kubernetes object\n\t\/\/ and returns them grouped by metric family.\n\tgenerateMetricsFunc func(interface{}) []FamilyStringer\n}\n\n\/\/ NewMetricsStore returns a new MetricsStore\nfunc NewMetricsStore(headers []string, generateFunc func(interface{}) []FamilyStringer) *MetricsStore {\n\treturn &MetricsStore{\n\t\tgenerateMetricsFunc: generateFunc,\n\t\theaders:             headers,\n\t\tmetrics:             map[types.UID][]string{},\n\t}\n}\n\n\/\/ Implementing k8s.io\/client-go\/tools\/cache.Store interface\n\n\/\/ TODO: Proper comments on all functions below.\nfunc (s *MetricsStore) Add(obj interface{}) error {\n\to, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tfamilies := s.generateMetricsFunc(obj)\n\tfamilyStrings := make([]string, len(families))\n\n\tfor i, f := range families {\n\t\tfamilyStrings[i] = f.String()\n\t}\n\n\ts.metrics[o.GetUID()] = familyStrings\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) Update(obj interface{}) error {\n\t\/\/ For now, just call Add, in the future one could check if the resource\n\t\/\/ version changed?\n\treturn s.Add(obj)\n}\n\nfunc (s *MetricsStore) Delete(obj interface{}) error {\n\n\to, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tdelete(s.metrics, o.GetUID())\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) List() []interface{} {\n\treturn nil\n}\n\nfunc (s *MetricsStore) ListKeys() []string {\n\treturn nil\n}\n\nfunc (s *MetricsStore) Get(obj interface{}) (item interface{}, exists bool, err error) {\n\treturn nil, false, nil\n}\n\nfunc (s *MetricsStore) GetByKey(key string) (item interface{}, exists bool, err error) {\n\treturn nil, false, nil\n}\n\n\/\/ Replace will delete the contents of the store, using instead the\n\/\/ given list.\nfunc (s *MetricsStore) Replace(list []interface{}, _ string) error {\n\ts.mutex.Lock()\n\ts.metrics = map[types.UID][]string{}\n\ts.mutex.Unlock()\n\n\tfor _, o := range list {\n\t\terr := s.Add(o)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *MetricsStore) Resync() error {\n\treturn nil\n}\n\n\/\/ WriteAll writes all metrics of the store into the given writer, zipped with the\n\/\/ help text of each metric family.\nfunc (s *MetricsStore) WriteAll(w io.Writer) {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\n\tfor i, help := range s.headers {\n\t\tw.Write([]byte(help))\n\t\tw.Write([]byte{'\\n'})\n\t\tfor _, metricFamilies := range s.metrics {\n\t\t\tw.Write([]byte(metricFamilies[i]))\n\t\t}\n\t}\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 flowcontrol\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"k8s.io\/apiserver\/pkg\/server\/mux\"\n\tfq \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\"\n\t\"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\/eventclock\"\n\tfqs \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\/queueset\"\n\t\"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/metrics\"\n\tfcrequest \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/request\"\n\tkubeinformers \"k8s.io\/client-go\/informers\"\n\t\"k8s.io\/klog\/v2\"\n\t\"k8s.io\/utils\/clock\"\n\n\tflowcontrol \"k8s.io\/api\/flowcontrol\/v1beta2\"\n\tflowcontrolclient \"k8s.io\/client-go\/kubernetes\/typed\/flowcontrol\/v1beta2\"\n)\n\n\/\/ ConfigConsumerAsFieldManager is how the config consuminng\n\/\/ controller appears in an ObjectMeta ManagedFieldsEntry.Manager\nconst ConfigConsumerAsFieldManager = \"api-priority-and-fairness-config-consumer-v1\"\n\n\/\/ Interface defines how the API Priority and Fairness filter interacts with the underlying system.\ntype Interface interface {\n\t\/\/ Handle takes care of queuing and dispatching a request\n\t\/\/ characterized by the given digest.  The given `noteFn` will be\n\t\/\/ invoked with the results of request classification.\n\t\/\/ The given `workEstimator` is called, if at all, after noteFn.\n\t\/\/ `workEstimator` will be invoked only when the request\n\t\/\/  is classified as non 'exempt'.\n\t\/\/ 'workEstimator', when invoked, must return the\n\t\/\/ work parameters for the request.\n\t\/\/ If the request is queued then `queueNoteFn` will be called twice,\n\t\/\/ first with `true` and then with `false`; otherwise\n\t\/\/ `queueNoteFn` will not be called at all.  If Handle decides\n\t\/\/ that the request should be executed then `execute()` will be\n\t\/\/ invoked once to execute the request; otherwise `execute()` will\n\t\/\/ not be invoked.\n\t\/\/ Handle() should never return while execute() is running, even if\n\t\/\/ ctx is cancelled or times out.\n\tHandle(ctx context.Context,\n\t\trequestDigest RequestDigest,\n\t\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\t\tworkEstimator func() fcrequest.WorkEstimate,\n\t\tqueueNoteFn fq.QueueNoteFn,\n\t\texecFn func(),\n\t)\n\n\t\/\/ MaintainObservations is a helper for maintaining statistics.\n\tMaintainObservations(stopCh <-chan struct{})\n\n\t\/\/ Run monitors config objects from the main apiservers and causes\n\t\/\/ any needed changes to local behavior.  This method ceases\n\t\/\/ activity and returns after the given channel is closed.\n\tRun(stopCh <-chan struct{}) error\n\n\t\/\/ Install installs debugging endpoints to the web-server.\n\tInstall(c *mux.PathRecorderMux)\n\n\t\/\/ WatchTracker provides the WatchTracker interface.\n\tWatchTracker\n}\n\n\/\/ This request filter implements https:\/\/github.com\/kubernetes\/enhancements\/blob\/master\/keps\/sig-api-machinery\/1040-priority-and-fairness\/README.md\n\n\/\/ New creates a new instance to implement API priority and fairness\nfunc New(\n\tinformerFactory kubeinformers.SharedInformerFactory,\n\tflowcontrolClient flowcontrolclient.FlowcontrolV1beta2Interface,\n\tserverConcurrencyLimit int,\n\trequestWaitLimit time.Duration,\n) Interface {\n\tclk := eventclock.Real{}\n\treturn NewTestable(TestableConfig{\n\t\tName:                   \"Controller\",\n\t\tClock:                  clk,\n\t\tAsFieldManager:         ConfigConsumerAsFieldManager,\n\t\tFoundToDangling:        func(found bool) bool { return !found },\n\t\tInformerFactory:        informerFactory,\n\t\tFlowcontrolClient:      flowcontrolClient,\n\t\tServerConcurrencyLimit: serverConcurrencyLimit,\n\t\tRequestWaitLimit:       requestWaitLimit,\n\t\tReqsObsPairGenerator:   metrics.PriorityLevelConcurrencyObserverPairGenerator,\n\t\tExecSeatsObsGenerator:  metrics.PriorityLevelExecutionSeatsObserverGenerator,\n\t\tQueueSetFactory:        fqs.NewQueueSetFactory(clk),\n\t})\n}\n\n\/\/ TestableConfig carries the parameters to an implementation that is testable\ntype TestableConfig struct {\n\t\/\/ Name of the controller\n\tName string\n\n\t\/\/ Clock to use in timing deliberate delays\n\tClock clock.PassiveClock\n\n\t\/\/ AsFieldManager is the string to use in the metadata for\n\t\/\/ server-side apply.  Normally this is\n\t\/\/ `ConfigConsumerAsFieldManager`.  This is exposed as a parameter\n\t\/\/ so that a test of competing controllers can supply different\n\t\/\/ values.\n\tAsFieldManager string\n\n\t\/\/ FoundToDangling maps the boolean indicating whether a\n\t\/\/ FlowSchema's referenced PLC exists to the boolean indicating\n\t\/\/ that FlowSchema's status should indicate a dangling reference.\n\t\/\/ This is a parameter so that we can write tests of what happens\n\t\/\/ when servers disagree on that bit of Status.\n\tFoundToDangling func(bool) bool\n\n\t\/\/ InformerFactory to use in building the controller\n\tInformerFactory kubeinformers.SharedInformerFactory\n\n\t\/\/ FlowcontrolClient to use for manipulating config objects\n\tFlowcontrolClient flowcontrolclient.FlowcontrolV1beta2Interface\n\n\t\/\/ ServerConcurrencyLimit for the controller to enforce\n\tServerConcurrencyLimit int\n\n\t\/\/ RequestWaitLimit configured on the server\n\tRequestWaitLimit time.Duration\n\n\t\/\/ ObsPairGenerator for metrics about requests\n\tReqsObsPairGenerator metrics.RatioedChangeObserverPairGenerator\n\n\t\/\/ RatioedChangeObserverPairGenerator for metrics about seats occupied by all phases of execution\n\tExecSeatsObsGenerator metrics.RatioedChangeObserverGenerator\n\n\t\/\/ QueueSetFactory for the queuing implementation\n\tQueueSetFactory fq.QueueSetFactory\n}\n\n\/\/ NewTestable is extra flexible to facilitate testing\nfunc NewTestable(config TestableConfig) Interface {\n\treturn newTestableController(config)\n}\n\nfunc (cfgCtlr *configController) Handle(ctx context.Context, requestDigest RequestDigest,\n\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\tworkEstimator func() fcrequest.WorkEstimate,\n\tqueueNoteFn fq.QueueNoteFn,\n\texecFn func()) {\n\tfs, pl, isExempt, req, startWaitingTime := cfgCtlr.startRequest(ctx, requestDigest, noteFn, workEstimator, queueNoteFn)\n\tqueued := startWaitingTime != time.Time{}\n\tif req == nil {\n\t\tif queued {\n\t\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t\t}\n\t\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, reject\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt)\n\t\treturn\n\t}\n\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued)\n\tvar executed bool\n\tidle, panicking := true, true\n\tdefer func() {\n\t\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v, Finish() => panicking=%v idle=%v\",\n\t\t\trequestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued, panicking, idle)\n\t\tif idle {\n\t\t\tcfgCtlr.maybeReap(pl.Name)\n\t\t}\n\t}()\n\tidle = req.Finish(func() {\n\t\tif queued {\n\t\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t\t}\n\t\tmetrics.AddDispatch(ctx, pl.Name, fs.Name)\n\t\texecuted = true\n\t\tstartExecutionTime := time.Now()\n\t\tdefer func() {\n\t\t\tmetrics.ObserveExecutionDuration(ctx, pl.Name, fs.Name, time.Since(startExecutionTime))\n\t\t}()\n\t\texecFn()\n\t})\n\tif queued && !executed {\n\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t}\n\tpanicking = false\n}\n<commit_msg>For each call, log apf_execution_time<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 flowcontrol\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"k8s.io\/apiserver\/pkg\/server\/httplog\"\n\t\"k8s.io\/apiserver\/pkg\/server\/mux\"\n\tfq \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\"\n\t\"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\/eventclock\"\n\tfqs \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/fairqueuing\/queueset\"\n\t\"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/metrics\"\n\tfcrequest \"k8s.io\/apiserver\/pkg\/util\/flowcontrol\/request\"\n\tkubeinformers \"k8s.io\/client-go\/informers\"\n\t\"k8s.io\/klog\/v2\"\n\t\"k8s.io\/utils\/clock\"\n\n\tflowcontrol \"k8s.io\/api\/flowcontrol\/v1beta2\"\n\tflowcontrolclient \"k8s.io\/client-go\/kubernetes\/typed\/flowcontrol\/v1beta2\"\n)\n\n\/\/ ConfigConsumerAsFieldManager is how the config consuminng\n\/\/ controller appears in an ObjectMeta ManagedFieldsEntry.Manager\nconst ConfigConsumerAsFieldManager = \"api-priority-and-fairness-config-consumer-v1\"\n\n\/\/ Interface defines how the API Priority and Fairness filter interacts with the underlying system.\ntype Interface interface {\n\t\/\/ Handle takes care of queuing and dispatching a request\n\t\/\/ characterized by the given digest.  The given `noteFn` will be\n\t\/\/ invoked with the results of request classification.\n\t\/\/ The given `workEstimator` is called, if at all, after noteFn.\n\t\/\/ `workEstimator` will be invoked only when the request\n\t\/\/  is classified as non 'exempt'.\n\t\/\/ 'workEstimator', when invoked, must return the\n\t\/\/ work parameters for the request.\n\t\/\/ If the request is queued then `queueNoteFn` will be called twice,\n\t\/\/ first with `true` and then with `false`; otherwise\n\t\/\/ `queueNoteFn` will not be called at all.  If Handle decides\n\t\/\/ that the request should be executed then `execute()` will be\n\t\/\/ invoked once to execute the request; otherwise `execute()` will\n\t\/\/ not be invoked.\n\t\/\/ Handle() should never return while execute() is running, even if\n\t\/\/ ctx is cancelled or times out.\n\tHandle(ctx context.Context,\n\t\trequestDigest RequestDigest,\n\t\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\t\tworkEstimator func() fcrequest.WorkEstimate,\n\t\tqueueNoteFn fq.QueueNoteFn,\n\t\texecFn func(),\n\t)\n\n\t\/\/ MaintainObservations is a helper for maintaining statistics.\n\tMaintainObservations(stopCh <-chan struct{})\n\n\t\/\/ Run monitors config objects from the main apiservers and causes\n\t\/\/ any needed changes to local behavior.  This method ceases\n\t\/\/ activity and returns after the given channel is closed.\n\tRun(stopCh <-chan struct{}) error\n\n\t\/\/ Install installs debugging endpoints to the web-server.\n\tInstall(c *mux.PathRecorderMux)\n\n\t\/\/ WatchTracker provides the WatchTracker interface.\n\tWatchTracker\n}\n\n\/\/ This request filter implements https:\/\/github.com\/kubernetes\/enhancements\/blob\/master\/keps\/sig-api-machinery\/1040-priority-and-fairness\/README.md\n\n\/\/ New creates a new instance to implement API priority and fairness\nfunc New(\n\tinformerFactory kubeinformers.SharedInformerFactory,\n\tflowcontrolClient flowcontrolclient.FlowcontrolV1beta2Interface,\n\tserverConcurrencyLimit int,\n\trequestWaitLimit time.Duration,\n) Interface {\n\tclk := eventclock.Real{}\n\treturn NewTestable(TestableConfig{\n\t\tName:                   \"Controller\",\n\t\tClock:                  clk,\n\t\tAsFieldManager:         ConfigConsumerAsFieldManager,\n\t\tFoundToDangling:        func(found bool) bool { return !found },\n\t\tInformerFactory:        informerFactory,\n\t\tFlowcontrolClient:      flowcontrolClient,\n\t\tServerConcurrencyLimit: serverConcurrencyLimit,\n\t\tRequestWaitLimit:       requestWaitLimit,\n\t\tReqsObsPairGenerator:   metrics.PriorityLevelConcurrencyObserverPairGenerator,\n\t\tExecSeatsObsGenerator:  metrics.PriorityLevelExecutionSeatsObserverGenerator,\n\t\tQueueSetFactory:        fqs.NewQueueSetFactory(clk),\n\t})\n}\n\n\/\/ TestableConfig carries the parameters to an implementation that is testable\ntype TestableConfig struct {\n\t\/\/ Name of the controller\n\tName string\n\n\t\/\/ Clock to use in timing deliberate delays\n\tClock clock.PassiveClock\n\n\t\/\/ AsFieldManager is the string to use in the metadata for\n\t\/\/ server-side apply.  Normally this is\n\t\/\/ `ConfigConsumerAsFieldManager`.  This is exposed as a parameter\n\t\/\/ so that a test of competing controllers can supply different\n\t\/\/ values.\n\tAsFieldManager string\n\n\t\/\/ FoundToDangling maps the boolean indicating whether a\n\t\/\/ FlowSchema's referenced PLC exists to the boolean indicating\n\t\/\/ that FlowSchema's status should indicate a dangling reference.\n\t\/\/ This is a parameter so that we can write tests of what happens\n\t\/\/ when servers disagree on that bit of Status.\n\tFoundToDangling func(bool) bool\n\n\t\/\/ InformerFactory to use in building the controller\n\tInformerFactory kubeinformers.SharedInformerFactory\n\n\t\/\/ FlowcontrolClient to use for manipulating config objects\n\tFlowcontrolClient flowcontrolclient.FlowcontrolV1beta2Interface\n\n\t\/\/ ServerConcurrencyLimit for the controller to enforce\n\tServerConcurrencyLimit int\n\n\t\/\/ RequestWaitLimit configured on the server\n\tRequestWaitLimit time.Duration\n\n\t\/\/ ObsPairGenerator for metrics about requests\n\tReqsObsPairGenerator metrics.RatioedChangeObserverPairGenerator\n\n\t\/\/ RatioedChangeObserverPairGenerator for metrics about seats occupied by all phases of execution\n\tExecSeatsObsGenerator metrics.RatioedChangeObserverGenerator\n\n\t\/\/ QueueSetFactory for the queuing implementation\n\tQueueSetFactory fq.QueueSetFactory\n}\n\n\/\/ NewTestable is extra flexible to facilitate testing\nfunc NewTestable(config TestableConfig) Interface {\n\treturn newTestableController(config)\n}\n\nfunc (cfgCtlr *configController) Handle(ctx context.Context, requestDigest RequestDigest,\n\tnoteFn func(fs *flowcontrol.FlowSchema, pl *flowcontrol.PriorityLevelConfiguration, flowDistinguisher string),\n\tworkEstimator func() fcrequest.WorkEstimate,\n\tqueueNoteFn fq.QueueNoteFn,\n\texecFn func()) {\n\tfs, pl, isExempt, req, startWaitingTime := cfgCtlr.startRequest(ctx, requestDigest, noteFn, workEstimator, queueNoteFn)\n\tqueued := startWaitingTime != time.Time{}\n\tif req == nil {\n\t\tif queued {\n\t\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t\t}\n\t\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, reject\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt)\n\t\treturn\n\t}\n\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v\", requestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued)\n\tvar executed bool\n\tidle, panicking := true, true\n\tdefer func() {\n\t\tklog.V(7).Infof(\"Handle(%#+v) => fsName=%q, distMethod=%#+v, plName=%q, isExempt=%v, queued=%v, Finish() => panicking=%v idle=%v\",\n\t\t\trequestDigest, fs.Name, fs.Spec.DistinguisherMethod, pl.Name, isExempt, queued, panicking, idle)\n\t\tif idle {\n\t\t\tcfgCtlr.maybeReap(pl.Name)\n\t\t}\n\t}()\n\tidle = req.Finish(func() {\n\t\tif queued {\n\t\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t\t}\n\t\tmetrics.AddDispatch(ctx, pl.Name, fs.Name)\n\t\texecuted = true\n\t\tstartExecutionTime := time.Now()\n\t\tdefer func() {\n\t\t\texecutionTime := time.Since(startExecutionTime)\n\t\t\thttplog.AddKeyValue(ctx, \"apf_execution_time\", executionTime)\n\t\t\tmetrics.ObserveExecutionDuration(ctx, pl.Name, fs.Name, executionTime)\n\t\t}()\n\t\texecFn()\n\t})\n\tif queued && !executed {\n\t\tmetrics.ObserveWaitingDuration(ctx, pl.Name, fs.Name, strconv.FormatBool(req != nil), time.Since(startWaitingTime))\n\t}\n\tpanicking = false\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\toldcmds \"github.com\/ipfs\/go-ipfs\/commands\"\n\n\tcmds \"gx\/ipfs\/QmWGm4AbZEbnmdgVTza52MSNpEmBdFVqzmAysRbjrRyGbH\/go-ipfs-cmds\"\n\tcmdkit \"gx\/ipfs\/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg\/go-ipfs-cmdkit\"\n)\n\nconst (\n\tverboseOptionName = \"v\"\n)\n\nvar ActiveReqsCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"List commands run on this IPFS node.\",\n\t\tShortDescription: `\nLists running and recently run commands.\n`,\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\tctx := env.(*oldcmds.Context)\n\t\treturn cmds.EmitOnce(res, ctx.ReqLog.Report())\n\t},\n\tOptions: []cmdkit.Option{\n\t\tcmdkit.BoolOption(\"verbose\", verboseOptionName, \"Print extra information.\"),\n\t},\n\tSubcommands: map[string]*cmds.Command{\n\t\t\"clear\":    clearInactiveCmd,\n\t\t\"set-time\": setRequestClearCmd,\n\t},\n\tEncoders: cmds.EncoderMap{\n\t\tcmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]*cmds.ReqLogEntry) error {\n\t\t\tverbose, _ := req.Options[verboseOptionName].(bool)\n\n\t\t\ttw := tabwriter.NewWriter(w, 4, 4, 2, ' ', 0)\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprint(tw, \"ID\\t\")\n\t\t\t}\n\t\t\tfmt.Fprint(tw, \"Command\\t\")\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprint(tw, \"Arguments\\tOptions\\t\")\n\t\t\t}\n\t\t\tfmt.Fprintln(tw, \"Active\\tStartTime\\tRunTime\")\n\n\t\t\tfor _, req := range *out {\n\t\t\t\tif verbose {\n\t\t\t\t\tfmt.Fprintf(tw, \"%d\\t\", req.ID)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(tw, \"%s\\t\", req.Command)\n\t\t\t\tif verbose {\n\t\t\t\t\tfmt.Fprintf(tw, \"%v\\t[\", req.Args)\n\t\t\t\t\tvar keys []string\n\t\t\t\t\tfor k := range req.Options {\n\t\t\t\t\t\tkeys = append(keys, k)\n\t\t\t\t\t}\n\t\t\t\t\tsort.Strings(keys)\n\n\t\t\t\t\tfor _, k := range keys {\n\t\t\t\t\t\tfmt.Fprintf(tw, \"%s=%v,\", k, req.Options[k])\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(tw, \"]\\t\")\n\t\t\t\t}\n\n\t\t\t\tvar live time.Duration\n\t\t\t\tif req.Active {\n\t\t\t\t\tlive = time.Since(req.StartTime)\n\t\t\t\t} else {\n\t\t\t\t\tlive = req.EndTime.Sub(req.StartTime)\n\t\t\t\t}\n\t\t\t\tt := req.StartTime.Format(time.Stamp)\n\t\t\t\tfmt.Fprintf(tw, \"%t\\t%s\\t%s\\n\", req.Active, t, live)\n\t\t\t}\n\t\t\ttw.Flush()\n\n\t\t\treturn nil\n\t\t}),\n\t},\n\tType: []*cmds.ReqLogEntry{},\n}\n\nvar clearInactiveCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"Clear inactive requests from the log.\",\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\tctx := env.(*oldcmds.Context)\n\t\tctx.ReqLog.ClearInactive()\n\t\treturn nil\n\t},\n}\n\nvar setRequestClearCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"Set how long to keep inactive requests in the log.\",\n\t},\n\tArguments: []cmdkit.Argument{\n\t\tcmdkit.StringArg(\"time\", true, false, \"Time to keep inactive requests in log.\"),\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\ttval, err := time.ParseDuration(req.Arguments[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx := env.(*oldcmds.Context)\n\t\tctx.ReqLog.SetKeepTime(tval)\n\n\t\treturn nil\n\t},\n}\n<commit_msg>commands: fix verbose flag for the active commands command<commit_after>package commands\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\toldcmds \"github.com\/ipfs\/go-ipfs\/commands\"\n\n\tcmds \"gx\/ipfs\/QmWGm4AbZEbnmdgVTza52MSNpEmBdFVqzmAysRbjrRyGbH\/go-ipfs-cmds\"\n\tcmdkit \"gx\/ipfs\/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg\/go-ipfs-cmdkit\"\n)\n\nconst (\n\tverboseOptionName = \"verbose\"\n)\n\nvar ActiveReqsCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"List commands run on this IPFS node.\",\n\t\tShortDescription: `\nLists running and recently run commands.\n`,\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\tctx := env.(*oldcmds.Context)\n\t\treturn cmds.EmitOnce(res, ctx.ReqLog.Report())\n\t},\n\tOptions: []cmdkit.Option{\n\t\tcmdkit.BoolOption(verboseOptionName, \"v\", \"Print extra information.\"),\n\t},\n\tSubcommands: map[string]*cmds.Command{\n\t\t\"clear\":    clearInactiveCmd,\n\t\t\"set-time\": setRequestClearCmd,\n\t},\n\tEncoders: cmds.EncoderMap{\n\t\tcmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *[]*cmds.ReqLogEntry) error {\n\t\t\tverbose, _ := req.Options[verboseOptionName].(bool)\n\n\t\t\ttw := tabwriter.NewWriter(w, 4, 4, 2, ' ', 0)\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprint(tw, \"ID\\t\")\n\t\t\t}\n\t\t\tfmt.Fprint(tw, \"Command\\t\")\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprint(tw, \"Arguments\\tOptions\\t\")\n\t\t\t}\n\t\t\tfmt.Fprintln(tw, \"Active\\tStartTime\\tRunTime\")\n\n\t\t\tfor _, req := range *out {\n\t\t\t\tif verbose {\n\t\t\t\t\tfmt.Fprintf(tw, \"%d\\t\", req.ID)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(tw, \"%s\\t\", req.Command)\n\t\t\t\tif verbose {\n\t\t\t\t\tfmt.Fprintf(tw, \"%v\\t[\", req.Args)\n\t\t\t\t\tvar keys []string\n\t\t\t\t\tfor k := range req.Options {\n\t\t\t\t\t\tkeys = append(keys, k)\n\t\t\t\t\t}\n\t\t\t\t\tsort.Strings(keys)\n\n\t\t\t\t\tfor _, k := range keys {\n\t\t\t\t\t\tfmt.Fprintf(tw, \"%s=%v,\", k, req.Options[k])\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintf(tw, \"]\\t\")\n\t\t\t\t}\n\n\t\t\t\tvar live time.Duration\n\t\t\t\tif req.Active {\n\t\t\t\t\tlive = time.Since(req.StartTime)\n\t\t\t\t} else {\n\t\t\t\t\tlive = req.EndTime.Sub(req.StartTime)\n\t\t\t\t}\n\t\t\t\tt := req.StartTime.Format(time.Stamp)\n\t\t\t\tfmt.Fprintf(tw, \"%t\\t%s\\t%s\\n\", req.Active, t, live)\n\t\t\t}\n\t\t\ttw.Flush()\n\n\t\t\treturn nil\n\t\t}),\n\t},\n\tType: []*cmds.ReqLogEntry{},\n}\n\nvar clearInactiveCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"Clear inactive requests from the log.\",\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\tctx := env.(*oldcmds.Context)\n\t\tctx.ReqLog.ClearInactive()\n\t\treturn nil\n\t},\n}\n\nvar setRequestClearCmd = &cmds.Command{\n\tHelptext: cmdkit.HelpText{\n\t\tTagline: \"Set how long to keep inactive requests in the log.\",\n\t},\n\tArguments: []cmdkit.Argument{\n\t\tcmdkit.StringArg(\"time\", true, false, \"Time to keep inactive requests in log.\"),\n\t},\n\tRun: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {\n\t\ttval, err := time.ParseDuration(req.Arguments[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tctx := env.(*oldcmds.Context)\n\t\tctx.ReqLog.SetKeepTime(tval)\n\n\t\treturn nil\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package terraform\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/addrs\"\n\t\"github.com\/hashicorp\/terraform\/config\/configschema\"\n\t\"github.com\/hashicorp\/terraform\/configs\"\n\t\"github.com\/hashicorp\/terraform\/tfdiags\"\n)\n\n\/\/ Schemas is a container for various kinds of schema that Terraform needs\n\/\/ during processing.\ntype Schemas struct {\n\tproviders    map[string]*ProviderSchema\n\tprovisioners map[string]*configschema.Block\n}\n\n\/\/ ProviderSchema returns the entire ProviderSchema object that was produced\n\/\/ by the plugin for the given provider, or nil if no such schema is available.\n\/\/\n\/\/ It's usually better to go use the more precise methods offered by type\n\/\/ Schemas to handle this detail automatically.\nfunc (ss *Schemas) ProviderSchema(typeName string) *ProviderSchema {\n\tif ss.providers == nil {\n\t\treturn nil\n\t}\n\treturn ss.providers[typeName]\n}\n\n\/\/ ProviderConfig returns the schema for the provider configuration of the\n\/\/ given provider type, or nil if no such schema is available.\nfunc (ss *Schemas) ProviderConfig(typeName string) *configschema.Block {\n\tps := ss.ProviderSchema(typeName)\n\tif ps == nil {\n\t\treturn nil\n\t}\n\treturn ps.Provider\n}\n\n\/\/ ResourceTypeConfig returns the schema for the configuration of a given\n\/\/ resource type belonging to a given provider type, or nil of no such\n\/\/ schema is available.\n\/\/\n\/\/ In many cases the provider type is inferrable from the resource type name,\n\/\/ but this is not always true because users can override the provider for\n\/\/ a resource using the \"provider\" meta-argument. Therefore it's important to\n\/\/ always pass the correct provider name, even though it many cases it feels\n\/\/ redundant.\nfunc (ss *Schemas) ResourceTypeConfig(providerType string, resourceType string) *configschema.Block {\n\tps := ss.ProviderSchema(providerType)\n\tif ps == nil || ps.ResourceTypes == nil {\n\t\treturn nil\n\t}\n\n\treturn ps.ResourceTypes[resourceType]\n}\n\n\/\/ DataSourceConfig returns the schema for the configuration of a given\n\/\/ data source belonging to a given provider type, or nil of no such\n\/\/ schema is available.\n\/\/\n\/\/ In many cases the provider type is inferrable from the data source name,\n\/\/ but this is not always true because users can override the provider for\n\/\/ a resource using the \"provider\" meta-argument. Therefore it's important to\n\/\/ always pass the correct provider name, even though it many cases it feels\n\/\/ redundant.\nfunc (ss *Schemas) DataSourceConfig(providerType string, dataSource string) *configschema.Block {\n\tps := ss.ProviderSchema(providerType)\n\tif ps == nil || ps.DataSources == nil {\n\t\treturn nil\n\t}\n\n\treturn ps.DataSources[dataSource]\n}\n\n\/\/ ProvisionerConfig returns the schema for the configuration of a given\n\/\/ provisioner, or nil of no such schema is available.\nfunc (ss *Schemas) ProvisionerConfig(name string) *configschema.Block {\n\treturn ss.provisioners[name]\n}\n\n\/\/ LoadSchemas searches the given configuration and state (either of which may\n\/\/ be nil) for constructs that have an associated schema, requests the\n\/\/ necessary schemas from the given component factory (which may _not_ be nil),\n\/\/ and returns a single object representing all of the necessary schemas.\n\/\/\n\/\/ If an error is returned, it may be a wrapped tfdiags.Diagnostics describing\n\/\/ errors across multiple separate objects. Errors here will usually indicate\n\/\/ either misbehavior on the part of one of the providers or of the provider\n\/\/ protocol itself. When returned with errors, the returned schemas object is\n\/\/ still valid but may be incomplete.\nfunc LoadSchemas(config *configs.Config, state *State, components contextComponentFactory) (*Schemas, error) {\n\tschemas := &Schemas{\n\t\tproviders:    map[string]*ProviderSchema{},\n\t\tprovisioners: map[string]*configschema.Block{},\n\t}\n\tvar diags tfdiags.Diagnostics\n\n\tnewDiags := loadProviderSchemas(schemas.providers, config, state, components)\n\tdiags = diags.Append(newDiags)\n\tnewDiags = loadProvisionerSchemas(schemas.provisioners, config, components)\n\tdiags = diags.Append(newDiags)\n\n\treturn schemas, diags.Err()\n}\n\nfunc loadProviderSchemas(schemas map[string]*ProviderSchema, config *configs.Config, state *State, components contextComponentFactory) tfdiags.Diagnostics {\n\tvar diags tfdiags.Diagnostics\n\n\tensure := func(typeName string) {\n\t\tif _, exists := schemas[typeName]; exists {\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] LoadSchemas: retrieving schema for provider type %q\", typeName)\n\t\tprovider, err := components.ResourceProvider(typeName, \"early\/\"+typeName)\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[typeName] = &ProviderSchema{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to instantiate provider %q to obtain schema: %s\", typeName, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif closer, ok := provider.(ResourceProviderCloser); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ FIXME: The provider interface is currently awkward in that it\n\t\t\/\/ requires us to tell the provider which resources types and data\n\t\t\/\/ sources we need. In future this will change to just return\n\t\t\/\/ everything available, but for now we'll fake that by fetching all\n\t\t\/\/ of the available names and then requesting them.\n\t\tresourceTypes := provider.Resources()\n\t\tdataSources := provider.DataSources()\n\t\tresourceTypeNames := make([]string, len(resourceTypes))\n\t\tfor i, o := range resourceTypes {\n\t\t\tresourceTypeNames[i] = o.Name\n\t\t}\n\t\tdataSourceNames := make([]string, len(dataSources))\n\t\tfor i, o := range dataSources {\n\t\t\tdataSourceNames[i] = o.Name\n\t\t}\n\n\t\tschema, err := provider.GetSchema(&ProviderSchemaRequest{\n\t\t\tResourceTypes: resourceTypeNames,\n\t\t\tDataSources:   dataSourceNames,\n\t\t})\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[typeName] = &ProviderSchema{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to retrieve schema from provider %q: %s\", typeName, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tschemas[typeName] = schema\n\t}\n\n\tif config != nil {\n\t\tfor _, pc := range config.Module.ProviderConfigs {\n\t\t\tensure(pc.Name)\n\t\t}\n\t\tfor _, rc := range config.Module.ManagedResources {\n\t\t\tproviderAddr := rc.ProviderConfigAddr()\n\t\t\tensure(providerAddr.Type)\n\t\t}\n\t\tfor _, rc := range config.Module.DataResources {\n\t\t\tproviderAddr := rc.ProviderConfigAddr()\n\t\t\tensure(providerAddr.Type)\n\t\t}\n\n\t\t\/\/ Must also visit our child modules, recursively.\n\t\tfor _, cc := range config.Children {\n\t\t\tchildDiags := loadProviderSchemas(schemas, cc, nil, components)\n\t\t\tdiags = diags.Append(childDiags)\n\t\t}\n\t}\n\n\tif state != nil {\n\t\tfor _, ms := range state.Modules {\n\t\t\tfor rsKey, rs := range ms.Resources {\n\t\t\t\tproviderAddrStr := rs.Provider\n\t\t\t\tproviderAddr, addrDiags := addrs.ParseAbsProviderConfigStr(providerAddrStr)\n\t\t\t\tif addrDiags.HasErrors() {\n\t\t\t\t\t\/\/ Should happen only if someone has tampered manually with\n\t\t\t\t\t\/\/ the state, since we always write valid provider addrs.\n\t\t\t\t\tmoduleAddrStr := normalizeModulePath(ms.Path).String()\n\t\t\t\t\tif moduleAddrStr == \"\" {\n\t\t\t\t\t\tmoduleAddrStr = \"the root module\"\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ For now this is a warning, since there are many existing\n\t\t\t\t\t\/\/ test fixtures that have invalid provider configurations.\n\t\t\t\t\t\/\/ There's a check deeper in Terraform that makes this a\n\t\t\t\t\t\/\/ failure when an empty\/invalid provider string is present\n\t\t\t\t\t\/\/ in practice.\n\t\t\t\t\tlog.Printf(\"[WARN] LoadSchemas: Resource %s in %s has invalid provider address %q in its state\", rsKey, moduleAddrStr, providerAddrStr)\n\t\t\t\t\tdiags = diags.Append(\n\t\t\t\t\t\ttfdiags.SimpleWarning(fmt.Sprintf(\"Resource %s in %s has invalid provider address %q in its state\", rsKey, moduleAddrStr, providerAddrStr)),\n\t\t\t\t\t)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tensure(providerAddr.ProviderConfig.Type)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diags\n}\n\nfunc loadProvisionerSchemas(schemas map[string]*configschema.Block, config *configs.Config, components contextComponentFactory) tfdiags.Diagnostics {\n\tvar diags tfdiags.Diagnostics\n\n\tensure := func(name string) {\n\t\tif _, exists := schemas[name]; exists {\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] LoadSchemas: retrieving schema for provisioner %q\", name)\n\t\tprovisioner, err := components.ResourceProvisioner(name, \"early\/\"+name)\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[name] = &configschema.Block{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to instantiate provisioner %q to obtain schema: %s\", name, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif closer, ok := provisioner.(ResourceProvisionerCloser); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\tschema, err := provisioner.GetConfigSchema()\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[name] = &configschema.Block{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to retrieve schema from provisioner %q: %s\", name, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tschemas[name] = schema\n\t}\n\n\tif config != nil {\n\t\tfor _, rc := range config.Module.ManagedResources {\n\t\t\tfor _, pc := range rc.Managed.Provisioners {\n\t\t\t\tensure(pc.Type)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diags\n}\n\n\/\/ ProviderSchema represents the schema for a provider's own configuration\n\/\/ and the configuration for some or all of its resources and data sources.\n\/\/\n\/\/ The completeness of this structure depends on how it was constructed.\n\/\/ When constructed for a configuration, it will generally include only\n\/\/ resource types and data sources used by that configuration.\ntype ProviderSchema struct {\n\tProvider      *configschema.Block\n\tResourceTypes map[string]*configschema.Block\n\tDataSources   map[string]*configschema.Block\n}\n\n\/\/ ProviderSchemaRequest is used to describe to a ResourceProvider which\n\/\/ aspects of schema are required, when calling the GetSchema method.\ntype ProviderSchemaRequest struct {\n\tResourceTypes []string\n\tDataSources   []string\n}\n<commit_msg>core: LoadSchemas must detect provisioners in non-root modules<commit_after>package terraform\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/addrs\"\n\t\"github.com\/hashicorp\/terraform\/config\/configschema\"\n\t\"github.com\/hashicorp\/terraform\/configs\"\n\t\"github.com\/hashicorp\/terraform\/tfdiags\"\n)\n\n\/\/ Schemas is a container for various kinds of schema that Terraform needs\n\/\/ during processing.\ntype Schemas struct {\n\tproviders    map[string]*ProviderSchema\n\tprovisioners map[string]*configschema.Block\n}\n\n\/\/ ProviderSchema returns the entire ProviderSchema object that was produced\n\/\/ by the plugin for the given provider, or nil if no such schema is available.\n\/\/\n\/\/ It's usually better to go use the more precise methods offered by type\n\/\/ Schemas to handle this detail automatically.\nfunc (ss *Schemas) ProviderSchema(typeName string) *ProviderSchema {\n\tif ss.providers == nil {\n\t\treturn nil\n\t}\n\treturn ss.providers[typeName]\n}\n\n\/\/ ProviderConfig returns the schema for the provider configuration of the\n\/\/ given provider type, or nil if no such schema is available.\nfunc (ss *Schemas) ProviderConfig(typeName string) *configschema.Block {\n\tps := ss.ProviderSchema(typeName)\n\tif ps == nil {\n\t\treturn nil\n\t}\n\treturn ps.Provider\n}\n\n\/\/ ResourceTypeConfig returns the schema for the configuration of a given\n\/\/ resource type belonging to a given provider type, or nil of no such\n\/\/ schema is available.\n\/\/\n\/\/ In many cases the provider type is inferrable from the resource type name,\n\/\/ but this is not always true because users can override the provider for\n\/\/ a resource using the \"provider\" meta-argument. Therefore it's important to\n\/\/ always pass the correct provider name, even though it many cases it feels\n\/\/ redundant.\nfunc (ss *Schemas) ResourceTypeConfig(providerType string, resourceType string) *configschema.Block {\n\tps := ss.ProviderSchema(providerType)\n\tif ps == nil || ps.ResourceTypes == nil {\n\t\treturn nil\n\t}\n\n\treturn ps.ResourceTypes[resourceType]\n}\n\n\/\/ DataSourceConfig returns the schema for the configuration of a given\n\/\/ data source belonging to a given provider type, or nil of no such\n\/\/ schema is available.\n\/\/\n\/\/ In many cases the provider type is inferrable from the data source name,\n\/\/ but this is not always true because users can override the provider for\n\/\/ a resource using the \"provider\" meta-argument. Therefore it's important to\n\/\/ always pass the correct provider name, even though it many cases it feels\n\/\/ redundant.\nfunc (ss *Schemas) DataSourceConfig(providerType string, dataSource string) *configschema.Block {\n\tps := ss.ProviderSchema(providerType)\n\tif ps == nil || ps.DataSources == nil {\n\t\treturn nil\n\t}\n\n\treturn ps.DataSources[dataSource]\n}\n\n\/\/ ProvisionerConfig returns the schema for the configuration of a given\n\/\/ provisioner, or nil of no such schema is available.\nfunc (ss *Schemas) ProvisionerConfig(name string) *configschema.Block {\n\treturn ss.provisioners[name]\n}\n\n\/\/ LoadSchemas searches the given configuration and state (either of which may\n\/\/ be nil) for constructs that have an associated schema, requests the\n\/\/ necessary schemas from the given component factory (which may _not_ be nil),\n\/\/ and returns a single object representing all of the necessary schemas.\n\/\/\n\/\/ If an error is returned, it may be a wrapped tfdiags.Diagnostics describing\n\/\/ errors across multiple separate objects. Errors here will usually indicate\n\/\/ either misbehavior on the part of one of the providers or of the provider\n\/\/ protocol itself. When returned with errors, the returned schemas object is\n\/\/ still valid but may be incomplete.\nfunc LoadSchemas(config *configs.Config, state *State, components contextComponentFactory) (*Schemas, error) {\n\tschemas := &Schemas{\n\t\tproviders:    map[string]*ProviderSchema{},\n\t\tprovisioners: map[string]*configschema.Block{},\n\t}\n\tvar diags tfdiags.Diagnostics\n\n\tnewDiags := loadProviderSchemas(schemas.providers, config, state, components)\n\tdiags = diags.Append(newDiags)\n\tnewDiags = loadProvisionerSchemas(schemas.provisioners, config, components)\n\tdiags = diags.Append(newDiags)\n\n\treturn schemas, diags.Err()\n}\n\nfunc loadProviderSchemas(schemas map[string]*ProviderSchema, config *configs.Config, state *State, components contextComponentFactory) tfdiags.Diagnostics {\n\tvar diags tfdiags.Diagnostics\n\n\tensure := func(typeName string) {\n\t\tif _, exists := schemas[typeName]; exists {\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] LoadSchemas: retrieving schema for provider type %q\", typeName)\n\t\tprovider, err := components.ResourceProvider(typeName, \"early\/\"+typeName)\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[typeName] = &ProviderSchema{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to instantiate provider %q to obtain schema: %s\", typeName, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif closer, ok := provider.(ResourceProviderCloser); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ FIXME: The provider interface is currently awkward in that it\n\t\t\/\/ requires us to tell the provider which resources types and data\n\t\t\/\/ sources we need. In future this will change to just return\n\t\t\/\/ everything available, but for now we'll fake that by fetching all\n\t\t\/\/ of the available names and then requesting them.\n\t\tresourceTypes := provider.Resources()\n\t\tdataSources := provider.DataSources()\n\t\tresourceTypeNames := make([]string, len(resourceTypes))\n\t\tfor i, o := range resourceTypes {\n\t\t\tresourceTypeNames[i] = o.Name\n\t\t}\n\t\tdataSourceNames := make([]string, len(dataSources))\n\t\tfor i, o := range dataSources {\n\t\t\tdataSourceNames[i] = o.Name\n\t\t}\n\n\t\tschema, err := provider.GetSchema(&ProviderSchemaRequest{\n\t\t\tResourceTypes: resourceTypeNames,\n\t\t\tDataSources:   dataSourceNames,\n\t\t})\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[typeName] = &ProviderSchema{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to retrieve schema from provider %q: %s\", typeName, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tschemas[typeName] = schema\n\t}\n\n\tif config != nil {\n\t\tfor _, pc := range config.Module.ProviderConfigs {\n\t\t\tensure(pc.Name)\n\t\t}\n\t\tfor _, rc := range config.Module.ManagedResources {\n\t\t\tproviderAddr := rc.ProviderConfigAddr()\n\t\t\tensure(providerAddr.Type)\n\t\t}\n\t\tfor _, rc := range config.Module.DataResources {\n\t\t\tproviderAddr := rc.ProviderConfigAddr()\n\t\t\tensure(providerAddr.Type)\n\t\t}\n\n\t\t\/\/ Must also visit our child modules, recursively.\n\t\tfor _, cc := range config.Children {\n\t\t\tchildDiags := loadProviderSchemas(schemas, cc, nil, components)\n\t\t\tdiags = diags.Append(childDiags)\n\t\t}\n\t}\n\n\tif state != nil {\n\t\tfor _, ms := range state.Modules {\n\t\t\tfor rsKey, rs := range ms.Resources {\n\t\t\t\tproviderAddrStr := rs.Provider\n\t\t\t\tproviderAddr, addrDiags := addrs.ParseAbsProviderConfigStr(providerAddrStr)\n\t\t\t\tif addrDiags.HasErrors() {\n\t\t\t\t\t\/\/ Should happen only if someone has tampered manually with\n\t\t\t\t\t\/\/ the state, since we always write valid provider addrs.\n\t\t\t\t\tmoduleAddrStr := normalizeModulePath(ms.Path).String()\n\t\t\t\t\tif moduleAddrStr == \"\" {\n\t\t\t\t\t\tmoduleAddrStr = \"the root module\"\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ For now this is a warning, since there are many existing\n\t\t\t\t\t\/\/ test fixtures that have invalid provider configurations.\n\t\t\t\t\t\/\/ There's a check deeper in Terraform that makes this a\n\t\t\t\t\t\/\/ failure when an empty\/invalid provider string is present\n\t\t\t\t\t\/\/ in practice.\n\t\t\t\t\tlog.Printf(\"[WARN] LoadSchemas: Resource %s in %s has invalid provider address %q in its state\", rsKey, moduleAddrStr, providerAddrStr)\n\t\t\t\t\tdiags = diags.Append(\n\t\t\t\t\t\ttfdiags.SimpleWarning(fmt.Sprintf(\"Resource %s in %s has invalid provider address %q in its state\", rsKey, moduleAddrStr, providerAddrStr)),\n\t\t\t\t\t)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tensure(providerAddr.ProviderConfig.Type)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn diags\n}\n\nfunc loadProvisionerSchemas(schemas map[string]*configschema.Block, config *configs.Config, components contextComponentFactory) tfdiags.Diagnostics {\n\tvar diags tfdiags.Diagnostics\n\n\tensure := func(name string) {\n\t\tif _, exists := schemas[name]; exists {\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"[TRACE] LoadSchemas: retrieving schema for provisioner %q\", name)\n\t\tprovisioner, err := components.ResourceProvisioner(name, \"early\/\"+name)\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[name] = &configschema.Block{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to instantiate provisioner %q to obtain schema: %s\", name, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\tif closer, ok := provisioner.(ResourceProvisionerCloser); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\tschema, err := provisioner.GetConfigSchema()\n\t\tif err != nil {\n\t\t\t\/\/ We'll put a stub in the map so we won't re-attempt this on\n\t\t\t\/\/ future calls.\n\t\t\tschemas[name] = &configschema.Block{}\n\t\t\tdiags = diags.Append(\n\t\t\t\tfmt.Errorf(\"Failed to retrieve schema from provisioner %q: %s\", name, err),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tschemas[name] = schema\n\t}\n\n\tif config != nil {\n\t\tfor _, rc := range config.Module.ManagedResources {\n\t\t\tfor _, pc := range rc.Managed.Provisioners {\n\t\t\t\tensure(pc.Type)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Must also visit our child modules, recursively.\n\t\tfor _, cc := range config.Children {\n\t\t\tchildDiags := loadProvisionerSchemas(schemas, cc, components)\n\t\t\tdiags = diags.Append(childDiags)\n\t\t}\n\t}\n\n\treturn diags\n}\n\n\/\/ ProviderSchema represents the schema for a provider's own configuration\n\/\/ and the configuration for some or all of its resources and data sources.\n\/\/\n\/\/ The completeness of this structure depends on how it was constructed.\n\/\/ When constructed for a configuration, it will generally include only\n\/\/ resource types and data sources used by that configuration.\ntype ProviderSchema struct {\n\tProvider      *configschema.Block\n\tResourceTypes map[string]*configschema.Block\n\tDataSources   map[string]*configschema.Block\n}\n\n\/\/ ProviderSchemaRequest is used to describe to a ResourceProvider which\n\/\/ aspects of schema are required, when calling the GetSchema method.\ntype ProviderSchemaRequest struct {\n\tResourceTypes []string\n\tDataSources   []string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.\n\/\/ Revel Framework source code and usage is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage revel\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ Field represents a data field that may be collected in a web form.\ntype Field struct {\n\tName       string\n\tError      *ValidationError\n\tviewArgs   map[string]interface{}\n\tcontroller *Controller\n}\n\nfunc NewField(name string, viewArgs map[string]interface{}) *Field {\n\terr, _ := viewArgs[\"errors\"].(map[string]*ValidationError)[name]\n\tcontroller, _ := viewArgs[\"_controller\"].(*Controller)\n\treturn &Field{\n\t\tName:       name,\n\t\tError:      err,\n\t\tviewArgs:   viewArgs,\n\t\tcontroller: controller,\n\t}\n}\n\n\/\/ ID returns an identifier suitable for use as an HTML id.\nfunc (f *Field) ID() string {\n\treturn strings.Replace(f.Name, \".\", \"_\", -1)\n}\n\n\/\/ Flash returns the flashed value of this Field.\nfunc (f *Field) Flash() string {\n\tv, _ := f.viewArgs[\"flash\"].(map[string]string)[f.Name]\n\treturn v\n}\n\n\/\/ FlashArray returns the flashed value of this Field as a list split on comma.\nfunc (f *Field) FlashArray() []string {\n\tv := f.Flash()\n\tif v == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(v, \",\")\n}\n\nfunc readNext(nextKey string) (string, string) {\n\tswitch nextKey[0] {\n\tcase '[':\n\t\tidx := strings.IndexRune(nextKey, ']')\n\t\tif idx < 0 {\n\t\t\treturn nextKey[1:], \"\"\n\t\t} else {\n\t\t\treturn nextKey[1:idx], nextKey[idx+1:]\n\t\t}\n\tcase '.':\n\t\tnextKey = nextKey[1:]\n\t\tfallthrough\n\tdefault:\n\t\tidx := strings.IndexAny(nextKey, \".[\")\n\t\tif idx < 0 {\n\t\t\treturn nextKey, \"\"\n\t\t} else if nextKey[idx] == '.' {\n\t\t\treturn nextKey[:idx], nextKey[idx+1:]\n\t\t} else {\n\t\t\treturn nextKey[:idx], nextKey[idx:]\n\t\t}\n\t}\n}\n\n\/\/ Value returns the current value of this Field.\nfunc (f *Field) Value() interface{} {\n\tvar fieldName string\n\n\tvar nextKey = f.Name\n\tvar val interface{} = f.viewArgs\n\tfor nextKey != \"\" {\n\t\tfieldName, nextKey = readNext(nextKey)\n\n\t\trVal := reflect.ValueOf(val)\n\t\tkind := rVal.Kind()\n\t\tif kind == reflect.Map {\n\t\t\trFieldName := reflect.ValueOf(fieldName)\n\t\t\tval = rVal.MapIndex(rFieldName).Interface()\n\t\t\tif val == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif kind == reflect.Ptr {\n\t\t\trVal = rVal.Elem()\n\t\t}\n\t\trVal = rVal.FieldByName(fieldName)\n\t\tif !rVal.IsValid() {\n\t\t\treturn nil\n\t\t}\n\t\tval = rVal.Interface()\n\t}\n\n\treturn val\n}\n\n\/\/ ErrorClass returns ErrorCSSClass if this field has a validation error, else empty string.\nfunc (f *Field) ErrorClass() string {\n\tif f.Error != nil {\n\t\tif errorClass, ok := f.viewArgs[\"ERROR_CLASS\"]; ok {\n\t\t\treturn errorClass.(string)\n\t\t}\n\t\treturn ErrorCSSClass\n\t}\n\treturn \"\"\n}\n\n\/\/ Get the short name and translate it\nfunc (f *Field) ShortName() string {\n\tname := f.Name\n\tif i := strings.LastIndex(name, \".\"); i > 0 {\n\t\tname = name[i+1:]\n\t}\n\treturn f.Translate(name)\n}\n\n\/\/ Translate the text\nfunc (f *Field) Translate(text string, args ...interface{}) string {\n\tif f.controller != nil {\n\t\ttext = f.controller.Message(text, args...)\n\t}\n\treturn text\n}\n<commit_msg>fix panic<commit_after>\/\/ Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.\n\/\/ Revel Framework source code and usage is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage revel\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ Field represents a data field that may be collected in a web form.\ntype Field struct {\n\tName       string\n\tError      *ValidationError\n\tviewArgs   map[string]interface{}\n\tcontroller *Controller\n}\n\nfunc NewField(name string, viewArgs map[string]interface{}) *Field {\n\terr, _ := viewArgs[\"errors\"].(map[string]*ValidationError)[name]\n\tcontroller, _ := viewArgs[\"_controller\"].(*Controller)\n\treturn &Field{\n\t\tName:       name,\n\t\tError:      err,\n\t\tviewArgs:   viewArgs,\n\t\tcontroller: controller,\n\t}\n}\n\n\/\/ ID returns an identifier suitable for use as an HTML id.\nfunc (f *Field) ID() string {\n\treturn strings.Replace(f.Name, \".\", \"_\", -1)\n}\n\n\/\/ Flash returns the flashed value of this Field.\nfunc (f *Field) Flash() string {\n\tv, _ := f.viewArgs[\"flash\"].(map[string]string)[f.Name]\n\treturn v\n}\n\n\/\/ FlashArray returns the flashed value of this Field as a list split on comma.\nfunc (f *Field) FlashArray() []string {\n\tv := f.Flash()\n\tif v == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(v, \",\")\n}\n\nfunc readNext(nextKey string) (string, string) {\n\tswitch nextKey[0] {\n\tcase '[':\n\t\tidx := strings.IndexRune(nextKey, ']')\n\t\tif idx < 0 {\n\t\t\treturn nextKey[1:], \"\"\n\t\t} else {\n\t\t\treturn nextKey[1:idx], nextKey[idx+1:]\n\t\t}\n\tcase '.':\n\t\tnextKey = nextKey[1:]\n\t\tfallthrough\n\tdefault:\n\t\tidx := strings.IndexAny(nextKey, \".[\")\n\t\tif idx < 0 {\n\t\t\treturn nextKey, \"\"\n\t\t} else if nextKey[idx] == '.' {\n\t\t\treturn nextKey[:idx], nextKey[idx+1:]\n\t\t} else {\n\t\t\treturn nextKey[:idx], nextKey[idx:]\n\t\t}\n\t}\n}\n\n\/\/ Value returns the current value of this Field.\nfunc (f *Field) Value() interface{} {\n\tvar fieldName string\n\n\tvar nextKey = f.Name\n\tvar val interface{} = f.viewArgs\n\tfor nextKey != \"\" {\n\t\tfieldName, nextKey = readNext(nextKey)\n\n\t\trVal := reflect.ValueOf(val)\n\t\tkind := rVal.Kind()\n\t\tif kind == reflect.Map {\n\t\t\trFieldName := reflect.ValueOf(fieldName)\n\t\t\trVal = rVal.MapIndex(rFieldName)\n\t\t\tif !rVal.IsValid() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tval = rVal.Interface()\n\t\t\tif val == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif kind == reflect.Ptr {\n\t\t\trVal = rVal.Elem()\n\t\t}\n\t\trVal = rVal.FieldByName(fieldName)\n\t\tif !rVal.IsValid() {\n\t\t\treturn nil\n\t\t}\n\t\tval = rVal.Interface()\n\t\tif val == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn val\n}\n\n\/\/ ErrorClass returns ErrorCSSClass if this field has a validation error, else empty string.\nfunc (f *Field) ErrorClass() string {\n\tif f.Error != nil {\n\t\tif errorClass, ok := f.viewArgs[\"ERROR_CLASS\"]; ok {\n\t\t\treturn errorClass.(string)\n\t\t}\n\t\treturn ErrorCSSClass\n\t}\n\treturn \"\"\n}\n\n\/\/ Get the short name and translate it\nfunc (f *Field) ShortName() string {\n\tname := f.Name\n\tif i := strings.LastIndex(name, \".\"); i > 0 {\n\t\tname = name[i+1:]\n\t}\n\treturn f.Translate(name)\n}\n\n\/\/ Translate the text\nfunc (f *Field) Translate(text string, args ...interface{}) string {\n\tif f.controller != nil {\n\t\ttext = f.controller.Message(text, args...)\n\t}\n\treturn text\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar maxStorageString = flag.String(\"maxSize\", \"\",\n\t\"Approximate maximum amount of space to allocate\")\nvar maxStorage int64\n\nfunc hashFilename(base, hstr string) string {\n\treturn base + \"\/\" + hstr[:2] + \"\/\" + hstr\n}\n\ntype ReadSeekCloser interface {\n\tio.ReadSeeker\n\tio.Closer\n}\n\nfunc openBlob(hstr string) (ReadSeekCloser, error) {\n\treturn os.Open(hashFilename(*root, hstr))\n}\n\nfunc removeObject(h string) error {\n\terr := maybeRemoveBlobOwnership(h)\n\tif err == nil {\n\t\terr = os.Remove(hashFilename(*root, h))\n\t\tlog.Printf(\"Removed local copy of %v, result=%v\",\n\t\t\th, errorOrSuccess(err))\n\t}\n\treturn err\n}\n\nfunc forceRemoveObject(h string) error {\n\tremoveBlobOwnershipRecord(h, serverId)\n\treturn os.Remove(hashFilename(*root, h))\n}\n\nfunc verifyObjectHash(h string) error {\n\tf, err := openBlob(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tsh := getHash()\n\t_, err = io.Copy(sh, f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thstring := hex.EncodeToString(sh.Sum([]byte{}))\n\tif h != hstring {\n\t\terr = forceRemoveObject(h)\n\t\tlog.Printf(\"Removed corrupt file from disk: %v (was %v), result=%v\",\n\t\t\th, hstring, errorOrSuccess(err))\n\t\treturn fmt.Errorf(\"Hash from disk of %v was %v\", h, hstring)\n\t}\n\treturn nil\n}\n\nfunc shouldVerifyObject(h string) bool {\n\tb, err := getBlobOwnership(h)\n\tif err != nil {\n\t\treturn true\n\t}\n\t\/\/ True if we haven't checked the object in 30 days.\n\treturn b.Nodes[serverId].Add(30 * 24 * time.Hour).After(time.Now())\n}\n\nfunc verifyWorker(ch chan os.FileInfo) {\n\tnl, err := findAllNodes()\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't find node list during verify: %v\", err)\n\t\tnl = NodeList{}\n\t}\n\tfor info := range ch {\n\t\tvar err error\n\t\tforce := false\n\t\tif shouldVerifyObject(info.Name()) {\n\t\t\terr = verifyObjectHash(info.Name())\n\t\t\tforce = true\n\t\t}\n\t\tif err == nil {\n\t\t\trecordBlobOwnership(info.Name(), info.Size(), force)\n\t\t} else {\n\t\t\tlog.Printf(\"Invalid hash for object %v found at verification: %v\",\n\t\t\t\tinfo.Name(), err)\n\t\t\tremoveBlobOwnershipRecord(info.Name(), serverId)\n\t\t\tif len(nl) > 0 {\n\t\t\t\tsalvageBlob(info.Name(), \"\", 1, nl)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc quickVerifyWorker(ch chan os.FileInfo) {\n\tfor info := range ch {\n\t\trecordBlobOwnership(info.Name(), info.Size(), false)\n\t}\n}\n\nfunc reconcileWith(wf func(chan os.FileInfo)) error {\n\texplen := getHash().Size() * 2\n\n\tvch := make(chan os.FileInfo)\n\tdefer close(vch)\n\n\tfor i := 0; i < *verifyWorkers; i++ {\n\t\tgo wf(vch)\n\t}\n\n\treturn filepath.Walk(*root, 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() && !strings.HasPrefix(info.Name(), \"tmp\") &&\n\t\t\tlen(info.Name()) == explen {\n\n\t\t\tvch <- info\n\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc reconcile() error {\n\treturn reconcileWith(verifyWorker)\n}\n\nfunc quickReconcile() error {\n\treturn reconcileWith(quickVerifyWorker)\n}\n<commit_msg>Fully verification only when something is too old.<commit_after>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar maxStorageString = flag.String(\"maxSize\", \"\",\n\t\"Approximate maximum amount of space to allocate\")\nvar maxStorage int64\n\nfunc hashFilename(base, hstr string) string {\n\treturn base + \"\/\" + hstr[:2] + \"\/\" + hstr\n}\n\ntype ReadSeekCloser interface {\n\tio.ReadSeeker\n\tio.Closer\n}\n\nfunc openBlob(hstr string) (ReadSeekCloser, error) {\n\treturn os.Open(hashFilename(*root, hstr))\n}\n\nfunc removeObject(h string) error {\n\terr := maybeRemoveBlobOwnership(h)\n\tif err == nil {\n\t\terr = os.Remove(hashFilename(*root, h))\n\t\tlog.Printf(\"Removed local copy of %v, result=%v\",\n\t\t\th, errorOrSuccess(err))\n\t}\n\treturn err\n}\n\nfunc forceRemoveObject(h string) error {\n\tremoveBlobOwnershipRecord(h, serverId)\n\treturn os.Remove(hashFilename(*root, h))\n}\n\nfunc verifyObjectHash(h string) error {\n\tf, err := openBlob(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tsh := getHash()\n\t_, err = io.Copy(sh, f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thstring := hex.EncodeToString(sh.Sum([]byte{}))\n\tif h != hstring {\n\t\terr = forceRemoveObject(h)\n\t\tlog.Printf(\"Removed corrupt file from disk: %v (was %v), result=%v\",\n\t\t\th, hstring, errorOrSuccess(err))\n\t\treturn fmt.Errorf(\"Hash from disk of %v was %v\", h, hstring)\n\t}\n\treturn nil\n}\n\nfunc shouldVerifyObject(h string) bool {\n\tb, err := getBlobOwnership(h)\n\tif err != nil {\n\t\treturn true\n\t}\n\t\/\/ True if we haven't checked the object in 30 days.\n\treturn b.Nodes[serverId].Add(30 * 24 * time.Hour).Before(time.Now())\n}\n\nfunc verifyWorker(ch chan os.FileInfo) {\n\tnl, err := findAllNodes()\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't find node list during verify: %v\", err)\n\t\tnl = NodeList{}\n\t}\n\tfor info := range ch {\n\t\tvar err error\n\t\tforce := false\n\t\tif shouldVerifyObject(info.Name()) {\n\t\t\terr = verifyObjectHash(info.Name())\n\t\t\tforce = true\n\t\t}\n\t\tif err == nil {\n\t\t\trecordBlobOwnership(info.Name(), info.Size(), force)\n\t\t} else {\n\t\t\tlog.Printf(\"Invalid hash for object %v found at verification: %v\",\n\t\t\t\tinfo.Name(), err)\n\t\t\tremoveBlobOwnershipRecord(info.Name(), serverId)\n\t\t\tif len(nl) > 0 {\n\t\t\t\tsalvageBlob(info.Name(), \"\", 1, nl)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc quickVerifyWorker(ch chan os.FileInfo) {\n\tfor info := range ch {\n\t\trecordBlobOwnership(info.Name(), info.Size(), false)\n\t}\n}\n\nfunc reconcileWith(wf func(chan os.FileInfo)) error {\n\texplen := getHash().Size() * 2\n\n\tvch := make(chan os.FileInfo)\n\tdefer close(vch)\n\n\tfor i := 0; i < *verifyWorkers; i++ {\n\t\tgo wf(vch)\n\t}\n\n\treturn filepath.Walk(*root, 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() && !strings.HasPrefix(info.Name(), \"tmp\") &&\n\t\t\tlen(info.Name()) == explen {\n\n\t\t\tvch <- info\n\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc reconcile() error {\n\treturn reconcileWith(verifyWorker)\n}\n\nfunc quickReconcile() error {\n\treturn reconcileWith(quickVerifyWorker)\n}\n<|endoftext|>"}
{"text":"<commit_before>package box\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ TODO(ttacon): reconcile this with Folder for one common struct?\ntype File struct {\n\tID                string          `json:\"id,omitempty\"`\n\tFolderUploadEmail *AccessEmail    `json:\"folder_upload_email,omitempty\"`\n\tParent            *Item           `json:\"parent,omitempty\"`\n\tItemStatus        string          `json:\"item_status\"`\n\tItemCollection    *ItemCollection `json:\"item_collection\"`\n\tType              string          `json:\"type\"` \/\/ TODO(ttacon): enum\n\tDescription       string          `json:\"description\"`\n\tSize              int             `json:\"size\"`\n\tCreateBy          *Item           `json:\"created_by\"`\n\tModifiedBy        *Item           `json:\"modified_by\"`\n\tTrashedAt         *string         `json:\"trashed_at\"`          \/\/ TODO(ttacon): change to time.Time\n\tContentModifiedAt *string         `json:\"content_modified_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPurgedAt          *string         `json:\"purged_at\"`           \/\/ TODO(ttacon): change to time.Time, this field isn't documented but I keep getting it back...\n\tSharedLinkg       *string         `json:\"shared_link\"`\n\tSequenceId        string          `json:\"sequence_id\"`\n\tETag              *string         `json:\"etag\"`\n\tName              string          `json:\"name\"`\n\tCreatedAt         *string         `json:\"created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tOwnedBy           *Item           `json:\"owned_by\"`\n\tModifiedAt        *string         `json:\"modified_at\"`        \/\/ TODO(ttacon): change to time.Time\n\tContentCreatedAt  *string         `json:\"content_created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPathCollection    *PathCollection `json:\"path_collection\"`    \/\/ TODO(ttacon): make sure this is the correct kind of struct(ure)\n\tSharedLink        *Link           `json:\"shared_link\"`\n\n\tSHA1 string `json:\"sha1\"`\n}\n\ntype FileCollection struct {\n\tTotalCount int     `json:\"total_count\"`\n\tEntries    []*File `json:\"entries\"`\n}\n\n\/\/ Documentation: https:\/\/developer.box.com\/docs\/#files-get\nfunc (c *Client) GetFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation https:\/\/developer.box.com\/docs\/#files-upload-a-file\n\/\/ TODO(ttacon): deal with handling SHA1 headers\nfunc (c *Client) UploadFile(filePath, parentId string) (*http.Response, *FileCollection, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer file.Close()\n\n\tfileContents, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tbody   = &bytes.Buffer{}\n\t\twriter = multipart.NewWriter(body)\n\t)\n\n\t\/\/ write the file\n\tpart, err := writer.CreateFormFile(\"file\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpart.Write(fileContents)\n\n\t\/\/ write the other form fields we need\n\terr = writer.WriteField(\"filename\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = writer.WriteField(\"parent_id\", parentId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): add in content_created_at, content_modified_at\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): refactor to use Client.NewRequest\/Do when it supports\n\t\/\/ io.Writer\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"https:\/\/upload.box.com\/api\/2.0\/files\/content\"),\n\t\tbody,\n\t)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data FileCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-delete-a-file\nfunc (c *Client) DeleteFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-copy-a-file\nfunc (c *Client) CopyFile(fileId, parent, name string) (*http.Response, *File, error) {\n\tvar bodyData = map[string]interface{}{\n\t\t\"parent\": map[string]string{\n\t\t\t\"id\": parent,\n\t\t},\n\t\t\"name\": name,\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\/copy\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we return the http.Response as Box may return a 202 if there is not\n\/\/ yet a download link, or a 302 with the link - this allows the user to\n\/\/ decide what to do.\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-download-a-file\nfunc (c *Client) DownloadFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/content\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-versions-of-a-file\n\/\/ TODO(ttacon): don't use file collection, make actual structs specific to file versions\nfunc (c *Client) ViewVersionsOfFile(fileId string) (*http.Response, *FileCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/versions\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *FileCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we only return the response as there are many possible responses that we\n\/\/ feel the user should have control over\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-thumbnail-for-a-file\nfunc (c *Client) GetThumbnail(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/thumbnail.extension\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-create-a-shared-link-for-a-file\nfunc (c *Client) CreateSharedLinkForFile(fileId, access, unsharedAt string, canDownload, canPreview bool) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(access) > 0 {\n\t\tdataMap[\"access\"] = access\n\t}\n\t\/\/ TODO(ttacon): support unshared_at as time.Time\n\t\/\/ TODO(ttacon): validate access is open or company before add permissions\n\tif canDownload {\n\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\"can_download\": canDownload,\n\t\t}\n\t}\n\tif canPreview {\n\t\tif m, ok := dataMap[\"permissions\"]; ok {\n\t\t\tmVal, _ := m.(map[string]bool)\n\t\t\tmVal[\"can_preview\"] = canPreview\n\t\t} else {\n\t\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\t\"can_preview\": canPreview,\n\t\t\t}\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"PUT\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-trashed-file\nfunc (c *Client) GetTrashedFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-restore-a-trashed-item\nfunc (c *Client) RestoreTrashedItem(fileId, name, parentId string) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(name) > 0 {\n\t\tdataMap[\"name\"] = name\n\t}\n\tif len(parentId) > 0 {\n\t\tdataMap[\"parent\"] = map[string]string{\n\t\t\t\"id\": parentId,\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-permanently-delete-a-trashed-file\nfunc (c *Client) PermanentlyDeleteTrashedFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-the-comments-on-a-file\nfunc (c *Client) ViewCommentsOnFile(fileId string) (*http.Response, *CommentCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/comments\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *CommentCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-the-tasks-for-a-file\nfunc (c *Client) GetTasksForFile(fileId string) (*http.Response, *TaskCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/tasks\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *TaskCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n<commit_msg>refactor upload file a little<commit_after>package box\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ TODO(ttacon): reconcile this with Folder for one common struct?\ntype File struct {\n\tID                string          `json:\"id,omitempty\"`\n\tFolderUploadEmail *AccessEmail    `json:\"folder_upload_email,omitempty\"`\n\tParent            *Item           `json:\"parent,omitempty\"`\n\tItemStatus        string          `json:\"item_status\"`\n\tItemCollection    *ItemCollection `json:\"item_collection\"`\n\tType              string          `json:\"type\"` \/\/ TODO(ttacon): enum\n\tDescription       string          `json:\"description\"`\n\tSize              int             `json:\"size\"`\n\tCreateBy          *Item           `json:\"created_by\"`\n\tModifiedBy        *Item           `json:\"modified_by\"`\n\tTrashedAt         *string         `json:\"trashed_at\"`          \/\/ TODO(ttacon): change to time.Time\n\tContentModifiedAt *string         `json:\"content_modified_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPurgedAt          *string         `json:\"purged_at\"`           \/\/ TODO(ttacon): change to time.Time, this field isn't documented but I keep getting it back...\n\tSharedLinkg       *string         `json:\"shared_link\"`\n\tSequenceId        string          `json:\"sequence_id\"`\n\tETag              *string         `json:\"etag\"`\n\tName              string          `json:\"name\"`\n\tCreatedAt         *string         `json:\"created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tOwnedBy           *Item           `json:\"owned_by\"`\n\tModifiedAt        *string         `json:\"modified_at\"`        \/\/ TODO(ttacon): change to time.Time\n\tContentCreatedAt  *string         `json:\"content_created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPathCollection    *PathCollection `json:\"path_collection\"`    \/\/ TODO(ttacon): make sure this is the correct kind of struct(ure)\n\tSharedLink        *Link           `json:\"shared_link\"`\n\n\tSHA1 string `json:\"sha1\"`\n}\n\ntype FileCollection struct {\n\tTotalCount int     `json:\"total_count\"`\n\tEntries    []*File `json:\"entries\"`\n}\n\n\/\/ Documentation: https:\/\/developer.box.com\/docs\/#files-get\nfunc (c *Client) GetFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation https:\/\/developer.box.com\/docs\/#files-upload-a-file\n\/\/ TODO(ttacon): deal with handling SHA1 headers\nfunc (c *Client) UploadFile(filePath, parentId string) (*http.Response, *FileCollection, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer file.Close()\n\n\tfileContents, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tbody   = &bytes.Buffer{}\n\t\twriter = multipart.NewWriter(body)\n\t)\n\n\t\/\/ write the file\n\tpart, err := writer.CreateFormFile(\"file\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpart.Write(fileContents)\n\n\t\/\/ write the other form fields we need\n\terr = writer.WriteField(\"filename\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = writer.WriteField(\"parent_id\", parentId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): add in content_created_at, content_modified_at\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): refactor to use Client.NewRequest\/Do when it supports\n\t\/\/ io.Writer\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"https:\/\/upload.box.com\/api\/2.0\/files\/content\"),\n\t\tbody,\n\t)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *FileCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-delete-a-file\nfunc (c *Client) DeleteFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-copy-a-file\nfunc (c *Client) CopyFile(fileId, parent, name string) (*http.Response, *File, error) {\n\tvar bodyData = map[string]interface{}{\n\t\t\"parent\": map[string]string{\n\t\t\t\"id\": parent,\n\t\t},\n\t\t\"name\": name,\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\/copy\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we return the http.Response as Box may return a 202 if there is not\n\/\/ yet a download link, or a 302 with the link - this allows the user to\n\/\/ decide what to do.\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-download-a-file\nfunc (c *Client) DownloadFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/content\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-versions-of-a-file\n\/\/ TODO(ttacon): don't use file collection, make actual structs specific to file versions\nfunc (c *Client) ViewVersionsOfFile(fileId string) (*http.Response, *FileCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/versions\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *FileCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we only return the response as there are many possible responses that we\n\/\/ feel the user should have control over\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-thumbnail-for-a-file\nfunc (c *Client) GetThumbnail(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/thumbnail.extension\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-create-a-shared-link-for-a-file\nfunc (c *Client) CreateSharedLinkForFile(fileId, access, unsharedAt string, canDownload, canPreview bool) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(access) > 0 {\n\t\tdataMap[\"access\"] = access\n\t}\n\t\/\/ TODO(ttacon): support unshared_at as time.Time\n\t\/\/ TODO(ttacon): validate access is open or company before add permissions\n\tif canDownload {\n\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\"can_download\": canDownload,\n\t\t}\n\t}\n\tif canPreview {\n\t\tif m, ok := dataMap[\"permissions\"]; ok {\n\t\t\tmVal, _ := m.(map[string]bool)\n\t\t\tmVal[\"can_preview\"] = canPreview\n\t\t} else {\n\t\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\t\"can_preview\": canPreview,\n\t\t\t}\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"PUT\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-trashed-file\nfunc (c *Client) GetTrashedFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-restore-a-trashed-item\nfunc (c *Client) RestoreTrashedItem(fileId, name, parentId string) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(name) > 0 {\n\t\tdataMap[\"name\"] = name\n\t}\n\tif len(parentId) > 0 {\n\t\tdataMap[\"parent\"] = map[string]string{\n\t\t\t\"id\": parentId,\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-permanently-delete-a-trashed-file\nfunc (c *Client) PermanentlyDeleteTrashedFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-the-comments-on-a-file\nfunc (c *Client) ViewCommentsOnFile(fileId string) (*http.Response, *CommentCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/comments\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *CommentCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-the-tasks-for-a-file\nfunc (c *Client) GetTasksForFile(fileId string) (*http.Response, *TaskCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/tasks\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *TaskCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\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\n\t\"github.com\/paaff\/Filly\/files\"\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc main() {\n\t\/\/ Load configuration file\n\tviper.SetConfigName(\"fillyConf\")\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\".\/config\")\n\tvErr := viper.ReadInConfig()\n\tif vErr != nil {\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", vErr))\n\t} else {\n\t\tdirContent.ROOT_DIR = viper.GetString(\"root_dir\")\n\t}\n\n\t\/\/ Create a simple file server\n\tfs := http.FileServer(http.Dir(\".\/web\/dist\"))\n\thttp.Handle(\"\/\", fs)\n\n\t\/\/ GetDir endpoint\n\thttp.HandleFunc(\"\/browse\", browseHandler)\n\n\terr := http.ListenAndServe(\":1337\", nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n\n}\n\nfunc browseHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"POST\" {\n\t\tpath := r.FormValue(\"path\")\n\t\t\/\/ Browse from the POST form variable\n\t\tcont, status := dirContent.GetDirectoryContentInJSON(path)\n\t\tif cont != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tjson.NewEncoder(w).Encode(cont)\n\t\t} else {\n\t\t\t\/\/ Error handling.\n\t\t\terrorHandler(w, r, status)\n\t\t}\n\t}\n}\n\nfunc errorHandler(w http.ResponseWriter, r *http.Request, status int) {\n\tw.WriteHeader(status)\n\tif status == 404 {\n\t\tfmt.Fprint(w, \"404 - NOT FOUND\")\n\t}\n\n}\n<commit_msg>NO ISSUES HERE MOVE A LONG<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/paaff\/Filly\/files\"\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc main() {\n\t\/\/ Load configuration file\n\tviper.SetConfigName(\"fillyconf\")\n\tviper.SetConfigType(\"json\")\n\tviper.AddConfigPath(\".\/config\")\n\tvErr := viper.ReadInConfig()\n\tif vErr != nil {\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", vErr))\n\t} else {\n\t\tdirContent.ROOT_DIR = viper.GetString(\"root_dir\")\n\t}\n\n\t\/\/ Create a simple file server\n\tfs := http.FileServer(http.Dir(\".\/web\/dist\"))\n\thttp.Handle(\"\/\", fs)\n\n\t\/\/ GetDir endpoint\n\thttp.HandleFunc(\"\/browse\", browseHandler)\n\n\terr := http.ListenAndServe(\":1337\", nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n\n}\n\nfunc browseHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"POST\" {\n\t\tpath := r.FormValue(\"path\")\n\t\t\/\/ Browse from the POST form variable\n\t\tcont, status := dirContent.GetDirectoryContentInJSON(path)\n\t\tif cont != nil {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tjson.NewEncoder(w).Encode(cont)\n\t\t} else {\n\t\t\t\/\/ Error handling.\n\t\t\terrorHandler(w, r, status)\n\t\t}\n\t}\n}\n\nfunc errorHandler(w http.ResponseWriter, r *http.Request, status int) {\n\tw.WriteHeader(status)\n\tif status == 404 {\n\t\tfmt.Fprint(w, \"404 - NOT FOUND\")\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package openshift\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"reflect\"\n\t\"unsafe\"\n\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nconst (\n\tfieldKind            = \"kind\"\n\tfieldAPIVersion      = \"apiVersion\"\n\tfieldObjects         = \"objects\"\n\tfieldItems           = \"items\"\n\tfieldMetadata        = \"metadata\"\n\tfieldNamespace       = \"namespace\"\n\tfieldName            = \"name\"\n\tfieldResourceVersion = \"resourceVersion\"\n\n\tvalTemplate       = \"Template\"\n\tvalProjectRequest = \"ProjectRequest\"\n\tvalList           = \"List\"\n)\n\nvar (\n\tendpoints = map[string]map[string]string{\n\t\t\"POST\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects`,\n\t\t\t\"ProjectRequest\":         `\/oapi\/v1\/projectrequests`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges`,\n\t\t},\n\t\t\"PUT\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges\/{{ index . \"metadata\" \"name\"}}`,\n\t\t},\n\t\t\"GET\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges\/{{ index . \"metadata\" \"name\"}}`,\n\t\t},\n\t\t\/*\n\t\t\t\"PUT\": {\n\t\t\t\t\"ResourceQuota\": `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\t\"LimitRange\":    `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t},\n\t\t*\/\n\t\t\"DELETE\": {\n\t\t\t\"ResourceQuota\": `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t},\n\t}\n)\n\n\/\/ ApplyOptions contains options for connecting to the target API\ntype ApplyOptions struct {\n\tConfig\n\tOverwrite bool\n\tNamespace string\n}\n\nfunc (a ApplyOptions) withNamespace(namespace string) ApplyOptions {\n\treturn ApplyOptions{\n\t\tConfig:    a.Config,\n\t\tOverwrite: a.Overwrite,\n\t\tNamespace: namespace,\n\t}\n}\n\n\/\/ Apply a given template structure to a target API\nfunc Apply(source string, opts ApplyOptions) error {\n\n\tobjects, err := parseObjects(source, opts.Namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = allKnownTypes(objects)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = applyAll(objects, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc applyAll(objects []map[interface{}]interface{}, opts ApplyOptions) error {\n\tfor index, obj := range objects {\n\t\t_, err := apply(obj, \"POST\", opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif index == 0 {\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc apply(object map[interface{}]interface{}, action string, opts ApplyOptions) (map[interface{}]interface{}, error) {\n\tbody, err := yaml.Marshal(object)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl, err := createURL(opts.MasterURL, action, object)\n\tif url == \"\" {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(action, url, bytes.NewReader(body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Accept\", \"application\/yaml\")\n\treq.Header.Set(\"Content-Type\", \"application\/yaml\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+opts.Token)\n\n\t\/\/ for debug only\n\trb, _ := httputil.DumpRequest(req, true)\n\tif false {\n\t\tfmt.Println(string(rb))\n\t}\n\n\tclient := http.DefaultClient\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tb := buf.Bytes()\n\n\tvar respType map[interface{}]interface{}\n\terr = yaml.Unmarshal(b, &respType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode == http.StatusConflict {\n\t\t\/*\n\t\t\tif object[fieldKind] == valProjectRequest {\n\t\t\t\treturn respType, nil\n\t\t\t}\n\t\t\tresp, err := apply(object, \"GET\", opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmt.Println(resp)\n\t\t\tupdateResourceVersion(resp, object)\n\t\t\tfmt.Println(object)\n\t\t*\/\n\t\treturn apply(object, \"PUT\", opts)\n\t}\n\t\/*\n\t\tif resp.StatusCode == http.StatusForbidden && opts.Overwrite {\n\n\t\t} else\n\t*\/\n\tif resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Unknown response:\\n%v\\n%v\", *(*string)(unsafe.Pointer(&b)), string(rb))\n\t}\n\n\tfmt.Printf(\"%v %v %v in %v\\n\", action, respType[fieldKind], getName(respType), opts.Namespace)\n\treturn respType, nil\n}\n\nfunc updateResourceVersion(source, target map[interface{}]interface{}) {\n\tif sourceMeta, sourceMetaFound := source[fieldMetadata].(map[interface{}]interface{}); sourceMetaFound {\n\t\tif sourceVersion, sourceVersionFound := sourceMeta[fieldResourceVersion]; sourceVersionFound {\n\t\t\tif targetMeta, targetMetaFound := source[fieldMetadata].(map[interface{}]interface{}); targetMetaFound {\n\t\t\t\tfmt.Println(\"setting v\", sourceVersion, reflect.TypeOf(sourceVersion).Kind())\n\t\t\t\ttargetMeta[fieldResourceVersion] = sourceVersion\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getName(obj map[interface{}]interface{}) string {\n\tif meta, metaFound := obj[fieldMetadata].(map[interface{}]interface{}); metaFound {\n\t\tif name, nameFound := meta[fieldName].(string); nameFound {\n\t\t\treturn name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc parseObjects(source string, namespace string) ([]map[interface{}]interface{}, error) {\n\tvar template map[interface{}]interface{}\n\n\terr := yaml.Unmarshal([]byte(source), &template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif template[fieldKind] == valTemplate || template[fieldKind] == valList {\n\t\tvar ts []interface{}\n\t\tif template[fieldKind] == valTemplate {\n\t\t\tts = template[fieldObjects].([]interface{})\n\t\t} else if template[fieldKind] == valList {\n\t\t\tts = template[fieldItems].([]interface{})\n\t\t}\n\t\tvar objs []map[interface{}]interface{}\n\t\tfor _, obj := range ts {\n\t\t\tobjs = append(objs, obj.(map[interface{}]interface{}))\n\t\t}\n\t\tif namespace != \"\" {\n\t\t\tfor _, obj := range objs {\n\t\t\t\tif val, ok := obj[fieldMetadata].(map[interface{}]interface{}); ok {\n\t\t\t\t\tif _, ok := val[fieldNamespace]; !ok {\n\t\t\t\t\t\tval[fieldNamespace] = namespace\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn objs, nil\n\t}\n\treturn []map[interface{}]interface{}{template}, nil\n}\n\n\/\/ TODO: a bit off now that there are multiple Action methods\nfunc allKnownTypes(objects []map[interface{}]interface{}) error {\n\tm := multiError{}\n\tfor _, obj := range objects {\n\t\tif _, ok := endpoints[\"POST\"][obj[fieldKind].(string)]; !ok {\n\t\t\tm.Errors = append(m.Errors, fmt.Errorf(\"Unknown type: %v\", obj[fieldKind]))\n\t\t}\n\t}\n\tif len(m.Errors) > 0 {\n\t\treturn m\n\t}\n\treturn nil\n}\n\nfunc createURL(hostURL, action string, object map[interface{}]interface{}) (string, error) {\n\turlTemplate, found := endpoints[action][object[fieldKind].(string)]\n\tif !found {\n\t\treturn \"\", nil\n\t}\n\ttarget, err := template.New(\"url\").Parse(urlTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = target.Execute(&buf, object)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := buf.String()\n\treturn hostURL + str, nil\n}\n<commit_msg>Set correct target when updating resourceVersion<commit_after>package openshift\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"reflect\"\n\t\"unsafe\"\n\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nconst (\n\tfieldKind            = \"kind\"\n\tfieldAPIVersion      = \"apiVersion\"\n\tfieldObjects         = \"objects\"\n\tfieldItems           = \"items\"\n\tfieldMetadata        = \"metadata\"\n\tfieldNamespace       = \"namespace\"\n\tfieldName            = \"name\"\n\tfieldResourceVersion = \"resourceVersion\"\n\n\tvalTemplate       = \"Template\"\n\tvalProjectRequest = \"ProjectRequest\"\n\tvalList           = \"List\"\n)\n\nvar (\n\tendpoints = map[string]map[string]string{\n\t\t\"POST\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects`,\n\t\t\t\"ProjectRequest\":         `\/oapi\/v1\/projectrequests`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges`,\n\t\t},\n\t\t\"PUT\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges\/{{ index . \"metadata\" \"name\"}}`,\n\t\t},\n\t\t\"GET\": {\n\t\t\t\"Project\":                `\/oapi\/v1\/projects\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBinding\":            `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindings\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"RoleBindingRestriction\": `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/rolebindingrestrictions\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Route\":                  `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/routes\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"DeploymentConfig\":       `\/oapi\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/deploymentconfigs\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"PersistentVolumeClaim\":  `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/persistentvolumeclaims\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Service\":                `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/services\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"Secret\":                 `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/secrets\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ServiceAccount\":         `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/serviceaccounts\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ConfigMap\":              `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/configmaps\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"ResourceQuota\":          `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/resourcequotas\/{{ index . \"metadata\" \"name\"}}`,\n\t\t\t\"LimitRange\":             `\/api\/v1\/namespaces\/{{ index . \"metadata\" \"namespace\"}}\/limitranges\/{{ index . \"metadata\" \"name\"}}`,\n\t\t},\n\t}\n)\n\n\/\/ ApplyOptions contains options for connecting to the target API\ntype ApplyOptions struct {\n\tConfig\n\tOverwrite bool\n\tNamespace string\n}\n\nfunc (a ApplyOptions) withNamespace(namespace string) ApplyOptions {\n\treturn ApplyOptions{\n\t\tConfig:    a.Config,\n\t\tOverwrite: a.Overwrite,\n\t\tNamespace: namespace,\n\t}\n}\n\n\/\/ Apply a given template structure to a target API\nfunc Apply(source string, opts ApplyOptions) error {\n\n\tobjects, err := parseObjects(source, opts.Namespace)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = allKnownTypes(objects)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = applyAll(objects, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc applyAll(objects []map[interface{}]interface{}, opts ApplyOptions) error {\n\tfor index, obj := range objects {\n\t\t_, err := apply(obj, \"POST\", opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif index == 0 {\n\t\t\ttime.Sleep(time.Second * 2)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc apply(object map[interface{}]interface{}, action string, opts ApplyOptions) (map[interface{}]interface{}, error) {\n\tbody, err := yaml.Marshal(object)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl, err := createURL(opts.MasterURL, action, object)\n\tif url == \"\" {\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(action, url, bytes.NewReader(body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Accept\", \"application\/yaml\")\n\treq.Header.Set(\"Content-Type\", \"application\/yaml\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+opts.Token)\n\n\t\/\/ for debug only\n\trb, _ := httputil.DumpRequest(req, true)\n\tif false {\n\t\tfmt.Println(string(rb))\n\t}\n\n\tclient := http.DefaultClient\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(resp.Body)\n\tb := buf.Bytes()\n\n\tvar respType map[interface{}]interface{}\n\terr = yaml.Unmarshal(b, &respType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode == http.StatusConflict {\n\t\tif object[fieldKind] == valProjectRequest {\n\t\t\treturn respType, nil\n\t\t}\n\t\t\/*\n\t\t\tfmt.Println(\"Conflict-Update\")\n\t\t\tresp, err := apply(object, \"GET\", opts)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmt.Println(resp)\n\t\t\tupdateResourceVersion(resp, object)\n\t\t\tfmt.Println(object)\n\t\t*\/\n\t\treturn apply(object, \"PUT\", opts)\n\t}\n\t\/*\n\t\tif resp.StatusCode == http.StatusForbidden && opts.Overwrite {\n\n\t\t} else\n\t*\/\n\tif resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Unknown response:\\n%v\\n%v\", *(*string)(unsafe.Pointer(&b)), string(rb))\n\t}\n\n\tfmt.Printf(\"%v %v %v in %v\\n\", action, respType[fieldKind], getName(respType), opts.Namespace)\n\treturn respType, nil\n}\n\nfunc updateResourceVersion(source, target map[interface{}]interface{}) {\n\tif sourceMeta, sourceMetaFound := source[fieldMetadata].(map[interface{}]interface{}); sourceMetaFound {\n\t\tif sourceVersion, sourceVersionFound := sourceMeta[fieldResourceVersion]; sourceVersionFound {\n\t\t\tif targetMeta, targetMetaFound := target[fieldMetadata].(map[interface{}]interface{}); targetMetaFound {\n\t\t\t\tfmt.Println(\"setting v\", sourceVersion, reflect.TypeOf(sourceVersion).Kind())\n\t\t\t\ttargetMeta[fieldResourceVersion] = sourceVersion\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getName(obj map[interface{}]interface{}) string {\n\tif meta, metaFound := obj[fieldMetadata].(map[interface{}]interface{}); metaFound {\n\t\tif name, nameFound := meta[fieldName].(string); nameFound {\n\t\t\treturn name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc parseObjects(source string, namespace string) ([]map[interface{}]interface{}, error) {\n\tvar template map[interface{}]interface{}\n\n\terr := yaml.Unmarshal([]byte(source), &template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif template[fieldKind] == valTemplate || template[fieldKind] == valList {\n\t\tvar ts []interface{}\n\t\tif template[fieldKind] == valTemplate {\n\t\t\tts = template[fieldObjects].([]interface{})\n\t\t} else if template[fieldKind] == valList {\n\t\t\tts = template[fieldItems].([]interface{})\n\t\t}\n\t\tvar objs []map[interface{}]interface{}\n\t\tfor _, obj := range ts {\n\t\t\tobjs = append(objs, obj.(map[interface{}]interface{}))\n\t\t}\n\t\tif namespace != \"\" {\n\t\t\tfor _, obj := range objs {\n\t\t\t\tif val, ok := obj[fieldMetadata].(map[interface{}]interface{}); ok {\n\t\t\t\t\tif _, ok := val[fieldNamespace]; !ok {\n\t\t\t\t\t\tval[fieldNamespace] = namespace\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn objs, nil\n\t}\n\treturn []map[interface{}]interface{}{template}, nil\n}\n\n\/\/ TODO: a bit off now that there are multiple Action methods\nfunc allKnownTypes(objects []map[interface{}]interface{}) error {\n\tm := multiError{}\n\tfor _, obj := range objects {\n\t\tif _, ok := endpoints[\"POST\"][obj[fieldKind].(string)]; !ok {\n\t\t\tm.Errors = append(m.Errors, fmt.Errorf(\"Unknown type: %v\", obj[fieldKind]))\n\t\t}\n\t}\n\tif len(m.Errors) > 0 {\n\t\treturn m\n\t}\n\treturn nil\n}\n\nfunc createURL(hostURL, action string, object map[interface{}]interface{}) (string, error) {\n\turlTemplate, found := endpoints[action][object[fieldKind].(string)]\n\tif !found {\n\t\treturn \"\", nil\n\t}\n\ttarget, err := template.New(\"url\").Parse(urlTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\terr = target.Execute(&buf, object)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tstr := buf.String()\n\treturn hostURL + str, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Functions for generating images of fractal sets\npackage fract\n\nimport (\n\t\"image\"\n\t\"math\/cmplx\"\n)\n\nconst MaxIterations = 10000\n\n\/\/ Fractal image receiver\ntype Image interface {\n\tSetPixel(x, y, iterations int)\n\tBounds() image.Rectangle\n}\n\n\/\/ Generate Mandelbrot set\nfunc Mandelbrot(img Image, min, max complex128) {\n\tb := img.Bounds()\n\tdr := real(max-min) \/ float64(b.Dx())\n\tdi := imag(max-min) \/ float64(b.Dy())\n\n\tch := make(chan bool, b.Dx()*b.Dy())\n\n\tfor x := 0; x < b.Dx(); x++ {\n\t\tfor y := 0; y < b.Dy(); y++ {\n\t\t\tgo func() {\n\t\t\t\tz := complex(0, 0)\n\t\t\t\tc := min + complex(float64(x)*dr, float64(y)*di)\n\n\t\t\t\tn := 0\n\t\t\t\tfor ; n < MaxIterations; n++ {\n\t\t\t\t\tz = z*z + c\n\t\t\t\t\tif cmplx.Abs(z) > 2.0 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\timg.SetPixel(x+b.Min.X, y+b.Min.Y, n)\n\t\t\t\tch <- true\n\t\t\t}()\n\t\t}\n\t}\n\n\t\/\/ wait for all go routines to finish\n\tfor i := 0; i < b.Dx()*b.Dy(); i++ {\n\t\t<-ch\n\t}\n}\n<commit_msg>Add ColorImage type<commit_after>\/\/ Functions for generating images of fractal sets\npackage fract\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"math\/cmplx\"\n)\n\nconst MaxIterations = 10000\n\n\/\/ Fractal image receiver\ntype Image interface {\n\tSetPixel(x, y, iterations int)\n\tBounds() image.Rectangle\n}\n\n\/\/ Generate Mandelbrot set\nfunc Mandelbrot(img Image, min, max complex128) {\n\tb := img.Bounds()\n\tdr := real(max-min) \/ float64(b.Dx())\n\tdi := imag(max-min) \/ float64(b.Dy())\n\n\tch := make(chan bool, b.Dx()*b.Dy())\n\n\tfor x := 0; x < b.Dx(); x++ {\n\t\tfor y := 0; y < b.Dy(); y++ {\n\t\t\tgo func() {\n\t\t\t\tz := complex(0, 0)\n\t\t\t\tc := min + complex(float64(x)*dr, float64(y)*di)\n\n\t\t\t\tn := 0\n\t\t\t\tfor ; n < MaxIterations; n++ {\n\t\t\t\t\tz = z*z + c\n\t\t\t\t\tif cmplx.Abs(z) > 2.0 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\timg.SetPixel(x+b.Min.X, y+b.Min.Y, n)\n\t\t\t\tch <- true\n\t\t\t}()\n\t\t}\n\t}\n\n\t\/\/ wait for all go routines to finish\n\tfor i := 0; i < b.Dx()*b.Dy(); i++ {\n\t\t<-ch\n\t}\n}\n\ntype ColorImage struct {\n\trgb image.RGBA\n}\n\nfunc (img *ColorImage) SetPixel(x, y, iterations int) {\n\tcolor := color.RGBA{128, 0, 0, 0}\n\timg.rgb.Set(x, y, color)\n}\n\nfunc (img *ColorImage) Bounds() image.Rectangle {\n\treturn img.rgb.Bounds()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package frame provides plan9-like editable text images on a raster display. This implementation\n\/\/ preserves NUL bytes, and uses a set of replacement characters for undenderable text glyphs generated\n\/\/ with a smaller sized font (hexidecimal or ascii representation).\n\/\/\n\/\/ A frame's text is not addressable\npackage frame\n\nimport (\n\t\"github.com\/as\/frame\/box\"\n\t\"github.com\/as\/text\"\n\t\"image\"\n\t\"image\/draw\"\n)\n\nconst (\n\tTickWidth = 3\n\ttickOff   = 0\n\ttickOn    = 1\n)\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\treturn f.b\n}\nfunc (f *Frame) Size() image.Point {\n\tr := f.RGBA().Bounds()\n\treturn image.Pt(r.Dx(), r.Dy())\n}\n\ntype Frame struct {\n\tbox.Run\n\tColor\n\tFont         Font\n\tb            *image.RGBA\n\tr, entire    image.Rectangle\n\tmaxtab       int\n\tlastlinefull int\n\n\tp0 int64\n\tp1 int64\n\n\ttick      draw.Image\n\ttickback  draw.Image\n\tTicked    bool\n\ttickscale int\n\ttickoff   bool\n\tmaxlines  int\n\tmodified  bool\n\tnoredraw  bool\n\top        draw.Op\n\n\ttext.Drawer\n\n\t\/\/\tnpts int\n\tpts [][2]image.Point\n\n\tScroll func(int)\n\tfr     *Frame\n\n\thexFont *Font\n\thex     []draw.Image\n}\n\n\/\/ New creates a new frame on b with bounds r. The image b is used\n\/\/ as the frame's internal bitmap cache.\nfunc New(r image.Rectangle, ft Font, b *image.RGBA, cols Color) *Frame {\n\tf := &Frame{\n\t\tFont:   ft,\n\t\tmaxtab: 4 * ft.Measure(' '),\n\t\tColor:  cols,\n\t\tRun:    box.Run{Measure: ft.MeasureBytes},\n\t\top:     draw.Src,\n\t}\n\tf.setrects(r, b)\n\tf.inittick()\n\tf.fr = new(Frame)\n\tf.renderHex()\n\tf.Drawer = text.NewCached()\n\treturn f\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft Font) {\n\tf.r = r\n\tf.b = b\n\tf.Font = ft\n\tf.Run.Reset(f.Font.MeasureBytes)\n}\n\n\/\/ Dx returns the width of s in pixels\nfunc (f *Frame) Dx(s string) int {\n\treturn f.Font.Dx(s)\n}\n\n\/\/ Dy returns the height of a glyphs bounding box\nfunc (f *Frame) Dy() int {\n\treturn f.Font.Dy()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\nfunc (f *Frame) SetTick(style int) {\n\tf.tickoff = style == tickOff\n}\n\n\/\/ Full returns true if the last line in the frame is full\nfunc (f *Frame) Full() bool {\n\treturn f.lastlinefull == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\treturn f.Nlines\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\n\/\/ Select sets the range of the selected text\nfunc (f *Frame) Select(p0, p1 int64) {\n\tf.modified = true\n\tf.p0, f.p1 = p0, p1\n}\n\nfunc (f *Frame) inittick() {\n\th := f.Font.height + (f.Font.height \/ 5)\n\tr := image.Rect(0, 0, TickWidth, h)\n\tf.tickscale = 1 \/\/ TODO implement scalesize\n\tf.tick = image.NewRGBA(r)\n\tf.tickback = image.NewRGBA(r)\n\tdrawtick := func(x0, y0, x1, y1 int) {\n\t\tdraw.Draw(f.tick, image.Rect(x0, y0, x1, y1), f.Color.Text, image.ZP, draw.Src)\n\t}\n\tdrawtick(TickWidth\/2, 0, TickWidth\/2+1, h)\n\tdrawtick(0, 0, TickWidth, h\/5)\n\tdrawtick(0, h-h\/5, TickWidth, h)\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b *image.RGBA) {\n\tf.b = b\n\tf.entire = r\n\tf.r = r\n\tf.r.Max.Y -= f.r.Dy() % f.Font.height\n\tf.maxlines = f.r.Dy() \/ f.Font.height\n}\n\nfunc (f *Frame) clear(freeall bool) {\n\tif f.Nbox != 0 {\n\t\tf.Run.Delete(0, f.Nbox-1)\n\t}\n\tif f.Box != nil {\n\t\tfree(f.Box)\n\t}\n\tif freeall {\n\t\t\/\/ TODO: unnecessary\n\t\tfreeimage(f.tick)\n\t\tfreeimage(f.tickback)\n\t\tf.tick = nil\n\t\tf.tickback = nil\n\t}\n\tf.Box = nil\n\tf.Ticked = false\n}\n\nfunc free(i interface{}) {\n}\nfunc freeimage(i image.Image) {\n}\n<commit_msg>SetFont<commit_after>\/\/ Package frame provides plan9-like editable text images on a raster display. This implementation\n\/\/ preserves NUL bytes, and uses a set of replacement characters for undenderable text glyphs generated\n\/\/ with a smaller sized font (hexidecimal or ascii representation).\n\/\/\n\/\/ A frame's text is not addressable\npackage frame\n\nimport (\n\t\"github.com\/as\/frame\/box\"\n\t\"github.com\/as\/text\"\n\t\"image\"\n\t\"image\/draw\"\n)\n\nconst (\n\tTickWidth = 3\n\ttickOff   = 0\n\ttickOn    = 1\n)\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\treturn f.b\n}\nfunc (f *Frame) Size() image.Point {\n\tr := f.RGBA().Bounds()\n\treturn image.Pt(r.Dx(), r.Dy())\n}\n\ntype Frame struct {\n\tbox.Run\n\tColor\n\tFont         Font\n\tb            *image.RGBA\n\tr, entire    image.Rectangle\n\tmaxtab       int\n\tlastlinefull int\n\n\tp0 int64\n\tp1 int64\n\n\ttick      draw.Image\n\ttickback  draw.Image\n\tTicked    bool\n\ttickscale int\n\ttickoff   bool\n\tmaxlines  int\n\tmodified  bool\n\tnoredraw  bool\n\top        draw.Op\n\n\ttext.Drawer\n\n\t\/\/\tnpts int\n\tpts [][2]image.Point\n\n\tScroll func(int)\n\tfr     *Frame\n\n\thexFont *Font\n\thex     []draw.Image\n}\n\n\/\/ New creates a new frame on b with bounds r. The image b is used\n\/\/ as the frame's internal bitmap cache.\nfunc New(r image.Rectangle, ft Font, b *image.RGBA, cols Color) *Frame {\n\tf := &Frame{\n\t\tFont:   ft,\n\t\tmaxtab: 4 * ft.Measure(' '),\n\t\tColor:  cols,\n\t\tRun:    box.Run{Measure: ft.MeasureBytes},\n\t\top:     draw.Src,\n\t}\n\tf.setrects(r, b)\n\tf.inittick()\n\tf.fr = new(Frame)\n\tf.renderHex()\n\tf.Drawer = text.NewCached()\n\treturn f\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft Font) {\n\tf.r = r\n\tf.b = b\n}\n\nfunc (f *Frame) SetFont(ft Font){\n\tf.Font = ft\n\tf.Run.Reset(f.Font.MeasureBytes)\n\tf.Refresh()\n}\n\n\/\/ Dx returns the width of s in pixels\nfunc (f *Frame) Dx(s string) int {\n\treturn f.Font.Dx(s)\n}\n\n\/\/ Dy returns the height of a glyphs bounding box\nfunc (f *Frame) Dy() int {\n\treturn f.Font.Dy()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\nfunc (f *Frame) SetTick(style int) {\n\tf.tickoff = style == tickOff\n}\n\n\/\/ Full returns true if the last line in the frame is full\nfunc (f *Frame) Full() bool {\n\treturn f.lastlinefull == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\treturn f.Nlines\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\n\/\/ Select sets the range of the selected text\nfunc (f *Frame) Select(p0, p1 int64) {\n\tf.modified = true\n\tf.p0, f.p1 = p0, p1\n}\n\nfunc (f *Frame) inittick() {\n\th := f.Font.height + (f.Font.height \/ 5)\n\tr := image.Rect(0, 0, TickWidth, h)\n\tf.tickscale = 1 \/\/ TODO implement scalesize\n\tf.tick = image.NewRGBA(r)\n\tf.tickback = image.NewRGBA(r)\n\tdrawtick := func(x0, y0, x1, y1 int) {\n\t\tdraw.Draw(f.tick, image.Rect(x0, y0, x1, y1), f.Color.Text, image.ZP, draw.Src)\n\t}\n\tdrawtick(TickWidth\/2, 0, TickWidth\/2+1, h)\n\tdrawtick(0, 0, TickWidth, h\/5)\n\tdrawtick(0, h-h\/5, TickWidth, h)\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b *image.RGBA) {\n\tf.b = b\n\tf.entire = r\n\tf.r = r\n\tf.r.Max.Y -= f.r.Dy() % f.Font.height\n\tf.maxlines = f.r.Dy() \/ f.Font.height\n}\n\nfunc (f *Frame) clear(freeall bool) {\n\tif f.Nbox != 0 {\n\t\tf.Run.Delete(0, f.Nbox-1)\n\t}\n\tif f.Box != nil {\n\t\tfree(f.Box)\n\t}\n\tif freeall {\n\t\t\/\/ TODO: unnecessary\n\t\tfreeimage(f.tick)\n\t\tfreeimage(f.tickback)\n\t\tf.tick = nil\n\t\tf.tickback = nil\n\t}\n\tf.Box = nil\n\tf.Ticked = false\n}\n\nfunc free(i interface{}) {\n}\nfunc freeimage(i image.Image) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/breunigs\/frank\/frank\"\n\tirc \"github.com\/fluffle\/goirc\/client\"\n\t\"log\"\n\t\"strings\"\n)\n\n\/\/~ const instaJoin = \"#chaos-hd\"\nconst instaJoin = \"#test\"\n\nconst nickServPass = \"k6CA9b9cfrLAPKmjlJGTIDO2bRyTN6\"\n\nconst ircServer = \"irc.twice-irc.de\"\n\nfunc main() {\n\tflag.Parse() \/\/ parses the logging flags. TODO\n\n\tc := irc.SimpleClient(\"frank\", \"frank\", \"Frank Böterrich der Zweite\")\n\tc.SSL = true\n\n\t\/\/ connect\n\tc.AddHandler(irc.CONNECTED,\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\tlog.Printf(\"Connected as: %s\\n\", conn.Me.Nick)\n\t\t\tconn.Privmsg(\"nickserv\", \"identify \"+nickServPass)\n\t\t\tfor _, cn := range strings.Split(instaJoin, \" \") {\n\t\t\t\tif cn != \"\" {\n\t\t\t\t\tconn.Join(cn)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\/\/ react\n\tc.AddHandler(\"PRIVMSG\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\t\/\/~ tgt := line.Args[0]\n\t\t\t\/\/~ msg := line.Args[1]\n\n\t\t\tgo func() { frank.RaumBang(conn, line) }()\n\t\t\tgo func() { frank.UriFind(conn, line) }()\n\n\t\t\t\/\/~ log.Printf(\"      Debug: tgt: %s, msg: %s\\n\", tgt, msg)\n\t\t})\n\n\t\/\/ auto follow invites\n\tc.AddHandler(\"INVITE\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\ttgt := line.Args[0]\n\t\t\tcnnl := line.Args[1]\n\t\t\tif conn.Me.Nick != tgt {\n\t\t\t\tlog.Printf(\"WTF: received invite for %s but target was %s\\n\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Printf(\"Following invite for channel: %s\\n\", cnnl)\n\t\t\tconn.Join(cnnl)\n\t\t})\n\n\t\/\/ auto deop frank\n\tc.AddHandler(\"MODE\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\tif len(line.Args) != 3 {\n\t\t\t\t\/\/ mode statement cannot be not in a channel, so ignore\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif line.Args[2] != conn.Me.Nick {\n\t\t\t\t\/\/ not referring to us\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif line.Args[1] != \"+o\" {\n\t\t\t\t\/\/ not relevant\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcn := line.Args[0]\n\t\t\tconn.Mode(cn, \"+v\", conn.Me.Nick)\n\t\t\tconn.Mode(cn, \"-o\", conn.Me.Nick)\n\t\t\tconn.Privmsg(cn, line.Nick+\": SKYNET® Protection activated\")\n\t\t})\n\n\t\/\/ disconnect\n\tquit := make(chan bool)\n\tc.AddHandler(irc.DISCONNECTED,\n\t\tfunc(conn *irc.Conn, line *irc.Line) { quit <- true })\n\n\t\/\/ go go GO!\n\tif err := c.Connect(ircServer); err != nil {\n\t\tlog.Printf(\"Connection error: %s\\n\", err)\n\t}\n\n\tlog.Printf(\"Frank has booted\\n\")\n\n\t\/\/ Wait for disconnect\n\t<-quit\n}\n<commit_msg>implement help in private query.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/breunigs\/frank\/frank\"\n\tirc \"github.com\/fluffle\/goirc\/client\"\n\t\"log\"\n\t\"strings\"\n)\n\n\/\/~ const instaJoin = \"#chaos-hd\"\nconst instaJoin = \"#test\"\n\nconst nickServPass = \"\"\n\nconst ircServer = \"irc.twice-irc.de\"\n\nfunc main() {\n\tflag.Parse() \/\/ parses the logging flags. TODO\n\n\tc := irc.SimpleClient(\"frank\", \"frank\", \"Frank Böterrich der Zweite\")\n\tc.SSL = true\n\n\t\/\/ connect\n\tc.AddHandler(irc.CONNECTED,\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\tlog.Printf(\"Connected as: %s\\n\", conn.Me.Nick)\n\t\t\tconn.Privmsg(\"nickserv\", \"identify \"+nickServPass)\n\t\t\tfor _, cn := range strings.Split(instaJoin, \" \") {\n\t\t\t\tif cn != \"\" {\n\t\t\t\t\tconn.Join(cn)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\n\t\/\/ react\n\tc.AddHandler(\"PRIVMSG\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\t\/\/~ tgt := line.Args[0]\n\t\t\t\/\/~ msg := line.Args[1]\n\n\t\t\tgo func() { frank.RaumBang(conn, line) }()\n\t\t\tgo func() { frank.UriFind(conn, line) }()\n\n\t\t\tif line.Args[0] == conn.Me.nick && line.Args[1] == \"help\" {\n\t\t\t\tconn.Privmsg(line.Nick, \"It’s a game to find out what \" + conn.Me.Nick + \"can do.\");\n\t\t\t\tconn.Privmsg(line.Nick, \"1. Most likely I can find out the <title> of an URL, if:\");\n\t\t\t\tconn.Privmsg(line.Nick, \"  – I am in the channel where it is posted\");\n\t\t\t\tconn.Privmsg(line.Nick, \"  – you sent it in a query to me\");\n\t\t\t\tconn.Privmsg(line.Nick, \"  I’m going to cache that URL for a certain amount of time.\");\n\t\t\t\tconn.Privmsg(line.Nick, \"2. I’ll answer to !raum in certain channels.\");\n\t\t\t\tconn.Privmsg(line.Nick, \"If you need more details, please look at my source:\");\n\t\t\t\tconn.Privmsg(line.Nick, \"https:\/\/github.com\/breunigs\/frank\");\n\t\t\t}\n\n\t\t\t\/\/~ log.Printf(\"      Debug: tgt: %s, msg: %s\\n\", tgt, msg)\n\t\t})\n\n\t\/\/ auto follow invites\n\tc.AddHandler(\"INVITE\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\ttgt := line.Args[0]\n\t\t\tcnnl := line.Args[1]\n\t\t\tif conn.Me.Nick != tgt {\n\t\t\t\tlog.Printf(\"WTF: received invite for %s but target was %s\\n\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Printf(\"Following invite for channel: %s\\n\", cnnl)\n\t\t\tconn.Join(cnnl)\n\t\t})\n\n\t\/\/ auto deop frank\n\tc.AddHandler(\"MODE\",\n\t\tfunc(conn *irc.Conn, line *irc.Line) {\n\t\t\tif len(line.Args) != 3 {\n\t\t\t\t\/\/ mode statement cannot be not in a channel, so ignore\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif line.Args[2] != conn.Me.Nick {\n\t\t\t\t\/\/ not referring to us\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif line.Args[1] != \"+o\" {\n\t\t\t\t\/\/ not relevant\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tcn := line.Args[0]\n\t\t\tconn.Mode(cn, \"+v\", conn.Me.Nick)\n\t\t\tconn.Mode(cn, \"-o\", conn.Me.Nick)\n\t\t\tconn.Privmsg(cn, line.Nick+\": SKYNET® Protection activated\")\n\t\t})\n\n\t\/\/ disconnect\n\tquit := make(chan bool)\n\tc.AddHandler(irc.DISCONNECTED,\n\t\tfunc(conn *irc.Conn, line *irc.Line) { quit <- true })\n\n\t\/\/ go go GO!\n\tif err := c.Connect(ircServer); err != nil {\n\t\tlog.Printf(\"Connection error: %s\\n\", err)\n\t}\n\n\tlog.Printf(\"Frank has booted\\n\")\n\n\t\/\/ Wait for disconnect\n\t<-quit\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2012 Mostafa Hajizadeh\n\/\/ Copyright (C) 2014-5 Steve Francia\n\n\/\/ package fsync keeps two files or directories in sync.\n\/\/\n\/\/         err := fsync.Sync(\"~\/dst\", \".\")\n\/\/\n\/\/ After the above code, if err is nil, every file and directory in the current\n\/\/ directory is copied to ~\/dst and has the same permissions. Consequent calls\n\/\/ will only copy changed or new files.\n\/\/\n\/\/ SyncTo is a helper function which helps you sync a groups of files or\n\/\/ directories into a single destination. For instance, calling\n\/\/\n\/\/     SyncTo(\"public\", \"build\/app.js\", \"build\/app.css\", \"images\", \"fonts\")\n\/\/\n\/\/ is equivalent to calling\n\/\/\n\/\/     Sync(\"public\/app.js\", \"build\/app.js\")\n\/\/     Sync(\"public\/app.css\", \"build\/app.css\")\n\/\/     Sync(\"public\/images\", \"images\")\n\/\/     Sync(\"public\/fonts\", \"fonts\")\n\/\/\n\/\/ Actually, this is how SyncTo is implemented: consequent calls to Sync.\n\/\/\n\/\/ By default, sync code ignores extra files in the destination that don’t have\n\/\/ identicals in the source. Setting Delete field of a Syncer to true changes\n\/\/ this behavior and deletes these extra files.\n\npackage fsync\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/spf13\/afero\"\n)\n\nvar (\n\tErrFileOverDir = errors.New(\n\t\t\"fsync: trying to overwrite a non-empty directory with a file\")\n)\n\n\/\/ Sync copies files and directories inside src into dst.\nfunc Sync(dst, src string) error {\n\treturn NewSyncer().Sync(dst, src)\n}\n\n\/\/ SyncTo syncs srcs files and directories into to directory.\nfunc SyncTo(to string, srcs ...string) error {\n\treturn NewSyncer().SyncTo(to, srcs...)\n}\n\n\/\/ Type Syncer provides functions for syncing files.\ntype Syncer struct {\n\t\/\/ Set this to true to delete files in the destination that don't exist\n\t\/\/ in the source.\n\tDelete bool\n\t\/\/ By default, modification times are synced. This can be turned off by\n\t\/\/ setting this to true.\n\tNoTimes bool\n\t\/\/ TODO add options for not checking content for equality\n\n\tSrcFs  afero.Fs\n\tDestFs afero.Fs\n}\n\n\/\/ NewSyncer creates a new instance of Syncer with default options.\nfunc NewSyncer() *Syncer {\n\treturn &Syncer{SrcFs: new(afero.OsFs), DestFs: new(afero.OsFs)}\n}\n\n\/\/ Sync copies files and directories inside src into dst.\nfunc (s *Syncer) Sync(dst, src string) error {\n\t\/\/ make sure src exists\n\tif _, err := s.SrcFs.Stat(src); err != nil {\n\t\treturn err\n\t}\n\t\/\/ return error instead of replacing a non-empty directory with a file\n\tif b, err := s.checkDir(dst, src); err != nil {\n\t\treturn err\n\t} else if b {\n\t\treturn ErrFileOverDir\n\t}\n\n\treturn s.syncRecover(dst, src)\n}\n\n\/\/ SyncTo syncs srcs files or directories into to directory.\nfunc (s *Syncer) SyncTo(to string, srcs ...string) error {\n\tfor _, src := range srcs {\n\t\tdst := filepath.Join(to, path.Base(src))\n\t\tif err := s.Sync(dst, src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ syncRecover handles errors and calls sync\nfunc (s *Syncer) syncRecover(dst, src string) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif _, ok := r.(runtime.Error); ok {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\n\ts.sync(dst, src)\n\treturn nil\n}\n\n\/\/ sync updates dst to match with src, handling both files and directories.\nfunc (s *Syncer) sync(dst, src string) {\n\t\/\/ sync permissions and modification times after handling content\n\tdefer s.syncstats(dst, src)\n\n\t\/\/ read files info\n\tdstat, err := s.SrcFs.Stat(dst)\n\tif err != nil && !os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\tsstat, err := s.SrcFs.Stat(src)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn \/\/ src was deleted before we could copy it\n\t}\n\tcheck(err)\n\n\tif !sstat.IsDir() {\n\t\t\/\/ src is a file\n\t\t\/\/ delete dst if its a directory\n\t\tif dstat != nil && dstat.IsDir() {\n\t\t\tcheck(s.DestFs.RemoveAll(dst))\n\t\t}\n\t\tif !s.equal(dst, src) {\n\t\t\t\/\/ perform copy\n\t\t\tdf, err := s.DestFs.Create(dst)\n\t\t\tcheck(err)\n\t\t\tdefer df.Close()\n\t\t\tsf, err := s.SrcFs.Open(src)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheck(err)\n\t\t\tdefer sf.Close()\n\t\t\t_, err = io.Copy(df, sf)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheck(err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ src is a directory\n\t\/\/ make dst if necessary\n\tif dstat == nil {\n\t\t\/\/ dst does not exist; create directory\n\t\tcheck(s.DestFs.MkdirAll(dst, 0755)) \/\/ permissions will be synced later\n\t} else if !dstat.IsDir() {\n\t\t\/\/ dst is a file; remove and create directory\n\t\tcheck(s.DestFs.Remove(dst))\n\t\tcheck(s.DestFs.MkdirAll(dst, 0755)) \/\/ permissions will be synced later\n\t}\n\n\t\/\/ go through sf files and sync them\n\tfiles, err := afero.ReadDir(s.SrcFs, src)\n\tif os.IsNotExist(err) {\n\t\treturn\n\t}\n\tcheck(err)\n\t\/\/ make a map of filenames for quick lookup; used in deletion\n\t\/\/ deletion below\n\tm := make(map[string]bool, len(files))\n\tfor _, file := range files {\n\t\tdst2 := filepath.Join(dst, file.Name())\n\t\tsrc2 := filepath.Join(src, file.Name())\n\t\ts.sync(dst2, src2)\n\t\tm[file.Name()] = true\n\t}\n\n\t\/\/ delete files from dst that does not exist in src\n\tif s.Delete {\n\t\tfiles, err = afero.ReadDir(s.DestFs, dst)\n\t\tcheck(err)\n\t\tfor _, file := range files {\n\t\t\tif !m[file.Name()] {\n\t\t\t\tcheck(s.DestFs.RemoveAll(filepath.Join(dst, file.Name())))\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ syncstats makes sure dst has the same pemissions and modification time as src\nfunc (s *Syncer) syncstats(dst, src string) {\n\t\/\/ get file infos; return if not exist and panic if error\n\tdstat, err1 := s.DestFs.Stat(dst)\n\tsstat, err2 := s.SrcFs.Stat(src)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\treturn\n\t}\n\tcheck(err1)\n\tcheck(err2)\n\n\t\/\/ update dst's permission bits\n\tif dstat.Mode().Perm() != sstat.Mode().Perm() {\n\t\tcheck(s.DestFs.Chmod(dst, sstat.Mode().Perm()))\n\t}\n\n\t\/\/ update dst's modification time\n\tif !s.NoTimes {\n\t\tif !dstat.ModTime().Equal(sstat.ModTime()) {\n\t\t\terr := s.DestFs.Chtimes(dst, sstat.ModTime(), sstat.ModTime())\n\t\t\tcheck(err)\n\t\t}\n\t}\n}\n\n\/\/ equal returns true if both files are equal\nfunc (s *Syncer) equal(a, b string) bool {\n\t\/\/ get file infos\n\tinfo1, err1 := os.Stat(a)\n\tinfo2, err2 := os.Stat(b)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\treturn false\n\t}\n\tcheck(err1)\n\tcheck(err2)\n\n\t\/\/ check sizes\n\tif info1.Size() != info2.Size() {\n\t\treturn false\n\t}\n\n\t\/\/ both have the same size, check the contents\n\tf1, err := os.Open(a)\n\tcheck(err)\n\tdefer f1.Close()\n\tf2, err := os.Open(b)\n\tcheck(err)\n\tdefer f2.Close()\n\tbuf1 := make([]byte, 1000)\n\tbuf2 := make([]byte, 1000)\n\tfor {\n\t\t\/\/ read from both\n\t\tn1, err := f1.Read(buf1)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\t\tn2, err := f2.Read(buf2)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ compare read bytes\n\t\tif !bytes.Equal(buf1[:n1], buf2[:n2]) {\n\t\t\treturn false\n\t\t}\n\n\t\t\/\/ end of both files\n\t\tif n1 == 0 && n2 == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ checkDir returns true if dst is a non-empty directory and src is a file\nfunc (s *Syncer) checkDir(dst, src string) (b bool, err error) {\n\t\/\/ read file info\n\tdstat, err := os.Stat(dst)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tsstat, err := os.Stat(src)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ return false is dst is not a directory or src is a directory\n\tif !dstat.IsDir() || sstat.IsDir() {\n\t\treturn false, nil\n\t}\n\n\t\/\/ dst is a directory and src is a file\n\t\/\/ check if dst is non-empty\n\t\/\/ read dst directory\n\n\tfiles, err := afero.ReadDir(s.DestFs, dst)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(files) > 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>fix spf13\/hugo#1800, typo found by @Skrylar<commit_after>\/\/ Copyright (C) 2012 Mostafa Hajizadeh\n\/\/ Copyright (C) 2014-5 Steve Francia\n\n\/\/ package fsync keeps two files or directories in sync.\n\/\/\n\/\/         err := fsync.Sync(\"~\/dst\", \".\")\n\/\/\n\/\/ After the above code, if err is nil, every file and directory in the current\n\/\/ directory is copied to ~\/dst and has the same permissions. Consequent calls\n\/\/ will only copy changed or new files.\n\/\/\n\/\/ SyncTo is a helper function which helps you sync a groups of files or\n\/\/ directories into a single destination. For instance, calling\n\/\/\n\/\/     SyncTo(\"public\", \"build\/app.js\", \"build\/app.css\", \"images\", \"fonts\")\n\/\/\n\/\/ is equivalent to calling\n\/\/\n\/\/     Sync(\"public\/app.js\", \"build\/app.js\")\n\/\/     Sync(\"public\/app.css\", \"build\/app.css\")\n\/\/     Sync(\"public\/images\", \"images\")\n\/\/     Sync(\"public\/fonts\", \"fonts\")\n\/\/\n\/\/ Actually, this is how SyncTo is implemented: consequent calls to Sync.\n\/\/\n\/\/ By default, sync code ignores extra files in the destination that don’t have\n\/\/ identicals in the source. Setting Delete field of a Syncer to true changes\n\/\/ this behavior and deletes these extra files.\n\npackage fsync\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/spf13\/afero\"\n)\n\nvar (\n\tErrFileOverDir = errors.New(\n\t\t\"fsync: trying to overwrite a non-empty directory with a file\")\n)\n\n\/\/ Sync copies files and directories inside src into dst.\nfunc Sync(dst, src string) error {\n\treturn NewSyncer().Sync(dst, src)\n}\n\n\/\/ SyncTo syncs srcs files and directories into to directory.\nfunc SyncTo(to string, srcs ...string) error {\n\treturn NewSyncer().SyncTo(to, srcs...)\n}\n\n\/\/ Type Syncer provides functions for syncing files.\ntype Syncer struct {\n\t\/\/ Set this to true to delete files in the destination that don't exist\n\t\/\/ in the source.\n\tDelete bool\n\t\/\/ By default, modification times are synced. This can be turned off by\n\t\/\/ setting this to true.\n\tNoTimes bool\n\t\/\/ TODO add options for not checking content for equality\n\n\tSrcFs  afero.Fs\n\tDestFs afero.Fs\n}\n\n\/\/ NewSyncer creates a new instance of Syncer with default options.\nfunc NewSyncer() *Syncer {\n\treturn &Syncer{SrcFs: new(afero.OsFs), DestFs: new(afero.OsFs)}\n}\n\n\/\/ Sync copies files and directories inside src into dst.\nfunc (s *Syncer) Sync(dst, src string) error {\n\t\/\/ make sure src exists\n\tif _, err := s.SrcFs.Stat(src); err != nil {\n\t\treturn err\n\t}\n\t\/\/ return error instead of replacing a non-empty directory with a file\n\tif b, err := s.checkDir(dst, src); err != nil {\n\t\treturn err\n\t} else if b {\n\t\treturn ErrFileOverDir\n\t}\n\n\treturn s.syncRecover(dst, src)\n}\n\n\/\/ SyncTo syncs srcs files or directories into to directory.\nfunc (s *Syncer) SyncTo(to string, srcs ...string) error {\n\tfor _, src := range srcs {\n\t\tdst := filepath.Join(to, path.Base(src))\n\t\tif err := s.Sync(dst, src); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ syncRecover handles errors and calls sync\nfunc (s *Syncer) syncRecover(dst, src string) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif _, ok := r.(runtime.Error); ok {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\n\ts.sync(dst, src)\n\treturn nil\n}\n\n\/\/ sync updates dst to match with src, handling both files and directories.\nfunc (s *Syncer) sync(dst, src string) {\n\t\/\/ sync permissions and modification times after handling content\n\tdefer s.syncstats(dst, src)\n\n\t\/\/ read files info\n\tdstat, err := s.DestFs.Stat(dst)\n\tif err != nil && !os.IsNotExist(err) {\n\t\tpanic(err)\n\t}\n\tsstat, err := s.SrcFs.Stat(src)\n\tif err != nil && os.IsNotExist(err) {\n\t\treturn \/\/ src was deleted before we could copy it\n\t}\n\tcheck(err)\n\n\tif !sstat.IsDir() {\n\t\t\/\/ src is a file\n\t\t\/\/ delete dst if its a directory\n\t\tif dstat != nil && dstat.IsDir() {\n\t\t\tcheck(s.DestFs.RemoveAll(dst))\n\t\t}\n\t\tif !s.equal(dst, src) {\n\t\t\t\/\/ perform copy\n\t\t\tdf, err := s.DestFs.Create(dst)\n\t\t\tcheck(err)\n\t\t\tdefer df.Close()\n\t\t\tsf, err := s.SrcFs.Open(src)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheck(err)\n\t\t\tdefer sf.Close()\n\t\t\t_, err = io.Copy(df, sf)\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheck(err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ src is a directory\n\t\/\/ make dst if necessary\n\tif dstat == nil {\n\t\t\/\/ dst does not exist; create directory\n\t\tcheck(s.DestFs.MkdirAll(dst, 0755)) \/\/ permissions will be synced later\n\t} else if !dstat.IsDir() {\n\t\t\/\/ dst is a file; remove and create directory\n\t\tcheck(s.DestFs.Remove(dst))\n\t\tcheck(s.DestFs.MkdirAll(dst, 0755)) \/\/ permissions will be synced later\n\t}\n\n\t\/\/ go through sf files and sync them\n\tfiles, err := afero.ReadDir(s.SrcFs, src)\n\tif os.IsNotExist(err) {\n\t\treturn\n\t}\n\tcheck(err)\n\t\/\/ make a map of filenames for quick lookup; used in deletion\n\t\/\/ deletion below\n\tm := make(map[string]bool, len(files))\n\tfor _, file := range files {\n\t\tdst2 := filepath.Join(dst, file.Name())\n\t\tsrc2 := filepath.Join(src, file.Name())\n\t\ts.sync(dst2, src2)\n\t\tm[file.Name()] = true\n\t}\n\n\t\/\/ delete files from dst that does not exist in src\n\tif s.Delete {\n\t\tfiles, err = afero.ReadDir(s.DestFs, dst)\n\t\tcheck(err)\n\t\tfor _, file := range files {\n\t\t\tif !m[file.Name()] {\n\t\t\t\tcheck(s.DestFs.RemoveAll(filepath.Join(dst, file.Name())))\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ syncstats makes sure dst has the same pemissions and modification time as src\nfunc (s *Syncer) syncstats(dst, src string) {\n\t\/\/ get file infos; return if not exist and panic if error\n\tdstat, err1 := s.DestFs.Stat(dst)\n\tsstat, err2 := s.SrcFs.Stat(src)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\treturn\n\t}\n\tcheck(err1)\n\tcheck(err2)\n\n\t\/\/ update dst's permission bits\n\tif dstat.Mode().Perm() != sstat.Mode().Perm() {\n\t\tcheck(s.DestFs.Chmod(dst, sstat.Mode().Perm()))\n\t}\n\n\t\/\/ update dst's modification time\n\tif !s.NoTimes {\n\t\tif !dstat.ModTime().Equal(sstat.ModTime()) {\n\t\t\terr := s.DestFs.Chtimes(dst, sstat.ModTime(), sstat.ModTime())\n\t\t\tcheck(err)\n\t\t}\n\t}\n}\n\n\/\/ equal returns true if both files are equal\nfunc (s *Syncer) equal(a, b string) bool {\n\t\/\/ get file infos\n\tinfo1, err1 := os.Stat(a)\n\tinfo2, err2 := os.Stat(b)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\treturn false\n\t}\n\tcheck(err1)\n\tcheck(err2)\n\n\t\/\/ check sizes\n\tif info1.Size() != info2.Size() {\n\t\treturn false\n\t}\n\n\t\/\/ both have the same size, check the contents\n\tf1, err := os.Open(a)\n\tcheck(err)\n\tdefer f1.Close()\n\tf2, err := os.Open(b)\n\tcheck(err)\n\tdefer f2.Close()\n\tbuf1 := make([]byte, 1000)\n\tbuf2 := make([]byte, 1000)\n\tfor {\n\t\t\/\/ read from both\n\t\tn1, err := f1.Read(buf1)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\t\tn2, err := f2.Read(buf2)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ compare read bytes\n\t\tif !bytes.Equal(buf1[:n1], buf2[:n2]) {\n\t\t\treturn false\n\t\t}\n\n\t\t\/\/ end of both files\n\t\tif n1 == 0 && n2 == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ checkDir returns true if dst is a non-empty directory and src is a file\nfunc (s *Syncer) checkDir(dst, src string) (b bool, err error) {\n\t\/\/ read file info\n\tdstat, err := os.Stat(dst)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tsstat, err := os.Stat(src)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ return false is dst is not a directory or src is a directory\n\tif !dstat.IsDir() || sstat.IsDir() {\n\t\treturn false, nil\n\t}\n\n\t\/\/ dst is a directory and src is a file\n\t\/\/ check if dst is non-empty\n\t\/\/ read dst directory\n\n\tfiles, err := afero.ReadDir(s.DestFs, dst)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(files) > 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\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\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/fatih\/structs\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfunc Inspect(args ...interface{}) {\n\tspew.Dump(args)\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 empty\")\n\t}\n\tif sliceVal == nil {\n\t\treturn ret, errors.New(\"where: value is nil\")\n\t}\n\n\tif reflect.TypeOf(in).Kind() != reflect.Slice {\n\t\treturn ret, errors.New(\"where: source is no slice value\")\n\t}\n\n\ts := reflect.ValueOf(in)\n\tfor i := 0; i < s.Len(); i++ {\n\t\tval := s.Index(i)\n\n\t\tInspect(val)\n\t\tst := structs.New(val)\n\t\tfield, ok := st.FieldOk(sliceKey)\n\t\tif !ok {\n\t\t\treturn ret, errors.New(\"where: invalid input type\")\n\t\t}\n\t\tif field.Value() == sliceVal {\n\t\t\tret = append(ret, val)\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@1446222954<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\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/fatih\/structs\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfunc Inspect(args ...interface{}) {\n\tspew.Dump(args)\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 empty\")\n\t}\n\tif sliceVal == nil {\n\t\treturn ret, errors.New(\"where: value is nil\")\n\t}\n\n\tif reflect.TypeOf(in).Kind() != reflect.Slice {\n\t\treturn ret, errors.New(\"where: source is no slice value\")\n\t}\n\n\ts := reflect.ValueOf(in)\n\tfor i := 0; i < s.Len(); i++ {\n\t\tval := s.Index(i)\n\n\t\tInspect(val)\n\t\tst := structs.New(val.Interface())\n\t\tfield, ok := st.FieldOk(sliceKey)\n\t\tif !ok {\n\t\t\treturn ret, errors.New(\"where: invalid input type\")\n\t\t}\n\t\tif field.Value() == sliceVal {\n\t\t\tret = append(ret, val)\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>\/\/ 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\"os\"\n\t\"time\"\n\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\/plugin\"\n\t\"github.com\/getgauge\/gauge\/reporter\"\n\t\"github.com\/getgauge\/gauge\/version\"\n\n\t\"github.com\/getgauge\/gauge\/plugin\/install\"\n\t\"github.com\/getgauge\/gauge\/projectInit\"\n\t\"github.com\/getgauge\/gauge\/refactor\"\n\t\"github.com\/getgauge\/gauge\/util\"\n\tflag \"github.com\/getgauge\/mflag\"\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 pluginVersion = 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 strategy = flag.String([]string{\"-strategy\"}, \"lazy\", \"Set the parallelization strategy for execution. Possible options are: `eager`, `lazy`. Ex: gauge -p --strategy=\\\"eager\\\"\")\nvar doNotRandomize = flag.Bool([]string{\"-sort\", \"s\"}, false, \"Run specs in Alphabetical Order. Eg: gauge -s specs\")\nvar validate = flag.Bool([]string{\"-validate\", \"#-check\"}, false, \"Check for validation and parse errors. Eg: gauge --validate specs\")\nvar updateAll = flag.Bool([]string{\"-update-all\"}, false, \"Updates all the installed Gauge plugins. Eg: gauge --update-all\")\nvar checkUpdates = flag.Bool([]string{\"#-check-updates\"}, false, \"Checks for Gauge and plugins updates. Eg: gauge --check-updates\")\nvar listTemplates = flag.Bool([]string{\"-list-templates\"}, false, \"Lists all the Gauge templates available. Eg: gauge --list-templates\")\n\nfunc main() {\n\tflag.Parse()\n\tprojectInit.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(*logLevel)\n\tif *gaugeVersion {\n\t\tprintVersion()\n\t} else if *initialize != \"\" {\n\t\tprojectInit.InitializeProject(*initialize)\n\t} else if *installZip != \"\" && *installPlugin != \"\" {\n\t\tinstall.InstallPluginZip(*installZip, *installPlugin)\n\t} else if *installPlugin != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*installPlugin, *pluginVersion, \"Successfully installed plugin => %s\")\n\t} else if *uninstallPlugin != \"\" {\n\t\tinstall.UninstallPlugin(*uninstallPlugin, *pluginVersion)\n\t} else if *installAll {\n\t\tinstall.InstallAllPlugins()\n\t} else if *update != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*update, *pluginVersion, \"Successfully updated plugin => %s\")\n\t} else if *updateAll {\n\t\tinstall.UpdatePlugins()\n\t} else if *checkUpdates {\n\t\tinstall.PrintUpdateInfoWithDetails()\n\t} else if *addPlugin != \"\" {\n\t\tinstall.AddPluginToProject(*addPlugin, *pluginArgs)\n\t} else if *listTemplates {\n\t\tprojectInit.ListTemplates()\n\t} else if flag.NFlag() == 0 && len(flag.Args()) == 0 {\n\t\tprintUsage()\n\t\tos.Exit(0)\n\t} else if validGaugeProject {\n\t\tif *refactorSteps != \"\" {\n\t\t\tstartChan := api.StartAPI()\n\t\t\tif len(flag.Args()) != 1 {\n\t\t\t\tlogger.Error(\"flag needs two arguments: --refactor\\n.Usage : gauge --refactor {old step} {new step}\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trefactor.RefactorSteps(*refactorSteps, flag.Args()[0], startChan)\n\t\t} else if *daemonize {\n\t\t\tapi.RunInBackground(*apiPort)\n\t\t} else if *specFilesToFormat != \"\" {\n\t\t\tformatter.FormatSpecFilesIn(*specFilesToFormat)\n\t\t} else if *validate {\n\t\t\texecution.ParseAndValidateSpecs(flag.Args())\n\t\t} else {\n\t\t\texitCode := execution.ExecuteSpecs(*parallel, flag.Args())\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t} else {\n\t\tlogger.Error(err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nfunc printVersion() {\n\tfmt.Printf(\"Gauge version: %s\\n\\n\", version.CurrentGaugeVersion.String())\n\tfmt.Println(\"Plugins\\n-------\")\n\tallPluginsWithVersion, err := plugin.GetAllInstalledPluginsWithVersion()\n\tif err != nil {\n\t\tfmt.Println(\"No plugins found\")\n\t\tfmt.Println(\"Plugins can be installed with `gauge --install {plugin-name}`\")\n\t\tos.Exit(0)\n\t}\n\tfor _, pluginInfo := range allPluginsWithVersion {\n\t\tfmt.Printf(\"%s (%s)\\n\", pluginInfo.Name, pluginInfo.Version.String())\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}\n\nfunc initPackageFlags() {\n\tif *parallel {\n\t\t*simpleConsoleOutput = true\n\t}\n\treporter.SimpleConsoleOutput = *simpleConsoleOutput\n\treporter.Verbose = *verbosity\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\texecution.Strategy = *strategy\n\tif *distribute != -1 {\n\t\texecution.Strategy = execution.EAGER\n\t}\n}\n<commit_msg>updating verbose flag def<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\"os\"\n\t\"time\"\n\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\/plugin\"\n\t\"github.com\/getgauge\/gauge\/reporter\"\n\t\"github.com\/getgauge\/gauge\/version\"\n\n\t\"github.com\/getgauge\/gauge\/plugin\/install\"\n\t\"github.com\/getgauge\/gauge\/projectInit\"\n\t\"github.com\/getgauge\/gauge\/refactor\"\n\t\"github.com\/getgauge\/gauge\/util\"\n\tflag \"github.com\/getgauge\/mflag\"\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 step level reporting on console, default being scenario level. Eg: gauge --verbose specs\")\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 pluginVersion = 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 strategy = flag.String([]string{\"-strategy\"}, \"lazy\", \"Set the parallelization strategy for execution. Possible options are: `eager`, `lazy`. Ex: gauge -p --strategy=\\\"eager\\\"\")\nvar doNotRandomize = flag.Bool([]string{\"-sort\", \"s\"}, false, \"Run specs in Alphabetical Order. Eg: gauge -s specs\")\nvar validate = flag.Bool([]string{\"-validate\", \"#-check\"}, false, \"Check for validation and parse errors. Eg: gauge --validate specs\")\nvar updateAll = flag.Bool([]string{\"-update-all\"}, false, \"Updates all the installed Gauge plugins. Eg: gauge --update-all\")\nvar checkUpdates = flag.Bool([]string{\"#-check-updates\"}, false, \"Checks for Gauge and plugins updates. Eg: gauge --check-updates\")\nvar listTemplates = flag.Bool([]string{\"-list-templates\"}, false, \"Lists all the Gauge templates available. Eg: gauge --list-templates\")\n\nfunc main() {\n\tflag.Parse()\n\tprojectInit.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(*logLevel)\n\tif *gaugeVersion {\n\t\tprintVersion()\n\t} else if *initialize != \"\" {\n\t\tprojectInit.InitializeProject(*initialize)\n\t} else if *installZip != \"\" && *installPlugin != \"\" {\n\t\tinstall.InstallPluginZip(*installZip, *installPlugin)\n\t} else if *installPlugin != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*installPlugin, *pluginVersion, \"Successfully installed plugin => %s\")\n\t} else if *uninstallPlugin != \"\" {\n\t\tinstall.UninstallPlugin(*uninstallPlugin, *pluginVersion)\n\t} else if *installAll {\n\t\tinstall.InstallAllPlugins()\n\t} else if *update != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*update, *pluginVersion, \"Successfully updated plugin => %s\")\n\t} else if *updateAll {\n\t\tinstall.UpdatePlugins()\n\t} else if *checkUpdates {\n\t\tinstall.PrintUpdateInfoWithDetails()\n\t} else if *addPlugin != \"\" {\n\t\tinstall.AddPluginToProject(*addPlugin, *pluginArgs)\n\t} else if *listTemplates {\n\t\tprojectInit.ListTemplates()\n\t} else if flag.NFlag() == 0 && len(flag.Args()) == 0 {\n\t\tprintUsage()\n\t\tos.Exit(0)\n\t} else if validGaugeProject {\n\t\tif *refactorSteps != \"\" {\n\t\t\tstartChan := api.StartAPI()\n\t\t\tif len(flag.Args()) != 1 {\n\t\t\t\tlogger.Error(\"flag needs two arguments: --refactor\\n.Usage : gauge --refactor {old step} {new step}\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\trefactor.RefactorSteps(*refactorSteps, flag.Args()[0], startChan)\n\t\t} else if *daemonize {\n\t\t\tapi.RunInBackground(*apiPort)\n\t\t} else if *specFilesToFormat != \"\" {\n\t\t\tformatter.FormatSpecFilesIn(*specFilesToFormat)\n\t\t} else if *validate {\n\t\t\texecution.ParseAndValidateSpecs(flag.Args())\n\t\t} else {\n\t\t\texitCode := execution.ExecuteSpecs(*parallel, flag.Args())\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t} else {\n\t\tlogger.Error(err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nfunc printVersion() {\n\tfmt.Printf(\"Gauge version: %s\\n\\n\", version.CurrentGaugeVersion.String())\n\tfmt.Println(\"Plugins\\n-------\")\n\tallPluginsWithVersion, err := plugin.GetAllInstalledPluginsWithVersion()\n\tif err != nil {\n\t\tfmt.Println(\"No plugins found\")\n\t\tfmt.Println(\"Plugins can be installed with `gauge --install {plugin-name}`\")\n\t\tos.Exit(0)\n\t}\n\tfor _, pluginInfo := range allPluginsWithVersion {\n\t\tfmt.Printf(\"%s (%s)\\n\", pluginInfo.Name, pluginInfo.Version.String())\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}\n\nfunc initPackageFlags() {\n\tif *parallel {\n\t\t*simpleConsoleOutput = true\n\t}\n\treporter.SimpleConsoleOutput = *simpleConsoleOutput\n\treporter.Verbose = *verbosity\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\texecution.Strategy = *strategy\n\tif *distribute != -1 {\n\t\texecution.Strategy = execution.EAGER\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/pachyderm\/pachyderm\/src\/cmd\/pachctl\/cmd\"\n\t\"go.pedge.io\/env\"\n)\n\ntype appEnv struct {\n\tAddress string `env:\"PACH_ADDRESS,default=0.0.0.0:30650\"`\n}\n\nfunc main() {\n\tenv.Main(do, &appEnv{})\n}\n\nfunc do(appEnvObj interface{}) error {\n\tappEnv := appEnvObj.(*appEnv)\n\trootCmd, err := cmd.PachctlCmd(appEnv.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn rootCmd.Execute()\n}\n<commit_msg>Pachctl looks for ADDRESS not PACH_ADDRESS.<commit_after>package main\n\nimport (\n\t\"github.com\/pachyderm\/pachyderm\/src\/cmd\/pachctl\/cmd\"\n\t\"go.pedge.io\/env\"\n)\n\ntype appEnv struct {\n\tAddress string `env:\"ADDRESS,default=0.0.0.0:30650\"`\n}\n\nfunc main() {\n\tenv.Main(do, &appEnv{})\n}\n\nfunc do(appEnvObj interface{}) error {\n\tappEnv := appEnvObj.(*appEnv)\n\trootCmd, err := cmd.PachctlCmd(appEnv.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn rootCmd.Execute()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 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 helpers\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/cilium\/cilium\/test\/config\"\n\tginkgoext \"github.com\/cilium\/cilium\/test\/ginkgo-ext\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"golang.org\/x\/crypto\/ssh\"\n)\n\nvar (\n\t\/\/SSHMetaLogs is a buffer where all commands sent over ssh are saved.\n\tSSHMetaLogs = ginkgoext.NewWriter(new(bytes.Buffer))\n)\n\n\/\/ SSHMeta contains metadata to SSH into a remote location to run tests\ntype SSHMeta struct {\n\tsshClient *SSHClient\n\tenv       []string\n\trawConfig []byte\n\tnodeName  string\n\tlogger    *logrus.Entry\n}\n\n\/\/ CreateSSHMeta returns an SSHMeta with the specified host, port, and user, as\n\/\/ well as an according SSHClient.\nfunc CreateSSHMeta(host string, port int, user string) *SSHMeta {\n\treturn &SSHMeta{\n\t\tsshClient: GetSSHClient(host, port, user),\n\t}\n}\n\nfunc (s *SSHMeta) String() string {\n\treturn fmt.Sprintf(\"environment: %s, SSHClient: %s\", s.env, s.sshClient.String())\n\n}\n\n\/\/ GetVagrantSSHMeta returns a SSHMeta initialized based on the provided\n\/\/ SSH-config target.\nfunc GetVagrantSSHMeta(vmName string) *SSHMeta {\n\tconfig, err := GetVagrantSSHMetadata(vmName)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tlog.Debugf(\"generated SSHConfig for node %s\", vmName)\n\tnodes, err := ImportSSHconfig(config)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error importing ssh config\")\n\t\treturn nil\n\t}\n\tvar node *SSHConfig\n\tlog.Debugf(\"done importing ssh config\")\n\tfor name := range nodes {\n\t\tif strings.HasPrefix(name, vmName) {\n\t\t\tnode = nodes[name]\n\t\t\tbreak\n\t\t}\n\t}\n\tif node == nil {\n\t\tlog.Errorf(\"Node %s not found in ssh config\", vmName)\n\t\treturn nil\n\t}\n\tsshMeta := &SSHMeta{\n\t\tsshClient: node.GetSSHClient(),\n\t\trawConfig: config,\n\t\tnodeName:  vmName,\n\t}\n\n\tsshMeta.setBasePath()\n\treturn sshMeta\n}\n\n\/\/ setBasePath if the SSHConfig is defined we set the BasePath to the GOPATH,\n\/\/ from golang 1.8 GOPATH is by default $HOME\/go so we also check that.\nfunc (s *SSHMeta) setBasePath() {\n\tif config.CiliumTestConfig.SSHConfig == \"\" {\n\t\treturn\n\t}\n\n\tgopath := s.Exec(\"echo $GOPATH\").SingleOut()\n\tif gopath != \"\" {\n\t\tBasePath = filepath.Join(gopath, CiliumPath)\n\t\treturn\n\t}\n\n\thome := s.Exec(\"echo $HOME\").SingleOut()\n\tif home == \"\" {\n\t\treturn\n\t}\n\n\tBasePath = filepath.Join(home, \"go\", CiliumPath)\n\treturn\n}\n\n\/\/ Execute executes cmd on the provided node and stores the stdout \/ stderr of\n\/\/ the command in the provided buffers. Returns false if the command failed\n\/\/ during its execution.\nfunc (s *SSHMeta) Execute(cmd string, stdout io.Writer, stderr io.Writer) error {\n\tif stdout == nil {\n\t\tstdout = os.Stdout\n\t}\n\n\tif stderr == nil {\n\t\tstderr = os.Stderr\n\t}\n\tfmt.Fprintln(SSHMetaLogs, cmd)\n\tcommand := &SSHCommand{\n\t\tPath:   cmd,\n\t\tStdin:  os.Stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\terr := s.sshClient.RunCommand(command)\n\treturn err\n}\n\n\/\/ ExecWithSudo returns the result of executing the provided cmd via SSH using\n\/\/ sudo.\nfunc (s *SSHMeta) ExecWithSudo(cmd string, options ...ExecOptions) *CmdRes {\n\tcommand := fmt.Sprintf(\"sudo %s\", cmd)\n\treturn s.Exec(command, options...)\n}\n\n\/\/ ExecOptions options to execute Exec and ExecWithContext\ntype ExecOptions struct {\n\tSkipLog bool\n}\n\n\/\/ Exec returns the results of executing the provided cmd via SSH.\nfunc (s *SSHMeta) Exec(cmd string, options ...ExecOptions) *CmdRes {\n\tvar ops ExecOptions\n\tif len(options) > 0 {\n\t\tops = options[0]\n\t}\n\n\tlog.Debugf(\"running command: %s\", cmd)\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\texit := true\n\terr := s.Execute(cmd, stdout, stderr)\n\tif err != nil {\n\t\texit = false\n\t}\n\tres := CmdRes{\n\t\tcmd:     cmd,\n\t\tstdout:  stdout,\n\t\tstderr:  stderr,\n\t\tsuccess: exit,\n\t}\n\t\/\/ Set the exitCode if the error is an ExitError\n\tif exiterr, ok := err.(*ssh.ExitError); ok {\n\t\tres.exitcode = exiterr.Waitmsg.ExitStatus()\n\t}\n\tif !ops.SkipLog {\n\t\tres.SendToLog()\n\t}\n\treturn &res\n}\n\n\/\/ GetCopy returns a copy of SSHMeta, useful for parallel requests\nfunc (s *SSHMeta) GetCopy() *SSHMeta {\n\tnodes, err := ImportSSHconfig(s.rawConfig)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"while importing ssh config for meta copy\")\n\t\treturn nil\n\t}\n\n\tconfig := nodes[s.nodeName]\n\tif config == nil {\n\t\tlog.Errorf(\"no node %s in imported config\", s.nodeName)\n\t\treturn nil\n\t}\n\n\tcopy := &SSHMeta{\n\t\tsshClient: config.GetSSHClient(),\n\t\trawConfig: s.rawConfig,\n\t\tnodeName:  s.nodeName,\n\t}\n\n\treturn copy\n}\n\n\/\/ ExecContext returns the results of running cmd via SSH in the specified\n\/\/ context.\nfunc (s *SSHMeta) ExecContext(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes {\n\tif ctx == nil {\n\t\tpanic(\"no context provided\")\n\t}\n\n\tvar ops ExecOptions\n\tif len(options) > 0 {\n\t\tops = options[0]\n\t}\n\n\tfmt.Fprintln(SSHMetaLogs, cmd)\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\n\tcommand := &SSHCommand{\n\t\tPath:   cmd,\n\t\tStdin:  os.Stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\n\tres := CmdRes{\n\t\tcmd:     cmd,\n\t\tstdout:  stdout,\n\t\tstderr:  stderr,\n\t\tsuccess: false,\n\t}\n\n\tgo func() {\n\t\ts.sshClient.RunCommandContext(ctx, command)\n\t\tif !ops.SkipLog {\n\t\t\tres.SendToLog()\n\t\t}\n\t}()\n\n\treturn &res\n}\n<commit_msg>test: report collection prints error from ssh.RunCommand<commit_after>\/\/ Copyright 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 helpers\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/cilium\/cilium\/test\/config\"\n\tginkgoext \"github.com\/cilium\/cilium\/test\/ginkgo-ext\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"golang.org\/x\/crypto\/ssh\"\n)\n\nvar (\n\t\/\/SSHMetaLogs is a buffer where all commands sent over ssh are saved.\n\tSSHMetaLogs = ginkgoext.NewWriter(new(bytes.Buffer))\n)\n\n\/\/ SSHMeta contains metadata to SSH into a remote location to run tests\ntype SSHMeta struct {\n\tsshClient *SSHClient\n\tenv       []string\n\trawConfig []byte\n\tnodeName  string\n\tlogger    *logrus.Entry\n}\n\n\/\/ CreateSSHMeta returns an SSHMeta with the specified host, port, and user, as\n\/\/ well as an according SSHClient.\nfunc CreateSSHMeta(host string, port int, user string) *SSHMeta {\n\treturn &SSHMeta{\n\t\tsshClient: GetSSHClient(host, port, user),\n\t}\n}\n\nfunc (s *SSHMeta) String() string {\n\treturn fmt.Sprintf(\"environment: %s, SSHClient: %s\", s.env, s.sshClient.String())\n\n}\n\n\/\/ GetVagrantSSHMeta returns a SSHMeta initialized based on the provided\n\/\/ SSH-config target.\nfunc GetVagrantSSHMeta(vmName string) *SSHMeta {\n\tconfig, err := GetVagrantSSHMetadata(vmName)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tlog.Debugf(\"generated SSHConfig for node %s\", vmName)\n\tnodes, err := ImportSSHconfig(config)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Error importing ssh config\")\n\t\treturn nil\n\t}\n\tvar node *SSHConfig\n\tlog.Debugf(\"done importing ssh config\")\n\tfor name := range nodes {\n\t\tif strings.HasPrefix(name, vmName) {\n\t\t\tnode = nodes[name]\n\t\t\tbreak\n\t\t}\n\t}\n\tif node == nil {\n\t\tlog.Errorf(\"Node %s not found in ssh config\", vmName)\n\t\treturn nil\n\t}\n\tsshMeta := &SSHMeta{\n\t\tsshClient: node.GetSSHClient(),\n\t\trawConfig: config,\n\t\tnodeName:  vmName,\n\t}\n\n\tsshMeta.setBasePath()\n\treturn sshMeta\n}\n\n\/\/ setBasePath if the SSHConfig is defined we set the BasePath to the GOPATH,\n\/\/ from golang 1.8 GOPATH is by default $HOME\/go so we also check that.\nfunc (s *SSHMeta) setBasePath() {\n\tif config.CiliumTestConfig.SSHConfig == \"\" {\n\t\treturn\n\t}\n\n\tgopath := s.Exec(\"echo $GOPATH\").SingleOut()\n\tif gopath != \"\" {\n\t\tBasePath = filepath.Join(gopath, CiliumPath)\n\t\treturn\n\t}\n\n\thome := s.Exec(\"echo $HOME\").SingleOut()\n\tif home == \"\" {\n\t\treturn\n\t}\n\n\tBasePath = filepath.Join(home, \"go\", CiliumPath)\n\treturn\n}\n\n\/\/ Execute executes cmd on the provided node and stores the stdout \/ stderr of\n\/\/ the command in the provided buffers. Returns false if the command failed\n\/\/ during its execution.\nfunc (s *SSHMeta) Execute(cmd string, stdout io.Writer, stderr io.Writer) error {\n\tif stdout == nil {\n\t\tstdout = os.Stdout\n\t}\n\n\tif stderr == nil {\n\t\tstderr = os.Stderr\n\t}\n\tfmt.Fprintln(SSHMetaLogs, cmd)\n\tcommand := &SSHCommand{\n\t\tPath:   cmd,\n\t\tStdin:  os.Stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\terr := s.sshClient.RunCommand(command)\n\treturn err\n}\n\n\/\/ ExecWithSudo returns the result of executing the provided cmd via SSH using\n\/\/ sudo.\nfunc (s *SSHMeta) ExecWithSudo(cmd string, options ...ExecOptions) *CmdRes {\n\tcommand := fmt.Sprintf(\"sudo %s\", cmd)\n\treturn s.Exec(command, options...)\n}\n\n\/\/ ExecOptions options to execute Exec and ExecWithContext\ntype ExecOptions struct {\n\tSkipLog bool\n}\n\n\/\/ Exec returns the results of executing the provided cmd via SSH.\nfunc (s *SSHMeta) Exec(cmd string, options ...ExecOptions) *CmdRes {\n\tvar ops ExecOptions\n\tif len(options) > 0 {\n\t\tops = options[0]\n\t}\n\n\tlog.Debugf(\"running command: %s\", cmd)\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\texit := true\n\terr := s.Execute(cmd, stdout, stderr)\n\tif err != nil {\n\t\texit = false\n\t}\n\n\tres := CmdRes{\n\t\tcmd:     cmd,\n\t\tstdout:  stdout,\n\t\tstderr:  stderr,\n\t\tsuccess: exit,\n\t}\n\t\/\/ Set res's exitcode if the error is an ExitError\n\tif exiterr, ok := err.(*ssh.ExitError); ok {\n\t\tres.exitcode = exiterr.Waitmsg.ExitStatus()\n\t} else {\n\t\t\/\/ Log other error types. They are likely from SSH or the network\n\t\tlog.WithError(err).Errorf(\"Error executing command '%s'\", cmd)\n\t}\n\n\tif !ops.SkipLog {\n\t\tres.SendToLog()\n\t}\n\treturn &res\n}\n\n\/\/ GetCopy returns a copy of SSHMeta, useful for parallel requests\nfunc (s *SSHMeta) GetCopy() *SSHMeta {\n\tnodes, err := ImportSSHconfig(s.rawConfig)\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"while importing ssh config for meta copy\")\n\t\treturn nil\n\t}\n\n\tconfig := nodes[s.nodeName]\n\tif config == nil {\n\t\tlog.Errorf(\"no node %s in imported config\", s.nodeName)\n\t\treturn nil\n\t}\n\n\tcopy := &SSHMeta{\n\t\tsshClient: config.GetSSHClient(),\n\t\trawConfig: s.rawConfig,\n\t\tnodeName:  s.nodeName,\n\t}\n\n\treturn copy\n}\n\n\/\/ ExecContext returns the results of running cmd via SSH in the specified\n\/\/ context.\nfunc (s *SSHMeta) ExecContext(ctx context.Context, cmd string, options ...ExecOptions) *CmdRes {\n\tif ctx == nil {\n\t\tpanic(\"no context provided\")\n\t}\n\n\tvar ops ExecOptions\n\tif len(options) > 0 {\n\t\tops = options[0]\n\t}\n\n\tfmt.Fprintln(SSHMetaLogs, cmd)\n\tstdout := new(bytes.Buffer)\n\tstderr := new(bytes.Buffer)\n\n\tcommand := &SSHCommand{\n\t\tPath:   cmd,\n\t\tStdin:  os.Stdin,\n\t\tStdout: stdout,\n\t\tStderr: stderr,\n\t}\n\n\tres := CmdRes{\n\t\tcmd:     cmd,\n\t\tstdout:  stdout,\n\t\tstderr:  stderr,\n\t\tsuccess: false,\n\t}\n\n\tgo func() {\n\t\ts.sshClient.RunCommandContext(ctx, command)\n\t\tif !ops.SkipLog {\n\t\t\tres.SendToLog()\n\t\t}\n\t}()\n\n\treturn &res\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n     \"http\"\n     \"json\"\n     \"flag\"\n     \"exec\"\n     \"os\"\n     \"io\/ioutil\"\n     \"strings\"\n\t\/\/iface \"flunky\/interfaces\"\n\tdaemon \"flunky\/daemon\"\n)\n\n\ntype outletNode struct{\n     Address   string\n     Outlet    string\n}\n\nvar resources       map[string]outletNode\nvar powerDaemon     *daemon.Daemon\nvar fileDir         string\n\/\/var resourcesLock   sync.Mutex   shouldn't need a lock, never changing data.\n\nfunc init() {\n     flag.StringVar(&fileDir, \"F\", \"..\/..\/..\/etc\/Power\/\", \"Directory where client files can be found.\")\n     \n     flag.Parse()\n     \n     powerDaemon = daemon.New(\"Power\", fileDir)\n     \n     powerDaemon.DaemonLog.Log(\"Initializting data for daemon setup.\")\n     \n     powerDBFile, error := os.Open(fileDir + \"power.db\")\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to open power.db for reading.\", error)\n     \n     someBytes, error := ioutil.ReadAll(powerDBFile)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read from file power.db.\", error)\n     \n     error = powerDBFile.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close power.db.\", error)\n     \n     error = json.Unmarshal(someBytes, &resources)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to unmarshal data read from power.db file.\", error)\n}\n\n\nfunc DumpCall(w http.ResponseWriter, req *http.Request) {\n        powerDaemon.DaemonLog.LogHttp(req)\n        req.ProtoMinor = 0\n       \/* username, authed, _ := powerDaemon.AuthN.HTTPAuthenticate(req)\n        if !authed {\n                powerDaemon.DaemonLog.LogError(fmt.Sprintf(\"User Authentications for %s failed\", username), os.NewError(\"Access Denied\"))\n                return\n        }*\/\n        tmp, err := json.Marshal(resources)\n        powerDaemon.DaemonLog.LogError(\"Cannot Marshal power resources\", err)\n        _, err = w.Write(tmp)\n        if err != nil {\n                http.Error(w, \"Cannot write to socket\", 500)\n        }\n}\n\nfunc rebootList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Rebooting list given by client.\")\n     var nodes []string\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from reboot POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close reboot request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be rebooted.\", error)\n     \n     for _, value := range nodes {\n          go func(value string) {\n               error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"reboot\", resources[value].Outlet).Run()\n               powerDaemon.DaemonLog.LogError(\"ERROR: Failed to run powerCont.sh in rebootList.\", error)\n          }(value)\n     }\n}\n\nfunc offList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Turning off list of nodes given by client.\")\n     var nodes []string\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from off POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close off request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be turned off.\", error)\n     \n     for _, value := range nodes {\n          go func(value string) {\n               error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"off\", resources[value].Outlet).Run()\n               powerDaemon.DaemonLog.LogError(\"ERROR: Failed to run powerCont.sh in offList.\", error)\n          }(value)\n     }\n}\n\nfunc statusList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Retreiving status for list given by client.\")\n     var nodes []string\n     outletStatus := make(map[string]string)\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from off POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close off request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be turned off.\", error)\n     \n     for _, value := range nodes {\n          _, ok := outletStatus[value]\n          \n          if !ok {\n               someBytes, error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"status\").Output()\n               powerDaemon.DaemonLog.LogError(\"ERROR: Failed to execute powerCont.sh and get out put in power status request.\", error)\n\n               tmpStatusLines := strings.Split(string(someBytes), \"\\n\")\n\n               for i := 18 ; i < 42 ; i++ {\n                    tmpStatusFields := strings.Split(tmpStatusLines[i], \" \")\n\n                    for _, value2 := range nodes {\n                         if resources[value2].Address == resources[value].Address && resources[value2].Outlet == tmpStatusFields[3] {\n                              outletStatus[value2] = tmpStatusFields[13]\n                         }\n                    }\n               }\n          }\n     }\n\n     jsonStat, error := json.Marshal(outletStatus)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to marshal outlet status response.\", error)\n     \n     _, error = writer.Write(jsonStat)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to write outlet status response.\", error)\n}\n\nfunc main() {\n     http.HandleFunc(\"\/dump\", DumpCall)\n     http.HandleFunc(\"\/reboot\", rebootList)\n     http.HandleFunc(\"\/off\", offList)\n     http.HandleFunc(\"\/status\", statusList)\n     \n     error := http.ListenAndServe(\":\" + powerDaemon.Cfg.Data[\"powerPort\"], nil)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to listen on http socket.\", error)\n}<commit_msg>added map security to power daemon.<commit_after>package main\n\nimport (\n     \"http\"\n     \"json\"\n     \"flag\"\n     \"exec\"\n     \"os\"\n     \"io\/ioutil\"\n     \"strings\"\n\t\/\/iface \"flunky\/interfaces\"\n\tdaemon \"flunky\/daemon\"\n)\n\n\ntype outletNode struct{\n     Address   string\n     Outlet    string\n}\n\nvar resources       map[string]outletNode\nvar powerDaemon     *daemon.Daemon\nvar fileDir         string\n\/\/var resourcesLock   sync.Mutex   shouldn't need a lock, never changing data.\n\nfunc init() {\n     flag.StringVar(&fileDir, \"F\", \"..\/..\/..\/etc\/Power\/\", \"Directory where client files can be found.\")\n     \n     flag.Parse()\n     \n     powerDaemon = daemon.New(\"Power\", fileDir)\n     \n     powerDaemon.DaemonLog.Log(\"Initializting data for daemon setup.\")\n     \n     powerDBFile, error := os.Open(fileDir + \"power.db\")\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to open power.db for reading.\", error)\n     \n     someBytes, error := ioutil.ReadAll(powerDBFile)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read from file power.db.\", error)\n     \n     error = powerDBFile.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close power.db.\", error)\n     \n     error = json.Unmarshal(someBytes, &resources)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to unmarshal data read from power.db file.\", error)\n}\n\n\nfunc DumpCall(w http.ResponseWriter, req *http.Request) {\n        powerDaemon.DaemonLog.LogHttp(req)\n        req.ProtoMinor = 0\n       \/* username, authed, _ := powerDaemon.AuthN.HTTPAuthenticate(req)\n        if !authed {\n                powerDaemon.DaemonLog.LogError(fmt.Sprintf(\"User Authentications for %s failed\", username), os.NewError(\"Access Denied\"))\n                return\n        }*\/\n        tmp, err := json.Marshal(resources)\n        powerDaemon.DaemonLog.LogError(\"Cannot Marshal power resources\", err)\n        _, err = w.Write(tmp)\n        if err != nil {\n                http.Error(w, \"Cannot write to socket\", 500)\n        }\n}\n\nfunc rebootList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Rebooting list given by client.\")\n     var nodes []string\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from reboot POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close reboot request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be rebooted.\", error)\n     \n     for _, value := range nodes {\n          if _, ok := resources[value] ; ok {\n               go func(value string) {\n                    error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"reboot\", resources[value].Outlet).Run()\n                    powerDaemon.DaemonLog.LogError(\"ERROR: Failed to run powerCont.sh in rebootList.\", error)\n               }(value)\n          }\n     }\n}\n\nfunc offList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Turning off list of nodes given by client.\")\n     var nodes []string\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from off POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close off request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be turned off.\", error)\n     \n     for _, value := range nodes {\n          if _, ok := resources[value] ; ok {\n               go func(value string) {\n                    error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"off\", resources[value].Outlet).Run()\n                    powerDaemon.DaemonLog.LogError(\"ERROR: Failed to run powerCont.sh in offList.\", error)\n               }(value)\n          }\n     }\n}\n\nfunc statusList(writer http.ResponseWriter, request *http.Request) {\n     \/\/This will free a requested node if the user is the owner of the node.  It removes\n     \/\/the node from current resources if it exists and also resets it in resources map.\n     powerDaemon.DaemonLog.Log(\"Retreiving status for list given by client.\")\n     var nodes []string\n     outletStatus := make(map[string]string)\n     request.ProtoMinor = 0\n     \n     _, authed, admin := powerDaemon.AuthN.HTTPAuthenticate(request)\n     \n     if !authed {\n          powerDaemon.DaemonLog.LogError(\"ERROR: Username password combo invalid.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     if !admin {\n          powerDaemon.DaemonLog.LogError(\"ERROR: No access to admin command.\", os.NewError(\"Access Denied\"))\n          return\n     }\n     \n     someBytes, error := ioutil.ReadAll(request.Body)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to read all from off POST.\", error)\n     \n     error = request.Body.Close()\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to close off request body.\", error)\n     \n     error = json.Unmarshal(someBytes, &nodes)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to unmarshal nodes to be turned off.\", error)\n     \n     for _, value := range nodes {\n          _, ok := outletStatus[value]\n          _, ok2 := resources[value]\n          \n          if !ok && ok2 {\n               someBytes, error = exec.Command(\".\/powerCont.sh\", resources[value].Address, \"admn\", \"admn\", \"status\").Output()\n               powerDaemon.DaemonLog.LogError(\"ERROR: Failed to execute powerCont.sh and get out put in power status request.\", error)\n\n               tmpStatusLines := strings.Split(string(someBytes), \"\\n\")\n\n               for i := 18 ; i < 42 ; i++ {\n                    tmpStatusFields := strings.Split(tmpStatusLines[i], \" \")\n\n                    for _, value2 := range nodes {\n                         if _, ok3 := resources[value2] ; ok3 && ok2 {\n                              if resources[value2].Address == resources[value].Address && resources[value2].Outlet == tmpStatusFields[3] {\n                                   outletStatus[value2] = tmpStatusFields[13]\n                              }\n                         }\n                    }\n               }\n          }\n     }\n\n     jsonStat, error := json.Marshal(outletStatus)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to marshal outlet status response.\", error)\n     \n     _, error = writer.Write(jsonStat)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Unable to write outlet status response.\", error)\n}\n\nfunc main() {\n     http.HandleFunc(\"\/dump\", DumpCall)\n     http.HandleFunc(\"\/reboot\", rebootList)\n     http.HandleFunc(\"\/off\", offList)\n     http.HandleFunc(\"\/status\", statusList)\n     \n     error := http.ListenAndServe(\":\" + powerDaemon.Cfg.Data[\"powerPort\"], nil)\n     powerDaemon.DaemonLog.LogError(\"ERROR: Failed to listen on http socket.\", error)\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\ntype nullFile struct {\n\tdata    []byte\n\tcontent string\n}\n\n\/\/ NotFoundFiles to return HTTP 404, not found\nvar NotFoundFiles = map[string]bool{\n\t\"7z\":   true,\n\t\"avi\":  true,\n\t\"bin\":  true,\n\t\"bz2\":  true,\n\t\"doc\":  true,\n\t\"docx\": true,\n\t\"exe\":  true,\n\t\"gz\":   true,\n\t\"iso\":  true,\n\t\"java\": true,\n\t\"mov\":  true,\n\t\"mp4\":  true,\n\t\"pdf\":  true,\n\t\"ppt\":  true,\n\t\"pptx\": true,\n\t\"lz\":   true,\n\t\"lzma\": true,\n\t\"sh\":   true,\n\t\"swf\":  true,\n\t\"rar\":  true,\n\t\"tar\":  true,\n\t\"tb2\":  true,\n\t\"tbz\":  true,\n\t\"tbz2\": true,\n\t\"tgz\":  true,\n\t\"txz\":  true,\n\t\"webp\": true,\n\t\"webm\": true,\n\t\"xls\":  true,\n\t\"xlsx\": true,\n\t\"xz\":   true,\n\t\"zip\":  true,\n}\n\n\/\/ AltSuffix maps alternative extensions to other valid nullFiles\nvar AltSuffix = map[string]string{\n\t\"asp\":  \"html\",\n\t\"aspx\": \"html\",\n\t\"cgi\":  \"html\",\n\t\"dll\":  \"html\",\n\t\"do\":   \"html\",\n\t\"htm\":  \"html\",\n\t\"jpeg\": \"jpg\",\n\t\"m4a\":  \"mp4\",\n\t\"m4b\":  \"mp4\",\n\t\"m4p\":  \"mp4\",\n\t\"m4r\":  \"mp4\",\n\t\"m4v\":  \"mp4\",\n\t\"tif\":  \"tiff\",\n\t\"xht\":  \"xhtml\",\n}\n\n\/\/ All known nullfiles\nvar nullFiles = map[string]nullFile{\n\t\"\": nullFile{nil, \"text\/plain\"}, \/\/ Catch-all empty suffix\n\t\"bmp\": nullFile{[]byte{\n\t\t'\\x42', '\\x4d', '\\x1e', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x1a', '\\x00', '\\x00', '\\x00', '\\x0c', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00',\n\t\t'\\x18', '\\x00', '\\x00', '\\x00', '\\xff', '\\x00',\n\t}, \"image\/bmp\"},\n\t\"css\": nullFile{nil, \"text\/css\"},\n\t\"csv\": nullFile{nil, \"text\/csv\"},\n\t\"gif\": nullFile{[]byte{\n\t\t'\\x47', '\\x49', '\\x46', '\\x38', '\\x39', '\\x61', '\\x01', '\\x00',\n\t\t'\\x01', '\\x00', '\\x80', '\\x00', '\\x00', '\\xff', '\\xff', '\\xff',\n\t\t'\\x00', '\\x00', '\\x00', '\\x21', '\\xf9', '\\x04', '\\x01', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x2c', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x02', '\\x02', '\\x44',\n\t\t'\\x01', '\\x00', '\\x3b',\n\t}, \"image\/gif\"},\n\t\"html\": nullFile{[]byte(\"<!DOCTYPE html><title>x<\/title>\"),\n\t\t\"text\/html\"},\n\t\"ico\": nullFile{[]byte{\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x01', '\\x01',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x18', '\\x00', '\\x30', '\\x00',\n\t\t'\\x00', '\\x00', '\\x16', '\\x00', '\\x00', '\\x00', '\\x28', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x02', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x18', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\xff', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t}, \"image\/x-icon\"},\n\t\"jpg\": nullFile{[]byte{\n\t\t'\\xff', '\\xd8', '\\xff', '\\xe0', '\\x00', '\\x10', '\\x4a', '\\x46',\n\t\t'\\x49', '\\x46', '\\x00', '\\x01', '\\x01', '\\x01', '\\x00', '\\x01',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\xff', '\\xdb', '\\x00', '\\x43',\n\t\t'\\x00', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xc0', '\\x00', '\\x0b', '\\x08', '\\x00', '\\x01',\n\t\t'\\x00', '\\x01', '\\x01', '\\x01', '\\x11', '\\x00', '\\xff', '\\xc4',\n\t\t'\\x00', '\\x14', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x03', '\\xff', '\\xc4', '\\x00', '\\x14',\n\t\t'\\x10', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\xff', '\\xda', '\\x00', '\\x08', '\\x01', '\\x01',\n\t\t'\\x00', '\\x00', '\\x3f', '\\x00', '\\x47', '\\xff', '\\xd9',\n\t}, \"image\/jpg\"},\n\t\"js\":   nullFile{nil, \"application\/javascript\"},\n\t\"json\": nullFile{[]byte(\"{}\"), \"application\/json\"},\n\t\"png\": nullFile{[]byte{\n\t\t'\\x89', '\\x50', '\\x4e', '\\x47', '\\x0d', '\\x0a', '\\x1a', '\\x0a',\n\t\t'\\x00', '\\x00', '\\x00', '\\x0d', '\\x49', '\\x48', '\\x44', '\\x52',\n\t\t'\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x01',\n\t\t'\\x08', '\\x06', '\\x00', '\\x00', '\\x00', '\\x1f', '\\x15', '\\xc4',\n\t\t'\\x89', '\\x00', '\\x00', '\\x00', '\\x0a', '\\x49', '\\x44', '\\x41',\n\t\t'\\x54', '\\x78', '\\x9c', '\\x63', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x05', '\\x00', '\\x01', '\\x0d', '\\x0a', '\\x2d', '\\xb4', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x49', '\\x45', '\\x4e', '\\x44', '\\xae',\n\t\t'\\x42', '\\x60', '\\x82',\n\t}, \"image\/png\"},\n\t\"tiff\": nullFile{[]byte{\n\t\t'\\x4d', '\\x4d', '\\x00', '\\x2a', '\\x00', '\\x00', '\\x00', '\\x08',\n\t\t'\\x00', '\\x07', '\\x01', '\\x00', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x01', '\\x01',\n\t\t'\\x00', '\\x03', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x01',\n\t\t'\\x00', '\\x00', '\\x01', '\\x06', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00', '\\x01', '\\x11',\n\t\t'\\x00', '\\x03', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x17', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x01', '\\x1a',\n\t\t'\\x00', '\\x05', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x00', '\\x64', '\\x01', '\\x1b', '\\x00', '\\x05', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x64', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x20', '\\x20', '\\x20', '\\x62', '\\x79', '\\x20',\n\t\t'\\x61', '\\x6c', '\\x6f', '\\x6b',\n\t}, \"image\/tiff\"},\n\t\"svg\": nullFile{[]byte{\n\t\t'\\x3c', '\\x73', '\\x76', '\\x67', '\\x20', '\\x78', '\\x6d', '\\x6c',\n\t\t'\\x6e', '\\x73', '\\x3d', '\\x22', '\\x68', '\\x74', '\\x74', '\\x70',\n\t\t'\\x3a', '\\x2f', '\\x2f', '\\x77', '\\x77', '\\x77', '\\x2e', '\\x77',\n\t\t'\\x33', '\\x2e', '\\x6f', '\\x72', '\\x67', '\\x2f', '\\x32', '\\x30',\n\t\t'\\x30', '\\x30', '\\x2f', '\\x73', '\\x76', '\\x67', '\\x22', '\\x2f',\n\t\t'\\x3e',\n\t}, \"image\/svg+xml\"},\n\t\"wasm\": nullFile{[]byte{\n\t\t'\\x00', '\\x61', '\\x73', '\\x6d', '\\x01', '\\x00', '\\x00', '\\x00',\n\t}, \"application\/wasm\"},\n\t\"xhtml\": nullFile{[]byte{\n\t\t'\\x3c', '\\x68', '\\x74', '\\x6d', '\\x6c', '\\x20', '\\x78', '\\x6d',\n\t\t'\\x6c', '\\x6e', '\\x73', '\\x3d', '\\x22', '\\x68', '\\x74', '\\x74',\n\t\t'\\x70', '\\x3a', '\\x2f', '\\x2f', '\\x77', '\\x77', '\\x77', '\\x2e',\n\t\t'\\x77', '\\x33', '\\x2e', '\\x6f', '\\x72', '\\x67', '\\x2f', '\\x31',\n\t\t'\\x39', '\\x39', '\\x39', '\\x2f', '\\x78', '\\x68', '\\x74', '\\x6d',\n\t\t'\\x6c', '\\x22', '\\x2f', '\\x3e',\n\t}, \"application\/xhtml+xml\"},\n\t\"xml\": nullFile{[]byte{\n\t\t'\\x3c', '\\x3f', '\\x78', '\\x6d', '\\x6c', '\\x20', '\\x76', '\\x65',\n\t\t'\\x72', '\\x73', '\\x69', '\\x6f', '\\x6e', '\\x3d', '\\x22', '\\x31',\n\t\t'\\x2e', '\\x31', '\\x22', '\\x3f', '\\x3e', '\\x3c', '\\x21', '\\x44',\n\t\t'\\x4f', '\\x43', '\\x54', '\\x59', '\\x50', '\\x45', '\\x20', '\\x5f',\n\t\t'\\x5b', '\\x3c', '\\x21', '\\x45', '\\x4c', '\\x45', '\\x4d', '\\x45',\n\t\t'\\x4e', '\\x54', '\\x20', '\\x5f', '\\x20', '\\x45', '\\x4d', '\\x50',\n\t\t'\\x54', '\\x59', '\\x3e', '\\x5d', '\\x3e', '\\x3c', '\\x5f', '\\x2f',\n\t\t'\\x3e',\n\t}, \"application\/xml\"},\n}\n<commit_msg>files: .mp3 returns 404<commit_after>package main\n\ntype nullFile struct {\n\tdata    []byte\n\tcontent string\n}\n\n\/\/ NotFoundFiles to return HTTP 404, not found\nvar NotFoundFiles = map[string]bool{\n\t\"7z\":   true,\n\t\"avi\":  true,\n\t\"bin\":  true,\n\t\"bz2\":  true,\n\t\"doc\":  true,\n\t\"docx\": true,\n\t\"exe\":  true,\n\t\"gz\":   true,\n\t\"iso\":  true,\n\t\"java\": true,\n\t\"mov\":  true,\n\t\"mp3\":  true,\n\t\"mp4\":  true,\n\t\"pdf\":  true,\n\t\"ppt\":  true,\n\t\"pptx\": true,\n\t\"lz\":   true,\n\t\"lzma\": true,\n\t\"sh\":   true,\n\t\"swf\":  true,\n\t\"rar\":  true,\n\t\"tar\":  true,\n\t\"tb2\":  true,\n\t\"tbz\":  true,\n\t\"tbz2\": true,\n\t\"tgz\":  true,\n\t\"txz\":  true,\n\t\"webp\": true,\n\t\"webm\": true,\n\t\"xls\":  true,\n\t\"xlsx\": true,\n\t\"xz\":   true,\n\t\"zip\":  true,\n}\n\n\/\/ AltSuffix maps alternative extensions to other valid nullFiles\nvar AltSuffix = map[string]string{\n\t\"asp\":  \"html\",\n\t\"aspx\": \"html\",\n\t\"cgi\":  \"html\",\n\t\"dll\":  \"html\",\n\t\"do\":   \"html\",\n\t\"htm\":  \"html\",\n\t\"jpeg\": \"jpg\",\n\t\"m4a\":  \"mp4\",\n\t\"m4b\":  \"mp4\",\n\t\"m4p\":  \"mp4\",\n\t\"m4r\":  \"mp4\",\n\t\"m4v\":  \"mp4\",\n\t\"tif\":  \"tiff\",\n\t\"xht\":  \"xhtml\",\n}\n\n\/\/ All known nullfiles\nvar nullFiles = map[string]nullFile{\n\t\"\": nullFile{nil, \"text\/plain\"}, \/\/ Catch-all empty suffix\n\t\"bmp\": nullFile{[]byte{\n\t\t'\\x42', '\\x4d', '\\x1e', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x1a', '\\x00', '\\x00', '\\x00', '\\x0c', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00',\n\t\t'\\x18', '\\x00', '\\x00', '\\x00', '\\xff', '\\x00',\n\t}, \"image\/bmp\"},\n\t\"css\": nullFile{nil, \"text\/css\"},\n\t\"csv\": nullFile{nil, \"text\/csv\"},\n\t\"gif\": nullFile{[]byte{\n\t\t'\\x47', '\\x49', '\\x46', '\\x38', '\\x39', '\\x61', '\\x01', '\\x00',\n\t\t'\\x01', '\\x00', '\\x80', '\\x00', '\\x00', '\\xff', '\\xff', '\\xff',\n\t\t'\\x00', '\\x00', '\\x00', '\\x21', '\\xf9', '\\x04', '\\x01', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x2c', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x02', '\\x02', '\\x44',\n\t\t'\\x01', '\\x00', '\\x3b',\n\t}, \"image\/gif\"},\n\t\"html\": nullFile{[]byte(\"<!DOCTYPE html><title>x<\/title>\"),\n\t\t\"text\/html\"},\n\t\"ico\": nullFile{[]byte{\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x01', '\\x01',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x18', '\\x00', '\\x30', '\\x00',\n\t\t'\\x00', '\\x00', '\\x16', '\\x00', '\\x00', '\\x00', '\\x28', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x02', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x00', '\\x18', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\xff', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t}, \"image\/x-icon\"},\n\t\"jpg\": nullFile{[]byte{\n\t\t'\\xff', '\\xd8', '\\xff', '\\xe0', '\\x00', '\\x10', '\\x4a', '\\x46',\n\t\t'\\x49', '\\x46', '\\x00', '\\x01', '\\x01', '\\x01', '\\x00', '\\x01',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\xff', '\\xdb', '\\x00', '\\x43',\n\t\t'\\x00', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff', '\\xff',\n\t\t'\\xff', '\\xff', '\\xc0', '\\x00', '\\x0b', '\\x08', '\\x00', '\\x01',\n\t\t'\\x00', '\\x01', '\\x01', '\\x01', '\\x11', '\\x00', '\\xff', '\\xc4',\n\t\t'\\x00', '\\x14', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x03', '\\xff', '\\xc4', '\\x00', '\\x14',\n\t\t'\\x10', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\xff', '\\xda', '\\x00', '\\x08', '\\x01', '\\x01',\n\t\t'\\x00', '\\x00', '\\x3f', '\\x00', '\\x47', '\\xff', '\\xd9',\n\t}, \"image\/jpg\"},\n\t\"js\":   nullFile{nil, \"application\/javascript\"},\n\t\"json\": nullFile{[]byte(\"{}\"), \"application\/json\"},\n\t\"png\": nullFile{[]byte{\n\t\t'\\x89', '\\x50', '\\x4e', '\\x47', '\\x0d', '\\x0a', '\\x1a', '\\x0a',\n\t\t'\\x00', '\\x00', '\\x00', '\\x0d', '\\x49', '\\x48', '\\x44', '\\x52',\n\t\t'\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x01',\n\t\t'\\x08', '\\x06', '\\x00', '\\x00', '\\x00', '\\x1f', '\\x15', '\\xc4',\n\t\t'\\x89', '\\x00', '\\x00', '\\x00', '\\x0a', '\\x49', '\\x44', '\\x41',\n\t\t'\\x54', '\\x78', '\\x9c', '\\x63', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x05', '\\x00', '\\x01', '\\x0d', '\\x0a', '\\x2d', '\\xb4', '\\x00',\n\t\t'\\x00', '\\x00', '\\x00', '\\x49', '\\x45', '\\x4e', '\\x44', '\\xae',\n\t\t'\\x42', '\\x60', '\\x82',\n\t}, \"image\/png\"},\n\t\"tiff\": nullFile{[]byte{\n\t\t'\\x4d', '\\x4d', '\\x00', '\\x2a', '\\x00', '\\x00', '\\x00', '\\x08',\n\t\t'\\x00', '\\x07', '\\x01', '\\x00', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x01', '\\x01',\n\t\t'\\x00', '\\x03', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x01',\n\t\t'\\x00', '\\x00', '\\x01', '\\x06', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x00', '\\x01', '\\x11',\n\t\t'\\x00', '\\x03', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x01', '\\x17', '\\x00', '\\x03', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x01', '\\x00', '\\x00', '\\x01', '\\x1a',\n\t\t'\\x00', '\\x05', '\\x00', '\\x00', '\\x00', '\\x01', '\\x00', '\\x00',\n\t\t'\\x00', '\\x64', '\\x01', '\\x1b', '\\x00', '\\x05', '\\x00', '\\x00',\n\t\t'\\x00', '\\x01', '\\x00', '\\x00', '\\x00', '\\x64', '\\x00', '\\x00',\n\t\t'\\x00', '\\x00', '\\x20', '\\x20', '\\x20', '\\x62', '\\x79', '\\x20',\n\t\t'\\x61', '\\x6c', '\\x6f', '\\x6b',\n\t}, \"image\/tiff\"},\n\t\"svg\": nullFile{[]byte{\n\t\t'\\x3c', '\\x73', '\\x76', '\\x67', '\\x20', '\\x78', '\\x6d', '\\x6c',\n\t\t'\\x6e', '\\x73', '\\x3d', '\\x22', '\\x68', '\\x74', '\\x74', '\\x70',\n\t\t'\\x3a', '\\x2f', '\\x2f', '\\x77', '\\x77', '\\x77', '\\x2e', '\\x77',\n\t\t'\\x33', '\\x2e', '\\x6f', '\\x72', '\\x67', '\\x2f', '\\x32', '\\x30',\n\t\t'\\x30', '\\x30', '\\x2f', '\\x73', '\\x76', '\\x67', '\\x22', '\\x2f',\n\t\t'\\x3e',\n\t}, \"image\/svg+xml\"},\n\t\"wasm\": nullFile{[]byte{\n\t\t'\\x00', '\\x61', '\\x73', '\\x6d', '\\x01', '\\x00', '\\x00', '\\x00',\n\t}, \"application\/wasm\"},\n\t\"xhtml\": nullFile{[]byte{\n\t\t'\\x3c', '\\x68', '\\x74', '\\x6d', '\\x6c', '\\x20', '\\x78', '\\x6d',\n\t\t'\\x6c', '\\x6e', '\\x73', '\\x3d', '\\x22', '\\x68', '\\x74', '\\x74',\n\t\t'\\x70', '\\x3a', '\\x2f', '\\x2f', '\\x77', '\\x77', '\\x77', '\\x2e',\n\t\t'\\x77', '\\x33', '\\x2e', '\\x6f', '\\x72', '\\x67', '\\x2f', '\\x31',\n\t\t'\\x39', '\\x39', '\\x39', '\\x2f', '\\x78', '\\x68', '\\x74', '\\x6d',\n\t\t'\\x6c', '\\x22', '\\x2f', '\\x3e',\n\t}, \"application\/xhtml+xml\"},\n\t\"xml\": nullFile{[]byte{\n\t\t'\\x3c', '\\x3f', '\\x78', '\\x6d', '\\x6c', '\\x20', '\\x76', '\\x65',\n\t\t'\\x72', '\\x73', '\\x69', '\\x6f', '\\x6e', '\\x3d', '\\x22', '\\x31',\n\t\t'\\x2e', '\\x31', '\\x22', '\\x3f', '\\x3e', '\\x3c', '\\x21', '\\x44',\n\t\t'\\x4f', '\\x43', '\\x54', '\\x59', '\\x50', '\\x45', '\\x20', '\\x5f',\n\t\t'\\x5b', '\\x3c', '\\x21', '\\x45', '\\x4c', '\\x45', '\\x4d', '\\x45',\n\t\t'\\x4e', '\\x54', '\\x20', '\\x5f', '\\x20', '\\x45', '\\x4d', '\\x50',\n\t\t'\\x54', '\\x59', '\\x3e', '\\x5d', '\\x3e', '\\x3c', '\\x5f', '\\x2f',\n\t\t'\\x3e',\n\t}, \"application\/xml\"},\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * 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 *\/\n\npackage main\n\n\/* This file will handle all file related business. It will explore the file\n * system for new files and will watch files for changes. In particular, this\n * file is the gate to the files table in the database. Other components (Parser)\n * should rely on this file to know if a file was explored or not. *\/\n\nimport (\n\tfsnotify \"gopkg.in\/fsnotify.v1\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nconst validCString string = `^[^\\.].*\\.c$`\nconst validHString string = `^[^\\.].*\\.h$`\n\nvar files chan string\nvar wg sync.WaitGroup\nvar watcher *fsnotify.Watcher\nvar writer chan *WriterDB\n\nfunc uptodateFile(file string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(file)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser is not executed\n\t\treturn true\n\t}\n\n\tif exist && uptodate {\n\t\treturn true\n\t} else {\n\t\twr.RemoveFileReferences(file)\n\t\twr.InsertFile(file, fi)\n\t\treturn false\n\t}\n}\n\nfunc processFile(parser *Parser) {\n\twg.Add(1)\n\tdefer wg.Done()\n\n\t\/\/ start exploring files\n\tfor {\n\t\tfile, ok := <-files\n\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif !uptodateFile(file) {\n\t\t\tlog.Println(\"parsing\", file)\n\t\t\tparser.Parse(file)\n\t\t}\n\t}\n}\n\nfunc traversePath(path string, visitDir func(string), visitC func(string)) {\n\tfilepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tlog.Println(\"error opening \", path, \" igoring\")\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\t\/\/ visit file\n\t\tif info.IsDir() {\n\t\t\tif info.Name()[0] == '.' {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t} else {\n\t\t\t\tvisitDir(path)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ ignore non-C files\n\t\t\tvalidC, _ := regexp.MatchString(validCString, path)\n\t\t\tif validC {\n\t\t\t\tvisitC(path)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc removeFileAndReparseDepends(file string, db *WriterDB) {\n\tdeps := db.RemoveFileDepsReferences(file)\n\tdb.RemoveFileReferences(file)\n\n\tfor _, d := range deps {\n\t\tfiles <- d\n\t}\n}\n\nfunc handleFileChange(event fsnotify.Event) {\n\n\tvalidC, _ := regexp.MatchString(validCString, event.Name)\n\tvalidH, _ := regexp.MatchString(validHString, event.Name)\n\n\tswitch {\n\tcase validC:\n\t\tfiles <- event.Name\n\tcase validH:\n\t\tdb := <-writer\n\t\texist, uptodate, _, err := db.UptodateFile(event.Name)\n\n\t\tif err != nil || (exist && !uptodate) {\n\t\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\t\t}\n\n\t\twriter <- db\n\t}\n}\n\nfunc handleDirChange(event fsnotify.Event) {\n\tswitch {\n\tcase event.Op&(fsnotify.Create) != 0:\n\t\t\/\/ explore the new dir\n\t\tvisitorDir := func(path string) {\n\t\t\t\/\/ add watcher to directory\n\t\t\twatcher.Add(path)\n\t\t}\n\t\tvisitorC := func(path string) {\n\t\t\t\/\/ put file in channel\n\t\t\tfiles <- path\n\t\t}\n\t\ttraversePath(event.Name, visitorDir, visitorC)\n\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\t\/\/ remove watcher from dir\n\t\twatcher.Remove(event.Name)\n\t}\n}\n\nfunc isDirectory(path string) (bool, error) {\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t} else {\n\t\treturn fi.IsDir(), nil\n\t}\n}\n\nfunc handleChange(event fsnotify.Event) {\n\n\t\/\/ ignore if hidden\n\tif filepath.Base(event.Name)[0] == '.' {\n\t\treturn\n\t}\n\n\t\/\/ first, we need to check if the file is a directory or not\n\tisDir, err := isDirectory(event.Name)\n\tif err != nil {\n\t\t\/\/ ignoring this event\n\t\treturn\n\t}\n\n\tif isDir {\n\t\thandleDirChange(event)\n\t} else {\n\t\thandleFileChange(event)\n\t}\n}\n\nfunc StartFilesHandler(indexDir []string, nIndexingThreads int, parser *Parser,\n\tdb *DBConnFactory) {\n\n\tfiles = make(chan string, nIndexingThreads)\n\twriter = make(chan *WriterDB, 1)\n\twriter <- db.NewWriter()\n\n\t\/\/ start threads to process files\n\tfor i := 0; i < nIndexingThreads; i++ {\n\t\tgo processFile(parser)\n\t}\n\n\t\/\/ start file watcher\n\twatcher, _ = fsnotify.NewWatcher()\n\tgo func() {\n\t\twg.Add(1)\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thandleChange(event)\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Println(\"watcher error: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ explore all the paths in indexDir and process all files\n\trd := db.NewReader()\n\tremovedFilesSet := rd.GetSetFilesInDB()\n\trd.Close()\n\tvisitorDir := func(path string) {\n\t\t\/\/ add watcher to directory\n\t\twatcher.Add(path)\n\t}\n\tvisitorC := func(path string) {\n\t\t\/\/ update set of removed files\n\t\tdelete(removedFilesSet, path)\n\t\t\/\/ put file in channel\n\t\tfiles <- path\n\t}\n\tfor _, path := range indexDir {\n\t\ttraversePath(path, visitorDir, visitorC)\n\t}\n\n\t\/\/ remove from DB deleted files\n\twr := <-writer\n\tfor path := range removedFilesSet {\n\t\twr.RemoveFileReferences(path)\n\t}\n\twriter <- wr\n}\n\nfunc UpdateDependency(file, dep string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(dep)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser move forward\n\t\treturn true\n\t}\n\n\tif !exist {\n\t\twr.InsertFile(dep, fi)\n\t} else if !uptodate {\n\t\tremoveFileAndReparseDepends(dep, wr)\n\t\tfiles <- file\n\t\treturn false\n\t}\n\n\twr.InsertDependency(file, dep)\n\treturn true\n}\n\nfunc CloseFilesHandler() {\n\tclose(files)\n\n\twr := <-writer\n\twr.Close()\n\tclose(writer)\n\n\twatcher.Close()\n\n\twg.Wait()\n}\n<commit_msg>Handling FS event remove and rename<commit_after>\/*\n * 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 *\/\n\npackage main\n\n\/* This file will handle all file related business. It will explore the file\n * system for new files and will watch files for changes. In particular, this\n * file is the gate to the files table in the database. Other components (Parser)\n * should rely on this file to know if a file was explored or not. *\/\n\nimport (\n\tfsnotify \"gopkg.in\/fsnotify.v1\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nconst validCString string = `^[^\\.].*\\.c$`\nconst validHString string = `^[^\\.].*\\.h$`\n\nvar files chan string\nvar wg sync.WaitGroup\nvar watcher *fsnotify.Watcher\nvar writer chan *WriterDB\n\nfunc uptodateFile(file string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(file)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser is not executed\n\t\treturn true\n\t}\n\n\tif exist && uptodate {\n\t\treturn true\n\t} else {\n\t\twr.RemoveFileReferences(file)\n\t\twr.InsertFile(file, fi)\n\t\treturn false\n\t}\n}\n\nfunc processFile(parser *Parser) {\n\twg.Add(1)\n\tdefer wg.Done()\n\n\t\/\/ start exploring files\n\tfor {\n\t\tfile, ok := <-files\n\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tif !uptodateFile(file) {\n\t\t\tlog.Println(\"parsing\", file)\n\t\t\tparser.Parse(file)\n\t\t}\n\t}\n}\n\nfunc traversePath(path string, visitDir func(string), visitC func(string)) {\n\tfilepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tlog.Println(\"error opening \", path, \" igoring\")\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\t\/\/ visit file\n\t\tif info.IsDir() {\n\t\t\tif info.Name()[0] == '.' {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t} else {\n\t\t\t\tvisitDir(path)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ ignore non-C files\n\t\t\tvalidC, _ := regexp.MatchString(validCString, path)\n\t\t\tif validC {\n\t\t\t\tvisitC(path)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc removeFileAndReparseDepends(file string, db *WriterDB) {\n\tdeps := db.RemoveFileDepsReferences(file)\n\tdb.RemoveFileReferences(file)\n\n\tfor _, d := range deps {\n\t\tfiles <- d\n\t}\n}\n\nfunc handleFileChange(event fsnotify.Event) {\n\n\tvalidC, _ := regexp.MatchString(validCString, event.Name)\n\tvalidH, _ := regexp.MatchString(validHString, event.Name)\n\n\tdb := <-writer\n\tdefer func() { writer <- db }()\n\n\tswitch {\n\tcase validC:\n\t\tswitch {\n\t\tcase event.Op&(fsnotify.Create|fsnotify.Write) != 0:\n\t\t\tfiles <- event.Name\n\t\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\t\tdb.RemoveFileReferences(event.Name)\n\t\t}\n\tcase validH:\n\t\texist, uptodate, _, err := db.UptodateFile(event.Name)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn\n\t\tcase event.Op&(fsnotify.Write) != 0:\n\t\t\tif exist && !uptodate {\n\t\t\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\t\t\t}\n\t\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\t\tif exist {\n\t\t\t\tremoveFileAndReparseDepends(filepath.Clean(event.Name), db)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc handleDirChange(event fsnotify.Event) {\n\tswitch {\n\tcase event.Op&(fsnotify.Create) != 0:\n\t\t\/\/ explore the new dir\n\t\tvisitorDir := func(path string) {\n\t\t\t\/\/ add watcher to directory\n\t\t\twatcher.Add(path)\n\t\t}\n\t\tvisitorC := func(path string) {\n\t\t\t\/\/ put file in channel\n\t\t\tfiles <- path\n\t\t}\n\t\ttraversePath(event.Name, visitorDir, visitorC)\n\tcase event.Op&(fsnotify.Remove|fsnotify.Rename) != 0:\n\t\t\/\/ remove watcher from dir\n\t\twatcher.Remove(event.Name)\n\t}\n}\n\nfunc isDirectory(path string) (bool, error) {\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn false, err\n\t} else {\n\t\treturn fi.IsDir(), nil\n\t}\n}\n\nfunc handleChange(event fsnotify.Event) {\n\n\t\/\/ ignore if hidden\n\tif filepath.Base(event.Name)[0] == '.' {\n\t\treturn\n\t}\n\n\t\/\/ first, we need to check if the file is a directory or not\n\tisDir, err := isDirectory(event.Name)\n\tif err != nil {\n\t\t\/\/ ignoring this event\n\t\treturn\n\t}\n\n\tif isDir {\n\t\thandleDirChange(event)\n\t} else {\n\t\thandleFileChange(event)\n\t}\n}\n\nfunc StartFilesHandler(indexDir []string, nIndexingThreads int, parser *Parser,\n\tdb *DBConnFactory) {\n\n\tfiles = make(chan string, nIndexingThreads)\n\twriter = make(chan *WriterDB, 1)\n\twriter <- db.NewWriter()\n\n\t\/\/ start threads to process files\n\tfor i := 0; i < nIndexingThreads; i++ {\n\t\tgo processFile(parser)\n\t}\n\n\t\/\/ start file watcher\n\twatcher, _ = fsnotify.NewWatcher()\n\tgo func() {\n\t\twg.Add(1)\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-watcher.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\thandleChange(event)\n\t\t\tcase err, ok := <-watcher.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlog.Println(\"watcher error: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ explore all the paths in indexDir and process all files\n\trd := db.NewReader()\n\tremovedFilesSet := rd.GetSetFilesInDB()\n\trd.Close()\n\tvisitorDir := func(path string) {\n\t\t\/\/ add watcher to directory\n\t\twatcher.Add(path)\n\t}\n\tvisitorC := func(path string) {\n\t\t\/\/ update set of removed files\n\t\tdelete(removedFilesSet, path)\n\t\t\/\/ put file in channel\n\t\tfiles <- path\n\t}\n\tfor _, path := range indexDir {\n\t\ttraversePath(path, visitorDir, visitorC)\n\t}\n\n\t\/\/ remove from DB deleted files\n\twr := <-writer\n\tfor path := range removedFilesSet {\n\t\twr.RemoveFileReferences(path)\n\t}\n\twriter <- wr\n}\n\nfunc UpdateDependency(file, dep string) bool {\n\twr := <-writer\n\tdefer func() { writer <- wr }()\n\n\texist, uptodate, fi, err := wr.UptodateFile(dep)\n\n\tif err != nil {\n\t\t\/\/ if there is an error with the dependency, we are going to\n\t\t\/\/ pretend everything is fine so the parser move forward\n\t\treturn true\n\t}\n\n\tif !exist {\n\t\twr.InsertFile(dep, fi)\n\t} else if !uptodate {\n\t\tremoveFileAndReparseDepends(dep, wr)\n\t\tfiles <- file\n\t\treturn false\n\t}\n\n\twr.InsertDependency(file, dep)\n\treturn true\n}\n\nfunc CloseFilesHandler() {\n\tclose(files)\n\n\twr := <-writer\n\twr.Close()\n\tclose(writer)\n\n\twatcher.Close()\n\n\twg.Wait()\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\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/logger\"\n\tmountpkg \"github.com\/googlecloudplatform\/gcsfuse\/internal\/mount\"\n\t\"github.com\/urfave\/cli\"\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 specified GCS bucket or all accessible buckets locally\",\n\t\tWriter:  os.Stderr,\n\t\tFlags: []cli.Flag{\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"app-name\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"The application name of this mount.\",\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\tcli.IntFlag{\n\t\t\t\tName:  \"rename-dir-limit\",\n\t\t\t\tValue: 0,\n\t\t\t\tUsage: \"Allow rename a directory containing fewer descendants \" +\n\t\t\t\t\t\"than this limit.\",\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:  \"endpoint\",\n\t\t\t\tValue: \"https:\/\/storage.googleapis.com:443\",\n\t\t\t\tUsage: \"The endpoint to connect to.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"billing-project\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Project to use for billing when accessing requester pays buckets. \" +\n\t\t\t\t\t\"(default: none)\",\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.StringFlag{\n\t\t\t\tName:  \"token-url\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"An url for getting an access token when key-file is absent.\",\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: -1,\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:  \"max-retry-sleep\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"The maximum duration allowed to sleep in a retry loop with \" +\n\t\t\t\t\t\"exponential backoff for failed requests to GCS backend. Once the \" +\n\t\t\t\t\t\"backoff duration exceeds this limit, the retry stops. The default \" +\n\t\t\t\t\t\"is 1 minute. A value of 0 disables retries.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"stat-cache-capacity\",\n\t\t\t\tValue: 4096,\n\t\t\t\tUsage: \"How many entries can the stat cache hold (impacts memory consumption)\",\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.BoolFlag{\n\t\t\t\tName:  \"experimental-local-file-cache\",\n\t\t\t\tUsage: \"Experimental: Cache GCS files on local disk for reads.\",\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\tcli.BoolFlag{\n\t\t\t\tName: \"disable-http2\",\n\t\t\t\tUsage: \"Once set, the protocol used for communicating with \" +\n\t\t\t\t\t\"GCS backend would be HTTP\/1.1, instead of the default HTTP\/2.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"max-conns-per-host\",\n\t\t\t\tValue: 10,\n\t\t\t\tUsage: \"The max number of TCP connections allowed per server. \" +\n\t\t\t\t\t\"This is effective when --disable-http2 is set.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Monitoring & Logging\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"experimental-stackdriver-export-interval\",\n\t\t\t\tValue: 0,\n\t\t\t\tUsage: \"Experimental: Export metrics to stackdriver with this interval. The default value 0 indicates no exporting.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"experimental-opentelemetry-collector-address\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Experimental: Export metrics to the OpenTelemetry collector at this address.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"log-file\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"The file for storing logs that can be parsed by \" +\n\t\t\t\t\t\"fluentd. When not provided, plain text logs are printed to \" +\n\t\t\t\t\t\"stdout.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"log-format\",\n\t\t\t\tValue: \"json\",\n\t\t\t\tUsage: \"The format of the log file: 'text' or 'json'.\",\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_fs\",\n\t\t\t\tUsage: \"Enable file system 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\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_mutex\",\n\t\t\t\tUsage: \"Print debug messages when a mutex is held too long.\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\ntype flagStorage struct {\n\tAppName    string\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\tRenameDirLimit int64\n\n\t\/\/ GCS\n\tEndpoint                           *url.URL\n\tBillingProject                     string\n\tKeyFile                            string\n\tTokenUrl                           string\n\tEgressBandwidthLimitBytesPerSecond float64\n\tOpRateLimitHz                      float64\n\n\t\/\/ Tuning\n\tMaxRetrySleep     time.Duration\n\tStatCacheCapacity int\n\tStatCacheTTL      time.Duration\n\tTypeCacheTTL      time.Duration\n\tLocalFileCache    bool\n\tTempDir           string\n\tDisableHTTP2      bool\n\tMaxConnsPerHost   int\n\n\t\/\/ Monitoring & Logging\n\tStackdriverExportInterval time.Duration\n\tOtelCollectorAddress      string\n\tLogFile                   string\n\tLogFormat                 string\n\n\t\/\/ Debugging\n\tDebugFuse       bool\n\tDebugFS         bool\n\tDebugGCS        bool\n\tDebugHTTP       bool\n\tDebugInvariants bool\n\tDebugMutex      bool\n}\n\nconst GCSFUSE_PARENT_PROCESS_DIR = \"gcsfuse-parent-process-dir\"\n\n\/\/ 1. Returns the same filepath in case of absolute path or empty filename.\n\/\/ 2. For relative path with . or .. or nothing, it resolves smartly the path\n\/\/ in case of child proces it resolves with respect to GCSFUSE_PARENT_PROCESS_DIR\n\/\/ otherwise with respect to the current working dir.\n\/\/ 3. For relative path starting with ~, it resolves with respect to home dir.\nfunc getResolvedPath(filePath string) (resolvedPath string, err error) {\n\tif filePath == \"\" || path.IsAbs(filePath) {\n\t\tresolvedPath = filePath\n\t\treturn\n\t}\n\n\t\/\/ Relative path starting with tilda (~)\n\tif strings.HasPrefix(filePath, \"~\/\") {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Fetch home dir: [%w]\", err)\n\t\t}\n\t\treturn filepath.Join(homeDir, filePath[2:]), err\n\t}\n\n\t\/\/ Means - relative path starting with ., .. or nothing.\n\tgcsfuseParentProcessDir, _ := os.LookupEnv(GCSFUSE_PARENT_PROCESS_DIR)\n\tgcsfuseParentProcessDir = strings.TrimSpace(gcsfuseParentProcessDir)\n\tif gcsfuseParentProcessDir == \"\" {\n\t\treturn filepath.Abs(filePath)\n\t} else {\n\t\treturn filepath.Join(gcsfuseParentProcessDir, filePath), err\n\t}\n}\n\n\/\/ This method resolves path in the context dictionary.\nfunc resolvePathForTheFlagInContext(flagKey string, c *cli.Context) (err error) {\n\tflagValue := c.String(flagKey)\n\tresolvedPath, err := getResolvedPath(flagValue)\n\tif err != nil {\n\t\treturn\n\t}\n\tc.Set(flagKey, resolvedPath)\n\tlogger.Infof(\"Value of [%s] resolved from [%s] to [%s]\\n\",\n\t\tflagKey, flagValue, resolvedPath)\n\treturn\n}\n\n\/\/ For parent process: it only resolves the path with respect to home folder.\n\/\/ For child process (when --foreground flag is disabled): it resolves\n\/\/ the path relative to both current directory and home directory\nfunc resolvePathForTheRequiredFlagInContext(c *cli.Context) (err error) {\n\terr = resolvePathForTheFlagInContext(\"log-file\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resolving for log-file: [%w]\", err)\n\t}\n\n\terr = resolvePathForTheFlagInContext(\"key-file\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resolving for key-file: [%w]\", err)\n\t}\n\n\treturn\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\tendpoint, err := url.Parse(c.String(\"endpoint\"))\n\tif err != nil {\n\t\tfmt.Printf(\"Could not parse endpoint\")\n\t\treturn nil\n\t}\n\tflags = &flagStorage{\n\t\tAppName:    c.String(\"app-name\"),\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\t\tRenameDirLimit: int64(c.Int(\"rename-dir-limit\")),\n\n\t\t\/\/ GCS,\n\t\tEndpoint:                           endpoint,\n\t\tBillingProject:                     c.String(\"billing-project\"),\n\t\tKeyFile:                            c.String(\"key-file\"),\n\t\tTokenUrl:                           c.String(\"token-url\"),\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\tMaxRetrySleep:     c.Duration(\"max-retry-sleep\"),\n\t\tStatCacheCapacity: c.Int(\"stat-cache-capacity\"),\n\t\tStatCacheTTL:      c.Duration(\"stat-cache-ttl\"),\n\t\tTypeCacheTTL:      c.Duration(\"type-cache-ttl\"),\n\t\tLocalFileCache:    c.Bool(\"experimental-local-file-cache\"),\n\t\tTempDir:           c.String(\"temp-dir\"),\n\t\tDisableHTTP2:      c.Bool(\"disable-http2\"),\n\t\tMaxConnsPerHost:   c.Int(\"max-conns-per-host\"),\n\n\t\t\/\/ Monitoring & Logging\n\t\tStackdriverExportInterval: c.Duration(\"experimental-stackdriver-export-interval\"),\n\t\tOtelCollectorAddress:      c.String(\"experimental-opentelemetry-collector-address\"),\n\t\tLogFile:                   c.String(\"log-file\"),\n\t\tLogFormat:                 c.String(\"log-format\"),\n\n\t\t\/\/ Debugging,\n\t\tDebugFuse:       c.Bool(\"debug_fuse\"),\n\t\tDebugGCS:        c.Bool(\"debug_gcs\"),\n\t\tDebugFS:         c.Bool(\"debug_fs\"),\n\t\tDebugHTTP:       c.Bool(\"debug_http\"),\n\t\tDebugInvariants: c.Bool(\"debug_invariants\"),\n\t\tDebugMutex:      c.Bool(\"debug_mutex\"),\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: %w\", 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>Suppressing the log info when resolve was no-op<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\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/logger\"\n\tmountpkg \"github.com\/googlecloudplatform\/gcsfuse\/internal\/mount\"\n\t\"github.com\/urfave\/cli\"\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 specified GCS bucket or all accessible buckets locally\",\n\t\tWriter:  os.Stderr,\n\t\tFlags: []cli.Flag{\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"app-name\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"The application name of this mount.\",\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\tcli.IntFlag{\n\t\t\t\tName:  \"rename-dir-limit\",\n\t\t\t\tValue: 0,\n\t\t\t\tUsage: \"Allow rename a directory containing fewer descendants \" +\n\t\t\t\t\t\"than this limit.\",\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:  \"endpoint\",\n\t\t\t\tValue: \"https:\/\/storage.googleapis.com:443\",\n\t\t\t\tUsage: \"The endpoint to connect to.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"billing-project\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Project to use for billing when accessing requester pays buckets. \" +\n\t\t\t\t\t\"(default: none)\",\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.StringFlag{\n\t\t\t\tName:  \"token-url\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"An url for getting an access token when key-file is absent.\",\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: -1,\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:  \"max-retry-sleep\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"The maximum duration allowed to sleep in a retry loop with \" +\n\t\t\t\t\t\"exponential backoff for failed requests to GCS backend. Once the \" +\n\t\t\t\t\t\"backoff duration exceeds this limit, the retry stops. The default \" +\n\t\t\t\t\t\"is 1 minute. A value of 0 disables retries.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"stat-cache-capacity\",\n\t\t\t\tValue: 4096,\n\t\t\t\tUsage: \"How many entries can the stat cache hold (impacts memory consumption)\",\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.BoolFlag{\n\t\t\t\tName:  \"experimental-local-file-cache\",\n\t\t\t\tUsage: \"Experimental: Cache GCS files on local disk for reads.\",\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\tcli.BoolFlag{\n\t\t\t\tName: \"disable-http2\",\n\t\t\t\tUsage: \"Once set, the protocol used for communicating with \" +\n\t\t\t\t\t\"GCS backend would be HTTP\/1.1, instead of the default HTTP\/2.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"max-conns-per-host\",\n\t\t\t\tValue: 10,\n\t\t\t\tUsage: \"The max number of TCP connections allowed per server. \" +\n\t\t\t\t\t\"This is effective when --disable-http2 is set.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Monitoring & Logging\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"experimental-stackdriver-export-interval\",\n\t\t\t\tValue: 0,\n\t\t\t\tUsage: \"Experimental: Export metrics to stackdriver with this interval. The default value 0 indicates no exporting.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"experimental-opentelemetry-collector-address\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Experimental: Export metrics to the OpenTelemetry collector at this address.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"log-file\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"The file for storing logs that can be parsed by \" +\n\t\t\t\t\t\"fluentd. When not provided, plain text logs are printed to \" +\n\t\t\t\t\t\"stdout.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"log-format\",\n\t\t\t\tValue: \"json\",\n\t\t\t\tUsage: \"The format of the log file: 'text' or 'json'.\",\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_fs\",\n\t\t\t\tUsage: \"Enable file system 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\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_mutex\",\n\t\t\t\tUsage: \"Print debug messages when a mutex is held too long.\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\ntype flagStorage struct {\n\tAppName    string\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\tRenameDirLimit int64\n\n\t\/\/ GCS\n\tEndpoint                           *url.URL\n\tBillingProject                     string\n\tKeyFile                            string\n\tTokenUrl                           string\n\tEgressBandwidthLimitBytesPerSecond float64\n\tOpRateLimitHz                      float64\n\n\t\/\/ Tuning\n\tMaxRetrySleep     time.Duration\n\tStatCacheCapacity int\n\tStatCacheTTL      time.Duration\n\tTypeCacheTTL      time.Duration\n\tLocalFileCache    bool\n\tTempDir           string\n\tDisableHTTP2      bool\n\tMaxConnsPerHost   int\n\n\t\/\/ Monitoring & Logging\n\tStackdriverExportInterval time.Duration\n\tOtelCollectorAddress      string\n\tLogFile                   string\n\tLogFormat                 string\n\n\t\/\/ Debugging\n\tDebugFuse       bool\n\tDebugFS         bool\n\tDebugGCS        bool\n\tDebugHTTP       bool\n\tDebugInvariants bool\n\tDebugMutex      bool\n}\n\nconst GCSFUSE_PARENT_PROCESS_DIR = \"gcsfuse-parent-process-dir\"\n\n\/\/ 1. Returns the same filepath in case of absolute path or empty filename.\n\/\/ 2. For relative path with . or .. or nothing, it resolves smartly the path\n\/\/ in case of child proces it resolves with respect to GCSFUSE_PARENT_PROCESS_DIR\n\/\/ otherwise with respect to the current working dir.\n\/\/ 3. For relative path starting with ~, it resolves with respect to home dir.\nfunc getResolvedPath(filePath string) (resolvedPath string, err error) {\n\tif filePath == \"\" || path.IsAbs(filePath) {\n\t\tresolvedPath = filePath\n\t\treturn\n\t}\n\n\t\/\/ Relative path starting with tilda (~)\n\tif strings.HasPrefix(filePath, \"~\/\") {\n\t\thomeDir, err := os.UserHomeDir()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Fetch home dir: [%w]\", err)\n\t\t}\n\t\treturn filepath.Join(homeDir, filePath[2:]), err\n\t}\n\n\t\/\/ Means - relative path starting with ., .. or nothing.\n\tgcsfuseParentProcessDir, _ := os.LookupEnv(GCSFUSE_PARENT_PROCESS_DIR)\n\tgcsfuseParentProcessDir = strings.TrimSpace(gcsfuseParentProcessDir)\n\tif gcsfuseParentProcessDir == \"\" {\n\t\treturn filepath.Abs(filePath)\n\t} else {\n\t\treturn filepath.Join(gcsfuseParentProcessDir, filePath), err\n\t}\n}\n\n\/\/ This method resolves path in the context dictionary.\nfunc resolvePathForTheFlagInContext(flagKey string, c *cli.Context) (err error) {\n\tflagValue := c.String(flagKey)\n\tresolvedPath, err := getResolvedPath(flagValue)\n\tif err != nil {\n\t\treturn\n\t}\n\tc.Set(flagKey, resolvedPath)\n\n\tif flagValue != resolvedPath {\n\t\tlogger.Infof(\"Value of [%s] resolved from [%s] to [%s]\\n\",\n\t\t\tflagKey, flagValue, resolvedPath)\n\t}\n\n\treturn\n}\n\n\/\/ For parent process: it only resolves the path with respect to home folder.\n\/\/ For child process (when --foreground flag is disabled): it resolves\n\/\/ the path relative to both current directory and home directory\nfunc resolvePathForTheRequiredFlagInContext(c *cli.Context) (err error) {\n\terr = resolvePathForTheFlagInContext(\"log-file\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resolving for log-file: [%w]\", err)\n\t}\n\n\terr = resolvePathForTheFlagInContext(\"key-file\", c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"resolving for key-file: [%w]\", err)\n\t}\n\n\treturn\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\tendpoint, err := url.Parse(c.String(\"endpoint\"))\n\tif err != nil {\n\t\tfmt.Printf(\"Could not parse endpoint\")\n\t\treturn nil\n\t}\n\tflags = &flagStorage{\n\t\tAppName:    c.String(\"app-name\"),\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\t\tRenameDirLimit: int64(c.Int(\"rename-dir-limit\")),\n\n\t\t\/\/ GCS,\n\t\tEndpoint:                           endpoint,\n\t\tBillingProject:                     c.String(\"billing-project\"),\n\t\tKeyFile:                            c.String(\"key-file\"),\n\t\tTokenUrl:                           c.String(\"token-url\"),\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\tMaxRetrySleep:     c.Duration(\"max-retry-sleep\"),\n\t\tStatCacheCapacity: c.Int(\"stat-cache-capacity\"),\n\t\tStatCacheTTL:      c.Duration(\"stat-cache-ttl\"),\n\t\tTypeCacheTTL:      c.Duration(\"type-cache-ttl\"),\n\t\tLocalFileCache:    c.Bool(\"experimental-local-file-cache\"),\n\t\tTempDir:           c.String(\"temp-dir\"),\n\t\tDisableHTTP2:      c.Bool(\"disable-http2\"),\n\t\tMaxConnsPerHost:   c.Int(\"max-conns-per-host\"),\n\n\t\t\/\/ Monitoring & Logging\n\t\tStackdriverExportInterval: c.Duration(\"experimental-stackdriver-export-interval\"),\n\t\tOtelCollectorAddress:      c.String(\"experimental-opentelemetry-collector-address\"),\n\t\tLogFile:                   c.String(\"log-file\"),\n\t\tLogFormat:                 c.String(\"log-format\"),\n\n\t\t\/\/ Debugging,\n\t\tDebugFuse:       c.Bool(\"debug_fuse\"),\n\t\tDebugGCS:        c.Bool(\"debug_gcs\"),\n\t\tDebugFS:         c.Bool(\"debug_fs\"),\n\t\tDebugHTTP:       c.Bool(\"debug_http\"),\n\t\tDebugInvariants: c.Bool(\"debug_invariants\"),\n\t\tDebugMutex:      c.Bool(\"debug_mutex\"),\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: %w\", 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 felixcheck\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/streadway\/amqp\"\n\t\"github.com\/tatsushid\/go-fastping\"\n)\n\nimport (\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tsysName     = \"1.3.6.1.2.1.1.5.0\"\n\tmaxPingTime = 4 * time.Second\n)\n\ntype CheckFunction func() Event\ntype MultiCheckFunction func() []Event\n\nfunc (f CheckFunction) Tags(tags ...string) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Tags = tags\n\t\treturn result\n\t}\n}\n\nfunc (f CheckFunction) Attributes(attributes map[string]string) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Attributes = attributes\n\t\treturn result\n\t}\n}\n\nfunc (f CheckFunction) Ttl(ttl float32) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Ttl = ttl\n\t\treturn result\n\t}\n}\n\nfunc NewPingChecker(host, service, ip string) CheckFunction {\n\treturn func() Event {\n\t\tvar retRtt time.Duration = 0\n\t\tvar result Event = Event{Host: host, Service: service, State: \"critical\"}\n\n\t\tp := fastping.NewPinger()\n\t\tp.MaxRTT = maxPingTime\n\t\tra, err := net.ResolveIPAddr(\"ip4:icmp\", ip)\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t}\n\n\t\tp.AddIPAddr(ra)\n\t\tp.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {\n\t\t\tresult.State = \"ok\"\n\t\t\tresult.Metric = float32(retRtt.Nanoseconds() \/ 1e6)\n\t\t}\n\n\t\terr = p.Run()\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t}\n\t\treturn result\n\t}\n}\n\ntype TcpCheckerConf struct {\n\tretries   int\n\ttimeout   time.Duration\n\tretrytime time.Duration\n}\n\nvar DefaultTcpCheckConf = TcpCheckerConf{\n\tretries:   3,\n\ttimeout:   2 * time.Second,\n\tretrytime: 1 * time.Second,\n}\n\nfunc NewTcpPortChecker(host, service, ip string, port int, conf TcpCheckerConf) CheckFunction {\n\treturn func() Event {\n\t\tvar err error\n\t\tvar conn net.Conn\n\n\t\tfor attempt := 0; attempt < conf.retries; attempt++ {\n\t\t\tconn, err = net.DialTimeout(\"tcp\", fmt.Sprintf(\"%s:%d\", ip, port), conf.timeout)\n\t\t\tif err == nil {\n\t\t\t\tconn.Close()\n\t\t\t\treturn Event{Host: host, Service: service, State: \"ok\"}\n\t\t\t}\n\t\t\ttime.Sleep(conf.retrytime)\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: \"critical\"}\n\t}\n}\n\ntype ValidateHttpResponseFunction func(resp *http.Response) (state, description string)\n\nfunc BodyGreaterThan(minLength int) ValidateHttpResponseFunction {\n\treturn func(httpResp *http.Response) (state, description string) {\n\t\tif httpResp.StatusCode != 200 {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Response %d\", httpResp.StatusCode)\n\t\t}\n\t\tif httpResp.Body == nil {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Empty body\")\n\t\t}\n\t\tbody, err := ioutil.ReadAll(httpResp.Body)\n\t\tif err != nil {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Error geting body\")\n\t\t}\n\t\tif len(body) < minLength {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Obtained %d bytes, expected more than %d\", len(body), minLength)\n\t\t} else {\n\t\t\treturn \"ok\", \"\"\n\t\t}\n\t\treturn \"critical\", \"unknown condition\"\n\t}\n}\n\nfunc NewGenericHttpChecker(host, service, url string, validationFunc ValidateHttpResponseFunction) CheckFunction {\n\treturn func() Event {\n\t\tvar t1 = time.Now()\n\n\t\tresponse, err := http.Get(url)\n\t\tmilliseconds := float32((time.Now().Sub(t1)).Nanoseconds() \/ 1e6)\n\t\tresult := Event{Host: host, Service: service, State: \"critical\", Metric: milliseconds}\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t} else {\n\t\t\tif response.Body != nil {\n\t\t\t\tdefer response.Body.Close()\n\t\t\t}\n\t\t\tresult.State, result.Description = validationFunc(response)\n\t\t}\n\t\treturn result\n\t}\n}\n\nfunc NewHttpChecker(host, service, url string, expectedStatusCode int) CheckFunction {\n\treturn NewGenericHttpChecker(host, service, url,\n\t\tfunc(httpResp *http.Response) (string, string) {\n\t\t\tif httpResp.StatusCode == expectedStatusCode {\n\t\t\t\treturn \"ok\", \"\"\n\t\t\t} else {\n\t\t\t\treturn \"critical\", fmt.Sprintf(\"Response %d\", httpResp.StatusCode)\n\t\t\t}\n\t\t})\n}\n\ntype SnmpCheckerConf struct {\n\tretries    int\n\ttimeout    time.Duration\n\toidToCheck string\n}\n\nvar DefaultSnmpCheckConf = SnmpCheckerConf{\n\tretries:    1,\n\ttimeout:    1 * time.Second,\n\toidToCheck: sysName,\n}\n\nfunc NewSnmpChecker(host, service, ip, community string, conf SnmpCheckerConf) CheckFunction {\n\treturn func() Event {\n\n\t\t_, err := snmpGet(ip, community, []string{conf.oidToCheck}, conf.timeout, conf.retries)\n\t\tif err == nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"ok\", Description: err.Error()}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewC4CMTSTempChecker(host, service, ip, community string, maxAllowedTemp int) CheckFunction {\n\treturn func() Event {\n\n\t\tresult, err := snmpWalk(ip, community, \"1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29\", 2*time.Second, 1)\n\n\t\tif err == nil {\n\t\t\tmax := 0\n\t\t\tfor _, r := range result {\n\t\t\t\tif r.Value.(int) != 999 && r.Value.(int) > max {\n\t\t\t\t\tmax = r.Value.(int)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc getMaxValueFromSnmpWalk(oid, ip, community string) (uint, error) {\n\tresult, err := snmpWalk(ip, community, oid, 2*time.Second, 1)\n\tif err == nil {\n\t\tmax := uint(0)\n\t\tfor _, r := range result {\n\t\t\tif r.Value.(uint) > max {\n\t\t\t\tmax = r.Value.(uint)\n\t\t\t}\n\t\t}\n\t\treturn max, nil\n\t} else {\n\t\treturn 0, err\n\t}\n}\n\nfunc NewJuniperTempChecker(host, service, ip, community string, maxAllowedTemp uint) CheckFunction {\n\treturn func() Event {\n\t\tmax, err := getMaxValueFromSnmpWalk(\"1.3.6.1.4.1.2636.3.1.13.1.7\", ip, community)\n\t\tif err == nil {\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewJuniperCpuChecker(host, service, ip, community string, maxAllowedTemp uint) CheckFunction {\n\treturn func() Event {\n\t\tmax, err := getMaxValueFromSnmpWalk(\"1.3.6.1.4.1.2636.3.1.13.1.8\", ip, community)\n\t\tif err == nil {\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewRabbitMQQueueLenCheck(host, service, amqpuri, queue string, max int) CheckFunction {\n\treturn func() Event {\n\t\tresult := Event{Host: host, Service: service}\n\n\t\tconn, err := amqp.Dial(amqpuri)\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\n\t\tch, err := conn.Channel()\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\n\t\tqueueInfo, err := ch.QueueInspect(queue)\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\n\t\tvar state string = \"critical\"\n\t\tif queueInfo.Messages <= max {\n\t\t\tstate = \"ok\"\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(queueInfo.Messages)}\n\t}\n}\n\nfunc NewMysqlConnectionCheck(host, service, mysqluri string) CheckFunction {\n\treturn func() Event {\n\t\tu, err := url.Parse(mysqluri)\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\n\t\tif u.User == nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: \"No user defined\"}\n\t\t}\n\t\tpassword, hasPassword := u.User.Password()\n\t\tif !hasPassword {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: \"No password defined\"}\n\t\t}\n\t\thostAndPort := u.Host\n\t\tif !strings.Contains(hostAndPort, \":\") {\n\t\t\thostAndPort = hostAndPort + \":3306\"\n\t\t}\n\t\tcon, err := sql.Open(\"mysql\", u.User.Username()+\":\"+password+\"@\"+\"tcp(\"+hostAndPort+\")\"+u.Path)\n\t\tdefer con.Close()\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t\tq := `select CURTIME()`\n\t\trow := con.QueryRow(q)\n\t\tvar date string\n\t\terr = row.Scan(&date)\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: \"ok\"}\n\t}\n}\n\ntype ObtainMetricFunction func() float32\ntype CalculateStateFunction func(float32) string\n\nfunc NewGenericCheck(host, service string, metricFunc ObtainMetricFunction, stateFunc CalculateStateFunction) CheckFunction {\n\treturn func() Event {\n\t\tvalue := metricFunc()\n\t\tvar state string = stateFunc(value)\n\t\treturn Event{Host: host, Service: service, State: state, Metric: value}\n\t}\n}\n<commit_msg>Added metric to NewTcpPortChecker<commit_after>package felixcheck\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/streadway\/amqp\"\n\t\"github.com\/tatsushid\/go-fastping\"\n)\n\nimport (\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tsysName     = \"1.3.6.1.2.1.1.5.0\"\n\tmaxPingTime = 4 * time.Second\n)\n\ntype CheckFunction func() Event\ntype MultiCheckFunction func() []Event\n\nfunc (f CheckFunction) Tags(tags ...string) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Tags = tags\n\t\treturn result\n\t}\n}\n\nfunc (f CheckFunction) Attributes(attributes map[string]string) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Attributes = attributes\n\t\treturn result\n\t}\n}\n\nfunc (f CheckFunction) Ttl(ttl float32) CheckFunction {\n\treturn func() Event {\n\t\tresult := f()\n\t\tresult.Ttl = ttl\n\t\treturn result\n\t}\n}\n\nfunc NewPingChecker(host, service, ip string) CheckFunction {\n\treturn func() Event {\n\t\tvar retRtt time.Duration = 0\n\t\tvar result Event = Event{Host: host, Service: service, State: \"critical\"}\n\n\t\tp := fastping.NewPinger()\n\t\tp.MaxRTT = maxPingTime\n\t\tra, err := net.ResolveIPAddr(\"ip4:icmp\", ip)\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t}\n\n\t\tp.AddIPAddr(ra)\n\t\tp.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {\n\t\t\tresult.State = \"ok\"\n\t\t\tresult.Metric = float32(retRtt.Nanoseconds() \/ 1e6)\n\t\t}\n\n\t\terr = p.Run()\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t}\n\t\treturn result\n\t}\n}\n\ntype TcpCheckerConf struct {\n\tretries   int\n\ttimeout   time.Duration\n\tretrytime time.Duration\n}\n\nvar DefaultTcpCheckConf = TcpCheckerConf{\n\tretries:   3,\n\ttimeout:   2 * time.Second,\n\tretrytime: 1 * time.Second,\n}\n\nfunc NewTcpPortChecker(host, service, ip string, port int, conf TcpCheckerConf) CheckFunction {\n\treturn func() Event {\n\t\tvar err error\n\t\tvar conn net.Conn\n\n\t\tfor attempt := 0; attempt < conf.retries; attempt++ {\n\t\t\tvar t1 = time.Now()\n\t\t\tconn, err = net.DialTimeout(\"tcp\", fmt.Sprintf(\"%s:%d\", ip, port), conf.timeout)\n\t\t\tif err == nil {\n\t\t\t\tconn.Close()\n\t\t\t\tmilliseconds := float32((time.Now().Sub(t1)).Nanoseconds() \/ 1e6)\n\t\t\t\treturn Event{Host: host, Service: service, State: \"ok\", Metric: milliseconds}\n\t\t\t}\n\t\t\ttime.Sleep(conf.retrytime)\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: \"critical\"}\n\t}\n}\n\ntype ValidateHttpResponseFunction func(resp *http.Response) (state, description string)\n\nfunc BodyGreaterThan(minLength int) ValidateHttpResponseFunction {\n\treturn func(httpResp *http.Response) (state, description string) {\n\t\tif httpResp.StatusCode != 200 {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Response %d\", httpResp.StatusCode)\n\t\t}\n\t\tif httpResp.Body == nil {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Empty body\")\n\t\t}\n\t\tbody, err := ioutil.ReadAll(httpResp.Body)\n\t\tif err != nil {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Error geting body\")\n\t\t}\n\t\tif len(body) < minLength {\n\t\t\treturn \"critical\", fmt.Sprintf(\"Obtained %d bytes, expected more than %d\", len(body), minLength)\n\t\t} else {\n\t\t\treturn \"ok\", \"\"\n\t\t}\n\t\treturn \"critical\", \"unknown condition\"\n\t}\n}\n\nfunc NewGenericHttpChecker(host, service, url string, validationFunc ValidateHttpResponseFunction) CheckFunction {\n\treturn func() Event {\n\t\tvar t1 = time.Now()\n\n\t\tresponse, err := http.Get(url)\n\t\tmilliseconds := float32((time.Now().Sub(t1)).Nanoseconds() \/ 1e6)\n\t\tresult := Event{Host: host, Service: service, State: \"critical\", Metric: milliseconds}\n\t\tif err != nil {\n\t\t\tresult.Description = err.Error()\n\t\t} else {\n\t\t\tif response.Body != nil {\n\t\t\t\tdefer response.Body.Close()\n\t\t\t}\n\t\t\tresult.State, result.Description = validationFunc(response)\n\t\t}\n\t\treturn result\n\t}\n}\n\nfunc NewHttpChecker(host, service, url string, expectedStatusCode int) CheckFunction {\n\treturn NewGenericHttpChecker(host, service, url,\n\t\tfunc(httpResp *http.Response) (string, string) {\n\t\t\tif httpResp.StatusCode == expectedStatusCode {\n\t\t\t\treturn \"ok\", \"\"\n\t\t\t} else {\n\t\t\t\treturn \"critical\", fmt.Sprintf(\"Response %d\", httpResp.StatusCode)\n\t\t\t}\n\t\t})\n}\n\ntype SnmpCheckerConf struct {\n\tretries    int\n\ttimeout    time.Duration\n\toidToCheck string\n}\n\nvar DefaultSnmpCheckConf = SnmpCheckerConf{\n\tretries:    1,\n\ttimeout:    1 * time.Second,\n\toidToCheck: sysName,\n}\n\nfunc NewSnmpChecker(host, service, ip, community string, conf SnmpCheckerConf) CheckFunction {\n\treturn func() Event {\n\n\t\t_, err := snmpGet(ip, community, []string{conf.oidToCheck}, conf.timeout, conf.retries)\n\t\tif err == nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"ok\", Description: err.Error()}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewC4CMTSTempChecker(host, service, ip, community string, maxAllowedTemp int) CheckFunction {\n\treturn func() Event {\n\n\t\tresult, err := snmpWalk(ip, community, \"1.3.6.1.4.1.4998.1.1.10.1.4.2.1.29\", 2*time.Second, 1)\n\n\t\tif err == nil {\n\t\t\tmax := 0\n\t\t\tfor _, r := range result {\n\t\t\t\tif r.Value.(int) != 999 && r.Value.(int) > max {\n\t\t\t\t\tmax = r.Value.(int)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc getMaxValueFromSnmpWalk(oid, ip, community string) (uint, error) {\n\tresult, err := snmpWalk(ip, community, oid, 2*time.Second, 1)\n\tif err == nil {\n\t\tmax := uint(0)\n\t\tfor _, r := range result {\n\t\t\tif r.Value.(uint) > max {\n\t\t\t\tmax = r.Value.(uint)\n\t\t\t}\n\t\t}\n\t\treturn max, nil\n\t} else {\n\t\treturn 0, err\n\t}\n}\n\nfunc NewJuniperTempChecker(host, service, ip, community string, maxAllowedTemp uint) CheckFunction {\n\treturn func() Event {\n\t\tmax, err := getMaxValueFromSnmpWalk(\"1.3.6.1.4.1.2636.3.1.13.1.7\", ip, community)\n\t\tif err == nil {\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewJuniperCpuChecker(host, service, ip, community string, maxAllowedTemp uint) CheckFunction {\n\treturn func() Event {\n\t\tmax, err := getMaxValueFromSnmpWalk(\"1.3.6.1.4.1.2636.3.1.13.1.8\", ip, community)\n\t\tif err == nil {\n\t\t\tvar state string = \"critical\"\n\t\t\tif max < maxAllowedTemp {\n\t\t\t\tstate = \"ok\"\n\t\t\t}\n\t\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(max)}\n\t\t} else {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t}\n}\n\nfunc NewRabbitMQQueueLenCheck(host, service, amqpuri, queue string, max int) CheckFunction {\n\treturn func() Event {\n\t\tresult := Event{Host: host, Service: service}\n\n\t\tconn, err := amqp.Dial(amqpuri)\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\n\t\tch, err := conn.Channel()\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\t\tdefer ch.Close()\n\t\tdefer conn.Close()\n\n\t\tqueueInfo, err := ch.QueueInspect(queue)\n\t\tif err != nil {\n\t\t\tresult.State = \"critical\"\n\t\t\tresult.Description = err.Error()\n\t\t\treturn result\n\t\t}\n\n\t\tvar state string = \"critical\"\n\t\tif queueInfo.Messages <= max {\n\t\t\tstate = \"ok\"\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: state, Metric: float32(queueInfo.Messages)}\n\t}\n}\n\nfunc NewMysqlConnectionCheck(host, service, mysqluri string) CheckFunction {\n\treturn func() Event {\n\t\tu, err := url.Parse(mysqluri)\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\n\t\tif u.User == nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: \"No user defined\"}\n\t\t}\n\t\tpassword, hasPassword := u.User.Password()\n\t\tif !hasPassword {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: \"No password defined\"}\n\t\t}\n\t\thostAndPort := u.Host\n\t\tif !strings.Contains(hostAndPort, \":\") {\n\t\t\thostAndPort = hostAndPort + \":3306\"\n\t\t}\n\t\tcon, err := sql.Open(\"mysql\", u.User.Username()+\":\"+password+\"@\"+\"tcp(\"+hostAndPort+\")\"+u.Path)\n\t\tdefer con.Close()\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t\tq := `select CURTIME()`\n\t\trow := con.QueryRow(q)\n\t\tvar date string\n\t\terr = row.Scan(&date)\n\t\tif err != nil {\n\t\t\treturn Event{Host: host, Service: service, State: \"critical\", Description: err.Error()}\n\t\t}\n\t\treturn Event{Host: host, Service: service, State: \"ok\"}\n\t}\n}\n\ntype ObtainMetricFunction func() float32\ntype CalculateStateFunction func(float32) string\n\nfunc NewGenericCheck(host, service string, metricFunc ObtainMetricFunction, stateFunc CalculateStateFunction) CheckFunction {\n\treturn func() Event {\n\t\tvalue := metricFunc()\n\t\tvar state string = stateFunc(value)\n\t\treturn Event{Host: host, Service: service, State: state, Metric: value}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximun keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, log_dir string, log_rotate int64) http.Server {\n\tapache_log, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif log_dir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stdout),\n\t\t}\n\t} else if log_dir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stderr),\n\t\t}\n\t} else if log_dir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlog_file := log_dir\n\tlink_name := log_dir\n\tif !strings.HasSuffix(log_dir, \"\/\") {\n\t\tlog_file += \"\/\"\n\t\tlink_name += \"\/\"\n\n\t}\n\tlog_file += \"access_log.%Y%m%d%H%M\"\n\tlink_name += \"current\"\n\n\trl, err := rotatelogs.New(\n\t\tlog_file,\n\t\trotatelogs.WithLinkName(link_name),\n\t\trotatelogs.WithMaxAge(time.Duration(log_rotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"rotatelogs.New failed: %v\", err))\n\t}\n\n\treturn http.Server{\n\t\tHandler: apache_log.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy_handler.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\toriginalHost := r.Host\n\t\thostSplited := strings.Split(originalHost, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplited {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplited[0:lastPartIndex], \".\")\n\t\tpr.Host = pr.URL.Host\n\t\tif hostSplited[lastPartIndex] == \"ccnproxy-https\" || hostSplited[lastPartIndex] == \"ccnproxy-secure\" || hostSplited[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy_handler.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<commit_msg>split host and port<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximun keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, log_dir string, log_rotate int64) http.Server {\n\tapache_log, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif log_dir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stdout),\n\t\t}\n\t} else if log_dir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stderr),\n\t\t}\n\t} else if log_dir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlog_file := log_dir\n\tlink_name := log_dir\n\tif !strings.HasSuffix(log_dir, \"\/\") {\n\t\tlog_file += \"\/\"\n\t\tlink_name += \"\/\"\n\n\t}\n\tlog_file += \"access_log.%Y%m%d%H%M\"\n\tlink_name += \"current\"\n\n\trl, err := rotatelogs.New(\n\t\tlog_file,\n\t\trotatelogs.WithLinkName(link_name),\n\t\trotatelogs.WithMaxAge(time.Duration(log_rotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"rotatelogs.New failed: %v\", err))\n\t}\n\n\treturn http.Server{\n\t\tHandler: apache_log.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy_handler.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\thost, _, err := net.SplitHostPort(r.Host)\n\t\tif err != nil {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\thostSplited := strings.Split(host, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplited {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplited[0:lastPartIndex], \".\")\n\t\tpr.Host = pr.URL.Host\n\t\tif hostSplited[lastPartIndex] == \"ccnproxy-https\" || hostSplited[lastPartIndex] == \"ccnproxy-secure\" || hostSplited[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy_handler.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 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 k8sTest\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/test\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar _ = Describe(\"K8sTunnelTest\", func() {\n\n\tvar kubectl *helpers.Kubectl\n\tvar demoDSPath string\n\tvar initialized bool\n\tvar logger *logrus.Entry\n\n\tinitialize := func() {\n\t\tif initialized == true {\n\t\t\treturn\n\t\t}\n\t\tlogger = log.WithFields(logrus.Fields{\"testName\": \"K8sTunnelTest\"})\n\t\tlogger.Info(\"Starting\")\n\n\t\tkubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)\n\t\tdemoDSPath = kubectl.ManifestGet(\"demo_ds.yaml\")\n\t\tkubectl.Exec(\"kubectl -n kube-system delete ds cilium\")\n\t\t\/\/ Expect(res.Correct()).Should(BeTrue())\n\n\t\twaitToDeleteCilium(kubectl, logger)\n\t\tinitialized = true\n\t}\n\n\tBeforeEach(func() {\n\t\tinitialize()\n\t\tkubectl.NodeCleanMetadata()\n\t\tkubectl.Apply(demoDSPath)\n\t}, 600)\n\n\tAfterEach(func() {\n\t\tkubectl.Delete(demoDSPath)\n\t})\n\n\tIt(\"Check VXLAN mode\", func() {\n\t\tpath := kubectl.ManifestGet(\"cilium_ds.yaml\")\n\t\tkubectl.Apply(path)\n\t\t_, err := kubectl.WaitforPods(helpers.KubeSystemNamespace, \"-l k8s-app=cilium\", 5000)\n\t\tExpect(err).Should(BeNil())\n\n\t\tciliumPod, err := kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)\n\t\tExpect(err).Should(BeNil())\n\n\t\t_, err = kubectl.CiliumNodesWait()\n\t\tExpect(err).Should(BeNil())\n\t\t\/\/Make sure that we delete the ds in case of fail\n\t\tdefer kubectl.Delete(path)\n\n\t\tBy(\"Checking that BPF tunnels are in place\")\n\t\tstatus := kubectl.CiliumExec(ciliumPod, \"cilium bpf tunnel list | wc -l\")\n\t\tif tunnels, _ := status.IntOutput(); tunnels != 4 {\n\t\t\tcmds := []string{\n\t\t\t\t\"cilium bpf tunnel list\",\n\t\t\t}\n\t\t\tkubectl.CiliumReport(helpers.KubeSystemNamespace, ciliumPod, cmds)\n\t\t}\n\n\t\tstatus.ExpectSuccess()\n\t\tExpect(status.IntOutput()).Should(Equal(4))\n\n\t\tBy(\"Checking that BPF tunnels are working correctly\")\n\t\ttunnStatus := isNodeNetworkingWorking(kubectl, \"zgroup=testDS\")\n\t\tExpect(tunnStatus).Should(BeTrue())\n\t\tkubectl.Delete(path)\n\t\twaitToDeleteCilium(kubectl, logger)\n\t}, 600)\n\n\tIt(\"Check Geneve mode\", func() {\n\t\tpath := kubectl.ManifestGet(\"cilium_ds_geneve.yaml\")\n\t\tkubectl.Apply(path)\n\t\t_, err := kubectl.WaitforPods(helpers.KubeSystemNamespace, \"-l k8s-app=cilium\", 5000)\n\t\tExpect(err).Should(BeNil())\n\n\t\tciliumPod, err := kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)\n\t\tExpect(err).Should(BeNil())\n\n\t\t_, err = kubectl.CiliumNodesWait()\n\t\tExpect(err).Should(BeNil())\n\n\t\t\/\/Make sure that we delete the ds in case of fail\n\t\tdefer kubectl.Delete(path)\n\n\t\t\/\/Check that cilium detects a\n\t\tBy(\"Checking that BPF tunnels are in place\")\n\t\tstatus := kubectl.CiliumExec(ciliumPod, \"cilium bpf tunnel list | wc -l\")\n\t\tstatus.ExpectSuccess()\n\t\tif tunnels, _ := status.IntOutput(); tunnels != 4 {\n\t\t\tcmds := []string{\n\t\t\t\t\"cilium bpf tunnel list\",\n\t\t\t}\n\t\t\tkubectl.CiliumReport(helpers.KubeSystemNamespace, ciliumPod, cmds)\n\t\t}\n\t\tExpect(status.IntOutput()).Should(Equal(4))\n\n\t\tBy(\"Checking that BPF tunnels are working correctly\")\n\t\ttunnStatus := isNodeNetworkingWorking(kubectl, \"zgroup=testDS\")\n\t\tExpect(tunnStatus).Should(BeTrue())\n\t\t\/\/FIXME: Maybe added here a cilium bpf tunnel status?\n\t\tkubectl.Delete(path)\n\t\twaitToDeleteCilium(kubectl, logger)\n\t}, 600)\n})\n\nfunc isNodeNetworkingWorking(kubectl *helpers.Kubectl, filter string) bool {\n\twaitReady, _ := kubectl.WaitforPods(helpers.DefaultNamespace, fmt.Sprintf(\"-l %s\", filter), 3000)\n\tExpect(waitReady).Should(BeTrue())\n\tpods, err := kubectl.GetPodNames(helpers.DefaultNamespace, filter)\n\tExpect(err).Should(BeNil())\n\tpodIP, err := kubectl.Get(\n\t\thelpers.DefaultNamespace,\n\t\tfmt.Sprintf(\"pod %s -o json\", pods[1])).Filter(\"{.status.podIP}\")\n\tExpect(err).Should(BeNil())\n\t_, err = kubectl.ExecPodCmd(helpers.DefaultNamespace, pods[0], helpers.Ping(podIP.String()))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc waitToDeleteCilium(kubectl *helpers.Kubectl, logger *logrus.Entry) {\n\tstatus := 1\n\tfor status > 0 {\n\t\tpods, err := kubectl.GetCiliumPods(helpers.KubeSystemNamespace)\n\t\tstatus := len(pods)\n\t\tlogger.Infof(\"Cilium pods terminating '%d' err='%v' pods='%v'\", status, err, pods)\n\t\tif status == 0 {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n<commit_msg>Ginkgo: Fix timeout on K8sTunnelTest<commit_after>\/\/ Copyright 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 k8sTest\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/test\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar _ = Describe(\"K8sTunnelTest\", func() {\n\n\tvar kubectl *helpers.Kubectl\n\tvar demoDSPath string\n\tvar initialized bool\n\tvar logger *logrus.Entry\n\n\tinitialize := func() {\n\t\tif initialized == true {\n\t\t\treturn\n\t\t}\n\t\tlogger = log.WithFields(logrus.Fields{\"testName\": \"K8sTunnelTest\"})\n\t\tlogger.Info(\"Starting\")\n\n\t\tkubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)\n\t\tdemoDSPath = kubectl.ManifestGet(\"demo_ds.yaml\")\n\t\tkubectl.Exec(\"kubectl -n kube-system delete ds cilium\")\n\t\t\/\/ Expect(res.Correct()).Should(BeTrue())\n\n\t\twaitToDeleteCilium(kubectl, logger)\n\t\tinitialized = true\n\t}\n\n\tBeforeEach(func() {\n\t\tinitialize()\n\t\tkubectl.NodeCleanMetadata()\n\t\tkubectl.Apply(demoDSPath)\n\t}, 600)\n\n\tAfterEach(func() {\n\t\tif CurrentGinkgoTestDescription().Failed {\n\t\t\tciliumPod, _ := kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)\n\t\t\tkubectl.CiliumReport(helpers.KubeSystemNamespace, ciliumPod, []string{\n\t\t\t\t\"cilium bpf tunnel list\",\n\t\t\t\t\"cilium endpoint list\"})\n\t\t}\n\n\t\tkubectl.Delete(demoDSPath)\n\t})\n\n\tIt(\"Check VXLAN mode\", func() {\n\t\tpath := kubectl.ManifestGet(\"cilium_ds.yaml\")\n\t\tkubectl.Apply(path)\n\t\t_, err := kubectl.WaitforPods(helpers.KubeSystemNamespace, \"-l k8s-app=cilium\", 500)\n\t\tExpect(err).Should(BeNil())\n\n\t\tciliumPod, err := kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)\n\t\tExpect(err).Should(BeNil())\n\n\t\t_, err = kubectl.CiliumNodesWait()\n\t\tExpect(err).Should(BeNil())\n\t\t\/\/Make sure that we delete the ds in case of fail\n\t\tdefer kubectl.Delete(path)\n\n\t\tBy(\"Checking that BPF tunnels are in place\")\n\t\tstatus := kubectl.CiliumExec(ciliumPod, \"cilium bpf tunnel list | wc -l\")\n\t\tif tunnels, _ := status.IntOutput(); tunnels != 4 {\n\t\t\tcmds := []string{\n\t\t\t\t\"cilium bpf tunnel list\",\n\t\t\t}\n\t\t\tkubectl.CiliumReport(helpers.KubeSystemNamespace, ciliumPod, cmds)\n\t\t}\n\n\t\tstatus.ExpectSuccess()\n\t\tExpect(status.IntOutput()).Should(Equal(4))\n\n\t\tBy(\"Checking that BPF tunnels are working correctly\")\n\t\ttunnStatus := isNodeNetworkingWorking(kubectl, \"zgroup=testDS\")\n\t\tExpect(tunnStatus).Should(BeTrue())\n\t\tkubectl.Delete(path)\n\t\twaitToDeleteCilium(kubectl, logger)\n\t}, 600)\n\n\tIt(\"Check Geneve mode\", func() {\n\t\tpath := kubectl.ManifestGet(\"cilium_ds_geneve.yaml\")\n\t\tkubectl.Apply(path)\n\t\t_, err := kubectl.WaitforPods(helpers.KubeSystemNamespace, \"-l k8s-app=cilium\", 500)\n\t\tExpect(err).Should(BeNil())\n\n\t\tciliumPod, err := kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)\n\t\tExpect(err).Should(BeNil())\n\n\t\t_, err = kubectl.CiliumNodesWait()\n\t\tExpect(err).Should(BeNil())\n\n\t\t\/\/Make sure that we delete the ds in case of fail\n\t\tdefer kubectl.Delete(path)\n\n\t\t\/\/Check that cilium detects a\n\t\tBy(\"Checking that BPF tunnels are in place\")\n\t\tstatus := kubectl.CiliumExec(ciliumPod, \"cilium bpf tunnel list | wc -l\")\n\t\tstatus.ExpectSuccess()\n\t\tif tunnels, _ := status.IntOutput(); tunnels != 4 {\n\t\t\tcmds := []string{\n\t\t\t\t\"cilium bpf tunnel list\",\n\t\t\t}\n\t\t\tkubectl.CiliumReport(helpers.KubeSystemNamespace, ciliumPod, cmds)\n\t\t}\n\t\tExpect(status.IntOutput()).Should(Equal(4))\n\n\t\tBy(\"Checking that BPF tunnels are working correctly\")\n\t\ttunnStatus := isNodeNetworkingWorking(kubectl, \"zgroup=testDS\")\n\t\tExpect(tunnStatus).Should(BeTrue())\n\t\t\/\/FIXME: Maybe added here a cilium bpf tunnel status?\n\t\tkubectl.Delete(path)\n\t\twaitToDeleteCilium(kubectl, logger)\n\t}, 600)\n})\n\nfunc isNodeNetworkingWorking(kubectl *helpers.Kubectl, filter string) bool {\n\twaitReady, _ := kubectl.WaitforPods(helpers.DefaultNamespace, fmt.Sprintf(\"-l %s\", filter), 3000)\n\tExpect(waitReady).Should(BeTrue())\n\tpods, err := kubectl.GetPodNames(helpers.DefaultNamespace, filter)\n\tExpect(err).Should(BeNil())\n\tpodIP, err := kubectl.Get(\n\t\thelpers.DefaultNamespace,\n\t\tfmt.Sprintf(\"pod %s -o json\", pods[1])).Filter(\"{.status.podIP}\")\n\tExpect(err).Should(BeNil())\n\t_, err = kubectl.ExecPodCmd(helpers.DefaultNamespace, pods[0], helpers.Ping(podIP.String()))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc waitToDeleteCilium(kubectl *helpers.Kubectl, logger *logrus.Entry) {\n\tstatus := 1\n\tfor status > 0 {\n\t\tpods, err := kubectl.GetCiliumPods(helpers.KubeSystemNamespace)\n\t\tstatus := len(pods)\n\t\tlogger.Infof(\"Cilium pods terminating '%d' err='%v' pods='%v'\", status, err, pods)\n\t\tif status == 0 {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\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\n\/\/ Package messagebird is an official library for interacting with MessageBird.com API.\n\/\/ The MessageBird API connects your website or application to operators around the world. With our API you can integrate SMS, Chat & Voice.\n\/\/ More documentation you can find on the MessageBird developers portal: https:\/\/developers.messagebird.com\/\npackage messagebird\n\nimport (\n\t\"bytes\"\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\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ ClientVersion is used in User-Agent request header to provide server with API level.\n\tClientVersion = \"5.0.0\"\n\n\t\/\/ Endpoint points you to MessageBird REST API.\n\tEndpoint = \"https:\/\/rest.messagebird.com\"\n\n\t\/\/ httpClientTimeout is used to limit http.Client waiting time.\n\thttpClientTimeout = 15 * time.Second\n)\n\nvar (\n\t\/\/ ErrUnexpectedResponse is used when there was an internal server error and nothing can be done at this point.\n\tErrUnexpectedResponse = errors.New(\"The MessageBird API is currently unavailable\")\n)\n\n\/\/ Client is used to access API with a given key.\n\/\/ Uses standard lib HTTP client internally, so should be reused instead of created as needed and it is safe for concurrent use.\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{\n\t\tAccessKey: accessKey,\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: httpClientTimeout,\n\t\t},\n\t}\n}\n\n\/\/ Request is for internal use only and unstable.\nfunc (c *Client) Request(v interface{}, method, path string, data interface{}) error {\n\tif !strings.HasPrefix(path, \"https:\/\/\") && !strings.HasPrefix(path, \"http:\/\/\") {\n\t\tpath = fmt.Sprintf(\"%s\/%s\", Endpoint, path)\n\t}\n\turi, err := url.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar jsonEncoded []byte\n\tif data != nil {\n\t\tjsonEncoded, err = json.Marshal(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trequest, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(jsonEncoded))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest.Header.Set(\"Content-Type\", \"application\/json\")\n\trequest.Header.Set(\"Accept\", \"application\/json\")\n\trequest.Header.Set(\"Authorization\", \"AccessKey \"+c.AccessKey)\n\trequest.Header.Set(\"User-Agent\", \"MessageBird\/ApiClient\/\"+ClientVersion+\" Go\/\"+runtime.Version())\n\n\tif c.DebugLog != nil {\n\t\tif data != nil {\n\t\t\tc.DebugLog.Printf(\"HTTP REQUEST: %s %s %s\", method, uri.String(), jsonEncoded)\n\t\t} else {\n\t\t\tc.DebugLog.Printf(\"HTTP REQUEST: %s %s\", method, uri.String())\n\t\t}\n\t}\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\tc.DebugLog.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 == http.StatusInternalServerError {\n\t\treturn ErrUnexpectedResponse\n\t}\n\n\t\/\/ Status code 204 is returned for successful DELETE requests. Don't try to\n\t\/\/ unmarshal the body: that would return errors.\n\tif response.StatusCode == http.StatusNoContent && response.ContentLength == 0 {\n\t\treturn nil\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 == http.StatusOK || response.StatusCode == http.StatusCreated {\n\t\tif err := json.Unmarshal(responseBody, &v); err != nil {\n\t\t\treturn fmt.Errorf(\"could not decode response JSON, %s: %v\", string(responseBody), err)\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Anything else than a 200\/201\/500 should be a JSON error.\n\tvar errorResponse ErrorResponse\n\tif err := json.Unmarshal(responseBody, &errorResponse); err != nil {\n\t\treturn err\n\t}\n\n\treturn errorResponse\n}\n<commit_msg>Use switch to determine response errors, in favour of if<commit_after>\/\/\n\/\/ Copyright (c) 2014 MessageBird B.V.\n\/\/ All rights reserved.\n\/\/\n\/\/ Author: Maurice Nonnekes <maurice@messagebird.com>\n\n\/\/ Package messagebird is an official library for interacting with MessageBird.com API.\n\/\/ The MessageBird API connects your website or application to operators around the world. With our API you can integrate SMS, Chat & Voice.\n\/\/ More documentation you can find on the MessageBird developers portal: https:\/\/developers.messagebird.com\/\npackage messagebird\n\nimport (\n\t\"bytes\"\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\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ ClientVersion is used in User-Agent request header to provide server with API level.\n\tClientVersion = \"5.0.0\"\n\n\t\/\/ Endpoint points you to MessageBird REST API.\n\tEndpoint = \"https:\/\/rest.messagebird.com\"\n\n\t\/\/ httpClientTimeout is used to limit http.Client waiting time.\n\thttpClientTimeout = 15 * time.Second\n)\n\nvar (\n\t\/\/ ErrUnexpectedResponse is used when there was an internal server error and nothing can be done at this point.\n\tErrUnexpectedResponse = errors.New(\"The MessageBird API is currently unavailable\")\n)\n\n\/\/ Client is used to access API with a given key.\n\/\/ Uses standard lib HTTP client internally, so should be reused instead of created as needed and it is safe for concurrent use.\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{\n\t\tAccessKey: accessKey,\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: httpClientTimeout,\n\t\t},\n\t}\n}\n\n\/\/ Request is for internal use only and unstable.\nfunc (c *Client) Request(v interface{}, method, path string, data interface{}) error {\n\tif !strings.HasPrefix(path, \"https:\/\/\") && !strings.HasPrefix(path, \"http:\/\/\") {\n\t\tpath = fmt.Sprintf(\"%s\/%s\", Endpoint, path)\n\t}\n\turi, err := url.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar jsonEncoded []byte\n\tif data != nil {\n\t\tjsonEncoded, err = json.Marshal(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\trequest, err := http.NewRequest(method, uri.String(), bytes.NewBuffer(jsonEncoded))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequest.Header.Set(\"Content-Type\", \"application\/json\")\n\trequest.Header.Set(\"Accept\", \"application\/json\")\n\trequest.Header.Set(\"Authorization\", \"AccessKey \"+c.AccessKey)\n\trequest.Header.Set(\"User-Agent\", \"MessageBird\/ApiClient\/\"+ClientVersion+\" Go\/\"+runtime.Version())\n\n\tif c.DebugLog != nil {\n\t\tif data != nil {\n\t\t\tc.DebugLog.Printf(\"HTTP REQUEST: %s %s %s\", method, uri.String(), jsonEncoded)\n\t\t} else {\n\t\t\tc.DebugLog.Printf(\"HTTP REQUEST: %s %s\", method, uri.String())\n\t\t}\n\t}\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\tc.DebugLog.Printf(\"HTTP RESPONSE: %s\", string(responseBody))\n\t}\n\n\tswitch response.StatusCode {\n\tcase http.StatusOK, http.StatusCreated:\n\t\t\/\/ Status codes 200 and 201 are indicative of being able to convert the\n\t\t\/\/ response body to the struct that was specified.\n\t\tif err := json.Unmarshal(responseBody, &v); err != nil {\n\t\t\treturn fmt.Errorf(\"could not decode response JSON, %s: %v\", string(responseBody), err)\n\t\t}\n\t\treturn nil\n\tcase http.StatusNoContent:\n\t\t\/\/ Status code 204 is returned for successful DELETE requests. Don't try to\n\t\t\/\/ unmarshal the body: that would return errors.\n\t\treturn nil\n\tcase http.StatusInternalServerError:\n\t\t\/\/ Status code 500 is a server error and means nothing can be done at this\n\t\t\/\/ point.\n\t\treturn ErrUnexpectedResponse\n\tdefault:\n\t\t\/\/ Anything else than a 200\/201\/204\/500 should be a JSON error.\n\t\tvar errorResponse ErrorResponse\n\t\tif err := json.Unmarshal(responseBody, &errorResponse); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errorResponse\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package sse\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype state uint8\n\nconst (\n\tstateConnecting state = 0\n\tstateOpen       state = 1\n\tstateClosed     state = 2\n)\n\n\/\/ Client is main struct that handles connecting\/streaming\/etc...\ntype Client struct {\n\tcl       *http.Client\n\treq      *http.Request\n\tr        io.ReadCloser\n\tlast     string\n\tretry    time.Duration\n\tstopChan chan struct{}\n\tevent    chan Event\n\n\tadd       chan listener\n\tlisteners map[string]func(Event)\n\n\tsync.RWMutex\n\treadyState state\n}\n\ntype listener struct {\n\tname string\n\tf    func(Event)\n}\n\n\/\/ Event is SSE event data represenation\ntype Event struct {\n\tID    string\n\tEvent string\n\tData  string\n}\n\n\/\/ Config is a struct used to define and override default parameters:\n\/\/   Client - *http.Client, if non provided, http.DefaultClient will be used.\n\/\/   URL    - URL of SSE stream to connect to. Must be provided. No default\n\/\/            value.\n\/\/   Retry  - time.Duration of how long should SSE client wait before trying\n\/\/            to reconnect after disconnection. Default is 2 seconds.\ntype Config struct {\n\tClient *http.Client\n\tURL    string\n\tRetry  time.Duration\n}\n\n\/\/ New creates a client based on a passed Config.\nfunc New(cfg *Config) (*Client, error) {\n\tif cfg.URL == \"\" {\n\t\treturn nil, errors.New(\"sse: URL config option MUST be provided\")\n\t}\n\treq, err := http.NewRequest(\"GET\", cfg.URL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sse: could not make request to %s: %v\", cfg.URL, err)\n\t}\n\treq.Header.Set(\"Cache-Control\", \"no-cache\")\n\treq.Header.Set(\"Accept\", \"text\/event-stream\")\n\tretry := 2 * time.Second\n\tif cfg.Retry != 0 {\n\t\tretry = cfg.Retry\n\t}\n\tclient := &Client{\n\t\treadyState: stateConnecting,\n\t\treq:        req,\n\t\tretry:      retry,\n\t\tevent:      make(chan Event),\n\t\tadd:        make(chan listener),\n\t\tstopChan:   make(chan struct{}),\n\t\tlisteners:  make(map[string]func(Event)),\n\t}\n\tclient.cl = http.DefaultClient\n\tif cfg.Client != nil {\n\t\tclient.cl = cfg.Client\n\t}\n\tgo client.run()\n\t\/\/go client.read()\n\treturn client, nil\n}\n\n\/\/ Connect connects to given SSE endpoint and starts reading the stream and\n\/\/ transmitting events.\nfunc (c *Client) Connect() {\n\tgo c.connect()\n}\n\n\/\/ AddListener adds a listener for a given event type. A listener is simple\n\/\/ callback function that passes Event struct.\nfunc (c *Client) AddListener(event string, f func(Event)) {\n\tc.add <- listener{\n\t\tname: event,\n\t\tf:    f,\n\t}\n}\n\n\/\/ Stop stops the client of accepting any more stream requests.\nfunc (c *Client) Stop() {\n\tc.stop()\n}\n\nfunc (c *Client) stop() {\n\tclose(c.stopChan)\n\tc.Lock()\n\tc.readyState = stateClosed\n\tc.Unlock()\n}\n\nfunc (c *Client) run() {\n\tfor {\n\t\tselect {\n\t\tcase l := <-c.add:\n\t\t\tc.listeners[l.name] = l.f\n\t\tcase event := <-c.event:\n\t\t\tf, ok := c.listeners[event.Event]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf(event)\n\t\tcase <-c.stopChan:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Client) read() {\n\tc.RLock()\n\tstate := c.readyState\n\tc.RUnlock()\n\tswitch state {\n\tcase stateOpen:\n\tcase stateConnecting:\n\t\treturn\n\tcase stateClosed:\n\t\treturn\n\tdefault:\n\t\treturn\n\t}\n\tc.decode()\n}\n\nfunc (c *Client) decode() {\n\tdefer c.r.Close()\n\tdec := bufio.NewReader(c.r)\n\t_, err := dec.Peek(1)\n\tif err == io.ErrUnexpectedEOF {\n\t\terr = io.EOF\n\t}\n\tif err != nil {\n\t\tc.fireErrorAndRecover(err)\n\t\treturn\n\t}\n\tfor {\n\t\tevent := new(Event)\n\t\tevent.Event = \"message\"\n\t\tfor {\n\t\t\tline, err := dec.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tc.fireErrorAndRecover(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif line == \"\\n\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tline = strings.TrimSuffix(line, \"\\n\")\n\t\t\tif strings.HasPrefix(line, \":\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsections := strings.SplitN(line, \":\", 2)\n\t\t\tfield, value := sections[0], \"\"\n\t\t\tif len(sections) == 2 {\n\t\t\t\tvalue = strings.TrimPrefix(sections[1], \" \")\n\t\t\t}\n\t\t\tswitch field {\n\t\t\tcase \"event\":\n\t\t\t\tevent.Event = value\n\t\t\tcase \"data\":\n\t\t\t\tevent.Data += value + \"\\n\"\n\t\t\tcase \"id\":\n\t\t\t\tevent.ID = value\n\t\t\t}\n\t\t}\n\t\tevent.Data = strings.TrimSuffix(event.Data, \"\\n\")\n\t\tc.event <- *event\n\t}\n}\n\nfunc (c *Client) connect() {\n\tc.req.Header.Set(\"Last-Event-ID\", c.last)\n\tresp, err := c.cl.Do(c.req)\n\tif err != nil {\n\t\tgo c.connect()\n\t\treturn\n\t}\n\t\/\/ TODO: check other status codes\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\t\/\/ TODO: check content-type\n\tcase http.StatusNoContent:\n\t\tc.stop()\n\t\treturn\n\tcase http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:\n\t\tc.reconnect()\n\t\treturn\n\tdefault:\n\t\tc.stop()\n\t\treturn\n\t}\n\tc.r = resp.Body\n\tc.fireOpen()\n}\n\nfunc (c *Client) reconnect() {\n\tc.Lock()\n\tc.readyState = stateConnecting\n\tc.Unlock()\n\ttime.Sleep(c.retry)\n\t\/\/ TODO: also implement exponential backoff delay\n\tgo c.connect()\n}\n\nfunc (c *Client) fireOpen() {\n\tc.Lock()\n\tc.readyState = stateOpen\n\tc.Unlock()\n\tgo c.read()\n\tevent := new(Event)\n\tevent.Event = \"open\"\n\tc.event <- *event\n}\n\nfunc (c *Client) fireErrorAndRecover(err error) {\n\tc.reconnect()\n\tevent := new(Event)\n\tevent.Event = \"error\"\n\tevent.Data = err.Error()\n\tc.event <- *event\n}\n<commit_msg>Set last event ID before processing event; Other small tweaks<commit_after>package sse\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype state uint8\n\nconst (\n\tstateConnecting state = 0\n\tstateOpen       state = 1\n\tstateClosed     state = 2\n)\n\n\/\/ Client is main struct that handles connecting\/streaming\/etc...\ntype Client struct {\n\tcl       *http.Client\n\treq      *http.Request\n\tr        io.ReadCloser\n\tlast     string\n\tretry    time.Duration\n\tstopChan chan struct{}\n\tevent    chan Event\n\n\tadd       chan listener\n\tlisteners map[string]func(Event)\n\n\tsync.RWMutex\n\treadyState state\n}\n\ntype listener struct {\n\tname string\n\tf    func(Event)\n}\n\n\/\/ Event is SSE event data represenation\ntype Event struct {\n\tID    string\n\tEvent string\n\tData  string\n}\n\n\/\/ Config is a struct used to define and override default parameters:\n\/\/   Client - *http.Client, if non provided, http.DefaultClient will be used.\n\/\/   URL    - URL of SSE stream to connect to. Must be provided. No default\n\/\/            value.\n\/\/   Retry  - time.Duration of how long should SSE client wait before trying\n\/\/            to reconnect after disconnection. Default is 2 seconds.\ntype Config struct {\n\tClient *http.Client\n\tURL    string\n\tRetry  time.Duration\n}\n\n\/\/ New creates a client based on a passed Config.\nfunc New(cfg *Config) (*Client, error) {\n\tif cfg.URL == \"\" {\n\t\treturn nil, errors.New(\"sse: URL config option MUST be provided\")\n\t}\n\treq, err := http.NewRequest(\"GET\", cfg.URL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sse: could not make request to %s: %v\", cfg.URL, err)\n\t}\n\treq.Header.Set(\"Cache-Control\", \"no-cache\")\n\treq.Header.Set(\"Accept\", \"text\/event-stream\")\n\tretry := 2 * time.Second\n\tif cfg.Retry != 0 {\n\t\tretry = cfg.Retry\n\t}\n\tclient := &Client{\n\t\treadyState: stateConnecting,\n\t\treq:        req,\n\t\tretry:      retry,\n\t\tevent:      make(chan Event),\n\t\tadd:        make(chan listener),\n\t\tstopChan:   make(chan struct{}),\n\t\tlisteners:  make(map[string]func(Event)),\n\t}\n\tclient.cl = http.DefaultClient\n\tif cfg.Client != nil {\n\t\tclient.cl = cfg.Client\n\t}\n\tgo client.run()\n\treturn client, nil\n}\n\n\/\/ Connect connects to given SSE endpoint and starts reading the stream and\n\/\/ transmitting events.\nfunc (c *Client) Connect() {\n\tgo c.connect()\n}\n\n\/\/ AddListener adds a listener for a given event type. A listener is simple\n\/\/ callback function that passes Event struct.\nfunc (c *Client) AddListener(event string, f func(Event)) {\n\tc.add <- listener{\n\t\tname: event,\n\t\tf:    f,\n\t}\n}\n\n\/\/ Stop stops the client of accepting any more stream requests.\nfunc (c *Client) Stop() {\n\tc.stop()\n}\n\nfunc (c *Client) stop() {\n\tclose(c.stopChan)\n\tc.Lock()\n\tc.readyState = stateClosed\n\tc.Unlock()\n}\n\nfunc (c *Client) run() {\n\tfor {\n\t\tselect {\n\t\tcase l := <-c.add:\n\t\t\tc.listeners[l.name] = l.f\n\t\tcase event := <-c.event:\n\t\t\tf, ok := c.listeners[event.Event]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif event.ID != \"\" {\n\t\t\t\tc.last = event.ID\n\t\t\t}\n\t\t\tf(event)\n\t\tcase <-c.stopChan:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *Client) read() {\n\tc.RLock()\n\tstate := c.readyState\n\tc.RUnlock()\n\tswitch state {\n\tcase stateOpen:\n\tcase stateConnecting:\n\t\treturn\n\tcase stateClosed:\n\t\treturn\n\tdefault:\n\t\treturn\n\t}\n\tc.decode()\n}\n\nfunc (c *Client) decode() {\n\tdefer c.r.Close()\n\tdec := bufio.NewReader(c.r)\n\t_, err := dec.Peek(1)\n\tif err == io.ErrUnexpectedEOF {\n\t\terr = io.EOF\n\t}\n\tif err != nil {\n\t\tc.fireErrorAndRecover(err)\n\t\treturn\n\t}\n\tfor {\n\t\tevent := new(Event)\n\t\tevent.Event = \"message\"\n\t\tfor {\n\t\t\tline, err := dec.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tc.fireErrorAndRecover(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif line == \"\\n\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tline = strings.TrimSuffix(line, \"\\n\")\n\t\t\tif strings.HasPrefix(line, \":\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsections := strings.SplitN(line, \":\", 2)\n\t\t\tfield, value := sections[0], \"\"\n\t\t\tif len(sections) == 2 {\n\t\t\t\tvalue = strings.TrimPrefix(sections[1], \" \")\n\t\t\t}\n\t\t\tswitch field {\n\t\t\tcase \"event\":\n\t\t\t\tevent.Event = value\n\t\t\tcase \"data\":\n\t\t\t\tevent.Data += value + \"\\n\"\n\t\t\tcase \"id\":\n\t\t\t\tevent.ID = value\n\t\t\t}\n\t\t}\n\t\tevent.Data = strings.TrimSuffix(event.Data, \"\\n\")\n\t\tc.event <- *event\n\t}\n}\n\nfunc (c *Client) connect() {\n\tc.req.Header.Set(\"Last-Event-ID\", c.last)\n\tresp, err := c.cl.Do(c.req)\n\tif err != nil {\n\t\tgo c.connect()\n\t\treturn\n\t}\n\t\/\/ TODO: check other status codes\n\tswitch resp.StatusCode {\n\tcase http.StatusOK:\n\t\t\/\/ TODO: check content-type\n\tcase http.StatusNoContent:\n\t\tc.stop()\n\t\treturn\n\tcase http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:\n\t\tc.reconnect()\n\t\treturn\n\tdefault:\n\t\tc.stop()\n\t\treturn\n\t}\n\tc.r = resp.Body\n\tc.fireOpen()\n}\n\nfunc (c *Client) reconnect() {\n\tc.Lock()\n\tc.readyState = stateConnecting\n\tc.Unlock()\n\ttime.Sleep(c.retry)\n\t\/\/ TODO: also implement exponential backoff delay\n\tgo c.connect()\n}\n\nfunc (c *Client) fireOpen() {\n\tc.Lock()\n\tc.readyState = stateOpen\n\tc.Unlock()\n\tgo c.read()\n\tevent := new(Event)\n\tevent.Event = \"open\"\n\tc.event <- *event\n}\n\nfunc (c *Client) fireErrorAndRecover(err error) {\n\tevent := new(Event)\n\tevent.Event = \"error\"\n\tevent.Data = err.Error()\n\tc.event <- *event\n\tc.reconnect()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The retryablehttp package provides a familiar HTTP client interface with\n\/\/ automatic retries and exponential backoff. It is a thin wrapper over the\n\/\/ standard net\/http client library and exposes nearly the same public API.\n\/\/ This makes retryablehttp very easy to drop into existing programs.\n\/\/\n\/\/ retryablehttp performs automatic retries under certain conditions. Mainly, if\n\/\/ an error is returned by the client (connection errors etc), or if a 500-range\n\/\/ response is received, then a retry is invoked. Otherwise, the response is\n\/\/ returned and left to the caller to interpret.\n\/\/\n\/\/ The main difference from net\/http is that requests which take a request body\n\/\/ (POST\/PUT et. al) require an io.ReadSeeker to be provided. This enables the\n\/\/ request body to be \"rewound\" if the initial request fails so that the full\n\/\/ request can be attempted again.\npackage retryablehttp\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/go-cleanhttp\"\n)\n\nvar (\n\t\/\/ Default retry configuration\n\tdefaultRetryWaitMin = 1 * time.Second\n\tdefaultRetryWaitMax = 30 * time.Second\n\tdefaultRetryMax     = 4\n\n\t\/\/ defaultClient is used for performing requests without explicitly making\n\t\/\/ a new client. It is purposely private to avoid modifications.\n\tdefaultClient = NewClient()\n\n\t\/\/ We need to consume response bodies to maintain http connections, but\n\t\/\/ limit the size we consume to respReadLimit.\n\trespReadLimit = int64(4096)\n)\n\n\/\/ LenReader is an interface implemented by many in-memory io.Reader's. Used\n\/\/ for automatically sending the right Content-Length header when possible.\ntype LenReader interface {\n\tLen() int\n}\n\n\/\/ Request wraps the metadata needed to create HTTP requests.\ntype Request struct {\n\t\/\/ body is a seekable reader over the request body payload. This is\n\t\/\/ used to rewind the request data in between retries.\n\tbody io.ReadSeeker\n\n\t\/\/ Embed an HTTP request directly. This makes a *Request act exactly\n\t\/\/ like an *http.Request so that all meta methods are supported.\n\t*http.Request\n}\n\n\/\/ NewRequest creates a new wrapped request.\nfunc NewRequest(method, url string, body io.ReadSeeker) (*Request, error) {\n\t\/\/ Wrap the body in a noop ReadCloser if non-nil. This prevents the\n\t\/\/ reader from being closed by the HTTP client.\n\tvar rcBody io.ReadCloser\n\tif body != nil {\n\t\trcBody = ioutil.NopCloser(body)\n\t}\n\n\t\/\/ Make the request with the noop-closer for the body.\n\thttpReq, err := http.NewRequest(method, url, rcBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if we can set the Content-Length automatically.\n\tif lr, ok := body.(LenReader); ok {\n\t\thttpReq.ContentLength = int64(lr.Len())\n\t}\n\n\treturn &Request{body, httpReq}, nil\n}\n\n\/\/ RequestLogHook allows a function to run before each retry. The HTTP\n\/\/ request which will be made, and the retry number (0 for the initial\n\/\/ request) are available to users. The internal logger is exposed to\n\/\/ consumers.\ntype RequestLogHook func(*log.Logger, *http.Request, int)\n\n\/\/ ResponseLogHook is like RequestLogHook, but allows running a function\n\/\/ on each HTTP response. This function will be invoked at the end of\n\/\/ every HTTP request executed, regardless of whether a subsequent retry\n\/\/ needs to be performed or not. If the response body is read or closed\n\/\/ from this method, this will affect the response returned from Do().\ntype ResponseLogHook func(*log.Logger, *http.Response)\n\n\/\/ CheckRetry specifies a policy for handling retries. It is called\n\/\/ following each request with the response and error values returned by\n\/\/ the http.Client. If CheckRetry returns false, the Client stops retrying\n\/\/ and returns the response to the caller. If CheckRetry returns an error,\n\/\/ that error value is returned in lieu of the error from the request. The\n\/\/ Client will close any response body when retrying, but if the retry is\n\/\/ aborted it is up to the CheckResponse callback to properly close any\n\/\/ response body before returning.\ntype CheckRetry func(resp *http.Response, err error) (bool, error)\n\n\/\/ Backoff specifies a policy for how long to wait between retries.\n\/\/ It is called after a failing request to determine the amount of time\n\/\/ that should pass before trying again.\ntype Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration\n\n\/\/ ErrorHandler is called if retries are expired, containing the last status\n\/\/ from the http library. If not specified, default behavior for the library is\n\/\/ to close the body and return an error indicating how many tries were\n\/\/ attempted. If overriding this, be sure to close the body if needed.\ntype ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error)\n\n\/\/ Client is used to make HTTP requests. It adds additional functionality\n\/\/ like automatic retries to tolerate minor outages.\ntype Client struct {\n\tHTTPClient *http.Client \/\/ Internal HTTP client.\n\tLogger     *log.Logger  \/\/ Customer logger instance.\n\n\tRetryWaitMin time.Duration \/\/ Minimum time to wait\n\tRetryWaitMax time.Duration \/\/ Maximum time to wait\n\tRetryMax     int           \/\/ Maximum number of retries\n\n\t\/\/ RequestLogHook allows a user-supplied function to be called\n\t\/\/ before each retry.\n\tRequestLogHook RequestLogHook\n\n\t\/\/ ResponseLogHook allows a user-supplied function to be called\n\t\/\/ with the response from each HTTP request executed.\n\tResponseLogHook ResponseLogHook\n\n\t\/\/ CheckRetry specifies the policy for handling retries, and is called\n\t\/\/ after each request. The default policy is DefaultRetryPolicy.\n\tCheckRetry CheckRetry\n\n\t\/\/ Backoff specifies the policy for how long to wait between retries\n\tBackoff Backoff\n\n\t\/\/ ErrorHandler specifies the custom error handler to use, if any\n\tErrorHandler ErrorHandler\n}\n\n\/\/ NewClient creates a new Client with default settings.\nfunc NewClient() *Client {\n\treturn &Client{\n\t\tHTTPClient:   cleanhttp.DefaultClient(),\n\t\tLogger:       log.New(os.Stderr, \"\", log.LstdFlags),\n\t\tRetryWaitMin: defaultRetryWaitMin,\n\t\tRetryWaitMax: defaultRetryWaitMax,\n\t\tRetryMax:     defaultRetryMax,\n\t\tCheckRetry:   DefaultRetryPolicy,\n\t\tBackoff:      DefaultBackoff,\n\t}\n}\n\n\/\/ DefaultRetryPolicy provides a default callback for Client.CheckRetry, which\n\/\/ will retry on connection errors and server errors.\nfunc DefaultRetryPolicy(resp *http.Response, err error) (bool, error) {\n\tif err != nil {\n\t\treturn true, err\n\t}\n\t\/\/ Check the response code. We retry on 500-range responses to allow\n\t\/\/ the server time to recover, as 500's are typically not permanent\n\t\/\/ errors and may relate to outages on the server side. This will catch\n\t\/\/ invalid response codes as well, like 0 and 999.\n\tif resp.StatusCode == 0 || resp.StatusCode >= 500 {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\n\/\/ DefaultBackoff provides a default callback for Client.Backoff which\n\/\/ will perform exponential backoff based on the attempt number and limited\n\/\/ by the provided minimum and maximum durations.\nfunc DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {\n\tmult := math.Pow(2, float64(attemptNum)) * float64(min)\n\tsleep := time.Duration(mult)\n\tif float64(sleep) != mult || sleep > max {\n\t\tsleep = max\n\t}\n\treturn sleep\n}\n\n\/\/ LinearJitterBackoff provides a callback for Client.Backoff which will\n\/\/ perform linear backoff based on the attempt number and with jitter to\n\/\/ prevent a thundering herd.\n\/\/\n\/\/ min and max here are *not* absolute values. The number to be multipled by\n\/\/ the attempt number will be chosen at random from between them, thus they are\n\/\/ bounding the jitter.\n\/\/\n\/\/ For instance:\n\/\/ * To get strictly linear backoff of one second increasing each retry, set\n\/\/ both to one second (1s, 2s, 3s, 4s, ...)\n\/\/ * To get a small amount of jitter centered around one second increasing each\n\/\/ retry, set to around one second, such as a min of 800ms and max of 1200ms\n\/\/ (892ms, 2102ms, 2945ms, 4312ms, ...)\n\/\/ * To get extreme jitter, set to a very wide spread, such as a min of 100ms\n\/\/ and a max of 20s (15382ms, 292ms, 51321ms, 35234ms, ...)\nfunc LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {\n\t\/\/ attemptNum always starts at zero but we want to start at 1 for multiplication\n\tattemptNum++\n\n\tif max <= min {\n\t\t\/\/ Unclear what to do here, or they are the same, so return min *\n\t\t\/\/ attemptNum\n\t\treturn min * time.Duration(attemptNum)\n\t}\n\n\t\/\/ Seed rand; doing this every time is fine\n\trand := rand.New(rand.NewSource(int64(time.Now().Nanosecond())))\n\n\t\/\/ Pick a random number that lies somewhere between the min and max and\n\t\/\/ multiply by the attemptNum. attemptNum starts at zero so we always\n\t\/\/ increment here. We first get a random percentage, then apply that to the\n\t\/\/ difference between min and max, and add to min.\n\tjitter := rand.Float64() * float64(max-min)\n\tjitterMin := int64(jitter) + int64(min)\n\treturn time.Duration(jitterMin * int64(attemptNum))\n}\n\n\/\/ PassthroughErrorHandler is an ErrorHandler that directly passes through the\n\/\/ values from the net\/http library for the final request. The body is not\n\/\/ closed.\nfunc PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) {\n\treturn resp, err\n}\n\n\/\/ Do wraps calling an HTTP method with retries.\nfunc (c *Client) Do(req *Request) (*http.Response, error) {\n\tif c.Logger != nil {\n\t\tc.Logger.Printf(\"[DEBUG] %s %s\", req.Method, req.URL)\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tfor i := 0; ; i++ {\n\t\tvar code int \/\/ HTTP response code\n\n\t\t\/\/ Always rewind the request body when non-nil.\n\t\tif req.body != nil {\n\t\t\tif _, err := req.body.Seek(0, 0); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to seek body: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tif c.RequestLogHook != nil {\n\t\t\tc.RequestLogHook(c.Logger, req.Request, i)\n\t\t}\n\n\t\t\/\/ Attempt the request\n\t\tresp, err = c.HTTPClient.Do(req.Request)\n\t\tif resp != nil {\n\t\t\tcode = resp.StatusCode\n\t\t}\n\n\t\t\/\/ Check if we should continue with retries.\n\t\tcheckOK, checkErr := c.CheckRetry(resp, err)\n\n\t\tif err != nil {\n\t\t\tif c.Logger != nil {\n\t\t\t\tc.Logger.Printf(\"[ERR] %s %s request failed: %v\", req.Method, req.URL, err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Call this here to maintain the behavior of logging all requests,\n\t\t\t\/\/ even if CheckRetry signals to stop.\n\t\t\tif c.ResponseLogHook != nil {\n\t\t\t\t\/\/ Call the response logger function if provided.\n\t\t\t\tc.ResponseLogHook(c.Logger, resp)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Now decide if we should continue.\n\t\tif !checkOK {\n\t\t\tif checkErr != nil {\n\t\t\t\terr = checkErr\n\t\t\t}\n\t\t\treturn resp, err\n\t\t}\n\n\t\t\/\/ We do this before drainBody beause there's no need for the I\/O if\n\t\t\/\/ we're breaking out\n\t\tremain := c.RetryMax - i\n\t\tif remain == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ We're going to retry, consume any response to reuse the connection.\n\t\tif err == nil && resp != nil {\n\t\t\tc.drainBody(resp.Body)\n\t\t}\n\n\t\twait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp)\n\t\tdesc := fmt.Sprintf(\"%s %s\", req.Method, req.URL)\n\t\tif code > 0 {\n\t\t\tdesc = fmt.Sprintf(\"%s (status: %d)\", desc, code)\n\t\t}\n\t\tif c.Logger != nil {\n\t\t\tc.Logger.Printf(\"[DEBUG] %s: retrying in %s (%d left)\", desc, wait, remain)\n\t\t}\n\t\ttime.Sleep(wait)\n\t}\n\n\tif c.ErrorHandler != nil {\n\t\treturn c.ErrorHandler(resp, err, c.RetryMax+1)\n\t}\n\n\t\/\/ By default, we close the response body and return an error without\n\t\/\/ returning the response\n\tif resp != nil {\n\t\tresp.Body.Close()\n\t}\n\treturn nil, fmt.Errorf(\"%s %s giving up after %d attempts\",\n\t\treq.Method, req.URL, c.RetryMax+1)\n}\n\n\/\/ Try to read the response body so we can reuse this connection.\nfunc (c *Client) drainBody(body io.ReadCloser) {\n\tdefer body.Close()\n\t_, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit))\n\tif err != nil {\n\t\tif c.Logger != nil {\n\t\t\tc.Logger.Printf(\"[ERR] error reading response body: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ Get is a shortcut for doing a GET request without making a new client.\nfunc Get(url string) (*http.Response, error) {\n\treturn defaultClient.Get(url)\n}\n\n\/\/ Get is a convenience helper for doing simple GET requests.\nfunc (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}\n\n\/\/ Head is a shortcut for doing a HEAD request without making a new client.\nfunc Head(url string) (*http.Response, error) {\n\treturn defaultClient.Head(url)\n}\n\n\/\/ Head is a convenience method for doing simple HEAD requests.\nfunc (c *Client) Head(url string) (*http.Response, error) {\n\treq, err := NewRequest(\"HEAD\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}\n\n\/\/ Post is a shortcut for doing a POST request without making a new client.\nfunc Post(url, bodyType string, body io.ReadSeeker) (*http.Response, error) {\n\treturn defaultClient.Post(url, bodyType, body)\n}\n\n\/\/ Post is a convenience method for doing simple POST requests.\nfunc (c *Client) Post(url, bodyType string, body io.ReadSeeker) (*http.Response, 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 c.Do(req)\n}\n\n\/\/ PostForm is a shortcut to perform a POST with form data without creating\n\/\/ a new client.\nfunc PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn defaultClient.PostForm(url, data)\n}\n\n\/\/ PostForm is a convenience method for doing simple POST operations using\n\/\/ pre-filled url.Values form data.\nfunc (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn c.Post(url, \"application\/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n}\n<commit_msg>501 is not a valid code for retrying, so take it out of the default<commit_after>\/\/ The retryablehttp package provides a familiar HTTP client interface with\n\/\/ automatic retries and exponential backoff. It is a thin wrapper over the\n\/\/ standard net\/http client library and exposes nearly the same public API.\n\/\/ This makes retryablehttp very easy to drop into existing programs.\n\/\/\n\/\/ retryablehttp performs automatic retries under certain conditions. Mainly, if\n\/\/ an error is returned by the client (connection errors etc), or if a 500-range\n\/\/ response is received, then a retry is invoked. Otherwise, the response is\n\/\/ returned and left to the caller to interpret.\n\/\/\n\/\/ The main difference from net\/http is that requests which take a request body\n\/\/ (POST\/PUT et. al) require an io.ReadSeeker to be provided. This enables the\n\/\/ request body to be \"rewound\" if the initial request fails so that the full\n\/\/ request can be attempted again.\npackage retryablehttp\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/go-cleanhttp\"\n)\n\nvar (\n\t\/\/ Default retry configuration\n\tdefaultRetryWaitMin = 1 * time.Second\n\tdefaultRetryWaitMax = 30 * time.Second\n\tdefaultRetryMax     = 4\n\n\t\/\/ defaultClient is used for performing requests without explicitly making\n\t\/\/ a new client. It is purposely private to avoid modifications.\n\tdefaultClient = NewClient()\n\n\t\/\/ We need to consume response bodies to maintain http connections, but\n\t\/\/ limit the size we consume to respReadLimit.\n\trespReadLimit = int64(4096)\n)\n\n\/\/ LenReader is an interface implemented by many in-memory io.Reader's. Used\n\/\/ for automatically sending the right Content-Length header when possible.\ntype LenReader interface {\n\tLen() int\n}\n\n\/\/ Request wraps the metadata needed to create HTTP requests.\ntype Request struct {\n\t\/\/ body is a seekable reader over the request body payload. This is\n\t\/\/ used to rewind the request data in between retries.\n\tbody io.ReadSeeker\n\n\t\/\/ Embed an HTTP request directly. This makes a *Request act exactly\n\t\/\/ like an *http.Request so that all meta methods are supported.\n\t*http.Request\n}\n\n\/\/ NewRequest creates a new wrapped request.\nfunc NewRequest(method, url string, body io.ReadSeeker) (*Request, error) {\n\t\/\/ Wrap the body in a noop ReadCloser if non-nil. This prevents the\n\t\/\/ reader from being closed by the HTTP client.\n\tvar rcBody io.ReadCloser\n\tif body != nil {\n\t\trcBody = ioutil.NopCloser(body)\n\t}\n\n\t\/\/ Make the request with the noop-closer for the body.\n\thttpReq, err := http.NewRequest(method, url, rcBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if we can set the Content-Length automatically.\n\tif lr, ok := body.(LenReader); ok {\n\t\thttpReq.ContentLength = int64(lr.Len())\n\t}\n\n\treturn &Request{body, httpReq}, nil\n}\n\n\/\/ RequestLogHook allows a function to run before each retry. The HTTP\n\/\/ request which will be made, and the retry number (0 for the initial\n\/\/ request) are available to users. The internal logger is exposed to\n\/\/ consumers.\ntype RequestLogHook func(*log.Logger, *http.Request, int)\n\n\/\/ ResponseLogHook is like RequestLogHook, but allows running a function\n\/\/ on each HTTP response. This function will be invoked at the end of\n\/\/ every HTTP request executed, regardless of whether a subsequent retry\n\/\/ needs to be performed or not. If the response body is read or closed\n\/\/ from this method, this will affect the response returned from Do().\ntype ResponseLogHook func(*log.Logger, *http.Response)\n\n\/\/ CheckRetry specifies a policy for handling retries. It is called\n\/\/ following each request with the response and error values returned by\n\/\/ the http.Client. If CheckRetry returns false, the Client stops retrying\n\/\/ and returns the response to the caller. If CheckRetry returns an error,\n\/\/ that error value is returned in lieu of the error from the request. The\n\/\/ Client will close any response body when retrying, but if the retry is\n\/\/ aborted it is up to the CheckResponse callback to properly close any\n\/\/ response body before returning.\ntype CheckRetry func(resp *http.Response, err error) (bool, error)\n\n\/\/ Backoff specifies a policy for how long to wait between retries.\n\/\/ It is called after a failing request to determine the amount of time\n\/\/ that should pass before trying again.\ntype Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration\n\n\/\/ ErrorHandler is called if retries are expired, containing the last status\n\/\/ from the http library. If not specified, default behavior for the library is\n\/\/ to close the body and return an error indicating how many tries were\n\/\/ attempted. If overriding this, be sure to close the body if needed.\ntype ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error)\n\n\/\/ Client is used to make HTTP requests. It adds additional functionality\n\/\/ like automatic retries to tolerate minor outages.\ntype Client struct {\n\tHTTPClient *http.Client \/\/ Internal HTTP client.\n\tLogger     *log.Logger  \/\/ Customer logger instance.\n\n\tRetryWaitMin time.Duration \/\/ Minimum time to wait\n\tRetryWaitMax time.Duration \/\/ Maximum time to wait\n\tRetryMax     int           \/\/ Maximum number of retries\n\n\t\/\/ RequestLogHook allows a user-supplied function to be called\n\t\/\/ before each retry.\n\tRequestLogHook RequestLogHook\n\n\t\/\/ ResponseLogHook allows a user-supplied function to be called\n\t\/\/ with the response from each HTTP request executed.\n\tResponseLogHook ResponseLogHook\n\n\t\/\/ CheckRetry specifies the policy for handling retries, and is called\n\t\/\/ after each request. The default policy is DefaultRetryPolicy.\n\tCheckRetry CheckRetry\n\n\t\/\/ Backoff specifies the policy for how long to wait between retries\n\tBackoff Backoff\n\n\t\/\/ ErrorHandler specifies the custom error handler to use, if any\n\tErrorHandler ErrorHandler\n}\n\n\/\/ NewClient creates a new Client with default settings.\nfunc NewClient() *Client {\n\treturn &Client{\n\t\tHTTPClient:   cleanhttp.DefaultClient(),\n\t\tLogger:       log.New(os.Stderr, \"\", log.LstdFlags),\n\t\tRetryWaitMin: defaultRetryWaitMin,\n\t\tRetryWaitMax: defaultRetryWaitMax,\n\t\tRetryMax:     defaultRetryMax,\n\t\tCheckRetry:   DefaultRetryPolicy,\n\t\tBackoff:      DefaultBackoff,\n\t}\n}\n\n\/\/ DefaultRetryPolicy provides a default callback for Client.CheckRetry, which\n\/\/ will retry on connection errors and server errors.\nfunc DefaultRetryPolicy(resp *http.Response, err error) (bool, error) {\n\tif err != nil {\n\t\treturn true, err\n\t}\n\t\/\/ Check the response code. We retry on 500-range responses to allow\n\t\/\/ the server time to recover, as 500's are typically not permanent\n\t\/\/ errors and may relate to outages on the server side. This will catch\n\t\/\/ invalid response codes as well, like 0 and 999.\n\tif resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\n\/\/ DefaultBackoff provides a default callback for Client.Backoff which\n\/\/ will perform exponential backoff based on the attempt number and limited\n\/\/ by the provided minimum and maximum durations.\nfunc DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {\n\tmult := math.Pow(2, float64(attemptNum)) * float64(min)\n\tsleep := time.Duration(mult)\n\tif float64(sleep) != mult || sleep > max {\n\t\tsleep = max\n\t}\n\treturn sleep\n}\n\n\/\/ LinearJitterBackoff provides a callback for Client.Backoff which will\n\/\/ perform linear backoff based on the attempt number and with jitter to\n\/\/ prevent a thundering herd.\n\/\/\n\/\/ min and max here are *not* absolute values. The number to be multipled by\n\/\/ the attempt number will be chosen at random from between them, thus they are\n\/\/ bounding the jitter.\n\/\/\n\/\/ For instance:\n\/\/ * To get strictly linear backoff of one second increasing each retry, set\n\/\/ both to one second (1s, 2s, 3s, 4s, ...)\n\/\/ * To get a small amount of jitter centered around one second increasing each\n\/\/ retry, set to around one second, such as a min of 800ms and max of 1200ms\n\/\/ (892ms, 2102ms, 2945ms, 4312ms, ...)\n\/\/ * To get extreme jitter, set to a very wide spread, such as a min of 100ms\n\/\/ and a max of 20s (15382ms, 292ms, 51321ms, 35234ms, ...)\nfunc LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {\n\t\/\/ attemptNum always starts at zero but we want to start at 1 for multiplication\n\tattemptNum++\n\n\tif max <= min {\n\t\t\/\/ Unclear what to do here, or they are the same, so return min *\n\t\t\/\/ attemptNum\n\t\treturn min * time.Duration(attemptNum)\n\t}\n\n\t\/\/ Seed rand; doing this every time is fine\n\trand := rand.New(rand.NewSource(int64(time.Now().Nanosecond())))\n\n\t\/\/ Pick a random number that lies somewhere between the min and max and\n\t\/\/ multiply by the attemptNum. attemptNum starts at zero so we always\n\t\/\/ increment here. We first get a random percentage, then apply that to the\n\t\/\/ difference between min and max, and add to min.\n\tjitter := rand.Float64() * float64(max-min)\n\tjitterMin := int64(jitter) + int64(min)\n\treturn time.Duration(jitterMin * int64(attemptNum))\n}\n\n\/\/ PassthroughErrorHandler is an ErrorHandler that directly passes through the\n\/\/ values from the net\/http library for the final request. The body is not\n\/\/ closed.\nfunc PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) {\n\treturn resp, err\n}\n\n\/\/ Do wraps calling an HTTP method with retries.\nfunc (c *Client) Do(req *Request) (*http.Response, error) {\n\tif c.Logger != nil {\n\t\tc.Logger.Printf(\"[DEBUG] %s %s\", req.Method, req.URL)\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tfor i := 0; ; i++ {\n\t\tvar code int \/\/ HTTP response code\n\n\t\t\/\/ Always rewind the request body when non-nil.\n\t\tif req.body != nil {\n\t\t\tif _, err := req.body.Seek(0, 0); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to seek body: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tif c.RequestLogHook != nil {\n\t\t\tc.RequestLogHook(c.Logger, req.Request, i)\n\t\t}\n\n\t\t\/\/ Attempt the request\n\t\tresp, err = c.HTTPClient.Do(req.Request)\n\t\tif resp != nil {\n\t\t\tcode = resp.StatusCode\n\t\t}\n\n\t\t\/\/ Check if we should continue with retries.\n\t\tcheckOK, checkErr := c.CheckRetry(resp, err)\n\n\t\tif err != nil {\n\t\t\tif c.Logger != nil {\n\t\t\t\tc.Logger.Printf(\"[ERR] %s %s request failed: %v\", req.Method, req.URL, err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Call this here to maintain the behavior of logging all requests,\n\t\t\t\/\/ even if CheckRetry signals to stop.\n\t\t\tif c.ResponseLogHook != nil {\n\t\t\t\t\/\/ Call the response logger function if provided.\n\t\t\t\tc.ResponseLogHook(c.Logger, resp)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Now decide if we should continue.\n\t\tif !checkOK {\n\t\t\tif checkErr != nil {\n\t\t\t\terr = checkErr\n\t\t\t}\n\t\t\treturn resp, err\n\t\t}\n\n\t\t\/\/ We do this before drainBody beause there's no need for the I\/O if\n\t\t\/\/ we're breaking out\n\t\tremain := c.RetryMax - i\n\t\tif remain == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ We're going to retry, consume any response to reuse the connection.\n\t\tif err == nil && resp != nil {\n\t\t\tc.drainBody(resp.Body)\n\t\t}\n\n\t\twait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp)\n\t\tdesc := fmt.Sprintf(\"%s %s\", req.Method, req.URL)\n\t\tif code > 0 {\n\t\t\tdesc = fmt.Sprintf(\"%s (status: %d)\", desc, code)\n\t\t}\n\t\tif c.Logger != nil {\n\t\t\tc.Logger.Printf(\"[DEBUG] %s: retrying in %s (%d left)\", desc, wait, remain)\n\t\t}\n\t\ttime.Sleep(wait)\n\t}\n\n\tif c.ErrorHandler != nil {\n\t\treturn c.ErrorHandler(resp, err, c.RetryMax+1)\n\t}\n\n\t\/\/ By default, we close the response body and return an error without\n\t\/\/ returning the response\n\tif resp != nil {\n\t\tresp.Body.Close()\n\t}\n\treturn nil, fmt.Errorf(\"%s %s giving up after %d attempts\",\n\t\treq.Method, req.URL, c.RetryMax+1)\n}\n\n\/\/ Try to read the response body so we can reuse this connection.\nfunc (c *Client) drainBody(body io.ReadCloser) {\n\tdefer body.Close()\n\t_, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit))\n\tif err != nil {\n\t\tif c.Logger != nil {\n\t\t\tc.Logger.Printf(\"[ERR] error reading response body: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ Get is a shortcut for doing a GET request without making a new client.\nfunc Get(url string) (*http.Response, error) {\n\treturn defaultClient.Get(url)\n}\n\n\/\/ Get is a convenience helper for doing simple GET requests.\nfunc (c *Client) Get(url string) (*http.Response, error) {\n\treq, err := NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}\n\n\/\/ Head is a shortcut for doing a HEAD request without making a new client.\nfunc Head(url string) (*http.Response, error) {\n\treturn defaultClient.Head(url)\n}\n\n\/\/ Head is a convenience method for doing simple HEAD requests.\nfunc (c *Client) Head(url string) (*http.Response, error) {\n\treq, err := NewRequest(\"HEAD\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Do(req)\n}\n\n\/\/ Post is a shortcut for doing a POST request without making a new client.\nfunc Post(url, bodyType string, body io.ReadSeeker) (*http.Response, error) {\n\treturn defaultClient.Post(url, bodyType, body)\n}\n\n\/\/ Post is a convenience method for doing simple POST requests.\nfunc (c *Client) Post(url, bodyType string, body io.ReadSeeker) (*http.Response, 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 c.Do(req)\n}\n\n\/\/ PostForm is a shortcut to perform a POST with form data without creating\n\/\/ a new client.\nfunc PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn defaultClient.PostForm(url, data)\n}\n\n\/\/ PostForm is a convenience method for doing simple POST operations using\n\/\/ pre-filled url.Values form data.\nfunc (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {\n\treturn c.Post(url, \"application\/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n}\n<|endoftext|>"}
{"text":"<commit_before>package consulkv\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\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Config is used to configure the creation of a client\ntype Config struct {\n\t\/\/ Address is the address of the Consul server\n\tAddress string\n\n\t\/\/ Datacenter to use. If not provided, the default agent datacenter is used.\n\tDatacenter string\n\n\t\/\/ HTTPClient is the client to use. Default will be\n\t\/\/ used if not provided.\n\tHTTPClient *http.Client\n\n\t\/\/ WaitTime limits how long a Watch will block. If not provided,\n\t\/\/ the agent default values will be used.\n\tWaitTime time.Duration\n}\n\n\/\/ Client provides a client to Consul for K\/V data\ntype Client struct {\n\tconfig Config\n}\n\n\/\/ KVPair is used to represent a single K\/V entry\ntype KVPair struct {\n\tKey         string\n\tCreateIndex uint64\n\tModifyIndex uint64\n\tFlags       uint64\n\tValue       []byte\n}\n\n\/\/ KVPairs is a list of KVPair objects\ntype KVPairs []*KVPair\n\n\/\/ KVMeta provides meta data about a query\ntype KVMeta struct {\n\tModifyIndex uint64\n}\n\n\/\/ NewClient returns a new\nfunc NewClient(config *Config) (*Client, error) {\n\tclient := &Client{\n\t\tconfig: *config,\n\t}\n\treturn client, nil\n}\n\n\/\/ DefaultConfig returns a default configuration for the client\nfunc DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress:    \"127.0.0.1:8500\",\n\t\tHTTPClient: http.DefaultClient,\n\t}\n}\n\n\/\/ Get is used to lookup a single key\nfunc (c *Client) Get(key string) (*KVMeta, *KVPair, error) {\n\treturn selectOne(c.getRecurse(key, false, 0))\n}\n\n\/\/ List is used to lookup all keys with a prefix\nfunc (c *Client) List(prefix string) (*KVMeta, KVPairs, error) {\n\treturn c.getRecurse(prefix, true, 0)\n}\n\n\/\/ WatchGet is used to block and wait for a change on a key\nfunc (c *Client) WatchGet(key string, modifyIndex uint64) (*KVMeta, *KVPair, error) {\n\treturn selectOne(c.getRecurse(key, false, modifyIndex))\n}\n\n\/\/ WatchGet is used to block and wait for a change on a prefix\nfunc (c *Client) WatchList(prefix string, modifyIndex uint64) (*KVMeta, KVPairs, error) {\n\treturn c.getRecurse(prefix, true, modifyIndex)\n}\n\n\/\/ deleteRecurse does a delete with a potential recurse\nfunc (c *Client) getRecurse(key string, recurse bool, waitIndex uint64) (*KVMeta, KVPairs, error) {\n\turl := c.pathURL(key)\n\tquery := url.Query()\n\tif recurse {\n\t\tquery.Set(\"recurse\", \"1\")\n\t}\n\tif waitIndex > 0 {\n\t\tquery.Set(\"index\", strconv.FormatUint(waitIndex, 10))\n\t}\n\tif waitIndex > 0 && c.config.WaitTime > 0 {\n\t\twaitMsec := fmt.Sprintf(\"%dms\", c.config.WaitTime\/time.Millisecond)\n\t\tquery.Set(\"wait\", waitMsec)\n\t}\n\tif len(query) > 0 {\n\t\turl.RawQuery = query.Encode()\n\t}\n\treq := http.Request{\n\t\tMethod: \"GET\",\n\t\tURL:    url,\n\t}\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Decode the KVMeta\n\tmeta := &KVMeta{}\n\tindex, err := strconv.ParseUint(resp.Header.Get(\"X-Consul-Index\"), 10, 64)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to parse X-Consul-Index: %v\", err)\n\t}\n\tmeta.ModifyIndex = index\n\n\t\/\/ Ensure status code is 404 or 200\n\tif resp.StatusCode == 404 {\n\t\treturn meta, nil, nil\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, nil, fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\n\t\/\/ Decode the response\n\tdec := json.NewDecoder(resp.Body)\n\tvar out KVPairs\n\tif err := dec.Decode(&out); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn meta, out, nil\n}\n\n\/\/ Put is used to set a value for a given key\nfunc (c *Client) Put(key string, value []byte, flags uint64) error {\n\t_, err := c.putCAS(key, value, flags, 0, false)\n\treturn err\n}\n\n\/\/ CAS is used for a Check-And-Set operation\nfunc (c *Client) CAS(key string, value []byte, flags, index uint64) (bool, error) {\n\treturn c.putCAS(key, value, flags, index, true)\n}\n\n\/\/ putCAS is used to do a PUT with optional CAS\nfunc (c *Client) putCAS(key string, value []byte, flags, index uint64, cas bool) (bool, error) {\n\turl := c.pathURL(key)\n\tquery := url.Query()\n\tif cas {\n\t\tquery.Set(\"cas\", strconv.FormatUint(index, 10))\n\t}\n\tquery.Set(\"flags\", strconv.FormatUint(flags, 10))\n\turl.RawQuery = query.Encode()\n\treq := http.Request{\n\t\tMethod: \"PUT\",\n\t\tURL:    url,\n\t\tBody:   ioutil.NopCloser(bytes.NewReader(value)),\n\t}\n\treq.ContentLength = int64(len(value))\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn false, fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\tvar buf bytes.Buffer\n\tif _, err := io.Copy(&buf, resp.Body); err != nil {\n\t\treturn false, fmt.Errorf(\"Failed to read response: %v\", err)\n\t}\n\tres := strings.Contains(string(buf.Bytes()), \"true\")\n\treturn res, nil\n}\n\n\/\/ Delete is used to delete a single key\nfunc (c *Client) Delete(key string) error {\n\treturn c.deleteRecurse(key, false)\n}\n\n\/\/ DeleteTree is used to delete all keys with a prefix\nfunc (c *Client) DeleteTree(prefix string) error {\n\treturn c.deleteRecurse(prefix, true)\n}\n\n\/\/ deleteRecurse does a delete with a potential recurse\nfunc (c *Client) deleteRecurse(key string, recurse bool) error {\n\turl := c.pathURL(key)\n\tif recurse {\n\t\tquery := url.Query()\n\t\tquery.Set(\"recurse\", \"1\")\n\t\turl.RawQuery = query.Encode()\n\t}\n\treq := http.Request{\n\t\tMethod: \"DELETE\",\n\t\tURL:    url,\n\t}\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\treturn nil\n\n}\n\n\/\/ path is used to generate the HTTP path for a request\nfunc (c *Client) pathURL(key string) *url.URL {\n\turl := &url.URL{\n\t\tScheme: \"http\",\n\t\tHost:   c.config.Address,\n\t\tPath:   path.Join(\"\/v1\/kv\/\", key),\n\t}\n\tif c.config.Datacenter != \"\" {\n\t\tquery := url.Query()\n\t\tquery.Set(\"dc\", c.config.Datacenter)\n\t\turl.RawQuery = query.Encode()\n\t}\n\treturn url\n}\n\n\/\/ selectOne is used to grab only the first KVPair in a list\nfunc selectOne(meta *KVMeta, pairs KVPairs, err error) (*KVMeta, *KVPair, error) {\n\tvar pair *KVPair\n\tif len(pairs) > 0 {\n\t\tpair = pairs[0]\n\t}\n\treturn meta, pair, err\n}\n<commit_msg>lint fix to func documentation<commit_after>package consulkv\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\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Config is used to configure the creation of a client\ntype Config struct {\n\t\/\/ Address is the address of the Consul server\n\tAddress string\n\n\t\/\/ Datacenter to use. If not provided, the default agent datacenter is used.\n\tDatacenter string\n\n\t\/\/ HTTPClient is the client to use. Default will be\n\t\/\/ used if not provided.\n\tHTTPClient *http.Client\n\n\t\/\/ WaitTime limits how long a Watch will block. If not provided,\n\t\/\/ the agent default values will be used.\n\tWaitTime time.Duration\n}\n\n\/\/ Client provides a client to Consul for K\/V data\ntype Client struct {\n\tconfig Config\n}\n\n\/\/ KVPair is used to represent a single K\/V entry\ntype KVPair struct {\n\tKey         string\n\tCreateIndex uint64\n\tModifyIndex uint64\n\tFlags       uint64\n\tValue       []byte\n}\n\n\/\/ KVPairs is a list of KVPair objects\ntype KVPairs []*KVPair\n\n\/\/ KVMeta provides meta data about a query\ntype KVMeta struct {\n\tModifyIndex uint64\n}\n\n\/\/ NewClient returns a new\nfunc NewClient(config *Config) (*Client, error) {\n\tclient := &Client{\n\t\tconfig: *config,\n\t}\n\treturn client, nil\n}\n\n\/\/ DefaultConfig returns a default configuration for the client\nfunc DefaultConfig() *Config {\n\treturn &Config{\n\t\tAddress:    \"127.0.0.1:8500\",\n\t\tHTTPClient: http.DefaultClient,\n\t}\n}\n\n\/\/ Get is used to lookup a single key\nfunc (c *Client) Get(key string) (*KVMeta, *KVPair, error) {\n\treturn selectOne(c.getRecurse(key, false, 0))\n}\n\n\/\/ List is used to lookup all keys with a prefix\nfunc (c *Client) List(prefix string) (*KVMeta, KVPairs, error) {\n\treturn c.getRecurse(prefix, true, 0)\n}\n\n\/\/ WatchGet is used to block and wait for a change on a key\nfunc (c *Client) WatchGet(key string, modifyIndex uint64) (*KVMeta, *KVPair, error) {\n\treturn selectOne(c.getRecurse(key, false, modifyIndex))\n}\n\n\/\/ WatchList is used to block and wait for a change on a prefix\nfunc (c *Client) WatchList(prefix string, modifyIndex uint64) (*KVMeta, KVPairs, error) {\n\treturn c.getRecurse(prefix, true, modifyIndex)\n}\n\n\/\/ deleteRecurse does a delete with a potential recurse\nfunc (c *Client) getRecurse(key string, recurse bool, waitIndex uint64) (*KVMeta, KVPairs, error) {\n\turl := c.pathURL(key)\n\tquery := url.Query()\n\tif recurse {\n\t\tquery.Set(\"recurse\", \"1\")\n\t}\n\tif waitIndex > 0 {\n\t\tquery.Set(\"index\", strconv.FormatUint(waitIndex, 10))\n\t}\n\tif waitIndex > 0 && c.config.WaitTime > 0 {\n\t\twaitMsec := fmt.Sprintf(\"%dms\", c.config.WaitTime\/time.Millisecond)\n\t\tquery.Set(\"wait\", waitMsec)\n\t}\n\tif len(query) > 0 {\n\t\turl.RawQuery = query.Encode()\n\t}\n\treq := http.Request{\n\t\tMethod: \"GET\",\n\t\tURL:    url,\n\t}\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Decode the KVMeta\n\tmeta := &KVMeta{}\n\tindex, err := strconv.ParseUint(resp.Header.Get(\"X-Consul-Index\"), 10, 64)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to parse X-Consul-Index: %v\", err)\n\t}\n\tmeta.ModifyIndex = index\n\n\t\/\/ Ensure status code is 404 or 200\n\tif resp.StatusCode == 404 {\n\t\treturn meta, nil, nil\n\t} else if resp.StatusCode != 200 {\n\t\treturn nil, nil, fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\n\t\/\/ Decode the response\n\tdec := json.NewDecoder(resp.Body)\n\tvar out KVPairs\n\tif err := dec.Decode(&out); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn meta, out, nil\n}\n\n\/\/ Put is used to set a value for a given key\nfunc (c *Client) Put(key string, value []byte, flags uint64) error {\n\t_, err := c.putCAS(key, value, flags, 0, false)\n\treturn err\n}\n\n\/\/ CAS is used for a Check-And-Set operation\nfunc (c *Client) CAS(key string, value []byte, flags, index uint64) (bool, error) {\n\treturn c.putCAS(key, value, flags, index, true)\n}\n\n\/\/ putCAS is used to do a PUT with optional CAS\nfunc (c *Client) putCAS(key string, value []byte, flags, index uint64, cas bool) (bool, error) {\n\turl := c.pathURL(key)\n\tquery := url.Query()\n\tif cas {\n\t\tquery.Set(\"cas\", strconv.FormatUint(index, 10))\n\t}\n\tquery.Set(\"flags\", strconv.FormatUint(flags, 10))\n\turl.RawQuery = query.Encode()\n\treq := http.Request{\n\t\tMethod: \"PUT\",\n\t\tURL:    url,\n\t\tBody:   ioutil.NopCloser(bytes.NewReader(value)),\n\t}\n\treq.ContentLength = int64(len(value))\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn false, fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\tvar buf bytes.Buffer\n\tif _, err := io.Copy(&buf, resp.Body); err != nil {\n\t\treturn false, fmt.Errorf(\"Failed to read response: %v\", err)\n\t}\n\tres := strings.Contains(string(buf.Bytes()), \"true\")\n\treturn res, nil\n}\n\n\/\/ Delete is used to delete a single key\nfunc (c *Client) Delete(key string) error {\n\treturn c.deleteRecurse(key, false)\n}\n\n\/\/ DeleteTree is used to delete all keys with a prefix\nfunc (c *Client) DeleteTree(prefix string) error {\n\treturn c.deleteRecurse(prefix, true)\n}\n\n\/\/ deleteRecurse does a delete with a potential recurse\nfunc (c *Client) deleteRecurse(key string, recurse bool) error {\n\turl := c.pathURL(key)\n\tif recurse {\n\t\tquery := url.Query()\n\t\tquery.Set(\"recurse\", \"1\")\n\t\turl.RawQuery = query.Encode()\n\t}\n\treq := http.Request{\n\t\tMethod: \"DELETE\",\n\t\tURL:    url,\n\t}\n\tresp, err := c.config.HTTPClient.Do(&req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Unexpected response code: %d\", resp.StatusCode)\n\t}\n\treturn nil\n\n}\n\n\/\/ path is used to generate the HTTP path for a request\nfunc (c *Client) pathURL(key string) *url.URL {\n\turl := &url.URL{\n\t\tScheme: \"http\",\n\t\tHost:   c.config.Address,\n\t\tPath:   path.Join(\"\/v1\/kv\/\", key),\n\t}\n\tif c.config.Datacenter != \"\" {\n\t\tquery := url.Query()\n\t\tquery.Set(\"dc\", c.config.Datacenter)\n\t\turl.RawQuery = query.Encode()\n\t}\n\treturn url\n}\n\n\/\/ selectOne is used to grab only the first KVPair in a list\nfunc selectOne(meta *KVMeta, pairs KVPairs, err error) (*KVMeta, *KVPair, error) {\n\tvar pair *KVPair\n\tif len(pairs) > 0 {\n\t\tpair = pairs[0]\n\t}\n\treturn meta, pair, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package espsdk\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/dysolution\/sleepwalker\"\n)\n\n\/\/ A Client communicates with the ESP REST API.\ntype Client struct {\n\t*sleepwalker.Client\n}\n\n\/\/ A Result provides information about the response from the ESP REST API.\ntype Result struct {\n\tsleepwalker.Result\n}\n\n\/\/ GetClient provides a client for communicating with the ESP REST API.\nfunc GetClient(key, secret, username, password string, log *logrus.Logger) Client {\n\treturn Client{sleepwalker.GetClient(key, secret, username, password, OAuthEndpoint, ESPAPIRoot, log)}\n}\n\n\/\/ GetKeywords requests suggestions from the Getty controlled vocabulary\n\/\/ for the keywords provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c Client) GetKeywords() []byte { return []byte(\"not implemented\") }\n\n\/\/ GetPersonalities requests suggestions from the Getty controlled vocabulary\n\/\/ for the famous personalities provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c Client) GetPersonalities() []byte { return []byte(\"not implemented\") }\n\n\/\/ GetControlledValues returns complete lists of values and descriptions for\n\/\/ fields with controlled vocabularies, grouped by submission type.\nfunc (c Client) GetControlledValues() ControlledValues {\n\tdesc := \"Client.GetControlledValues\"\n\tresult, err := c.GetPath(ControlledValuesEndpoint)\n\tif err != nil {\n\t\treturn ControlledValues{}\n\t}\n\tresult.Log().Info(desc)\n\treturn parseCV(result)\n}\n\n\/\/ GetTranscoderMappings lists acceptable transcoder mapping values\n\/\/ for Getty and iStock video.\nfunc (c Client) GetTranscoderMappings() *TranscoderMappingList {\n\tdesc := \"Client.GetTranscoderMappings\"\n\tresult, err := c.GetPath(TranscoderMappingsEndpoint)\n\tif err != nil {\n\t\treturn &TranscoderMappingList{}\n\t}\n\tif result.Payload == nil {\n\t\treturn &TranscoderMappingList{}\n\t}\n\tresult.Log().Info(desc)\n\treturn TranscoderMappingList{}.Unmarshal(result.Payload)\n}\n\n\/\/ GetTermList lists all possible values for the given controlled vocabulary.\nfunc (c Client) GetTermList(endpoint string) *TermList {\n\tdesc := \"Client.GetTermList\"\n\tresult, err := c.GetPath(endpoint)\n\tif err != nil {\n\t\treturn &TermList{}\n\t}\n\tif result.Payload == nil {\n\t\treturn &TermList{}\n\t}\n\tresult.Log().Info(desc)\n\treturn TermList{}.Unmarshal(result.Payload)\n}\n\n\/\/ DeleteLastBatch looks up the newest Batch and deletes it.\nfunc DeleteLastBatch(c sleepwalker.RESTClient) (sleepwalker.Result, error) {\n\tlastBatch := Batch{}.Index(c).Last()\n\treturn c.Delete(lastBatch)\n}\n\n\/\/ SubmitLastPhoto subtmits the newest Contribution for review and publication.\nfunc SubmitLastPhoto(c sleepwalker.RESTClient) (sleepwalker.Result, error) {\n\tnewestBatch := Batch{}.Index(c).Last()\n\tnewestContribution, err := Contribution{\n\t\tSubmissionBatchID: newestBatch.ID,\n\t}.Index(c, newestBatch.ID).Last()\n\tif err != nil {\n\t\treturn sleepwalker.Result{}, err\n\t}\n\treturn c.Put(newestContribution, newestContribution.Path()+\"\/submit\")\n}\n<commit_msg>refactor: use config struct<commit_after>package espsdk\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/dysolution\/sleepwalker\"\n)\n\n\/\/ A Client communicates with the ESP REST API.\ntype Client struct {\n\t*sleepwalker.Client\n}\n\n\/\/ A Result provides information about the response from the ESP REST API.\ntype Result struct {\n\tsleepwalker.Result\n}\n\n\/\/ GetClient provides a client for communicating with the ESP REST API.\nfunc GetClient(key, secret, username, password, apiRoot string, log *logrus.Logger) Client {\n\tconfig := &sleepwalker.Config{\n\t\tCredentials: &sleepwalker.Credentials{\n\t\t\tAPIKey:    key,\n\t\t\tAPISecret: secret,\n\t\t\tUsername:  username,\n\t\t\tPassword:  password,\n\t\t},\n\t\tOAuthEndpoint: OAuthEndpoint,\n\t\tAPIRoot:       apiRoot,\n\t\tLogger:        log,\n\t}\n\treturn Client{sleepwalker.GetClient(config)}\n}\n\n\/\/ GetKeywords requests suggestions from the Getty controlled vocabulary\n\/\/ for the keywords provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c Client) GetKeywords() []byte { return []byte(\"not implemented\") }\n\n\/\/ GetPersonalities requests suggestions from the Getty controlled vocabulary\n\/\/ for the famous personalities provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c Client) GetPersonalities() []byte { return []byte(\"not implemented\") }\n\n\/\/ GetControlledValues returns complete lists of values and descriptions for\n\/\/ fields with controlled vocabularies, grouped by submission type.\nfunc (c Client) GetControlledValues() ControlledValues {\n\tdesc := \"Client.GetControlledValues\"\n\tresult, err := c.GetPath(ControlledValuesEndpoint)\n\tif err != nil {\n\t\treturn ControlledValues{}\n\t}\n\tresult.Log().Info(desc)\n\treturn parseCV(result)\n}\n\n\/\/ GetTranscoderMappings lists acceptable transcoder mapping values\n\/\/ for Getty and iStock video.\nfunc (c Client) GetTranscoderMappings() *TranscoderMappingList {\n\tdesc := \"Client.GetTranscoderMappings\"\n\tresult, err := c.GetPath(TranscoderMappingsEndpoint)\n\tif err != nil {\n\t\treturn &TranscoderMappingList{}\n\t}\n\tif result.Payload == nil {\n\t\treturn &TranscoderMappingList{}\n\t}\n\tresult.Log().Info(desc)\n\treturn TranscoderMappingList{}.Unmarshal(result.Payload)\n}\n\n\/\/ GetTermList lists all possible values for the given controlled vocabulary.\nfunc (c Client) GetTermList(endpoint string) *TermList {\n\tdesc := \"Client.GetTermList\"\n\tresult, err := c.GetPath(endpoint)\n\tif err != nil {\n\t\treturn &TermList{}\n\t}\n\tif result.Payload == nil {\n\t\treturn &TermList{}\n\t}\n\tresult.Log().Info(desc)\n\treturn TermList{}.Unmarshal(result.Payload)\n}\n\n\/\/ DeleteLastBatch looks up the newest Batch and deletes it.\nfunc DeleteLastBatch(c sleepwalker.RESTClient) (sleepwalker.Result, error) {\n\tlastBatch := Batch{}.Index(c).Last()\n\treturn c.Delete(lastBatch)\n}\n\n\/\/ SubmitLastPhoto subtmits the newest Contribution for review and publication.\nfunc SubmitLastPhoto(c sleepwalker.RESTClient) (sleepwalker.Result, error) {\n\tnewestBatch := Batch{}.Index(c).Last()\n\tnewestContribution, err := Contribution{\n\t\tSubmissionBatchID: newestBatch.ID,\n\t}.Index(c, newestBatch.ID).Last()\n\tif err != nil {\n\t\treturn sleepwalker.Result{}, err\n\t}\n\treturn c.Put(newestContribution, newestContribution.Path()+\"\/submit\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package cfclient\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/clientcredentials\"\n\t\"time\"\n)\n\n\/\/Client used to communicate with Cloud Foundry\ntype Client struct {\n\tConfig   Config\n\tEndpoint Endpoint\n}\n\ntype Endpoint struct {\n\tDopplerEndpoint string `json:\"doppler_logging_endpoint\"`\n\tLoggingEndpoint string `json:\"logging_endpoint\"`\n\tAuthEndpoint    string `json:\"authorization_endpoint\"`\n\tTokenEndpoint   string `json:\"token_endpoint\"`\n}\n\n\/\/Config is used to configure the creation of a client\ntype Config struct {\n\tApiAddress          string `json:\"api_url\"`\n\tUsername            string `json:\"user\"`\n\tPassword            string `json:\"password\"`\n\tClientID            string `json:\"client_id\"`\n\tClientSecret        string `json:\"client_secret\"`\n\tSkipSslValidation   bool   `json:\"skip_ssl_validation\"`\n\tHttpClient          *http.Client\n\tToken               string `json:\"auth_token\"`\n\tTokenSource         oauth2.TokenSource\n\ttokenSourceDeadline *time.Time\n\tUserAgent           string `json:\"user_agent\"`\n}\n\n\/\/ request is used to help build up a request\ntype request struct {\n\tmethod string\n\turl    string\n\tparams url.Values\n\tbody   io.Reader\n\tobj    interface{}\n}\n\n\/\/DefaultConfig configuration for client\n\/\/Keep LoginAdress for backward compatibility\n\/\/Need to be remove in close future\nfunc DefaultConfig() *Config {\n\treturn &Config{\n\t\tApiAddress:         \"http:\/\/api.bosh-lite.com\",\n\t\tUsername:           \"admin\",\n\t\tPassword:           \"admin\",\n\t\tToken:              \"\",\n\t\tSkipSslValidation:  false,\n\t\tHttpClient:         http.DefaultClient,\n\t\tUserAgent:          \"Go-CF-client\/1.1\",\n\t}\n}\n\nfunc DefaultEndpoint() *Endpoint {\n\treturn &Endpoint{\n\t\tDopplerEndpoint: \"wss:\/\/doppler.10.244.0.34.xip.io:443\",\n\t\tLoggingEndpoint: \"wss:\/\/loggregator.10.244.0.34.xip.io:443\",\n\t\tTokenEndpoint:   \"https:\/\/uaa.10.244.0.34.xip.io\",\n\t\tAuthEndpoint:    \"https:\/\/login.10.244.0.34.xip.io\",\n\t}\n}\n\n\/\/ NewClient returns a new client\nfunc NewClient(config *Config) (client *Client, err error) {\n\t\/\/ bootstrap the config\n\tdefConfig := DefaultConfig()\n\n\tif len(config.ApiAddress) == 0 {\n\t\tconfig.ApiAddress = defConfig.ApiAddress\n\t}\n\n\tif len(config.Username) == 0 {\n\t\tconfig.Username = defConfig.Username\n\t}\n\n\tif len(config.Password) == 0 {\n\t\tconfig.Password = defConfig.Password\n\t}\n\n\tif len(config.Token) == 0 {\n\t\tconfig.Token = defConfig.Token\n\t}\n\n\tif len(config.UserAgent) == 0 {\n\t\tconfig.UserAgent = defConfig.UserAgent\n\t}\n\n\tif config.HttpClient == nil {\n\t\tconfig.HttpClient = defConfig.HttpClient\n\t}\n\n\tif config.HttpClient.Transport == nil {\n\t\tconfig.HttpClient.Transport = shallowDefaultTransport()\n\t}\n\n\tvar tp *http.Transport\n\n\tswitch t := config.HttpClient.Transport.(type) {\n\tcase *http.Transport:\n\t\ttp = t\n\tcase *oauth2.Transport:\n\t\tif bt, ok := t.Base.(*http.Transport); ok {\n\t\t\ttp = bt\n\t\t}\n\t}\n\n\tif tp != nil {\n\t\tif tp.TLSClientConfig == nil {\n\t\t\ttp.TLSClientConfig = &tls.Config{}\n\t\t}\n\t\ttp.TLSClientConfig.InsecureSkipVerify = config.SkipSslValidation\n\t}\n\n\tclient = &Client{\n\t\tConfig: *config,\n\t}\n\n\tif err := client.refreshEndpoint(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}\n\nfunc shallowDefaultTransport() *http.Transport {\n\tdefaultTransport := http.DefaultTransport.(*http.Transport)\n\treturn &http.Transport{\n\t\tProxy:                 defaultTransport.Proxy,\n\t\tTLSHandshakeTimeout:   defaultTransport.TLSHandshakeTimeout,\n\t\tExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,\n\t}\n}\n\nfunc getUserAuth(ctx context.Context, config Config, endpoint *Endpoint) (Config, error) {\n\tauthConfig := &oauth2.Config{\n\t\tClientID: \"cf\",\n\t\tScopes:   []string{\"\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL:  endpoint.AuthEndpoint + \"\/oauth\/auth\",\n\t\t\tTokenURL: endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t\t},\n\t}\n\n\ttoken, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"Error getting token\")\n\t}\n\n\tconfig.tokenSourceDeadline = &token.Expiry\n\tconfig.TokenSource = authConfig.TokenSource(ctx, token)\n\tconfig.HttpClient = oauth2.NewClient(ctx, config.TokenSource)\n\n\treturn config, err\n}\n\nfunc getClientAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {\n\tauthConfig := &clientcredentials.Config{\n\t\tClientID:     config.ClientID,\n\t\tClientSecret: config.ClientSecret,\n\t\tTokenURL:     endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t}\n\n\tconfig.TokenSource = authConfig.TokenSource(ctx)\n\tconfig.HttpClient = authConfig.Client(ctx)\n\treturn config\n}\n\n\/\/ getUserTokenAuth initializes client credentials from existing bearer token.\nfunc getUserTokenAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {\n\tauthConfig := &oauth2.Config{\n\t\tClientID: \"cf\",\n\t\tScopes:   []string{\"\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL:  endpoint.AuthEndpoint + \"\/oauth\/auth\",\n\t\t\tTokenURL: endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t\t},\n\t}\n\n\t\/\/ Token is expected to have no \"bearer\" prefix\n\ttoken := &oauth2.Token{\n\t\tAccessToken: config.Token,\n\t\tTokenType:   \"Bearer\"}\n\n\tconfig.TokenSource = authConfig.TokenSource(ctx, token)\n\tconfig.HttpClient = oauth2.NewClient(ctx, config.TokenSource)\n\n\treturn config\n}\n\nfunc getInfo(api string, httpClient *http.Client) (*Endpoint, error) {\n\tvar endpoint Endpoint\n\n\tif api == \"\" {\n\t\treturn DefaultEndpoint(), nil\n\t}\n\n\tresp, err := httpClient.Get(api + \"\/v2\/info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\terr = decodeBody(resp, &endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &endpoint, err\n}\n\n\/\/ NewRequest is used to create a new request\nfunc (c *Client) NewRequest(method, path string) *request {\n\tr := &request{\n\t\tmethod: method,\n\t\turl:    c.Config.ApiAddress + path,\n\t\tparams: make(map[string][]string),\n\t}\n\treturn r\n}\n\n\/\/ NewRequestWithBody is used to create a new request with\n\/\/ arbigtrary body io.Reader.\nfunc (c *Client) NewRequestWithBody(method, path string, body io.Reader) *request {\n\tr := c.NewRequest(method, path)\n\n\t\/\/ Set request body\n\tr.body = body\n\n\treturn r\n}\n\n\/\/ DoRequest runs a request with our client\nfunc (c *Client) DoRequest(r *request) (*http.Response, error) {\n\treq, err := r.toHTTP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", c.Config.UserAgent)\n\tif r.body != nil {\n\t\treq.Header.Set(\"Content-type\", \"application\/json\")\n\t}\n\n\tresp, err := c.Config.HttpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode >= http.StatusBadRequest {\n\t\tvar cfErr CloudFoundryError\n\t\tif err := decodeBody(resp, &cfErr); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"Unable to decode body\")\n\t\t}\n\t\treturn nil, cfErr\n\t}\n\n\treturn resp, nil\n}\n\nfunc (c *Client) refreshEndpoint() error {\n\t\/\/ we want to keep the Timeout value from config.HttpClient\n\ttimeout := c.Config.HttpClient.Timeout\n\n\tctx := context.Background()\n\tctx = context.WithValue(ctx, oauth2.HTTPClient, c.Config.HttpClient)\n\n\tendpoint, err := getInfo(c.Config.ApiAddress, oauth2.NewClient(ctx, nil))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not get api \/v2\/info\")\n\t}\n\n\tswitch {\n\tcase c.Config.Token != \"\":\n\t\tc.Config = getUserTokenAuth(ctx, c.Config, endpoint)\n\tcase c.Config.ClientID != \"\":\n\t\tc.Config = getClientAuth(ctx, c.Config, endpoint)\n\tdefault:\n\t\tc.Config, err = getUserAuth(ctx, c.Config, endpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ make sure original Timeout value will be used\n\tif c.Config.HttpClient.Timeout != timeout {\n\t\tc.Config.HttpClient.Timeout = timeout\n\t}\n\n\treturn nil\n}\n\n\/\/ toHTTP converts the request to an HTTP request\nfunc (r *request) toHTTP() (*http.Request, error) {\n\n\t\/\/ Check if we should encode the body\n\tif r.body == nil && r.obj != nil {\n\t\tb, err := encodeBody(r.obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.body = b\n\t}\n\n\t\/\/ Create the HTTP request\n\treturn http.NewRequest(r.method, r.url, r.body)\n}\n\n\/\/ decodeBody is used to JSON decode a body\nfunc decodeBody(resp *http.Response, out interface{}) error {\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}\n\n\/\/ encodeBody is used to encode a request body\nfunc encodeBody(obj interface{}) (io.Reader, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tenc := json.NewEncoder(buf)\n\tif err := enc.Encode(obj); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}\n\nfunc (c *Client) GetToken() (string, error) {\n\tif c.Config.tokenSourceDeadline != nil && c.Config.tokenSourceDeadline.Before(time.Now()) {\n\t\tif err := c.refreshEndpoint(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\ttoken, err := c.Config.TokenSource.Token()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Error getting bearer token\")\n\t}\n\treturn \"bearer \" + token.AccessToken, nil\n}\n<commit_msg>Store endpoint in refreshEndpoint(). (#164)<commit_after>package cfclient\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/clientcredentials\"\n)\n\n\/\/Client used to communicate with Cloud Foundry\ntype Client struct {\n\tConfig   Config\n\tEndpoint Endpoint\n}\n\ntype Endpoint struct {\n\tDopplerEndpoint string `json:\"doppler_logging_endpoint\"`\n\tLoggingEndpoint string `json:\"logging_endpoint\"`\n\tAuthEndpoint    string `json:\"authorization_endpoint\"`\n\tTokenEndpoint   string `json:\"token_endpoint\"`\n}\n\n\/\/Config is used to configure the creation of a client\ntype Config struct {\n\tApiAddress          string `json:\"api_url\"`\n\tUsername            string `json:\"user\"`\n\tPassword            string `json:\"password\"`\n\tClientID            string `json:\"client_id\"`\n\tClientSecret        string `json:\"client_secret\"`\n\tSkipSslValidation   bool   `json:\"skip_ssl_validation\"`\n\tHttpClient          *http.Client\n\tToken               string `json:\"auth_token\"`\n\tTokenSource         oauth2.TokenSource\n\ttokenSourceDeadline *time.Time\n\tUserAgent           string `json:\"user_agent\"`\n}\n\n\/\/ request is used to help build up a request\ntype request struct {\n\tmethod string\n\turl    string\n\tparams url.Values\n\tbody   io.Reader\n\tobj    interface{}\n}\n\n\/\/DefaultConfig configuration for client\n\/\/Keep LoginAdress for backward compatibility\n\/\/Need to be remove in close future\nfunc DefaultConfig() *Config {\n\treturn &Config{\n\t\tApiAddress:        \"http:\/\/api.bosh-lite.com\",\n\t\tUsername:          \"admin\",\n\t\tPassword:          \"admin\",\n\t\tToken:             \"\",\n\t\tSkipSslValidation: false,\n\t\tHttpClient:        http.DefaultClient,\n\t\tUserAgent:         \"Go-CF-client\/1.1\",\n\t}\n}\n\nfunc DefaultEndpoint() *Endpoint {\n\treturn &Endpoint{\n\t\tDopplerEndpoint: \"wss:\/\/doppler.10.244.0.34.xip.io:443\",\n\t\tLoggingEndpoint: \"wss:\/\/loggregator.10.244.0.34.xip.io:443\",\n\t\tTokenEndpoint:   \"https:\/\/uaa.10.244.0.34.xip.io\",\n\t\tAuthEndpoint:    \"https:\/\/login.10.244.0.34.xip.io\",\n\t}\n}\n\n\/\/ NewClient returns a new client\nfunc NewClient(config *Config) (client *Client, err error) {\n\t\/\/ bootstrap the config\n\tdefConfig := DefaultConfig()\n\n\tif len(config.ApiAddress) == 0 {\n\t\tconfig.ApiAddress = defConfig.ApiAddress\n\t}\n\n\tif len(config.Username) == 0 {\n\t\tconfig.Username = defConfig.Username\n\t}\n\n\tif len(config.Password) == 0 {\n\t\tconfig.Password = defConfig.Password\n\t}\n\n\tif len(config.Token) == 0 {\n\t\tconfig.Token = defConfig.Token\n\t}\n\n\tif len(config.UserAgent) == 0 {\n\t\tconfig.UserAgent = defConfig.UserAgent\n\t}\n\n\tif config.HttpClient == nil {\n\t\tconfig.HttpClient = defConfig.HttpClient\n\t}\n\n\tif config.HttpClient.Transport == nil {\n\t\tconfig.HttpClient.Transport = shallowDefaultTransport()\n\t}\n\n\tvar tp *http.Transport\n\n\tswitch t := config.HttpClient.Transport.(type) {\n\tcase *http.Transport:\n\t\ttp = t\n\tcase *oauth2.Transport:\n\t\tif bt, ok := t.Base.(*http.Transport); ok {\n\t\t\ttp = bt\n\t\t}\n\t}\n\n\tif tp != nil {\n\t\tif tp.TLSClientConfig == nil {\n\t\t\ttp.TLSClientConfig = &tls.Config{}\n\t\t}\n\t\ttp.TLSClientConfig.InsecureSkipVerify = config.SkipSslValidation\n\t}\n\n\tclient = &Client{\n\t\tConfig: *config,\n\t}\n\n\tif err := client.refreshEndpoint(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}\n\nfunc shallowDefaultTransport() *http.Transport {\n\tdefaultTransport := http.DefaultTransport.(*http.Transport)\n\treturn &http.Transport{\n\t\tProxy:                 defaultTransport.Proxy,\n\t\tTLSHandshakeTimeout:   defaultTransport.TLSHandshakeTimeout,\n\t\tExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,\n\t}\n}\n\nfunc getUserAuth(ctx context.Context, config Config, endpoint *Endpoint) (Config, error) {\n\tauthConfig := &oauth2.Config{\n\t\tClientID: \"cf\",\n\t\tScopes:   []string{\"\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL:  endpoint.AuthEndpoint + \"\/oauth\/auth\",\n\t\t\tTokenURL: endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t\t},\n\t}\n\n\ttoken, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"Error getting token\")\n\t}\n\n\tconfig.tokenSourceDeadline = &token.Expiry\n\tconfig.TokenSource = authConfig.TokenSource(ctx, token)\n\tconfig.HttpClient = oauth2.NewClient(ctx, config.TokenSource)\n\n\treturn config, err\n}\n\nfunc getClientAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {\n\tauthConfig := &clientcredentials.Config{\n\t\tClientID:     config.ClientID,\n\t\tClientSecret: config.ClientSecret,\n\t\tTokenURL:     endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t}\n\n\tconfig.TokenSource = authConfig.TokenSource(ctx)\n\tconfig.HttpClient = authConfig.Client(ctx)\n\treturn config\n}\n\n\/\/ getUserTokenAuth initializes client credentials from existing bearer token.\nfunc getUserTokenAuth(ctx context.Context, config Config, endpoint *Endpoint) Config {\n\tauthConfig := &oauth2.Config{\n\t\tClientID: \"cf\",\n\t\tScopes:   []string{\"\"},\n\t\tEndpoint: oauth2.Endpoint{\n\t\t\tAuthURL:  endpoint.AuthEndpoint + \"\/oauth\/auth\",\n\t\t\tTokenURL: endpoint.TokenEndpoint + \"\/oauth\/token\",\n\t\t},\n\t}\n\n\t\/\/ Token is expected to have no \"bearer\" prefix\n\ttoken := &oauth2.Token{\n\t\tAccessToken: config.Token,\n\t\tTokenType:   \"Bearer\"}\n\n\tconfig.TokenSource = authConfig.TokenSource(ctx, token)\n\tconfig.HttpClient = oauth2.NewClient(ctx, config.TokenSource)\n\n\treturn config\n}\n\nfunc getInfo(api string, httpClient *http.Client) (*Endpoint, error) {\n\tvar endpoint Endpoint\n\n\tif api == \"\" {\n\t\treturn DefaultEndpoint(), nil\n\t}\n\n\tresp, err := httpClient.Get(api + \"\/v2\/info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\terr = decodeBody(resp, &endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &endpoint, err\n}\n\n\/\/ NewRequest is used to create a new request\nfunc (c *Client) NewRequest(method, path string) *request {\n\tr := &request{\n\t\tmethod: method,\n\t\turl:    c.Config.ApiAddress + path,\n\t\tparams: make(map[string][]string),\n\t}\n\treturn r\n}\n\n\/\/ NewRequestWithBody is used to create a new request with\n\/\/ arbigtrary body io.Reader.\nfunc (c *Client) NewRequestWithBody(method, path string, body io.Reader) *request {\n\tr := c.NewRequest(method, path)\n\n\t\/\/ Set request body\n\tr.body = body\n\n\treturn r\n}\n\n\/\/ DoRequest runs a request with our client\nfunc (c *Client) DoRequest(r *request) (*http.Response, error) {\n\treq, err := r.toHTTP()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"User-Agent\", c.Config.UserAgent)\n\tif r.body != nil {\n\t\treq.Header.Set(\"Content-type\", \"application\/json\")\n\t}\n\n\tresp, err := c.Config.HttpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode >= http.StatusBadRequest {\n\t\tvar cfErr CloudFoundryError\n\t\tif err := decodeBody(resp, &cfErr); err != nil {\n\t\t\treturn resp, errors.Wrap(err, \"Unable to decode body\")\n\t\t}\n\t\treturn nil, cfErr\n\t}\n\n\treturn resp, nil\n}\n\nfunc (c *Client) refreshEndpoint() error {\n\t\/\/ we want to keep the Timeout value from config.HttpClient\n\ttimeout := c.Config.HttpClient.Timeout\n\n\tctx := context.Background()\n\tctx = context.WithValue(ctx, oauth2.HTTPClient, c.Config.HttpClient)\n\n\tendpoint, err := getInfo(c.Config.ApiAddress, oauth2.NewClient(ctx, nil))\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not get api \/v2\/info\")\n\t}\n\n\tswitch {\n\tcase c.Config.Token != \"\":\n\t\tc.Config = getUserTokenAuth(ctx, c.Config, endpoint)\n\tcase c.Config.ClientID != \"\":\n\t\tc.Config = getClientAuth(ctx, c.Config, endpoint)\n\tdefault:\n\t\tc.Config, err = getUserAuth(ctx, c.Config, endpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ make sure original Timeout value will be used\n\tif c.Config.HttpClient.Timeout != timeout {\n\t\tc.Config.HttpClient.Timeout = timeout\n\t}\n\n\tc.Endpoint = *endpoint\n\treturn nil\n}\n\n\/\/ toHTTP converts the request to an HTTP request\nfunc (r *request) toHTTP() (*http.Request, error) {\n\n\t\/\/ Check if we should encode the body\n\tif r.body == nil && r.obj != nil {\n\t\tb, err := encodeBody(r.obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.body = b\n\t}\n\n\t\/\/ Create the HTTP request\n\treturn http.NewRequest(r.method, r.url, r.body)\n}\n\n\/\/ decodeBody is used to JSON decode a body\nfunc decodeBody(resp *http.Response, out interface{}) error {\n\tdefer resp.Body.Close()\n\tdec := json.NewDecoder(resp.Body)\n\treturn dec.Decode(out)\n}\n\n\/\/ encodeBody is used to encode a request body\nfunc encodeBody(obj interface{}) (io.Reader, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tenc := json.NewEncoder(buf)\n\tif err := enc.Encode(obj); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf, nil\n}\n\nfunc (c *Client) GetToken() (string, error) {\n\tif c.Config.tokenSourceDeadline != nil && c.Config.tokenSourceDeadline.Before(time.Now()) {\n\t\tif err := c.refreshEndpoint(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\ttoken, err := c.Config.TokenSource.Token()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Error getting bearer token\")\n\t}\n\treturn \"bearer \" + token.AccessToken, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package MQTTg\n\nimport (\n\t\"net\"\n)\n\ntype User struct {\n\tName   string\n\tPasswd string\n}\n\nfunc NewUser(name, pass string) *User {\n\treturn &User{\n\t\tName:   name,\n\t\tPasswd: pass,\n\t}\n}\n\ntype Client struct {\n\tCt        *Transport\n\tAddr      *net.UDPAddr\n\tID        string\n\tUser      *User\n\tKeepAlive uint16\n\tWill      *Will\n\tSubTopics []SubscribeTopic\n}\n\nfunc NewClient(t *Transport, addr *net.UDPAddr, id string, user *User, keepAlive uint16, will *Will) *Client {\n\t\/\/ TODO: when id is empty, then apply random\n\treturn &Client{\n\t\tCt:        t,\n\t\tAddr:      addr,\n\t\tID:        id,\n\t\tUser:      user,\n\t\tKeepAlive: keepAlive,\n\t\tWill:      will,\n\t\tSubTopics: make([]SubscribeTopic, 0),\n\t}\n}\n\nfunc (self *Client) AckSubscribeTopic(order int, code SubscribeReturnCode) error {\n\tif code != SubscribeFailure {\n\t\tself.SubTopics[order].QoS = uint8(code)\n\t\tself.SubTopics[order].State = SubscribeAck\n\t} else {\n\t\t\/\/failed\n\t}\n\treturn nil\n}\n\nfunc (self *Client) Subsclibe(topics []SubscribeTopic) error {\n\t\/\/ TODO: id should be considered\n\tsub := NewSubscribeMessage(0, topics)\n\terr := self.Ct.SendMessage(sub)\n\tif err == nil {\n\t\tself.SubTopics = append(self.SubTopics, topics...)\n\t}\n\treturn err\n}\n\nfunc (self *Client) Unsubscribe(topics [][]uint8) error {\n\tfor i, t := range self.SubTopics {\n\t\texist := false\n\t\tfor j, name := range topics {\n\t\t\tif string(t.Topic) == string(name) {\n\t\t\t\texist = true\n\t\t\t}\n\t\t}\n\t\tif exist {\n\t\t\tt.State = UnSubscribeNonAck\n\t\t} else {\n\t\t\t\/\/ error? or warnning\n\t\t\t\/\/ return error\n\t\t}\n\t}\n\t\/\/ id should be conidered\n\tunsub := NewUnsubscribeMessage(0, topics)\n\terr := self.Ct.SendMessage(unsub)\n\treturn err\n}\n\nfunc (self *Client) Ping() error {\n\tping := NewPingreqMessage()\n\terr := self.Ct.SendMessage(ping)\n\treturn err\n}\n\nfunc (self *Client) Disconnect() error {\n\tdc := NewDisconnectMessage()\n\terr := self.Ct.SendMessage(dc)\n\t\/\/ TODO: close connection\n\treturn err\n}\n\nfunc (self *Client) ReadLoop() error {\n\tfor {\n\t\tm, _, err := self.Ct.ReadMessageFrom()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch message := m.(type) {\n\t\tcase *ConnackMessage:\n\t\tcase *PublishMessage:\n\t\t\tif message.QoS == 3 {\n\t\t\t\t\/\/ error\n\t\t\t\t\/\/ close connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Dup {\n\t\t\t\t\/\/ re-delivered\n\t\t\t} else if message.Dup {\n\t\t\t\t\/\/ first time delivery\n\t\t\t}\n\n\t\t\tif message.Retain {\n\t\t\t\t\/\/ retained message comes\n\t\t\t} else {\n\t\t\t\t\/\/ non retained message\n\t\t\t}\n\n\t\t\tswitch message.QoS {\n\t\t\t\/\/ in any case, Dub must be 0\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tPuback(message.PacketID)\n\t\t\tcase 2:\n\t\t\t\tPubrec(message.PacketID)\n\t\t\t}\n\n\t\tcase *PubackMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\tcase *PubrecMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\t\tPubrel(message.PacketID)\n\t\tcase *PubrelMessage:\n\t\t\tPubcomp(message.PacketID)\n\t\tcase *PubcompMessage:\n\t\t\t\/\/ acknowledge the sent Pubrel packet\n\t\tcase *SubackMessage:\n\t\t\t\/\/ acknowledge the sent subscribe packet\n\t\t\tfor i, code := range message.ReturnCodes {\n\t\t\t\t_ = self.AckSubscribeTopic(i, code)\n\t\t\t}\n\t\tcase *UnsubackMessage:\n\t\t\t\/\/ acknowledged the sent unsubscribe packet\n\t\tcase *PingrespMessage:\n\t\tdefault:\n\t\t\t\/\/ when invalid messages come\n\t\t}\n\t}\n}\n<commit_msg>apply responses<commit_after>package MQTTg\n\nimport (\n\t\"net\"\n)\n\ntype User struct {\n\tName   string\n\tPasswd string\n}\n\nfunc NewUser(name, pass string) *User {\n\treturn &User{\n\t\tName:   name,\n\t\tPasswd: pass,\n\t}\n}\n\ntype Client struct {\n\tCt        *Transport\n\tAddr      *net.UDPAddr\n\tID        string\n\tUser      *User\n\tKeepAlive uint16\n\tWill      *Will\n\tSubTopics []SubscribeTopic\n}\n\nfunc NewClient(t *Transport, addr *net.UDPAddr, id string, user *User, keepAlive uint16, will *Will) *Client {\n\t\/\/ TODO: when id is empty, then apply random\n\treturn &Client{\n\t\tCt:        t,\n\t\tAddr:      addr,\n\t\tID:        id,\n\t\tUser:      user,\n\t\tKeepAlive: keepAlive,\n\t\tWill:      will,\n\t\tSubTopics: make([]SubscribeTopic, 0),\n\t}\n}\n\nfunc (self *Client) AckSubscribeTopic(order int, code SubscribeReturnCode) error {\n\tif code != SubscribeFailure {\n\t\tself.SubTopics[order].QoS = uint8(code)\n\t\tself.SubTopics[order].State = SubscribeAck\n\t} else {\n\t\t\/\/failed\n\t}\n\treturn nil\n}\n\nfunc (self *Client) Subsclibe(topics []SubscribeTopic) error {\n\t\/\/ TODO: id should be considered\n\tsub := NewSubscribeMessage(0, topics)\n\terr := self.Ct.SendMessage(sub)\n\tif err == nil {\n\t\tself.SubTopics = append(self.SubTopics, topics...)\n\t}\n\treturn err\n}\n\nfunc (self *Client) Unsubscribe(topics [][]uint8) error {\n\tfor i, t := range self.SubTopics {\n\t\texist := false\n\t\tfor j, name := range topics {\n\t\t\tif string(t.Topic) == string(name) {\n\t\t\t\texist = true\n\t\t\t}\n\t\t}\n\t\tif exist {\n\t\t\tt.State = UnSubscribeNonAck\n\t\t} else {\n\t\t\t\/\/ error? or warnning\n\t\t\t\/\/ return error\n\t\t}\n\t}\n\t\/\/ id should be conidered\n\tunsub := NewUnsubscribeMessage(0, topics)\n\terr := self.Ct.SendMessage(unsub)\n\treturn err\n}\n\nfunc (self *Client) Ping() error {\n\tping := NewPingreqMessage()\n\terr := self.Ct.SendMessage(ping)\n\treturn err\n}\n\nfunc (self *Client) Disconnect() error {\n\tdc := NewDisconnectMessage()\n\terr := self.Ct.SendMessage(dc)\n\t\/\/ TODO: close connection\n\treturn err\n}\n\nfunc (self *Client) ReadLoop() error {\n\tfor {\n\t\tm, _, err := self.Ct.ReadMessageFrom()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch message := m.(type) {\n\t\tcase *ConnackMessage:\n\t\tcase *PublishMessage:\n\t\t\tif message.QoS == 3 {\n\t\t\t\t\/\/ error\n\t\t\t\t\/\/ close connection\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif message.Dup {\n\t\t\t\t\/\/ re-delivered\n\t\t\t} else if message.Dup {\n\t\t\t\t\/\/ first time delivery\n\t\t\t}\n\n\t\t\tif message.Retain {\n\t\t\t\t\/\/ retained message comes\n\t\t\t} else {\n\t\t\t\t\/\/ non retained message\n\t\t\t}\n\n\t\t\tswitch message.QoS {\n\t\t\t\/\/ in any case, Dub must be 0\n\t\t\tcase 0:\n\t\t\tcase 1:\n\t\t\t\tself.Ct.Puback(message.PacketID)\n\t\t\tcase 2:\n\t\t\t\tself.Ct.Pubrec(message.PacketID)\n\t\t\t}\n\n\t\tcase *PubackMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\tcase *PubrecMessage:\n\t\t\t\/\/ acknowledge the sent Publish packet\n\t\t\tself.Ct.Pubrel(message.PacketID)\n\t\tcase *PubrelMessage:\n\t\t\tself.Ct.Pubcomp(message.PacketID)\n\t\tcase *PubcompMessage:\n\t\t\t\/\/ acknowledge the sent Pubrel packet\n\t\tcase *SubackMessage:\n\t\t\t\/\/ acknowledge the sent subscribe packet\n\t\t\tfor i, code := range message.ReturnCodes {\n\t\t\t\t_ = self.AckSubscribeTopic(i, code)\n\t\t\t}\n\t\tcase *UnsubackMessage:\n\t\t\t\/\/ acknowledged the sent unsubscribe packet\n\t\tcase *PingrespMessage:\n\t\tdefault:\n\t\t\t\/\/ when invalid messages come\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package espsdk\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"runtime\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\nvar pool *x509.CertPool\n\n\/\/ Serializable objects can be Marshaled into JSON.\ntype Serializable interface {\n\tMarshal() ([]byte, error)\n}\n\n\/\/ Findable objects can report the URL where they can be found.\ntype Findable interface {\n\tPath() string\n}\n\n\/\/ A RESTObject has a canonical API endpoint URL and can be serialized to JSON.\ntype RESTObject interface {\n\tSerializable\n\tFindable\n}\n\n\/\/ GetClient returns a Client that can be used to send requests to the ESP API.\nfunc GetClient(key, secret, username, password, uploadBucket string) *Client {\n\tcreds := credentials{\n\t\tAPIKey:      key,\n\t\tAPISecret:   secret,\n\t\tESPUsername: username,\n\t\tESPPassword: password,\n\t}\n\ttoken := getToken(&creds)\n\treturn &Client{creds, token, uploadBucket}\n}\n\n\/\/ A Client is able to request an access token and submit HTTP requests to\n\/\/ the ESP API.\ntype Client struct {\n\tcredentials\n\tToken        Token\n\tUploadBucket string\n}\n\n\/\/ getToken submits the provided credentials to Getty's OAuth2 endpoint\n\/\/ and returns a token that can be used to authenticate HTTP requests to the\n\/\/ ESP API.\nfunc getToken(credentials *credentials) Token {\n\tif credentials.areInvalid() {\n\t\tlog.Fatal(\"Not all required credentials were supplied.\")\n\t}\n\n\turi := oauthEndpoint\n\tlog.Debugf(\"%s\", uri)\n\tformValues := formValues(credentials)\n\tlog.Debugf(\"%s\", formValues.Encode())\n\n\tresp, err := http.PostForm(uri, formValues)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tpayload, err := ioutil.ReadAll(resp.Body)\n\tlog.Debugf(\"HTTP %d\", resp.StatusCode)\n\tlog.Debugf(\"%s\", payload)\n\treturn tokenFrom(payload)\n}\n\n\/\/ GetKeywords requests suggestions from the Getty controlled vocabulary\n\/\/ for the keywords provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c *Client) GetKeywords() []byte { return c.get(Keywords) }\n\n\/\/ GetPersonalities requests suggestions from the Getty controlled vocabulary\n\/\/ for the famous personalities provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c *Client) GetPersonalities() []byte { return c.get(Personalities) }\n\n\/\/ GetControlledValues returns complete lists of values and descriptions for\n\/\/ fields with controlled vocabularies, grouped by submission type.\n\/\/\n\/\/ TODO: not implemented (needs new struct type)\nfunc (c *Client) GetControlledValues() []byte { return c.get(ControlledValues) }\n\n\/\/ GetTranscoderMappings lists acceptable transcoder mapping values\n\/\/ for Getty and iStock video.\nfunc (c *Client) GetTranscoderMappings() TranscoderMappingList {\n\treturn TranscoderMappingList{}.Unmarshal(c.get(TranscoderMappings))\n}\n\n\/\/ GetTermList lists all possible values for the given controlled vocabulary.\nfunc (c *Client) GetTermList(endpoint string) TermList {\n\treturn TermList{}.Unmarshal(c.get(endpoint))\n}\n\n\/\/ Index requests a list of all Batches owned by the user.\nfunc (c *Client) Index(path string) *DeserializedObject {\n\tvar obj *DeserializedObject\n\treturn Deserialize(c.get(path), obj)\n}\n\n\/\/ VerboseCreate uses the provided metadata to create and object\n\/\/ and returns it along with metadata about the HTTP request, including\n\/\/ response time.\nfunc (c *Client) VerboseCreate(object Findable) (Result, error) {\n\tresult, err := c.verbosePost(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.VerboseCreate: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Update changes metadata for an existing Batch.\nfunc (c *Client) Update(object RESTObject) DeserializedObject {\n\treturn Unmarshal(c.put(object))\n}\n\n\/\/ VerboseUpdate uses the provided metadata to update an object and returns\n\/\/ metadata about the HTTP request, including response time.\nfunc (c *Client) VerboseUpdate(object Findable) (Result, error) {\n\tresult, err := c.verbosePut(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.VerboseUpdate: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Delete destroys the object at the provided path.\nfunc (c *Client) Delete(path string) DeserializedObject {\n\tbytes := c._delete(path)\n\tif len(bytes) > 0 {\n\t\treturn Unmarshal(bytes)\n\t}\n\t\/\/ successful deletion usually returns a 204 without a payload\/body\n\treturn DeserializedObject{}\n}\n\n\/\/ VerboseDelete destroys the object described by the provided object,\n\/\/ as long as enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) VerboseDelete(object Findable) (Result, error) {\n\tresult, err := c.verboseDelete(object.Path())\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Errorf(\"Client.VerboseDelete: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) verboseDelete(path string) (Result, error) {\n\tresult, err := c.performRequest(newRequest(\"DELETE\", path, c.Token, nil))\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ DeleteFromObject destroys the object described by the provided object,\n\/\/ as long as enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) DeleteFromObject(object RESTObject) DeserializedObject {\n\tbytes := c._delete(object.Path())\n\tif len(bytes) > 0 {\n\t\treturn Unmarshal(bytes)\n\t}\n\t\/\/ successful deletion usually returns a 204 without a payload\/body\n\treturn DeserializedObject{}\n}\n\n\/\/ Get requests the metadata for the object at the provided path.\nfunc (c *Client) Get(path string) DeserializedObject {\n\tpc, _, _, _ := runtime.Caller(0)\n\tcallerPC, _, _, _ := runtime.Caller(1)\n\tcaller := runtime.FuncForPC(callerPC).Name()\n\tmyself := runtime.FuncForPC(pc).Name()\n\tlogPrefix := fmt.Sprintf(\"%v %v)\", caller, myself)\n\tresult, err := c.verboseGet(path)\n\tif err != nil {\n\t\tresult.Log().Error(\"Client.Get\")\n\t}\n\tlog.WithFields(result.Stats()).Info(logPrefix)\n\treturn Unmarshal(result.VerboseResult.Payload)\n}\n\n\/\/ GetFromObject requests the metadata for the provided object, as long as\n\/\/ enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) GetFromObject(object RESTObject) DeserializedObject {\n\treturn Unmarshal(c.get(object.Path()))\n}\n\n\/\/ VerboseGet uses the provided metadata to request an object from the API\n\/\/ and returns it along with metadata about the HTTP request, including\n\/\/ response time.\nfunc (c *Client) VerboseGet(object Findable) (Result, error) {\n\tresult, err := c.verboseGet(object.Path())\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Errorf(\"Client.VerboseGet: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) verboseGet(path string) (Result, error) {\n\tresult, err := c.performRequest(newRequest(\"GET\", path, c.Token, nil))\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) get(path string) []byte {\n\trequest := newRequest(\"GET\", path, c.Token, nil)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tresult.Log().Debug(\"Client.get\")\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) verbosePost(object Findable) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\n\trequest := newRequest(\"POST\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tresult.Log().Debug(\"Client.verbosePost\")\n\treturn result, nil\n}\n\nfunc (c *Client) post(object RESTObject) []byte {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trequest := newRequest(\"POST\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debug()\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) put(object RESTObject) []byte {\n\tserializedObject, err := object.Marshal()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trequest := newRequest(\"PUT\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debug()\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) verbosePut(object Findable) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.verbosePut: %v\", err)\n\t\treturn Result{}, err\n\t}\n\trequest := newRequest(\"PUT\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.verbosePut: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) _delete(path string) []byte {\n\trequest := newRequest(\"DELETE\", path, c.Token, nil)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debugf(\"response payload: %s\\n\", result.Payload)\n\treturn result.Payload\n}\n\n\/\/ insecureClient returns an HTTP client that will not verify the validity\n\/\/ of an SSL certificate when performing a request.\nfunc insecureClient() *http.Client {\n\t\/\/ pool = x509.NewCertPool()\n\t\/\/ pool.AppendCertsFromPEM(pemCerts)\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\t\/\/ RootCAs:            pool},\n\t}\n\treturn &http.Client{Transport: tr}\n}\n\n\/\/ performRequest performs a request using the given parameters and\n\/\/ returns a struct that contains the HTTP status code and payload from\n\/\/ the server's response as well as metadata such as the response time.\nfunc (c Client) performRequest(p request) (Result, error) {\n\turi := ESPAPIRoot + p.Path\n\n\tif p.requiresAnObject() && p.Object != nil {\n\t\tlog.Debugf(\"Received serialized object: %s\", p.Object)\n\t}\n\treq, err := http.NewRequest(p.Verb, uri, bytes.NewBuffer(p.Object))\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Debug(\"Client.performRequest\")\n\t\treturn Result{}, err\n\t}\n\tp.httpRequest = req\n\n\tp.addHeaders(p.Token, c.APIKey)\n\n\tresult, err := getResult(insecureClient(), req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn Result{}, err\n\t}\n\treturn Result{p, result}, nil\n}\n\nfunc tokenFrom(payload []byte) Token {\n\tvar response map[string]string\n\tjson.Unmarshal(payload, &response)\n\treturn Token(response[\"access_token\"])\n}\n<commit_msg>enable easy reversion of batch creation<commit_after>package espsdk\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"runtime\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\nvar pool *x509.CertPool\n\n\/\/ Serializable objects can be Marshaled into JSON.\ntype Serializable interface {\n\tMarshal() ([]byte, error)\n}\n\n\/\/ Findable objects can report the URL where they can be found.\ntype Findable interface {\n\tPath() string\n}\n\n\/\/ A RESTObject has a canonical API endpoint URL and can be serialized to JSON.\ntype RESTObject interface {\n\tSerializable\n\tFindable\n}\n\n\/\/ GetClient returns a Client that can be used to send requests to the ESP API.\nfunc GetClient(key, secret, username, password, uploadBucket string) *Client {\n\tcreds := credentials{\n\t\tAPIKey:      key,\n\t\tAPISecret:   secret,\n\t\tESPUsername: username,\n\t\tESPPassword: password,\n\t}\n\ttoken := getToken(&creds)\n\treturn &Client{creds, token, uploadBucket}\n}\n\n\/\/ A Client is able to request an access token and submit HTTP requests to\n\/\/ the ESP API.\ntype Client struct {\n\tcredentials\n\tToken        Token\n\tUploadBucket string\n}\n\n\/\/ getToken submits the provided credentials to Getty's OAuth2 endpoint\n\/\/ and returns a token that can be used to authenticate HTTP requests to the\n\/\/ ESP API.\nfunc getToken(credentials *credentials) Token {\n\tif credentials.areInvalid() {\n\t\tlog.Fatal(\"Not all required credentials were supplied.\")\n\t}\n\n\turi := oauthEndpoint\n\tlog.Debugf(\"%s\", uri)\n\tformValues := formValues(credentials)\n\tlog.Debugf(\"%s\", formValues.Encode())\n\n\tresp, err := http.PostForm(uri, formValues)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\n\tpayload, err := ioutil.ReadAll(resp.Body)\n\tlog.Debugf(\"HTTP %d\", resp.StatusCode)\n\tlog.Debugf(\"%s\", payload)\n\treturn tokenFrom(payload)\n}\n\n\/\/ GetKeywords requests suggestions from the Getty controlled vocabulary\n\/\/ for the keywords provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c *Client) GetKeywords() []byte { return c.get(Keywords) }\n\n\/\/ GetPersonalities requests suggestions from the Getty controlled vocabulary\n\/\/ for the famous personalities provided.\n\/\/\n\/\/ TODO: not implemented (keywords and personalities need a new struct type)\nfunc (c *Client) GetPersonalities() []byte { return c.get(Personalities) }\n\n\/\/ GetControlledValues returns complete lists of values and descriptions for\n\/\/ fields with controlled vocabularies, grouped by submission type.\n\/\/\n\/\/ TODO: not implemented (needs new struct type)\nfunc (c *Client) GetControlledValues() []byte { return c.get(ControlledValues) }\n\n\/\/ GetTranscoderMappings lists acceptable transcoder mapping values\n\/\/ for Getty and iStock video.\nfunc (c *Client) GetTranscoderMappings() TranscoderMappingList {\n\treturn TranscoderMappingList{}.Unmarshal(c.get(TranscoderMappings))\n}\n\n\/\/ GetTermList lists all possible values for the given controlled vocabulary.\nfunc (c *Client) GetTermList(endpoint string) TermList {\n\treturn TermList{}.Unmarshal(c.get(endpoint))\n}\n\n\/\/ DeleteLastBatch looks up the newest Batch and deletes it.\nfunc (c *Client) DeleteLastBatch() (Result, error) {\n\tlastBatch := c.Index(Batches).Last()\n\treturn c.verboseDelete(lastBatch.Path())\n\n}\n\n\/\/ Index requests a list of all Batches owned by the user.\nfunc (c *Client) Index(path string) *DeserializedObject {\n\tvar obj *DeserializedObject\n\treturn Deserialize(c.get(path), obj)\n}\n\n\/\/ VerboseCreate uses the provided metadata to create and object\n\/\/ and returns it along with metadata about the HTTP request, including\n\/\/ response time.\nfunc (c *Client) VerboseCreate(object Findable) (Result, error) {\n\tresult, err := c.verbosePost(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.VerboseCreate: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Update changes metadata for an existing Batch.\nfunc (c *Client) Update(object RESTObject) DeserializedObject {\n\treturn Unmarshal(c.put(object))\n}\n\n\/\/ VerboseUpdate uses the provided metadata to update an object and returns\n\/\/ metadata about the HTTP request, including response time.\nfunc (c *Client) VerboseUpdate(object Findable) (Result, error) {\n\tresult, err := c.verbosePut(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.VerboseUpdate: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Delete destroys the object at the provided path.\nfunc (c *Client) Delete(path string) DeserializedObject {\n\tbytes := c._delete(path)\n\tif len(bytes) > 0 {\n\t\treturn Unmarshal(bytes)\n\t}\n\t\/\/ successful deletion usually returns a 204 without a payload\/body\n\treturn DeserializedObject{}\n}\n\n\/\/ VerboseDelete destroys the object described by the provided object,\n\/\/ as long as enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) VerboseDelete(object Findable) (Result, error) {\n\tresult, err := c.verboseDelete(object.Path())\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Errorf(\"Client.VerboseDelete: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) verboseDelete(path string) (Result, error) {\n\tresult, err := c.performRequest(newRequest(\"DELETE\", path, c.Token, nil))\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\n\/\/ DeleteFromObject destroys the object described by the provided object,\n\/\/ as long as enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) DeleteFromObject(object RESTObject) DeserializedObject {\n\tbytes := c._delete(object.Path())\n\tif len(bytes) > 0 {\n\t\treturn Unmarshal(bytes)\n\t}\n\t\/\/ successful deletion usually returns a 204 without a payload\/body\n\treturn DeserializedObject{}\n}\n\n\/\/ Get requests the metadata for the object at the provided path.\nfunc (c *Client) Get(path string) DeserializedObject {\n\tpc, _, _, _ := runtime.Caller(0)\n\tcallerPC, _, _, _ := runtime.Caller(1)\n\tcaller := runtime.FuncForPC(callerPC).Name()\n\tmyself := runtime.FuncForPC(pc).Name()\n\tlogPrefix := fmt.Sprintf(\"%v %v)\", caller, myself)\n\tresult, err := c.verboseGet(path)\n\tif err != nil {\n\t\tresult.Log().Error(\"Client.Get\")\n\t}\n\tlog.WithFields(result.Stats()).Info(logPrefix)\n\treturn Unmarshal(result.VerboseResult.Payload)\n}\n\n\/\/ GetFromObject requests the metadata for the provided object, as long as\n\/\/ enough data is provided to unambiguously identify it to the API.\nfunc (c *Client) GetFromObject(object RESTObject) DeserializedObject {\n\treturn Unmarshal(c.get(object.Path()))\n}\n\n\/\/ VerboseGet uses the provided metadata to request an object from the API\n\/\/ and returns it along with metadata about the HTTP request, including\n\/\/ response time.\nfunc (c *Client) VerboseGet(object Findable) (Result, error) {\n\tresult, err := c.verboseGet(object.Path())\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Errorf(\"Client.VerboseGet: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) verboseGet(path string) (Result, error) {\n\tresult, err := c.performRequest(newRequest(\"GET\", path, c.Token, nil))\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) get(path string) []byte {\n\trequest := newRequest(\"GET\", path, c.Token, nil)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tresult.Log().Debug(\"Client.get\")\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) verbosePost(object Findable) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\n\trequest := newRequest(\"POST\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\treturn Result{}, err\n\t}\n\tresult.Log().Debug(\"Client.verbosePost\")\n\treturn result, nil\n}\n\nfunc (c *Client) post(object RESTObject) []byte {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trequest := newRequest(\"POST\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debug()\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) put(object RESTObject) []byte {\n\tserializedObject, err := object.Marshal()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trequest := newRequest(\"PUT\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debug()\n\tlog.Debugf(\"%s\\n\", result.Payload)\n\treturn result.Payload\n}\n\nfunc (c *Client) verbosePut(object Findable) (Result, error) {\n\tserializedObject, err := Marshal(object)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.verbosePut: %v\", err)\n\t\treturn Result{}, err\n\t}\n\trequest := newRequest(\"PUT\", object.Path(), c.Token, serializedObject)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Errorf(\"Client.verbosePut: %v\", err)\n\t\treturn Result{}, err\n\t}\n\treturn result, nil\n}\n\nfunc (c *Client) _delete(path string) []byte {\n\trequest := newRequest(\"DELETE\", path, c.Token, nil)\n\tresult, err := c.performRequest(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tresult.Log().Debugf(\"response payload: %s\\n\", result.Payload)\n\treturn result.Payload\n}\n\n\/\/ insecureClient returns an HTTP client that will not verify the validity\n\/\/ of an SSL certificate when performing a request.\nfunc insecureClient() *http.Client {\n\t\/\/ pool = x509.NewCertPool()\n\t\/\/ pool.AppendCertsFromPEM(pemCerts)\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t},\n\t\t\/\/ RootCAs:            pool},\n\t}\n\treturn &http.Client{Transport: tr}\n}\n\n\/\/ performRequest performs a request using the given parameters and\n\/\/ returns a struct that contains the HTTP status code and payload from\n\/\/ the server's response as well as metadata such as the response time.\nfunc (c Client) performRequest(p request) (Result, error) {\n\turi := ESPAPIRoot + p.Path\n\n\tif p.requiresAnObject() && p.Object != nil {\n\t\tlog.Debugf(\"Received serialized object: %s\", p.Object)\n\t}\n\treq, err := http.NewRequest(p.Verb, uri, bytes.NewBuffer(p.Object))\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err,\n\t\t}).Debug(\"Client.performRequest\")\n\t\treturn Result{}, err\n\t}\n\tp.httpRequest = req\n\n\tp.addHeaders(p.Token, c.APIKey)\n\n\tresult, err := getResult(insecureClient(), req)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn Result{}, err\n\t}\n\treturn Result{p, result}, nil\n}\n\nfunc tokenFrom(payload []byte) Token {\n\tvar response map[string]string\n\tjson.Unmarshal(payload, &response)\n\treturn Token(response[\"access_token\"])\n}\n<|endoftext|>"}
{"text":"<commit_before>package paranoidhttp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ DefaultClient is the default Client whose setting is the same as http.DefaultClient.\nvar DefaultClient *http.Client\n\nvar (\n\tnetPrivateClassA *net.IPNet\n\tnetPrivateClassB *net.IPNet\n\tnetPrivateClassC *net.IPNet\n\tnetTestNet       *net.IPNet\n\tnet6To4Relay     *net.IPNet\n)\n\nfunc init() {\n\tvar err error\n\t_, netPrivateClassA, err = net.ParseCIDR(\"10.0.0.0\/8\")\n\tif err != nil {\n\t\tlog.Fatalf(\"10.0.0.0\/8 must be parsed\")\n\t}\n\t_, netPrivateClassB, err = net.ParseCIDR(\"172.16.0.0\/12\")\n\tif err != nil {\n\t\tlog.Fatalf(\"172.16.0.0\/12 must be parsed\")\n\t}\n\t_, netPrivateClassC, err = net.ParseCIDR(\"192.168.0.0\/16\")\n\tif err != nil {\n\t\tlog.Fatalf(\"192.168.0.0\/16 must be parsed\")\n\t}\n\t_, netTestNet, err = net.ParseCIDR(\"192.0.2.0\/24\")\n\tif err != nil {\n\t\tlog.Fatalf(\"192.0.2.0\/24 must be parsed\")\n\t}\n\t_, net6To4Relay, err = net.ParseCIDR(\"192.88.99.0\/24\")\n\tif err != nil {\n\t\tlog.Fatalf(\"192.88.99.0\/24 must be parsed\")\n\t}\n\n\tDefaultClient, _, _ = NewClient()\n}\n\nfunc safeAddr(hostport string) (string, error) {\n\thost, port, err := net.SplitHostPort(hostport)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip != nil {\n\t\tif ip.To4() != nil && isBadIPv4(ip) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t\treturn net.JoinHostPort(ip.String(), port), nil\n\t}\n\n\tif isBadHost(host) {\n\t\treturn \"\", fmt.Errorf(\"bad host is detected: %v\", host)\n\t}\n\n\tips, err := net.LookupIP(host) \/\/ TODO timeout\n\tif err != nil || len(ips) <= 0 {\n\t\treturn \"\", err\n\t}\n\tfor _, ip := range ips {\n\t\tif ip.To4() != nil && isBadIPv4(ip) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t}\n\treturn net.JoinHostPort(ips[0].String(), port), nil\n}\n\n\/\/ NewDialer returns a dialer function which only allows IPv4 connections.\n\/\/\n\/\/ This is used to create a new paranoid http.Client,\n\/\/ because I'm not sure about a paranoid behavior for IPv6 connections :(\nfunc NewDialer(dialer *net.Dialer) func(network, addr string) (net.Conn, error) {\n\treturn func(network, hostport string) (net.Conn, error) {\n\t\tswitch network {\n\t\tcase \"tcp\", \"tcp4\":\n\t\t\taddr, err := safeAddr(hostport)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn dialer.Dial(\"tcp4\", addr)\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"does not support any networks except tcp4\")\n\t\t}\n\t}\n}\n\n\/\/ NewClient returns a new http.Client configured to be paranoid for attackers.\n\/\/\n\/\/ This also returns http.Tranport and net.Dialer so that you can customize those behavior.\nfunc NewClient() (*http.Client, *http.Transport, *net.Dialer) {\n\tdialer := &net.Dialer{\n\t\tTimeout:   30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\ttransport := &http.Transport{\n\t\tProxy:               http.ProxyFromEnvironment,\n\t\tDial:                NewDialer(dialer),\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\treturn &http.Client{\n\t\tTimeout:   30 * time.Second,\n\t\tTransport: transport,\n\t}, transport, dialer\n}\n\nvar regLocalhost = regexp.MustCompile(\"(?i)^localhost$\")\nvar regHasSpace = regexp.MustCompile(\"(?i)\\\\s+\")\n\nfunc isBadHost(host string) bool {\n\tif regLocalhost.MatchString(host) {\n\t\treturn true\n\t}\n\tif regHasSpace.MatchString(host) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isBadIPv4(ip net.IP) bool {\n\tif ip.To4() == nil {\n\t\tpanic(\"cannot be called for IPv6\")\n\t}\n\n\tif ip.Equal(net.IPv4bcast) || !ip.IsGlobalUnicast() ||\n\t\tnetPrivateClassA.Contains(ip) || netPrivateClassB.Contains(ip) || netPrivateClassC.Contains(ip) ||\n\t\tnetTestNet.Contains(ip) || net6To4Relay.Contains(ip) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<commit_msg>define mustParseCIDR and refactor<commit_after>package paranoidhttp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ DefaultClient is the default Client whose setting is the same as http.DefaultClient.\nvar DefaultClient *http.Client\n\nfunc mustParseCIDR(addr string) *net.IPNet {\n\t_, ipnet, err := net.ParseCIDR(addr)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s must be parsed\", addr)\n\t}\n\treturn ipnet\n}\n\nvar (\n\tnetPrivateClassA = mustParseCIDR(\"10.0.0.0\/8\")\n\tnetPrivateClassB = mustParseCIDR(\"172.16.0.0\/12\")\n\tnetPrivateClassC = mustParseCIDR(\"192.168.0.0\/16\")\n\tnetTestNet       = mustParseCIDR(\"192.0.2.0\/24\")\n\tnet6To4Relay     = mustParseCIDR(\"192.88.99.0\/24\")\n)\n\nfunc init() {\n\tDefaultClient, _, _ = NewClient()\n}\n\nfunc safeAddr(hostport string) (string, error) {\n\thost, port, err := net.SplitHostPort(hostport)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tip := net.ParseIP(host)\n\tif ip != nil {\n\t\tif ip.To4() != nil && isBadIPv4(ip) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t\treturn net.JoinHostPort(ip.String(), port), nil\n\t}\n\n\tif isBadHost(host) {\n\t\treturn \"\", fmt.Errorf(\"bad host is detected: %v\", host)\n\t}\n\n\tips, err := net.LookupIP(host) \/\/ TODO timeout\n\tif err != nil || len(ips) <= 0 {\n\t\treturn \"\", err\n\t}\n\tfor _, ip := range ips {\n\t\tif ip.To4() != nil && isBadIPv4(ip) {\n\t\t\treturn \"\", fmt.Errorf(\"bad ip is detected: %v\", ip)\n\t\t}\n\t}\n\treturn net.JoinHostPort(ips[0].String(), port), nil\n}\n\n\/\/ NewDialer returns a dialer function which only allows IPv4 connections.\n\/\/\n\/\/ This is used to create a new paranoid http.Client,\n\/\/ because I'm not sure about a paranoid behavior for IPv6 connections :(\nfunc NewDialer(dialer *net.Dialer) func(network, addr string) (net.Conn, error) {\n\treturn func(network, hostport string) (net.Conn, error) {\n\t\tswitch network {\n\t\tcase \"tcp\", \"tcp4\":\n\t\t\taddr, err := safeAddr(hostport)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn dialer.Dial(\"tcp4\", addr)\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"does not support any networks except tcp4\")\n\t\t}\n\t}\n}\n\n\/\/ NewClient returns a new http.Client configured to be paranoid for attackers.\n\/\/\n\/\/ This also returns http.Tranport and net.Dialer so that you can customize those behavior.\nfunc NewClient() (*http.Client, *http.Transport, *net.Dialer) {\n\tdialer := &net.Dialer{\n\t\tTimeout:   30 * time.Second,\n\t\tKeepAlive: 30 * time.Second,\n\t}\n\ttransport := &http.Transport{\n\t\tProxy:               http.ProxyFromEnvironment,\n\t\tDial:                NewDialer(dialer),\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\treturn &http.Client{\n\t\tTimeout:   30 * time.Second,\n\t\tTransport: transport,\n\t}, transport, dialer\n}\n\nvar regLocalhost = regexp.MustCompile(\"(?i)^localhost$\")\nvar regHasSpace = regexp.MustCompile(\"(?i)\\\\s+\")\n\nfunc isBadHost(host string) bool {\n\tif regLocalhost.MatchString(host) {\n\t\treturn true\n\t}\n\tif regHasSpace.MatchString(host) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isBadIPv4(ip net.IP) bool {\n\tif ip.To4() == nil {\n\t\tpanic(\"cannot be called for IPv6\")\n\t}\n\n\tif ip.Equal(net.IPv4bcast) || !ip.IsGlobalUnicast() ||\n\t\tnetPrivateClassA.Contains(ip) || netPrivateClassB.Contains(ip) || netPrivateClassC.Contains(ip) ||\n\t\tnetTestNet.Contains(ip) || net6To4Relay.Contains(ip) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package prisclient\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/priscillachat\/prislog\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype Client struct {\n\traw      net.Conn\n\tdecoder  *json.Decoder\n\tencoder  *json.Encoder\n\tSourceId string\n\tType     string\n\tLogger   *prislog.PrisLog\n}\n\ntype CommandBlock struct {\n\tId      string   `json:\"id,omitempty\"`\n\tAction  string   `json:\"action,omitempty\"`\n\tType    string   `json:\"type,omitempty\"`\n\tTime    int64    `json:\"time,omitempty\"`\n\tData    string   `json:\"data,omitempty\"`\n\tArray   []string `json:\"array,omitempty\"`\n\tOptions []string `json:\"options,omitempty\"`\n}\n\ntype MessageBlock struct {\n\tMessage       string   `json:\"message,omitempty\"`\n\tFrom          string   `json:\"from,omitempty\"`\n\tRoom          string   `json:\"room,omitempty\"`\n\tMentioned     bool     `json:\"mentioned,omitempty\"`\n\tStripped      string   `json:\"stripped,omitempty\"`\n\tMentionNotify []string `json:\"mentionnotify,omitempty\"`\n}\n\ntype Query struct {\n\tType    string        `json:\"type,omitempty\"`\n\tSource  string        `json:\"source,omitempty\"`\n\tTo      string        `json:\"to,omitempty\"`\n\tCommand *CommandBlock `json:\"command,omitempty\"`\n\tMessage *MessageBlock `json:\"message,omitempty\"`\n}\n\nfunc RandomId() string {\n\tb := make([]byte, 8)\n\tio.ReadFull(rand.Reader, b)\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc NewClient(host, port, clientType, sourceid string,\n\tlogger *prislog.PrisLog) (*Client, error) {\n\n\tif clientType != \"adapter\" && clientType != \"responder\" {\n\t\treturn nil, errors.New(\"client type has to be adapter or responder\")\n\t}\n\n\tpris := new(Client)\n\n\tpris.Logger = logger\n\tpris.SourceId = sourceid\n\tpris.Type = clientType\n\n\tconn, err := net.Dial(\"tcp\", host+\":\"+port)\n\n\tif err != nil {\n\t\treturn pris, err\n\t}\n\n\tpris.raw = conn\n\tpris.decoder = json.NewDecoder(pris.raw)\n\tpris.encoder = json.NewEncoder(pris.raw)\n\n\treturn pris, nil\n}\n\nfunc (pris *Client) Engage() error {\n\tq := Query{\n\t\tType:   \"command\",\n\t\tSource: pris.SourceId,\n\t\tCommand: &CommandBlock{\n\t\t\tId:     RandomId(),\n\t\t\tAction: \"engage\",\n\t\t\tType:   pris.Type,\n\t\t\tTime:   time.Now().Unix(),\n\t\t},\n\t}\n\n\treturn pris.encoder.Encode(&q)\n}\n\nfunc (pris *Client) listen(out chan<- *Query) {\n\tvar q *Query\n\tfor {\n\t\tq = new(Query)\n\t\terr := pris.decoder.Decode(q)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tout <- &Query{\n\t\t\t\t\tType:   \"command\",\n\t\t\t\t\tSource: \"pris\",\n\t\t\t\t\tCommand: &CommandBlock{\n\t\t\t\t\t\tAction: \"disengage\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.Logger.Debug.Println(\"Query received:\", *q)\n\t\t\tif q.Type == \"message\" {\n\t\t\t\tpris.Logger.Debug.Println(\"Message:\", q.Message.Message)\n\t\t\t\tpris.Logger.Debug.Println(\"From:\", q.Message.From)\n\t\t\t\tpris.Logger.Debug.Println(\"Room:\", q.Message.Room)\n\t\t\t}\n\t\t\tout <- q\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query from server(?!!):\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) Run(toPris <-chan *Query, fromPris chan<- *Query) {\n\n\tgo pris.listen(fromPris)\n\tvar q *Query\n\tfor {\n\t\tq = <-toPris\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.encoder.Encode(q)\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query:\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) ValidateQuery(q *Query) bool {\n\tswitch {\n\tcase q.Type == \"command\" && q.Command != nil:\n\t\treturn true\n\tcase q.Type == \"message\" && q.Message != nil && q.Message.Room != \"\":\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>auto reconnect option<commit_after>package prisclient\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/priscillachat\/prislog\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype Client struct {\n\traw        net.Conn\n\tdecoder    *json.Decoder\n\tencoder    *json.Encoder\n\tSourceId   string\n\tclientType string\n\tlogger     *prislog.PrisLog\n\tautoRetry  bool\n\thost       string\n\tport       string\n}\n\ntype CommandBlock struct {\n\tId      string   `json:\"id,omitempty\"`\n\tAction  string   `json:\"action,omitempty\"`\n\tType    string   `json:\"type,omitempty\"`\n\tTime    int64    `json:\"time,omitempty\"`\n\tData    string   `json:\"data,omitempty\"`\n\tArray   []string `json:\"array,omitempty\"`\n\tOptions []string `json:\"options,omitempty\"`\n}\n\ntype MessageBlock struct {\n\tMessage       string   `json:\"message,omitempty\"`\n\tFrom          string   `json:\"from,omitempty\"`\n\tRoom          string   `json:\"room,omitempty\"`\n\tMentioned     bool     `json:\"mentioned,omitempty\"`\n\tStripped      string   `json:\"stripped,omitempty\"`\n\tMentionNotify []string `json:\"mentionnotify,omitempty\"`\n}\n\ntype Query struct {\n\tType    string        `json:\"type,omitempty\"`\n\tSource  string        `json:\"source,omitempty\"`\n\tTo      string        `json:\"to,omitempty\"`\n\tCommand *CommandBlock `json:\"command,omitempty\"`\n\tMessage *MessageBlock `json:\"message,omitempty\"`\n}\n\nfunc RandomId() string {\n\tb := make([]byte, 8)\n\tio.ReadFull(rand.Reader, b)\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc NewClient(host, port, clientType, sourceid string, autoretry bool,\n\tlogger *prislog.PrisLog) (*Client, error) {\n\n\tif clientType != \"adapter\" && clientType != \"responder\" {\n\t\treturn nil, errors.New(\"client type has to be adapter or responder\")\n\t}\n\n\tpris := new(Client)\n\n\tpris.logger = logger\n\tpris.SourceId = sourceid\n\tpris.clientType = clientType\n\tpris.autoRetry = autoretry\n\tpris.host = host\n\tpris.port = port\n\n\tpris.connect()\n\n\treturn pris, nil\n}\n\nfunc (pris *Client) connect() error {\n\tconn, err := net.Dial(\"tcp\", pris.host+\":\"+pris.port)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpris.raw = conn\n\tpris.decoder = json.NewDecoder(pris.raw)\n\tpris.encoder = json.NewEncoder(pris.raw)\n\n\terr = pris.Engage()\n\n\tif err != nil {\n\t\tpris.logger.Error.Println(\"Failed to engage:\", err)\n\t\treturn err\n\t}\n\n\tpris.logger.Info.Println(\"Priscilla engaged\")\n\n\treturn nil\n}\n\nfunc (pris *Client) Engage() error {\n\tq := Query{\n\t\tType:   \"command\",\n\t\tSource: pris.SourceId,\n\t\tCommand: &CommandBlock{\n\t\t\tId:     RandomId(),\n\t\t\tAction: \"engage\",\n\t\t\tType:   pris.clientType,\n\t\t\tTime:   time.Now().Unix(),\n\t\t},\n\t}\n\n\treturn pris.encoder.Encode(&q)\n}\n\nfunc (pris *Client) listen(out chan<- *Query) {\n\tvar q *Query\n\tfor {\n\t\tq = new(Query)\n\t\terr := pris.decoder.Decode(q)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tpris.logger.Error.Println(\"Priscilla disconnected\")\n\t\t\t\tif pris.autoRetry {\n\t\t\t\t\tpris.logger.Error.Println(\"Auto reconnect in 5 seconds...\")\n\t\t\t\t\ttime.Sleep(5 * time.Second)\n\t\t\t\t\terr := pris.connect()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpris.logger.Error.Println(\"Connect error:\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tout <- &Query{\n\t\t\t\t\t\tType:   \"command\",\n\t\t\t\t\t\tSource: \"pris\",\n\t\t\t\t\t\tCommand: &CommandBlock{\n\t\t\t\t\t\t\tAction: \"disengage\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.logger.Debug.Println(\"Query received:\", *q)\n\t\t\tif q.Type == \"message\" {\n\t\t\t\tpris.logger.Debug.Println(\"Message:\", q.Message.Message)\n\t\t\t\tpris.logger.Debug.Println(\"From:\", q.Message.From)\n\t\t\t\tpris.logger.Debug.Println(\"Room:\", q.Message.Room)\n\t\t\t}\n\t\t\tout <- q\n\t\t} else {\n\t\t\tpris.logger.Error.Println(\"Invalid query from server(?!!):\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) Run(toPris <-chan *Query, fromPris chan<- *Query) {\n\n\tgo pris.listen(fromPris)\n\tvar q *Query\n\tfor {\n\t\tq = <-toPris\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.encoder.Encode(q)\n\t\t} else {\n\t\t\tpris.logger.Error.Println(\"Invalid query:\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) ValidateQuery(q *Query) bool {\n\tswitch {\n\tcase q.Type == \"command\" && q.Command != nil:\n\t\treturn true\n\tcase q.Type == \"message\" && q.Message != nil && q.Message.Room != \"\":\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package gapi\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype Client struct {\n\tkey     string\n\tbaseURL url.URL\n\t*http.Client\n}\n\n\/\/New creates a new grafana client\n\/\/auth can be in user:pass format, or it can be an api key\nfunc New(auth, baseURL string) (*Client, error) {\n\tu, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := \"\"\n\tif strings.Contains(auth, \":\") {\n\t\tsplit := strings.Split(auth, \":\")\n\t\tu.User = url.UserPassword(split[0], split[1])\n\t} else {\n\t\tkey = fmt.Sprintf(\"Bearer %s\", auth)\n\t}\n\treturn &Client{\n\t\tkey,\n\t\t*u,\n\t\t&http.Client{},\n\t}, nil\n}\n\nfunc (c *Client) newRequest(method, requestPath string, query url.Values, body io.Reader) (*http.Request, error) {\n\turl := c.baseURL\n\turl.Path = path.Join(url.Path, requestPath)\n\turl.RawQuery = query.Encode()\n\treq, err := http.NewRequest(method, url.String(), body)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\tif c.key != \"\" {\n\t\treq.Header.Add(\"Authorization\", c.key)\n\t}\n\n\tif os.Getenv(\"GF_LOG\") != \"\" {\n\t\tif body == nil {\n\t\t\tlog.Println(\"request to \", url.String(), \"with no body data\")\n\t\t} else {\n\t\t\tlog.Println(\"request to \", url.String(), \"with body data\", body.(*bytes.Buffer).String())\n\t\t}\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treturn req, err\n}\n<commit_msg>include method in debug output<commit_after>package gapi\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype Client struct {\n\tkey     string\n\tbaseURL url.URL\n\t*http.Client\n}\n\n\/\/New creates a new grafana client\n\/\/auth can be in user:pass format, or it can be an api key\nfunc New(auth, baseURL string) (*Client, error) {\n\tu, err := url.Parse(baseURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey := \"\"\n\tif strings.Contains(auth, \":\") {\n\t\tsplit := strings.Split(auth, \":\")\n\t\tu.User = url.UserPassword(split[0], split[1])\n\t} else {\n\t\tkey = fmt.Sprintf(\"Bearer %s\", auth)\n\t}\n\treturn &Client{\n\t\tkey,\n\t\t*u,\n\t\t&http.Client{},\n\t}, nil\n}\n\nfunc (c *Client) newRequest(method, requestPath string, query url.Values, body io.Reader) (*http.Request, error) {\n\turl := c.baseURL\n\turl.Path = path.Join(url.Path, requestPath)\n\turl.RawQuery = query.Encode()\n\treq, err := http.NewRequest(method, url.String(), body)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\tif c.key != \"\" {\n\t\treq.Header.Add(\"Authorization\", c.key)\n\t}\n\n\tif os.Getenv(\"GF_LOG\") != \"\" {\n\t\tif body == nil {\n\t\t\tlog.Printf(\"request (%s) to %s with no body data\", method, url.String())\n\t\t} else {\n\t\t\tlog.Printf(\"request (%s) to %s with body data: %s\", method, url.String(), body.(*bytes.Buffer).String())\n\t\t}\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treturn req, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package fs\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\t\/\/ErrSrcNotExist src file doesnt exist\n\tErrSrcNotExist = errors.New(\"Source file does not exist\")\n\n\t\/\/ErrSrcNotRegularFile src file is not a regular file\n\tErrSrcNotRegularFile = errors.New(\"Source file is not a regular file\")\n\n\t\/\/ErrDstNotRegularFile dst file is not a regular file\n\tErrDstNotRegularFile = errors.New(\"Destination file is not a regular file\")\n)\n\n\/\/Fs is a static class that provides Filesystem type functions\ntype Fs struct{}\n\n\/\/NewFs generates a Fs object\nfunc NewFs() *Fs {\n\tmyFs := &Fs{}\n\treturn myFs\n}\n\n\/\/DoesFileExist just like it sounds\nfunc (fs *Fs) DoesFileExist(fullpath string) bool {\n\tlog.Debugln(\"DoesFileExist ENTER\")\n\tlog.Debugln(\"fullpath:\", fullpath)\n\n\tsfi, err := os.Stat(fullpath)\n\tif !os.IsNotExist(err) {\n\t\tlog.Debugln(\"Src Stat Failed:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn false\n\t}\n\tif !sfi.Mode().IsRegular() {\n\t\t\/\/cannot use non-regular files (e.g., directories, symlinks, devices, etc.)\n\t\tlog.Debugln(\"Src file is not regular\")\n\t\tlog.Debugln(\"DoesFileExist LEAVE\")\n\t\treturn false\n\t}\n\n\tlog.Debugln(\"File exists\")\n\tlog.Debugln(\"DoesFileExist LEAVE\")\n\treturn true\n}\n\n\/\/GetFullExePath returns the fullpath of the executable including the executable\n\/\/name itself\nfunc (fs *Fs) GetFullExePath() (string, error) {\n\tpath, err := os.Readlink(\"\/proc\/self\/exe\")\n\tif err != nil {\n\t\tlog.Errorln(\"Readlink failed:\", err)\n\t\treturn \"\", nil\n\t}\n\tlog.Debugln(\"EXE path:\", path)\n\treturn path, nil\n}\n\n\/\/GetPathFileFullFilename returns the parent folder name\nfunc (fs *Fs) GetPathFileFullFilename(path string) string {\n\tlog.Debugln(\"GetPathFileFullFilename ENTER\")\n\tlog.Debugln(\"path:\", path)\n\tlast := strings.LastIndex(path, string(filepath.Separator))\n\tif last == -1 {\n\t\tlog.Debugln(\"No slash. Return Path:\", path)\n\t\tlog.Debugln(\"GetPathFileFullFilename LEAVE\")\n\t\treturn path\n\t}\n\ttmp := path[0:last]\n\tlog.Debugln(\"Final Path:\", tmp)\n\tlog.Debugln(\"GetPathFileFullFilename LEAVE\")\n\treturn tmp\n}\n\n\/\/GetFullPath returns the fullpath of the executable without the executable name\nfunc (fs *Fs) GetFullPath() (string, error) {\n\tpath, err := os.Readlink(\"\/proc\/self\/exe\")\n\tif err != nil {\n\t\tlog.Errorln(\"Readlink failed:\", err)\n\t\treturn \"\", nil\n\t}\n\tlog.Debugln(\"EXE path:\", path)\n\n\ttmp := fs.GetPathFileFullFilename(path)\n\treturn tmp, nil\n}\n\n\/\/GetFilenameFromURIOrFullPath retrieves the filename from an URI\nfunc (fs *Fs) GetFilenameFromURIOrFullPath(path string) string {\n\tlog.Debugln(\"GetFilenameFromURI ENTER\")\n\tlog.Debugln(\"path:\", path)\n\n\tlast := strings.LastIndex(path, string(filepath.Separator))\n\tif last == -1 {\n\t\tlog.Debugln(\"No slash. Return Path:\", path)\n\t\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\t\treturn path\n\t}\n\tpathTmp := path[last+1:]\n\tlog.Debugln(\"Return Path:\", pathTmp)\n\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\n\treturn pathTmp\n}\n\n\/\/AppendSlash appends a slash to a path if one is needed\nfunc (fs *Fs) AppendSlash(path string) string {\n\tlog.Debugln(\"AppendSlash ENTER\")\n\tlog.Debugln(\"path:\", path)\n\tif path[len(path)-1] != filepath.Separator {\n\t\tpath += string(filepath.Separator)\n\t}\n\tlog.Debugln(\"Return Path:\", path)\n\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\treturn path\n}\n\n\/\/FileCopy copies the contents of the src file to the dst file\nfunc (fs *Fs) FileCopy(src string, dst string) error {\n\tlog.Debugln(\"FileCopy ENTER\")\n\tlog.Debugln(\"SRC:\", src)\n\tlog.Debugln(\"DST:\", dst)\n\n\tsfi, err := os.Stat(src)\n\tif err != nil {\n\t\tlog.Debugln(\"Src Stat Failed:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn ErrSrcNotExist\n\t}\n\tif !sfi.Mode().IsRegular() {\n\t\t\/\/cannot copy non-regular files (e.g., directories, symlinks, devices, etc.)\n\t\tlog.Debugln(\"Src file is not regular\")\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn ErrSrcNotRegularFile\n\t}\n\tdfi, err := os.Stat(dst)\n\tif err == nil {\n\t\tif !(dfi.Mode().IsRegular()) {\n\t\t\tlog.Debugln(\"Dst file is not regular\")\n\t\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\t\treturn ErrDstNotRegularFile\n\t\t}\n\t\tif os.SameFile(sfi, dfi) {\n\t\t\tlog.Debugln(\"Src and Dst files are the same\")\n\t\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/Copy the file\n\tin, err := os.OpenFile(src, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to open SRC file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\tdefer in.Close()\n\tout, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to open DST file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tif _, err = io.Copy(out, in); err != nil {\n\t\tlog.Debugln(\"Failed to copy file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to flush file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\n\tlog.Debugln(\"File copy succeeded\")\n\tlog.Debugln(\"FileCopy LEAVE\")\n\treturn nil\n}\n<commit_msg>File exists<commit_after>package fs\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\t\/\/ErrSrcNotExist src file doesnt exist\n\tErrSrcNotExist = errors.New(\"Source file does not exist\")\n\n\t\/\/ErrSrcNotRegularFile src file is not a regular file\n\tErrSrcNotRegularFile = errors.New(\"Source file is not a regular file\")\n\n\t\/\/ErrDstNotRegularFile dst file is not a regular file\n\tErrDstNotRegularFile = errors.New(\"Destination file is not a regular file\")\n)\n\n\/\/Fs is a static class that provides Filesystem type functions\ntype Fs struct{}\n\n\/\/NewFs generates a Fs object\nfunc NewFs() *Fs {\n\tmyFs := &Fs{}\n\treturn myFs\n}\n\n\/\/DoesFileExist just like it sounds\nfunc (fs *Fs) DoesFileExist(fullpath string) bool {\n\tlog.Debugln(\"DoesFileExist ENTER\")\n\tlog.Debugln(\"fullpath:\", fullpath)\n\n\tif _, err := os.Stat(fullpath); !os.IsNotExist(err) {\n\t\tlog.Debugln(fullpath, \"does exists\")\n\t\tlog.Debugln(\"DoesFileExist LEAVE\")\n\t\treturn true\n\t}\n\n\tlog.Debugln(fullpath, \"does not exists\")\n\tlog.Debugln(\"DoesFileExist LEAVE\")\n\treturn false\n}\n\n\/\/GetFullExePath returns the fullpath of the executable including the executable\n\/\/name itself\nfunc (fs *Fs) GetFullExePath() (string, error) {\n\tpath, err := os.Readlink(\"\/proc\/self\/exe\")\n\tif err != nil {\n\t\tlog.Errorln(\"Readlink failed:\", err)\n\t\treturn \"\", nil\n\t}\n\tlog.Debugln(\"EXE path:\", path)\n\treturn path, nil\n}\n\n\/\/GetPathFileFullFilename returns the parent folder name\nfunc (fs *Fs) GetPathFileFullFilename(path string) string {\n\tlog.Debugln(\"GetPathFileFullFilename ENTER\")\n\tlog.Debugln(\"path:\", path)\n\tlast := strings.LastIndex(path, string(filepath.Separator))\n\tif last == -1 {\n\t\tlog.Debugln(\"No slash. Return Path:\", path)\n\t\tlog.Debugln(\"GetPathFileFullFilename LEAVE\")\n\t\treturn path\n\t}\n\ttmp := path[0:last]\n\tlog.Debugln(\"Final Path:\", tmp)\n\tlog.Debugln(\"GetPathFileFullFilename LEAVE\")\n\treturn tmp\n}\n\n\/\/GetFullPath returns the fullpath of the executable without the executable name\nfunc (fs *Fs) GetFullPath() (string, error) {\n\tpath, err := os.Readlink(\"\/proc\/self\/exe\")\n\tif err != nil {\n\t\tlog.Errorln(\"Readlink failed:\", err)\n\t\treturn \"\", nil\n\t}\n\tlog.Debugln(\"EXE path:\", path)\n\n\ttmp := fs.GetPathFileFullFilename(path)\n\treturn tmp, nil\n}\n\n\/\/GetFilenameFromURIOrFullPath retrieves the filename from an URI\nfunc (fs *Fs) GetFilenameFromURIOrFullPath(path string) string {\n\tlog.Debugln(\"GetFilenameFromURI ENTER\")\n\tlog.Debugln(\"path:\", path)\n\n\tlast := strings.LastIndex(path, string(filepath.Separator))\n\tif last == -1 {\n\t\tlog.Debugln(\"No slash. Return Path:\", path)\n\t\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\t\treturn path\n\t}\n\tpathTmp := path[last+1:]\n\tlog.Debugln(\"Return Path:\", pathTmp)\n\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\n\treturn pathTmp\n}\n\n\/\/AppendSlash appends a slash to a path if one is needed\nfunc (fs *Fs) AppendSlash(path string) string {\n\tlog.Debugln(\"AppendSlash ENTER\")\n\tlog.Debugln(\"path:\", path)\n\tif path[len(path)-1] != filepath.Separator {\n\t\tpath += string(filepath.Separator)\n\t}\n\tlog.Debugln(\"Return Path:\", path)\n\tlog.Debugln(\"GetFilenameFromURI LEAVE\")\n\treturn path\n}\n\n\/\/FileCopy copies the contents of the src file to the dst file\nfunc (fs *Fs) FileCopy(src string, dst string) error {\n\tlog.Debugln(\"FileCopy ENTER\")\n\tlog.Debugln(\"SRC:\", src)\n\tlog.Debugln(\"DST:\", dst)\n\n\tsfi, err := os.Stat(src)\n\tif err != nil {\n\t\tlog.Debugln(\"Src Stat Failed:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn ErrSrcNotExist\n\t}\n\tif !sfi.Mode().IsRegular() {\n\t\t\/\/cannot copy non-regular files (e.g., directories, symlinks, devices, etc.)\n\t\tlog.Debugln(\"Src file is not regular\")\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn ErrSrcNotRegularFile\n\t}\n\tdfi, err := os.Stat(dst)\n\tif err == nil {\n\t\tif !(dfi.Mode().IsRegular()) {\n\t\t\tlog.Debugln(\"Dst file is not regular\")\n\t\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\t\treturn ErrDstNotRegularFile\n\t\t}\n\t\tif os.SameFile(sfi, dfi) {\n\t\t\tlog.Debugln(\"Src and Dst files are the same\")\n\t\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/Copy the file\n\tin, err := os.OpenFile(src, os.O_RDONLY, 0666)\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to open SRC file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\tdefer in.Close()\n\tout, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to open DST file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tif _, err = io.Copy(out, in); err != nil {\n\t\tlog.Debugln(\"Failed to copy file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\n\terr = out.Sync()\n\tif err != nil {\n\t\tlog.Debugln(\"Failed to flush file:\", err)\n\t\tlog.Debugln(\"FileCopy LEAVE\")\n\t\treturn err\n\t}\n\n\tlog.Debugln(\"File copy succeeded\")\n\tlog.Debugln(\"FileCopy LEAVE\")\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage ezk is an enhanced Zookeeper client. It uses the\nconnection and underlying operations from\nhttps:\/\/github.com\/samuel\/go-zookeeper\/zk\nin conjunction with automatic retry of operations via the\nhttps:\/\/github.com\/betable\/retry library.\n*\/\npackage ezk\n\nimport (\n\t\"github.com\/betable\/retry\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n\t\"time\"\n)\n\n\/\/ Client is a wrapper over github.com\/samuel\/go-zookeeper\/zk that retries all but one of its operations according to the ClientConfig.Retry function. The one exception is for CreateProtectedEphemeralSequential(); it is not retried automatically.\ntype Client struct {\n\n\t\/\/ The configuration for the client.\n\tCfg ClientConfig\n\n\t\/\/ The underlying github.com\/samuel\/go-zookeeper\/zk connection.\n\tConn *zk.Conn\n\n\t\/\/ WatchCh will be nil until Connect returns without error.\n\t\/\/ Watches that fire over the Zookeeper connection will be\n\t\/\/ received on WatchCh.\n\tWatchCh <-chan zk.Event\n}\n\n\/\/ ClientConfig is used to configure a Client; pass\n\/\/ it to NewClient().\ntype ClientConfig struct {\n\n\t\/\/ The Chroot directory will be prepended to all paths\n\tChroot string\n\n\t\/\/ The set of ACLs used by defeault when\n\t\/\/ calling Client.Create(), if the formal\n\t\/\/ parameter acl in Create() is length 0.\n\tAcl []zk.ACL\n\n\t\/\/ The URLs of the zookeepers to attempt to connect to.\n\tServers []string\n\n\t\/\/ SessionTimeout defaults to 10 seconds if not\n\t\/\/ otherwise set.\n\tSessionTimeout time.Duration\n\n\t\/\/ The Retry function determines how many times\n\t\/\/ and how often we retry our Zookeeper operations\n\t\/\/ before failing. See DefaultRetry() which is\n\t\/\/ used if this is not otherwise set.\n\tRetry Retry\n}\n\n\/\/ NewClient creates a new ezk.Client.\n\/\/ If the cfg.SessionTimout is set to 0\n\/\/ a default value of 10 seconds will be used.\n\/\/ If cfg.Retry is nil then the DefaultRetry\n\/\/ function will be used.\nfunc NewClient(cfg ClientConfig) *Client {\n\tif cfg.Retry == nil {\n\t\tcfg.Retry = DefaultRetry\n\t}\n\tif cfg.SessionTimeout == 0 {\n\t\tcfg.SessionTimeout = 10 * time.Second\n\t}\n\tcli := &Client{\n\t\tCfg: cfg,\n\t}\n\treturn cli\n}\n\n\/\/ Retry defines the type of the retry method to use.\ntype Retry func(op, path string, f func() error)\n\n\/\/ Connect connects to a Zookeeper server.\n\/\/ Upon success it sets the z.WatchCh and\n\/\/ z.Conn and returns nil.\n\/\/ If an error is returned then z.WatchCh and\n\/\/ z.Conn will not be set. Connect() will\n\/\/ typically only be needed once, but can be\n\/\/ called again if need be.\nfunc (z *Client) Connect() error {\n\tz.WatchCh = nil\n\tz.Conn = nil\n\tconn, ch, err := zk.Connect(z.Cfg.Servers, z.Cfg.SessionTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\tz.Conn = conn\n\tz.WatchCh = ch\n\treturn nil\n}\n\n\/\/ Close closes the connection to the Zookeeper server.\nfunc (z *Client) Close() {\n\tz.Conn.Close()\n}\n\n\/\/ Exists checks if a znode exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Exists(path string) (ok bool, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"exists\", path, func() error {\n\t\tok, s, err = z.Conn.Exists(path)\n\t\treturn err\n\t})\n\treturn ok, s, err\n}\n\n\/\/ ExistsW returns if a znode exists and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) ExistsW(path string) (ok bool, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"existsw\", path, func() error {\n\t\tok, s, ch, err = z.Conn.ExistsW(path)\n\t\treturn err\n\t})\n\treturn ok, s, ch, err\n}\n\n\/\/ Create creates a znode with a content. If\n\/\/ acl is nil then the z.Cfg.Acl set will be\n\/\/ applied to the new znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Create(path string, data []byte, flags int32, acl []zk.ACL) (s string, err error) {\n\tpath = z.fullpath(path)\n\tif len(acl) == 0 && len(z.Cfg.Acl) != 0 {\n\t\tacl = z.Cfg.Acl\n\t}\n\tz.Cfg.Retry(\"create\", path, func() error {\n\t\ts, err = z.Conn.Create(path, data, flags, acl)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ Delete deletes a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Delete(path string, version int32) (err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"delete\", path, func() error {\n\t\terr = z.Conn.Delete(path, version)\n\t\treturn err\n\t})\n\treturn err\n}\n\n\/\/ Get returns the contents of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Get(path string) (d []byte, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"get\", path, func() error {\n\t\td, s, err = z.Conn.Get(path)\n\t\treturn err\n\t})\n\treturn d, s, err\n}\n\n\/\/ GetW returns the contents of a znode and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) GetW(path string) (d []byte, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"getw\", path, func() error {\n\t\td, s, ch, err = z.Conn.GetW(path)\n\t\treturn err\n\t})\n\treturn d, s, ch, err\n}\n\n\/\/ Set writes content in an existent znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Set(path string, data []byte, version int32) (s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"set\", path, func() error {\n\t\ts, err = z.Conn.Set(path, data, version)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ Children returns the children of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Children(path string) (c []string, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"children\", path, func() error {\n\t\tc, s, err = z.Conn.Children(path)\n\t\treturn err\n\t})\n\treturn c, s, err\n}\n\n\/\/ ChildrenW returns the children of a znode and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) ChildrenW(path string) (c []string, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"childrenw\", path, func() error {\n\t\tc, s, ch, err = z.Conn.ChildrenW(path)\n\t\treturn err\n\t})\n\treturn c, s, ch, err\n}\n\n\/\/ Sync performs a sync from the master in the Zookeeper server.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Sync(path string) (s string, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"sync\", path, func() error {\n\t\ts, err = z.Conn.Sync(path)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ GetACL returns the ACL for a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) GetACL(path string) (a []zk.ACL, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"getacl\", path, func() error {\n\t\ta, s, err = z.Conn.GetACL(path)\n\t\treturn err\n\t})\n\treturn a, s, err\n}\n\n\/\/ SetACL sets a ACL to a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SetACL(path string, acl []zk.ACL, version int32) (s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"setacl\", path, func() error {\n\t\ts, err = z.Conn.SetACL(path, acl, version)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ CreateProtectedEphemeralSequential creates a sequential ephemeral znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be NOT be retried.\nfunc (z *Client) CreateProtectedEphemeralSequential(path string, data []byte, acl []zk.ACL) (string, error) {\n\tpath = z.fullpath(path)\n\treturn z.Conn.CreateProtectedEphemeralSequential(path, data, acl)\n}\n\n\/\/ CreateDir is a helper method that creates and empty znode if it does not exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) CreateDir(path string, acl []zk.ACL) error {\n\tpath = z.fullpath(path)\n\tok, _, err := z.Exists(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ok {\n\t\t_, err = z.Create(path, []byte{}, 0, acl)\n\t\tif err == zk.ErrNodeExists {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}\n\n\/\/ SafeSet is a helper method that writes a znode creating it first if it does not exists. It will sync the Zookeeper before checking if the node exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SafeSet(path string, data []byte, version int32, acl []zk.ACL) (*zk.Stat, error) {\n\tpath = z.fullpath(path)\n\t_, err := z.Sync(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tok, _, err := z.Exists(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !ok {\n\t\t_, err := z.Create(path, data, 0, acl)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, s, err := z.Exists(path)\n\t\treturn s, err\n\t}\n\n\treturn z.Set(path, data, version)\n}\n\n\/\/ SafeGet is a helper method that syncs Zookeeper and return the content of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SafeGet(path string) ([]byte, *zk.Stat, error) {\n\tpath = z.fullpath(path)\n\t_, err := z.Sync(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn z.Get(path)\n}\n\n\/\/ fullpath returns the path with the chroot prepended.\nfunc (z *Client) fullpath(path string) string {\n\t\/\/\tif z.Cfg.Chroot != \"\" && !strings.HasPrefix(path, z.Cfg.Chroot) {\n\t\/\/    return z.Cfg.Chroot + path\n\t\/\/\t}\n\t\/\/\treturn path\n\n\treturn z.Cfg.Chroot + path\n}\n\n\/\/ The DefaultRetry function will retry four times if the\n\/\/ first Zookeeper call fails, after sleeping in turn: 0ms, 100ms, 500ms and 1500ms.\nfunc DefaultRetry(op, path string, f func() error) {\n\tretry.NewExecutor().\n\t\tWithRetries(4).\n\t\tWithBackoff(retry.ExponentialDelayBackoff(100*time.Millisecond, 5)).\n\t\tWithErrorComparator(func(err error) bool {\n\t\treturn err == zk.ErrConnectionClosed || err == zk.ErrSessionExpired || err == zk.ErrSessionMoved\n\t}).Execute(f)\n}\n\n\/\/ A convenience version of Delete, DeleteNode deletes a znode,\n\/\/ using version -1 to delete any version.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) DeleteNode(path string) error {\n\treturn z.Delete(path, -1)\n}\n\n\/\/ A convenience version of Create, CreateNode supplies\n\/\/ empty data, 0 flags, and the default z.Cfg.Acl list\n\/\/ to a z.Create() call.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) CreateNode(path string) error {\n\t_, err := z.Create(path, []byte{}, 0, z.Cfg.Acl)\n\treturn err\n}\n<commit_msg>atg. fix dup fullpath issue.<commit_after>\/*\nPackage ezk is an enhanced Zookeeper client. It uses the\nconnection and underlying operations from\nhttps:\/\/github.com\/samuel\/go-zookeeper\/zk\nin conjunction with automatic retry of operations via the\nhttps:\/\/github.com\/betable\/retry library.\n*\/\npackage ezk\n\nimport (\n\t\"fmt\"\n\t\"github.com\/betable\/retry\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n\t\"time\"\n)\n\n\/\/ Client is a wrapper over github.com\/samuel\/go-zookeeper\/zk that retries all but one of its operations according to the ClientConfig.Retry function. The one exception is for CreateProtectedEphemeralSequential(); it is not retried automatically.\ntype Client struct {\n\n\t\/\/ The configuration for the client.\n\tCfg ClientConfig\n\n\t\/\/ The underlying github.com\/samuel\/go-zookeeper\/zk connection.\n\tConn *zk.Conn\n\n\t\/\/ WatchCh will be nil until Connect returns without error.\n\t\/\/ Watches that fire over the Zookeeper connection will be\n\t\/\/ received on WatchCh.\n\tWatchCh <-chan zk.Event\n}\n\n\/\/ ClientConfig is used to configure a Client; pass\n\/\/ it to NewClient().\ntype ClientConfig struct {\n\n\t\/\/ The Chroot directory will be prepended to all paths\n\tChroot string\n\n\t\/\/ The set of ACLs used by defeault when\n\t\/\/ calling Client.Create(), if the formal\n\t\/\/ parameter acl in Create() is length 0.\n\tAcl []zk.ACL\n\n\t\/\/ The URLs of the zookeepers to attempt to connect to.\n\tServers []string\n\n\t\/\/ SessionTimeout defaults to 10 seconds if not\n\t\/\/ otherwise set.\n\tSessionTimeout time.Duration\n\n\t\/\/ The Retry function determines how many times\n\t\/\/ and how often we retry our Zookeeper operations\n\t\/\/ before failing. See DefaultRetry() which is\n\t\/\/ used if this is not otherwise set.\n\tRetry Retry\n}\n\n\/\/ NewClient creates a new ezk.Client.\n\/\/ If the cfg.SessionTimout is set to 0\n\/\/ a default value of 10 seconds will be used.\n\/\/ If cfg.Retry is nil then the DefaultRetry\n\/\/ function will be used.\n\/\/ If cfg.Acl is length 0 then zk.WorldACL(zk.PermAll)\n\/\/ will be used.\nfunc NewClient(cfg ClientConfig) *Client {\n\tif cfg.Retry == nil {\n\t\tcfg.Retry = DefaultRetry\n\t}\n\tif cfg.SessionTimeout == 0 {\n\t\tcfg.SessionTimeout = 10 * time.Second\n\t}\n\tif len(cfg.Acl) == 0 {\n\t\tcfg.Acl = zk.WorldACL(zk.PermAll)\n\t}\n\tcli := &Client{\n\t\tCfg: cfg,\n\t}\n\treturn cli\n}\n\n\/\/ Retry defines the type of the retry method to use.\ntype Retry func(op, path string, f func() error)\n\n\/\/ Connect connects to a Zookeeper server.\n\/\/ Upon success it sets the z.WatchCh and\n\/\/ z.Conn and returns nil.\n\/\/ If an error is returned then z.WatchCh and\n\/\/ z.Conn will not be set. Connect() will\n\/\/ typically only be needed once, but can be\n\/\/ called again if need be.\nfunc (z *Client) Connect() error {\n\tz.WatchCh = nil\n\tz.Conn = nil\n\tconn, ch, err := zk.Connect(z.Cfg.Servers, z.Cfg.SessionTimeout)\n\tif err != nil {\n\t\treturn err\n\t}\n\tz.Conn = conn\n\tz.WatchCh = ch\n\n\t\/\/ make the Chroot dir; deliberately ignore err as\n\t\/\/ the Chroot node may already exist.\n\tz.Create(\"\", []byte{}, 0, z.Cfg.Acl)\n\treturn nil\n}\n\n\/\/ Close closes the connection to the Zookeeper server.\nfunc (z *Client) Close() {\n\tz.Conn.Close()\n}\n\n\/\/ Exists checks if a znode exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Exists(path string) (ok bool, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"exists\", path, func() error {\n\t\tok, s, err = z.Conn.Exists(path)\n\t\treturn err\n\t})\n\treturn ok, s, err\n}\n\n\/\/ ExistsW returns if a znode exists and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) ExistsW(path string) (ok bool, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"existsw\", path, func() error {\n\t\tok, s, ch, err = z.Conn.ExistsW(path)\n\t\treturn err\n\t})\n\treturn ok, s, ch, err\n}\n\n\/\/ Create creates a znode with a content. If\n\/\/ acl is nil then the z.Cfg.Acl set will be\n\/\/ applied to the new znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Create(path string, data []byte, flags int32, acl []zk.ACL) (s string, err error) {\n\tpath = z.fullpath(path)\n\tif len(acl) == 0 && len(z.Cfg.Acl) != 0 {\n\t\tacl = z.Cfg.Acl\n\t}\n\tz.Cfg.Retry(\"create\", path, func() error {\n\t\ts, err = z.Conn.Create(path, data, flags, acl)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ Delete deletes a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Delete(path string, version int32) (err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"delete\", path, func() error {\n\t\terr = z.Conn.Delete(path, version)\n\t\treturn err\n\t})\n\treturn err\n}\n\n\/\/ Get returns the contents of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Get(path string) (d []byte, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"get\", path, func() error {\n\t\td, s, err = z.Conn.Get(path)\n\t\treturn err\n\t})\n\treturn d, s, err\n}\n\n\/\/ GetW returns the contents of a znode and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) GetW(path string) (d []byte, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"getw\", path, func() error {\n\t\td, s, ch, err = z.Conn.GetW(path)\n\t\treturn err\n\t})\n\treturn d, s, ch, err\n}\n\n\/\/ Set writes content in an existent znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Set(path string, data []byte, version int32) (s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"set\", path, func() error {\n\t\tfmt.Printf(\"Set on path='%s'\\n\", path)\n\t\ts, err = z.Conn.Set(path, data, version)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ Children returns the children of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Children(path string) (c []string, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"children\", path, func() error {\n\t\tc, s, err = z.Conn.Children(path)\n\t\treturn err\n\t})\n\treturn c, s, err\n}\n\n\/\/ ChildrenW returns the children of a znode and sets a watch.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) ChildrenW(path string) (c []string, s *zk.Stat, ch <-chan zk.Event, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"childrenw\", path, func() error {\n\t\tc, s, ch, err = z.Conn.ChildrenW(path)\n\t\treturn err\n\t})\n\treturn c, s, ch, err\n}\n\n\/\/ Sync performs a sync from the master in the Zookeeper server.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) Sync(path string) (s string, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"sync\", path, func() error {\n\t\ts, err = z.Conn.Sync(path)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ GetACL returns the ACL for a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) GetACL(path string) (a []zk.ACL, s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"getacl\", path, func() error {\n\t\ta, s, err = z.Conn.GetACL(path)\n\t\treturn err\n\t})\n\treturn a, s, err\n}\n\n\/\/ SetACL sets a ACL to a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SetACL(path string, acl []zk.ACL, version int32) (s *zk.Stat, err error) {\n\tpath = z.fullpath(path)\n\tz.Cfg.Retry(\"setacl\", path, func() error {\n\t\ts, err = z.Conn.SetACL(path, acl, version)\n\t\treturn err\n\t})\n\treturn s, err\n}\n\n\/\/ CreateProtectedEphemeralSequential creates a sequential ephemeral znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be NOT be retried.\nfunc (z *Client) CreateProtectedEphemeralSequential(path string, data []byte, acl []zk.ACL) (string, error) {\n\tpath = z.fullpath(path)\n\treturn z.Conn.CreateProtectedEphemeralSequential(path, data, acl)\n}\n\n\/\/ CreateDir is a helper method that creates and empty znode if it does not exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) CreateDir(path string, acl []zk.ACL) error {\n\tpath = z.fullpath(path)\n\tok, _, err := z.Exists(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !ok {\n\t\t_, err = z.Create(path, []byte{}, 0, acl)\n\t\tif err == zk.ErrNodeExists {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn err\n}\n\n\/\/ SafeSet is a helper method that writes a znode creating it first if it does not exists. It will sync the Zookeeper before checking if the node exists.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SafeSet(path string, data []byte, version int32, acl []zk.ACL) (*zk.Stat, error) {\n\t_, err := z.Sync(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tok, _, err := z.Exists(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !ok {\n\t\t_, err := z.Create(path, data, 0, acl)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t_, s, err := z.Exists(path)\n\t\treturn s, err\n\t}\n\n\treturn z.Set(path, data, version)\n}\n\n\/\/ SafeGet is a helper method that syncs Zookeeper and return the content of a znode.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) SafeGet(path string) ([]byte, *zk.Stat, error) {\n\t_, err := z.Sync(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn z.Get(path)\n}\n\n\/\/ fullpath returns the path with the chroot prepended.\nfunc (z *Client) fullpath(path string) string {\n\t\/\/\tif z.Cfg.Chroot != \"\" && !strings.HasPrefix(path, z.Cfg.Chroot) {\n\t\/\/    return z.Cfg.Chroot + path\n\t\/\/\t}\n\t\/\/\treturn path\n\n\treturn z.Cfg.Chroot + path\n}\n\n\/\/ The DefaultRetry function will retry four times if the\n\/\/ first Zookeeper call fails, after sleeping in turn: 0ms, 100ms, 500ms and 1500ms.\nfunc DefaultRetry(op, path string, f func() error) {\n\tretry.NewExecutor().\n\t\tWithRetries(4).\n\t\tWithBackoff(retry.ExponentialDelayBackoff(100*time.Millisecond, 5)).\n\t\tWithErrorComparator(func(err error) bool {\n\t\treturn err == zk.ErrConnectionClosed || err == zk.ErrSessionExpired || err == zk.ErrSessionMoved\n\t}).Execute(f)\n}\n\n\/\/ A convenience version of Delete, DeleteNode deletes a znode,\n\/\/ using version -1 to delete any version.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) DeleteNode(path string) error {\n\treturn z.Delete(path, -1)\n}\n\n\/\/ A convenience version of Create, CreateNode supplies\n\/\/ empty data, 0 flags, and the default z.Cfg.Acl list\n\/\/ to a z.Create() call.\n\/\/ z.Cfg.Chroot will be prepended to path. The call will be retried.\nfunc (z *Client) CreateNode(path string) error {\n\t_, err := z.Create(path, []byte{}, 0, z.Cfg.Acl)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\n\tbaps3 \"github.com\/UniversityRadioYork\/baps3-go\"\n)\n\ntype Client struct {\n\tconn       net.Conn\n\treader     *bufio.Reader\n\twriter     *bufio.Writer\n\tresponseCh chan []byte\n\tOutgoing   chan []byte\n}\n\nfunc MakeClient(conn net.Conn, respCh chan []byte) *Client {\n\tclient := &Client{\n\t\tconn:       conn,\n\t\treader:     bufio.NewReader(conn),\n\t\twriter:     bufio.NewWriter(conn),\n\t\tresponseCh: respCh,\n\t\tOutgoing:   make(chan []byte),\n\t}\n\n\tgo client.Read()\n\tgo client.write()\n\n\tohai := MakeWelcomeMsg()\n\tdata, _ := ohai.Pack()\n\tclient.Outgoing <- data\n\n\treturn client\n}\n\nfunc MakeWelcomeMsg() *baps3.Message {\n\treturn baps3.NewMessage(baps3.RsOhai).AddArg(\"listd\").AddArg(\"0.0\")\n}\n\nfunc (c *Client) Close() {\n\tc.conn.Close()\n}\n\nfunc (c *Client) Read() {\n\tfor {\n\t\tdata, _ := c.reader.ReadBytes('\\n')\n\t\tc.responseCh <- data \/\/ Each client doesn't care what it got, that's for the server to handle\n\t}\n}\n\nfunc (c *Client) write() {\n\tfor data := range c.Outgoing {\n\t\t_, err := c.writer.Write(data)\n\t\tif err != nil {\n\t\t\tcontinue \/\/ TODO Handle\n\t\t}\n\t\tc.writer.Flush()\n\t}\n}\n<commit_msg>Remove unnecessary bufio.Writer<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\n\tbaps3 \"github.com\/UniversityRadioYork\/baps3-go\"\n)\n\ntype Client struct {\n\tconn       net.Conn\n\treader     *bufio.Reader\n\tresponseCh chan []byte\n\tOutgoing   chan []byte\n}\n\nfunc MakeClient(conn net.Conn, respCh chan []byte) *Client {\n\tclient := &Client{\n\t\tconn:       conn,\n\t\treader:     bufio.NewReader(conn),\n\t\tresponseCh: respCh,\n\t\tOutgoing:   make(chan []byte),\n\t}\n\n\tgo client.Read()\n\tgo client.write()\n\n\tohai := MakeWelcomeMsg()\n\tdata, _ := ohai.Pack()\n\tclient.Outgoing <- data\n\n\treturn client\n}\n\nfunc MakeWelcomeMsg() *baps3.Message {\n\treturn baps3.NewMessage(baps3.RsOhai).AddArg(\"listd\").AddArg(\"0.0\")\n}\n\nfunc (c *Client) Close() {\n\tc.conn.Close()\n}\n\nfunc (c *Client) Read() {\n\tfor {\n\t\tdata, _ := c.reader.ReadBytes('\\n')\n\t\tc.responseCh <- data \/\/ Each client doesn't care what it got, that's for the server to handle\n\t}\n}\n\nfunc (c *Client) write() {\n\tfor data := range c.Outgoing {\n\t\t_, err := c.conn.Write(data)\n\t\tif err != nil {\n\t\t\tcontinue \/\/ TODO Handle\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 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\n\/\/ Prometheus HTTP API client functionality.\n\/\/\n\/\/ TODO(julius): This functionality should be moved to a separate\n\/\/ library\/repository once we have a good name for it (client_* is already used\n\/\/ for the interface between metrics-exposing servers and Prometheus).\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n)\n\nconst (\n\tqueryPath      = \"\/api\/query\"\n\tqueryRangePath = \"\/api\/query_range\"\n\tmetricsPath    = \"\/api\/metrics\"\n\n\tscalarType = \"scalar\"\n\tvectorType = \"vector\"\n\tmatrixType = \"matrix\"\n\terrorType  = \"error\"\n)\n\n\/\/ Client is a client for executing queries against the Prometheus API.\ntype Client struct {\n\tEndpoint   string\n\thttpClient http.Client\n}\n\n\/\/ transport builds a new transport with the provided timeout.\nfunc transport(netw, addr string, timeout time.Duration) (connection net.Conn, err error) {\n\tdeadline := time.Now().Add(timeout)\n\tconnection, err = net.DialTimeout(netw, addr, timeout)\n\tif err == nil {\n\t\tconnection.SetDeadline(deadline)\n\t}\n\treturn\n}\n\n\/\/ NewClient creates a new Client, given a server URL and timeout.\nfunc NewClient(url string, timeout time.Duration) *Client {\n\treturn &Client{\n\t\tEndpoint: url,\n\t\thttpClient: http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: func(netw, addr string) (net.Conn, error) { return transport(netw, addr, timeout) },\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ Query performs an instant expression query via the Prometheus API.\nfunc (c *Client) Query(expr string) (QueryResponse, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = queryPath\n\tq := u.Query()\n\n\tq.Set(\"expr\", expr)\n\tu.RawQuery = q.Encode()\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r StubQueryResponse\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.Version != 1 {\n\t\treturn nil, fmt.Errorf(\"unsupported JSON format version %d\", r.Version)\n\t}\n\n\tvar typedResp QueryResponse\n\tswitch r.Type {\n\tcase errorType:\n\t\treturn nil, fmt.Errorf(\"query error: %s\", r.Value.(string))\n\tcase scalarType:\n\t\ttypedResp = &ScalarQueryResponse{}\n\tcase vectorType:\n\t\ttypedResp = &VectorQueryResponse{}\n\tcase matrixType:\n\t\ttypedResp = &MatrixQueryResponse{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid response type %s\", r.Type)\n\t}\n\n\tif err := json.Unmarshal(buf, typedResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn typedResp, err\n}\n\n\/\/ QueryRange performs an range expression query via the Prometheus API.\nfunc (c *Client) QueryRange(expr string, end float64, rangeSec uint64, step uint64) (*MatrixQueryResponse, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = queryRangePath\n\tq := u.Query()\n\n\tq.Set(\"expr\", expr)\n\tq.Set(\"end\", fmt.Sprintf(\"%f\", end))\n\tq.Set(\"range\", fmt.Sprintf(\"%d\", rangeSec))\n\tq.Set(\"step\", fmt.Sprintf(\"%d\", step))\n\tu.RawQuery = q.Encode()\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r StubQueryResponse\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.Version != 1 {\n\t\treturn nil, fmt.Errorf(\"unsupported JSON format version %d\", r.Version)\n\t}\n\n\tswitch r.Type {\n\tcase errorType:\n\t\treturn nil, fmt.Errorf(\"query error: %s\", r.Value.(string))\n\tcase matrixType:\n\t\tvar typedResp MatrixQueryResponse\n\t\tif err := json.Unmarshal(buf, &typedResp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &typedResp, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid response type %s\", r.Type)\n\t}\n}\n\n\/\/ Metrics retrieves the list of available metric names via the Prometheus API.\nfunc (c *Client) Metrics() ([]string, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = metricsPath\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r []string\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n<commit_msg>don't overwrite URL.Path<commit_after>\/\/ Copyright 2013 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\n\/\/ Prometheus HTTP API client functionality.\n\/\/\n\/\/ TODO(julius): This functionality should be moved to a separate\n\/\/ library\/repository once we have a good name for it (client_* is already used\n\/\/ for the interface between metrics-exposing servers and Prometheus).\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tqueryPath      = \"\/api\/query\"\n\tqueryRangePath = \"\/api\/query_range\"\n\tmetricsPath    = \"\/api\/metrics\"\n\n\tscalarType = \"scalar\"\n\tvectorType = \"vector\"\n\tmatrixType = \"matrix\"\n\terrorType  = \"error\"\n)\n\n\/\/ Client is a client for executing queries against the Prometheus API.\ntype Client struct {\n\tEndpoint   string\n\thttpClient http.Client\n}\n\n\/\/ transport builds a new transport with the provided timeout.\nfunc transport(netw, addr string, timeout time.Duration) (connection net.Conn, err error) {\n\tdeadline := time.Now().Add(timeout)\n\tconnection, err = net.DialTimeout(netw, addr, timeout)\n\tif err == nil {\n\t\tconnection.SetDeadline(deadline)\n\t}\n\treturn\n}\n\n\/\/ NewClient creates a new Client, given a server URL and timeout.\nfunc NewClient(url string, timeout time.Duration) *Client {\n\treturn &Client{\n\t\tEndpoint: url,\n\t\thttpClient: http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: func(netw, addr string) (net.Conn, error) { return transport(netw, addr, timeout) },\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ Query performs an instant expression query via the Prometheus API.\nfunc (c *Client) Query(expr string) (QueryResponse, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = strings.TrimRight(u.Path, \"\/\") + queryPath\n\tq := u.Query()\n\n\tq.Set(\"expr\", expr)\n\tu.RawQuery = q.Encode()\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r StubQueryResponse\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.Version != 1 {\n\t\treturn nil, fmt.Errorf(\"unsupported JSON format version %d\", r.Version)\n\t}\n\n\tvar typedResp QueryResponse\n\tswitch r.Type {\n\tcase errorType:\n\t\treturn nil, fmt.Errorf(\"query error: %s\", r.Value.(string))\n\tcase scalarType:\n\t\ttypedResp = &ScalarQueryResponse{}\n\tcase vectorType:\n\t\ttypedResp = &VectorQueryResponse{}\n\tcase matrixType:\n\t\ttypedResp = &MatrixQueryResponse{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid response type %s\", r.Type)\n\t}\n\n\tif err := json.Unmarshal(buf, typedResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn typedResp, err\n}\n\n\/\/ QueryRange performs an range expression query via the Prometheus API.\nfunc (c *Client) QueryRange(expr string, end float64, rangeSec uint64, step uint64) (*MatrixQueryResponse, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = strings.TrimRight(u.Path, \"\/\") + queryRangePath\n\tq := u.Query()\n\n\tq.Set(\"expr\", expr)\n\tq.Set(\"end\", fmt.Sprintf(\"%f\", end))\n\tq.Set(\"range\", fmt.Sprintf(\"%d\", rangeSec))\n\tq.Set(\"step\", fmt.Sprintf(\"%d\", step))\n\tu.RawQuery = q.Encode()\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r StubQueryResponse\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.Version != 1 {\n\t\treturn nil, fmt.Errorf(\"unsupported JSON format version %d\", r.Version)\n\t}\n\n\tswitch r.Type {\n\tcase errorType:\n\t\treturn nil, fmt.Errorf(\"query error: %s\", r.Value.(string))\n\tcase matrixType:\n\t\tvar typedResp MatrixQueryResponse\n\t\tif err := json.Unmarshal(buf, &typedResp); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &typedResp, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid response type %s\", r.Type)\n\t}\n}\n\n\/\/ Metrics retrieves the list of available metric names via the Prometheus API.\nfunc (c *Client) Metrics() ([]string, error) {\n\tu, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tu.Path = strings.TrimRight(u.Path, \"\/\") + metricsPath\n\n\tresp, err := c.httpClient.Get(u.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r []string\n\tif err := json.Unmarshal(buf, &r); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ S3 interface\npackage main\n\n\/\/ FIXME need to prevent anything but ListDir working for s3:\/\/\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/ncw\/swift\"\n\t\"io\"\n\t\"launchpad.net\/goamz\/aws\"\n\t\"launchpad.net\/goamz\/s3\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Constants\nconst (\n\tmetaMtime = \"X-Amz-Meta-Mtime\" \/\/ the meta key to store mtime in\n)\n\n\/\/ FsS3 represents a remote s3 server\ntype FsS3 struct {\n\tc      *s3.S3     \/\/ the connection to the s3 server\n\tb      *s3.Bucket \/\/ the connection to the bucket\n\tbucket string     \/\/ the bucket we are working on\n\tperm   s3.ACL     \/\/ permissions for new buckets \/ objects\n}\n\n\/\/ FsObjectS3 describes a s3 object\ntype FsObjectS3 struct {\n\t\/\/ Will definitely have everything but meta which may be nil\n\t\/\/\n\t\/\/ List will read everything but meta - to fill that in need to call\n\t\/\/ readMetaData\n\ts3           *FsS3      \/\/ what this object is part of\n\tremote       string     \/\/ The remote path\n\tetag         string     \/\/ md5sum of the object\n\tbytes        int64      \/\/ size of the object\n\tlastModified time.Time  \/\/ Last modified\n\tmeta         s3.Headers \/\/ The object metadata if known - may be nil\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Globals\nvar (\n\t\/\/ Flags\n\tawsAccessKeyId     = flag.String(\"aws-access-key-id\", os.Getenv(\"AWS_ACCESS_KEY_ID\"), \"AWS Access Key ID. Defaults to environment var AWS_ACCESS_KEY_ID.\")\n\tawsSecretAccessKey = flag.String(\"aws-secret-access-key\", os.Getenv(\"AWS_SECRET_ACCESS_KEY\"), \"AWS Secret Access Key (password). Defaults to environment var AWS_SECRET_ACCESS_KEY.\")\n\t\/\/ AWS endpoints: http:\/\/docs.amazonwebservices.com\/general\/latest\/gr\/rande.html#s3_region\n\ts3Endpoint           = flag.String(\"s3-endpoint\", os.Getenv(\"S3_ENDPOINT\"), \"S3 Endpoint. Defaults to environment var S3_ENDPOINT then https:\/\/s3.amazonaws.com\/.\")\n\ts3LocationConstraint = flag.String(\"s3-location-constraint\", os.Getenv(\"S3_LOCATION_CONSTRAINT\"), \"Location constraint for creating buckets only. Defaults to environment var S3_LOCATION_CONSTRAINT.\")\n)\n\n\/\/ String converts this FsS3 to a string\nfunc (f *FsS3) String() string {\n\treturn fmt.Sprintf(\"S3 bucket %s\", f.bucket)\n}\n\n\/\/ Pattern to match a s3 url\nvar s3Match = regexp.MustCompile(`^s3:\/\/([^\/]*)(.*)$`)\n\n\/\/ parseParse parses a s3 'url'\nfunc s3ParsePath(path string) (bucket, directory string, err error) {\n\tparts := s3Match.FindAllStringSubmatch(path, -1)\n\tif len(parts) != 1 || len(parts[0]) != 3 {\n\t\terr = fmt.Errorf(\"Couldn't parse s3 url %q\", path)\n\t} else {\n\t\tbucket, directory = parts[0][1], parts[0][2]\n\t\tdirectory = strings.Trim(directory, \"\/\")\n\t}\n\treturn\n}\n\n\/\/ s3Connection makes a connection to s3\nfunc s3Connection() (*s3.S3, error) {\n\t\/\/ Make the auth\n\tif *awsAccessKeyId == \"\" {\n\t\treturn nil, errors.New(\"Need -aws-access-key-id or environmental variable AWS_ACCESS_KEY_ID\")\n\t}\n\tif *awsSecretAccessKey == \"\" {\n\t\treturn nil, errors.New(\"Need -aws-secret-access-key or environmental variable AWS_SECRET_ACCESS_KEY\")\n\t}\n\tauth := aws.Auth{AccessKey: *awsAccessKeyId, SecretKey: *awsSecretAccessKey}\n\n\t\/\/ FIXME look through all the regions by name and use one of them if found\n\n\t\/\/ Synthesize the region\n\tif *s3Endpoint == \"\" {\n\t\t*s3Endpoint = \"https:\/\/s3.amazonaws.com\/\"\n\t}\n\tregion := aws.Region{\n\t\tName:                 \"s3\",\n\t\tS3Endpoint:           *s3Endpoint,\n\t\tS3LocationConstraint: false,\n\t}\n\tif *s3LocationConstraint != \"\" {\n\t\tregion.Name = *s3LocationConstraint\n\t\tregion.S3LocationConstraint = true\n\t}\n\n\tc := s3.New(auth, region)\n\treturn c, nil\n}\n\n\/\/ NewFsS3 contstructs an FsS3 from the path, bucket:path\nfunc NewFsS3(path string) (*FsS3, error) {\n\tbucket, directory, err := s3ParsePath(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif directory != \"\" {\n\t\treturn nil, fmt.Errorf(\"Directories not supported yet in %q: %q\", path, directory)\n\t}\n\tc, err := s3Connection()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf := &FsS3{\n\t\tc:      c,\n\t\tbucket: bucket,\n\t\tb:      c.Bucket(bucket),\n\t\tperm:   s3.Private, \/\/ FIXME need user to specify\n\t}\n\treturn f, nil\n}\n\n\/\/ Return an FsObject from a path\n\/\/\n\/\/ May return nil if an error occurred\nfunc (f *FsS3) NewFsObjectWithInfo(remote string, info *s3.Key) FsObject {\n\tfs := &FsObjectS3{\n\t\ts3:     f,\n\t\tremote: remote,\n\t}\n\tif info != nil {\n\t\t\/\/ Set info but not meta\n\t\tvar err error\n\t\tfs.lastModified, err = time.Parse(time.RFC3339, info.LastModified)\n\t\tif err != nil {\n\t\t\tFsLog(fs, \"Failed to read last modified: %s\", err)\n\t\t\tfs.lastModified = time.Now()\n\t\t}\n\t\tfs.etag = info.ETag\n\t\tfs.bytes = info.Size\n\t} else {\n\t\terr := fs.readMetaData() \/\/ reads info and meta, returning an error\n\t\tif err != nil {\n\t\t\t\/\/ logged already FsDebug(\"Failed to read info: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fs\n}\n\n\/\/ Return an FsObject from a path\n\/\/\n\/\/ May return nil if an error occurred\nfunc (f *FsS3) NewFsObject(remote string) FsObject {\n\treturn f.NewFsObjectWithInfo(remote, nil)\n}\n\n\/\/ Walk the path returning a channel of FsObjects\nfunc (f *FsS3) List() FsObjectsChan {\n\tout := make(FsObjectsChan, *checkers)\n\tgo func() {\n\t\t\/\/ FIXME need to implement ALL loop\n\t\tobjects, err := f.b.List(\"\", \"\", \"\", 10000)\n\t\tif err != nil {\n\t\t\tstats.Error()\n\t\t\tlog.Printf(\"Couldn't read bucket %q: %s\", f.bucket, err)\n\t\t} else {\n\t\t\tfor i := range objects.Contents {\n\t\t\t\tobject := &objects.Contents[i]\n\t\t\t\tif fs := f.NewFsObjectWithInfo(object.Key, object); fs != nil {\n\t\t\t\t\tout <- fs\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\n\/\/ Lists the buckets\nfunc (f *FsS3) ListDir() FsDirChan {\n\tout := make(FsDirChan, *checkers)\n\tgo func() {\n\t\tdefer close(out)\n\t\tbuckets, err := f.c.List()\n\t\tif err != nil {\n\t\t\tstats.Error()\n\t\t\tlog.Printf(\"Couldn't list buckets: %s\", err)\n\t\t} else {\n\t\t\tfor _, bucket := range buckets.Buckets {\n\t\t\t\twhen, _ := time.Parse(time.RFC3339, bucket.CreationDate)\n\t\t\t\tout <- &FsDir{\n\t\t\t\t\tName:  bucket.Name,\n\t\t\t\t\tWhen:  when,\n\t\t\t\t\tBytes: -1,\n\t\t\t\t\tCount: -1,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\n\/\/ Put the FsObject into the bucket\nfunc (f *FsS3) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {\n\t\/\/ Temporary FsObject under construction\n\tfs := &FsObjectS3{s3: f, remote: remote}\n\n\t\/\/ Set the mtime in the headers\n\theaders := s3.Headers{\n\t\tmetaMtime: swift.TimeToFloatString(modTime),\n\t}\n\n\t\/\/ Guess the content type\n\tcontentType := mime.TypeByExtension(path.Ext(remote))\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/octet-stream\"\n\t}\n\n\t_, err := fs.s3.b.PutReaderHeaders(remote, in, size, contentType, f.perm, headers)\n\treturn fs, err\n}\n\n\/\/ Mkdir creates the bucket if it doesn't exist\nfunc (f *FsS3) Mkdir() error {\n\terr := f.b.PutBucket(f.perm)\n\tif err, ok := err.(*s3.Error); ok {\n\t\tif err.Code == \"BucketAlreadyOwnedByYou\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Rmdir deletes the bucket\n\/\/\n\/\/ Returns an error if it isn't empty\nfunc (f *FsS3) Rmdir() error {\n\treturn f.b.DelBucket()\n}\n\n\/\/ Return the precision\nfunc (fs *FsS3) Precision() time.Duration {\n\treturn time.Nanosecond\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Return the remote path\nfunc (fs *FsObjectS3) Remote() string {\n\treturn fs.remote\n}\n\n\/\/ Md5sum returns the Md5sum of an object returning a lowercase hex string\nfunc (fs *FsObjectS3) Md5sum() (string, error) {\n\treturn strings.Trim(strings.ToLower(fs.etag), `\"`), nil\n}\n\n\/\/ Size returns the size of an object in bytes\nfunc (fs *FsObjectS3) Size() int64 {\n\treturn fs.bytes\n}\n\n\/\/ readMetaData gets the metadata if it hasn't already been fetched\n\/\/\n\/\/ it also sets the info\nfunc (fs *FsObjectS3) readMetaData() (err error) {\n\tif fs.meta != nil {\n\t\treturn nil\n\t}\n\n\theaders, err := fs.s3.b.Head(fs.remote, nil)\n\tif err != nil {\n\t\tFsDebug(fs, \"Failed to read info: %s\", err)\n\t\treturn err\n\t}\n\tsize, err := strconv.ParseInt(headers[\"Content-Length\"], 10, 64)\n\tif err != nil {\n\t\tFsDebug(fs, \"Failed to read size from: %q\", headers)\n\t\treturn err\n\t}\n\tfs.etag = headers[\"Etag\"]\n\tfs.bytes = size\n\tfs.meta = headers\n\tif fs.lastModified, err = time.Parse(http.TimeFormat, headers[\"Last-Modified\"]); err != nil {\n\t\tFsLog(fs, \"Failed to read last modified from HEAD: %s\", err)\n\t\tfs.lastModified = time.Now()\n\t}\n\treturn nil\n}\n\n\/\/ ModTime returns the modification time of the object\n\/\/\n\/\/ It attempts to read the objects mtime and if that isn't present the\n\/\/ LastModified returned in the http headers\nfunc (fs *FsObjectS3) ModTime() time.Time {\n\terr := fs.readMetaData()\n\tif err != nil {\n\t\tFsLog(fs, \"Failed to read metadata: %s\", err)\n\t\treturn time.Now()\n\t}\n\t\/\/ read mtime out of metadata if available\n\td, ok := fs.meta[metaMtime]\n\tif !ok {\n\t\t\/\/ FsDebug(fs, \"No metadata\")\n\t\treturn fs.lastModified\n\t}\n\tmodTime, err := swift.FloatStringToTime(d)\n\tif err != nil {\n\t\tFsLog(fs, \"Failed to read mtime from object: %s\", err)\n\t\treturn fs.lastModified\n\t}\n\treturn modTime\n}\n\n\/\/ Sets the modification time of the local fs object\nfunc (fs *FsObjectS3) SetModTime(modTime time.Time) {\n\terr := fs.readMetaData()\n\tif err != nil {\n\t\tstats.Error()\n\t\tFsLog(fs, \"Failed to read metadata: %s\", err)\n\t\treturn\n\t}\n\tfs.meta[metaMtime] = swift.TimeToFloatString(modTime)\n\t_, err = fs.s3.b.Update(fs.remote, fs.s3.perm, fs.meta)\n\tif err != nil {\n\t\tstats.Error()\n\t\tFsLog(fs, \"Failed to update remote mtime: %s\", err)\n\t}\n}\n\n\/\/ Is this object storable\nfunc (fs *FsObjectS3) Storable() bool {\n\treturn true\n}\n\n\/\/ Open an object for read\nfunc (fs *FsObjectS3) Open() (in io.ReadCloser, err error) {\n\tin, err = fs.s3.b.GetReader(fs.remote)\n\treturn\n}\n\n\/\/ Remove an object\nfunc (fs *FsObjectS3) Remove() error {\n\treturn fs.s3.b.Del(fs.remote)\n}\n\n\/\/ Check the interfaces are satisfied\nvar _ Fs = &FsS3{}\nvar _ FsObject = &FsObjectS3{}\n<commit_msg>Update after API changes in goamz\/s3<commit_after>\/\/ S3 interface\npackage main\n\n\/\/ FIXME need to prevent anything but ListDir working for s3:\/\/\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/ncw\/swift\"\n\t\"io\"\n\t\"launchpad.net\/goamz\/aws\"\n\t\"launchpad.net\/goamz\/s3\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Constants\nconst (\n\tmetaMtime = \"X-Amz-Meta-Mtime\" \/\/ the meta key to store mtime in\n)\n\n\/\/ FsS3 represents a remote s3 server\ntype FsS3 struct {\n\tc      *s3.S3     \/\/ the connection to the s3 server\n\tb      *s3.Bucket \/\/ the connection to the bucket\n\tbucket string     \/\/ the bucket we are working on\n\tperm   s3.ACL     \/\/ permissions for new buckets \/ objects\n}\n\n\/\/ FsObjectS3 describes a s3 object\ntype FsObjectS3 struct {\n\t\/\/ Will definitely have everything but meta which may be nil\n\t\/\/\n\t\/\/ List will read everything but meta - to fill that in need to call\n\t\/\/ readMetaData\n\ts3           *FsS3      \/\/ what this object is part of\n\tremote       string     \/\/ The remote path\n\tetag         string     \/\/ md5sum of the object\n\tbytes        int64      \/\/ size of the object\n\tlastModified time.Time  \/\/ Last modified\n\tmeta         s3.Headers \/\/ The object metadata if known - may be nil\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Globals\nvar (\n\t\/\/ Flags\n\tawsAccessKeyId     = flag.String(\"aws-access-key-id\", os.Getenv(\"AWS_ACCESS_KEY_ID\"), \"AWS Access Key ID. Defaults to environment var AWS_ACCESS_KEY_ID.\")\n\tawsSecretAccessKey = flag.String(\"aws-secret-access-key\", os.Getenv(\"AWS_SECRET_ACCESS_KEY\"), \"AWS Secret Access Key (password). Defaults to environment var AWS_SECRET_ACCESS_KEY.\")\n\t\/\/ AWS endpoints: http:\/\/docs.amazonwebservices.com\/general\/latest\/gr\/rande.html#s3_region\n\ts3Endpoint           = flag.String(\"s3-endpoint\", os.Getenv(\"S3_ENDPOINT\"), \"S3 Endpoint. Defaults to environment var S3_ENDPOINT then https:\/\/s3.amazonaws.com\/.\")\n\ts3LocationConstraint = flag.String(\"s3-location-constraint\", os.Getenv(\"S3_LOCATION_CONSTRAINT\"), \"Location constraint for creating buckets only. Defaults to environment var S3_LOCATION_CONSTRAINT.\")\n)\n\n\/\/ String converts this FsS3 to a string\nfunc (f *FsS3) String() string {\n\treturn fmt.Sprintf(\"S3 bucket %s\", f.bucket)\n}\n\n\/\/ Pattern to match a s3 url\nvar s3Match = regexp.MustCompile(`^s3:\/\/([^\/]*)(.*)$`)\n\n\/\/ parseParse parses a s3 'url'\nfunc s3ParsePath(path string) (bucket, directory string, err error) {\n\tparts := s3Match.FindAllStringSubmatch(path, -1)\n\tif len(parts) != 1 || len(parts[0]) != 3 {\n\t\terr = fmt.Errorf(\"Couldn't parse s3 url %q\", path)\n\t} else {\n\t\tbucket, directory = parts[0][1], parts[0][2]\n\t\tdirectory = strings.Trim(directory, \"\/\")\n\t}\n\treturn\n}\n\n\/\/ s3Connection makes a connection to s3\nfunc s3Connection() (*s3.S3, error) {\n\t\/\/ Make the auth\n\tif *awsAccessKeyId == \"\" {\n\t\treturn nil, errors.New(\"Need -aws-access-key-id or environmental variable AWS_ACCESS_KEY_ID\")\n\t}\n\tif *awsSecretAccessKey == \"\" {\n\t\treturn nil, errors.New(\"Need -aws-secret-access-key or environmental variable AWS_SECRET_ACCESS_KEY\")\n\t}\n\tauth := aws.Auth{AccessKey: *awsAccessKeyId, SecretKey: *awsSecretAccessKey}\n\n\t\/\/ FIXME look through all the regions by name and use one of them if found\n\n\t\/\/ Synthesize the region\n\tif *s3Endpoint == \"\" {\n\t\t*s3Endpoint = \"https:\/\/s3.amazonaws.com\/\"\n\t}\n\tregion := aws.Region{\n\t\tName:                 \"s3\",\n\t\tS3Endpoint:           *s3Endpoint,\n\t\tS3LocationConstraint: false,\n\t}\n\tif *s3LocationConstraint != \"\" {\n\t\tregion.Name = *s3LocationConstraint\n\t\tregion.S3LocationConstraint = true\n\t}\n\n\tc := s3.New(auth, region)\n\treturn c, nil\n}\n\n\/\/ NewFsS3 contstructs an FsS3 from the path, bucket:path\nfunc NewFsS3(path string) (*FsS3, error) {\n\tbucket, directory, err := s3ParsePath(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif directory != \"\" {\n\t\treturn nil, fmt.Errorf(\"Directories not supported yet in %q: %q\", path, directory)\n\t}\n\tc, err := s3Connection()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf := &FsS3{\n\t\tc:      c,\n\t\tbucket: bucket,\n\t\tb:      c.Bucket(bucket),\n\t\tperm:   s3.Private, \/\/ FIXME need user to specify\n\t}\n\treturn f, nil\n}\n\n\/\/ Return an FsObject from a path\n\/\/\n\/\/ May return nil if an error occurred\nfunc (f *FsS3) NewFsObjectWithInfo(remote string, info *s3.Key) FsObject {\n\tfs := &FsObjectS3{\n\t\ts3:     f,\n\t\tremote: remote,\n\t}\n\tif info != nil {\n\t\t\/\/ Set info but not meta\n\t\tvar err error\n\t\tfs.lastModified, err = time.Parse(time.RFC3339, info.LastModified)\n\t\tif err != nil {\n\t\t\tFsLog(fs, \"Failed to read last modified: %s\", err)\n\t\t\tfs.lastModified = time.Now()\n\t\t}\n\t\tfs.etag = info.ETag\n\t\tfs.bytes = info.Size\n\t} else {\n\t\terr := fs.readMetaData() \/\/ reads info and meta, returning an error\n\t\tif err != nil {\n\t\t\t\/\/ logged already FsDebug(\"Failed to read info: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fs\n}\n\n\/\/ Return an FsObject from a path\n\/\/\n\/\/ May return nil if an error occurred\nfunc (f *FsS3) NewFsObject(remote string) FsObject {\n\treturn f.NewFsObjectWithInfo(remote, nil)\n}\n\n\/\/ Walk the path returning a channel of FsObjects\nfunc (f *FsS3) List() FsObjectsChan {\n\tout := make(FsObjectsChan, *checkers)\n\tgo func() {\n\t\t\/\/ FIXME need to implement ALL loop\n\t\tobjects, err := f.b.List(\"\", \"\", \"\", 10000)\n\t\tif err != nil {\n\t\t\tstats.Error()\n\t\t\tlog.Printf(\"Couldn't read bucket %q: %s\", f.bucket, err)\n\t\t} else {\n\t\t\tfor i := range objects.Contents {\n\t\t\t\tobject := &objects.Contents[i]\n\t\t\t\tif fs := f.NewFsObjectWithInfo(object.Key, object); fs != nil {\n\t\t\t\t\tout <- fs\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\n\/\/ Lists the buckets\nfunc (f *FsS3) ListDir() FsDirChan {\n\tout := make(FsDirChan, *checkers)\n\tgo func() {\n\t\tdefer close(out)\n\t\tbuckets, err := f.c.ListBuckets()\n\t\tif err != nil {\n\t\t\tstats.Error()\n\t\t\tlog.Printf(\"Couldn't list buckets: %s\", err)\n\t\t} else {\n\t\t\tfor _, bucket := range buckets {\n\t\t\t\twhen, _ := time.Parse(time.RFC3339, bucket.CreationDate)\n\t\t\t\tout <- &FsDir{\n\t\t\t\t\tName:  bucket.Name,\n\t\t\t\t\tWhen:  when,\n\t\t\t\t\tBytes: -1,\n\t\t\t\t\tCount: -1,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\n\/\/ Put the FsObject into the bucket\nfunc (f *FsS3) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {\n\t\/\/ Temporary FsObject under construction\n\tfs := &FsObjectS3{s3: f, remote: remote}\n\n\t\/\/ Set the mtime in the headers\n\theaders := s3.Headers{\n\t\tmetaMtime: swift.TimeToFloatString(modTime),\n\t}\n\n\t\/\/ Guess the content type\n\tcontentType := mime.TypeByExtension(path.Ext(remote))\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/octet-stream\"\n\t}\n\n\t_, err := fs.s3.b.PutReaderHeaders(remote, in, size, contentType, f.perm, headers)\n\treturn fs, err\n}\n\n\/\/ Mkdir creates the bucket if it doesn't exist\nfunc (f *FsS3) Mkdir() error {\n\terr := f.b.PutBucket(f.perm)\n\tif err, ok := err.(*s3.Error); ok {\n\t\tif err.Code == \"BucketAlreadyOwnedByYou\" {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Rmdir deletes the bucket\n\/\/\n\/\/ Returns an error if it isn't empty\nfunc (f *FsS3) Rmdir() error {\n\treturn f.b.DelBucket()\n}\n\n\/\/ Return the precision\nfunc (fs *FsS3) Precision() time.Duration {\n\treturn time.Nanosecond\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Return the remote path\nfunc (fs *FsObjectS3) Remote() string {\n\treturn fs.remote\n}\n\n\/\/ Md5sum returns the Md5sum of an object returning a lowercase hex string\nfunc (fs *FsObjectS3) Md5sum() (string, error) {\n\treturn strings.Trim(strings.ToLower(fs.etag), `\"`), nil\n}\n\n\/\/ Size returns the size of an object in bytes\nfunc (fs *FsObjectS3) Size() int64 {\n\treturn fs.bytes\n}\n\n\/\/ readMetaData gets the metadata if it hasn't already been fetched\n\/\/\n\/\/ it also sets the info\nfunc (fs *FsObjectS3) readMetaData() (err error) {\n\tif fs.meta != nil {\n\t\treturn nil\n\t}\n\n\theaders, err := fs.s3.b.Head(fs.remote, nil)\n\tif err != nil {\n\t\tFsDebug(fs, \"Failed to read info: %s\", err)\n\t\treturn err\n\t}\n\tsize, err := strconv.ParseInt(headers[\"Content-Length\"], 10, 64)\n\tif err != nil {\n\t\tFsDebug(fs, \"Failed to read size from: %q\", headers)\n\t\treturn err\n\t}\n\tfs.etag = headers[\"Etag\"]\n\tfs.bytes = size\n\tfs.meta = headers\n\tif fs.lastModified, err = time.Parse(http.TimeFormat, headers[\"Last-Modified\"]); err != nil {\n\t\tFsLog(fs, \"Failed to read last modified from HEAD: %s\", err)\n\t\tfs.lastModified = time.Now()\n\t}\n\treturn nil\n}\n\n\/\/ ModTime returns the modification time of the object\n\/\/\n\/\/ It attempts to read the objects mtime and if that isn't present the\n\/\/ LastModified returned in the http headers\nfunc (fs *FsObjectS3) ModTime() time.Time {\n\terr := fs.readMetaData()\n\tif err != nil {\n\t\tFsLog(fs, \"Failed to read metadata: %s\", err)\n\t\treturn time.Now()\n\t}\n\t\/\/ read mtime out of metadata if available\n\td, ok := fs.meta[metaMtime]\n\tif !ok {\n\t\t\/\/ FsDebug(fs, \"No metadata\")\n\t\treturn fs.lastModified\n\t}\n\tmodTime, err := swift.FloatStringToTime(d)\n\tif err != nil {\n\t\tFsLog(fs, \"Failed to read mtime from object: %s\", err)\n\t\treturn fs.lastModified\n\t}\n\treturn modTime\n}\n\n\/\/ Sets the modification time of the local fs object\nfunc (fs *FsObjectS3) SetModTime(modTime time.Time) {\n\terr := fs.readMetaData()\n\tif err != nil {\n\t\tstats.Error()\n\t\tFsLog(fs, \"Failed to read metadata: %s\", err)\n\t\treturn\n\t}\n\tfs.meta[metaMtime] = swift.TimeToFloatString(modTime)\n\t_, err = fs.s3.b.Update(fs.remote, fs.s3.perm, fs.meta)\n\tif err != nil {\n\t\tstats.Error()\n\t\tFsLog(fs, \"Failed to update remote mtime: %s\", err)\n\t}\n}\n\n\/\/ Is this object storable\nfunc (fs *FsObjectS3) Storable() bool {\n\treturn true\n}\n\n\/\/ Open an object for read\nfunc (fs *FsObjectS3) Open() (in io.ReadCloser, err error) {\n\tin, err = fs.s3.b.GetReader(fs.remote)\n\treturn\n}\n\n\/\/ Remove an object\nfunc (fs *FsObjectS3) Remove() error {\n\treturn fs.s3.b.Del(fs.remote)\n}\n\n\/\/ Check the interfaces are satisfied\nvar _ Fs = &FsS3{}\nvar _ FsObject = &FsObjectS3{}\n<|endoftext|>"}
{"text":"<commit_before>package beanstalk\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Errors that can be returned by the beanstalk client functions.\nvar (\n\tErrBuried         = errors.New(\"Job is buried\")\n\tErrDraining       = errors.New(\"Server in draining mode\")\n\tErrExpectedCRLF   = errors.New(\"Expected CRLF after job body\")\n\tErrJobTooBig      = errors.New(\"Job body too big\")\n\tErrNotConnected   = errors.New(\"Not connected\")\n\tErrNotFound       = errors.New(\"Job not found\")\n\tErrNotIgnored     = errors.New(\"Tube cannot be ignored\")\n\tErrOutOfMemory    = errors.New(\"Server is out of memory\")\n\tErrUnexpectedResp = errors.New(\"Unexpected response from server\")\n)\n\n\/\/ Client implements a simple beanstalk API.\ntype Client struct {\n\toptions     Options\n\tconn        net.Conn\n\ttextConn    *textproto.Conn\n\tisConnected bool\n}\n\n\/\/ NewClient returns a new beanstalk Client object.\nfunc NewClient(conn net.Conn, options Options) *Client {\n\treturn &Client{\n\t\toptions:     SanitizeOptions(options),\n\t\tconn:        conn,\n\t\ttextConn:    textproto.NewConn(conn),\n\t\tisConnected: true}\n}\n\n\/\/ Close the connection to the beanstalk server.\nfunc (client *Client) Close() {\n\tif client.conn == nil {\n\t\treturn\n\t}\n\n\tclient.options.LogInfo(\"Closing connection to beanstalk server %s (local=%s)\", client.conn.RemoteAddr().String(), client.conn.LocalAddr().String())\n\tclient.conn.Close()\n\tclient.conn = nil\n}\n\n\/\/ Bury a reserved job. This is done after being unable to process the job and\n\/\/ it is likely that other consumers won't either.\nfunc (client *Client) Bury(job *Job, priority uint32) error {\n\t_, _, err := client.requestResponse(\"bury %d %d\", job.ID, priority)\n\tif err == ErrBuried {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\n\/\/ Delete a reserved job. This is done after successful processing.\nfunc (client *Client) Delete(job *Job) error {\n\t_, _, err := client.requestResponse(\"delete %d\", job.ID)\n\treturn err\n}\n\n\/\/ Ignore removes an active tube from the watch list.\nfunc (client *Client) Ignore(tube string) error {\n\t_, _, err := client.requestResponse(\"ignore %s\", tube)\n\treturn err\n}\n\n\/\/ Put a new job into beanstalk.\nfunc (client *Client) Put(putRequest *PutRequest) (uint64, error) {\n\tid, _, err := client.requestResponse(\"put %d %d %d %d\\r\\n%s\",\n\t\tputRequest.Params.Priority,\n\t\tputRequest.Params.Delay\/time.Second,\n\t\tputRequest.Params.TTR\/time.Second,\n\t\tlen(putRequest.Body),\n\t\tputRequest.Body)\n\n\treturn id, err\n}\n\n\/\/ Release a reserved job. This is done after being unable to process the job,\n\/\/ but another consumer might be successful.\nfunc (client *Client) Release(job *Job, priority uint32, delay time.Duration) error {\n\t_, _, err := client.requestResponse(\"release %d %d %d\", job.ID, priority, delay\/time.Second)\n\treturn err\n}\n\n\/\/ Reserve retrieves a new job.\nfunc (client *Client) Reserve() (*Job, error) {\n\terr := client.request(\"reserve-with-timeout %d\", client.options.ReserveTimeout\/time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Set a read deadline that is slightly longer than the reserve timeout.\n\tif client.options.ReserveTimeout != 0 {\n\t\tclient.conn.SetReadDeadline(time.Now().Add(client.options.ReserveTimeout + time.Second))\n\t\tdefer client.conn.SetReadDeadline(time.Time{})\n\t}\n\n\tjob := &Job{TTR: time.Second}\n\tjob.ID, job.Body, err = client.response()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif job.ID == 0 {\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Fetch the TTR value for this job via stats-job. If this fails, ignore it.\n\tif _, yaml, err := client.requestResponse(\"stats-job %d\", job.ID); err == nil {\n\t\tif val, err := yamlValue(yaml, \"pri\"); err == nil {\n\t\t\tif prio, err := strconv.ParseUint(val, 10, 32); err == nil {\n\t\t\t\tjob.Priority = uint32(prio)\n\t\t\t}\n\t\t}\n\n\t\tif val, err := yamlValue(yaml, \"ttr\"); err == nil {\n\t\t\tif ttr, err := strconv.Atoi(val); err == nil {\n\t\t\t\tjob.TTR = time.Duration(ttr) * time.Second\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Shave off 100 milliseconds to have some room to play with between touches.\n\tjob.TTR -= 100 * time.Millisecond\n\n\treturn job, nil\n}\n\n\/\/ Touch a job to extend the TTR of the reserved job.\nfunc (client *Client) Touch(job *Job) error {\n\t_, _, err := client.requestResponse(\"touch %d\", job.ID)\n\treturn err\n}\n\n\/\/ Use the specified tube for the upcoming put requests.\nfunc (client *Client) Use(tube string) error {\n\t_, _, err := client.requestResponse(\"use %s\", tube)\n\treturn err\n}\n\n\/\/ Watch adds a tube to the watch list.\nfunc (client *Client) Watch(tube string) error {\n\t_, _, err := client.requestResponse(\"watch %s\", tube)\n\treturn err\n}\n\n\/\/ request sends a request to the beanstalk server.\nfunc (client *Client) request(format string, args ...interface{}) error {\n\tif client.options.ReadWriteTimeout != 0 {\n\t\tclient.conn.SetWriteDeadline(time.Now().Add(client.options.ReadWriteTimeout))\n\t\tdefer client.conn.SetWriteDeadline(time.Time{})\n\t}\n\n\tif err := client.textConn.PrintfLine(format, args...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ response reads and parses a response from the beanstalk server.\nfunc (client *Client) response() (uint64, []byte, error) {\n\tline, err := client.textConn.ReadLine()\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\titems := strings.SplitN(line, \" \", 2)\n\tif len(items[0]) == 0 {\n\t\treturn 0, nil, ErrUnexpectedResp\n\t}\n\n\tvar response, rest = items[0], \"\"\n\tif len(items) == 2 {\n\t\trest = items[1]\n\t}\n\n\tswitch response {\n\t\/\/ Simple successful responses.\n\tcase \"DELETED\", \"RELEASED\", \"TIMED_OUT\", \"TOUCHED\", \"USING\", \"WATCHING\":\n\t\treturn 0, nil, nil\n\n\t\/\/ BURIED can either be a successful response to a _bury_ command or an\n\t\/\/ unsuccessful response to the _put_ and _release_ commands.\n\tcase \"BURIED\":\n\t\tif rest != \"\" {\n\t\t\t\/\/ The response to the _put_ command provides an id of the job.\n\t\t\tif id, err := strconv.ParseUint(rest, 10, 64); err == nil {\n\t\t\t\treturn id, nil, ErrBuried\n\t\t\t}\n\t\t}\n\n\t\treturn 0, nil, ErrBuried\n\n\t\/\/ INSERTED is a successful response to a _put_ command.\n\tcase \"INSERTED\":\n\t\tif id, err := strconv.ParseUint(rest, 10, 64); err == nil {\n\t\t\treturn id, nil, nil\n\t\t}\n\n\t\/\/ OK is a successful response to a request that responds with YAML data.\n\tcase \"OK\":\n\t\tif size, err := strconv.Atoi(rest); err == nil {\n\t\t\tbody := make([]byte, size+2)\n\t\t\tif _, err := io.ReadFull(client.textConn.R, body); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn 0, body[:size], nil\n\t\t}\n\n\t\/\/ A RESERVED response is a successful response to a _reserve_ command.\n\tcase \"RESERVED\":\n\t\tresInfo := strings.SplitN(rest, \" \", 2)\n\t\tif len(resInfo) != 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tid, err := strconv.ParseUint(resInfo[0], 10, 64)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tsize, err := strconv.Atoi(resInfo[1])\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tbody := make([]byte, size+2)\n\t\tif _, err := io.ReadFull(client.textConn.R, body); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn id, body[:size], nil\n\n\t\/\/ NOT_FOUND is a response to an unsuccessful _bury_, _delete_, _touch_ or\n\t\/\/ _release_ command.\n\tcase \"NOT_FOUND\":\n\t\treturn 0, nil, ErrNotFound\n\n\t\/\/ NOT_IGNORED is a response to an unsuccessful _ignore_ command.\n\tcase \"NOT_IGNORED\":\n\t\treturn 0, nil, ErrNotIgnored\n\n\t\/\/ The following responses can occur after an unsuccessful _put_ command.\n\tcase \"DRAINING\":\n\t\treturn 0, nil, ErrDraining\n\tcase \"EXPECTED_CRLF\":\n\t\treturn 0, nil, ErrExpectedCRLF\n\tcase \"JOB_TOO_BIG\":\n\t\treturn 0, nil, ErrJobTooBig\n\tcase \"OUT_OF_MEMORY\":\n\t\treturn 0, nil, ErrOutOfMemory\n\t}\n\n\treturn 0, nil, ErrUnexpectedResp\n}\n\n\/\/ requestResponse sends a request to the beanstalk server and then parses\n\/\/ and returns its response.\nfunc (client *Client) requestResponse(format string, args ...interface{}) (uint64, []byte, error) {\n\tif err := client.request(format, args...); err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif client.options.ReadWriteTimeout != 0 {\n\t\tclient.conn.SetReadDeadline(time.Now().Add(client.options.ReadWriteTimeout))\n\t\tdefer client.conn.SetReadDeadline(time.Time{})\n\t}\n\n\treturn client.response()\n}\n<commit_msg>Instead of returning error io.EOF, return ErrConnectionClosed which prints a nicer error message<commit_after>package beanstalk\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Errors that can be returned by the beanstalk client functions.\nvar (\n\tErrBuried           = errors.New(\"Job is buried\")\n\tErrConnectionClosed = errors.New(\"Remote end closed connection\")\n\tErrDraining         = errors.New(\"Server in draining mode\")\n\tErrExpectedCRLF     = errors.New(\"Expected CRLF after job body\")\n\tErrJobTooBig        = errors.New(\"Job body too big\")\n\tErrNotConnected     = errors.New(\"Not connected\")\n\tErrNotFound         = errors.New(\"Job not found\")\n\tErrNotIgnored       = errors.New(\"Tube cannot be ignored\")\n\tErrOutOfMemory      = errors.New(\"Server is out of memory\")\n\tErrUnexpectedResp   = errors.New(\"Unexpected response from server\")\n)\n\n\/\/ Client implements a simple beanstalk API.\ntype Client struct {\n\toptions     Options\n\tconn        net.Conn\n\ttextConn    *textproto.Conn\n\tisConnected bool\n}\n\n\/\/ NewClient returns a new beanstalk Client object.\nfunc NewClient(conn net.Conn, options Options) *Client {\n\treturn &Client{\n\t\toptions:     SanitizeOptions(options),\n\t\tconn:        conn,\n\t\ttextConn:    textproto.NewConn(conn),\n\t\tisConnected: true}\n}\n\n\/\/ Close the connection to the beanstalk server.\nfunc (client *Client) Close() {\n\tif client.conn == nil {\n\t\treturn\n\t}\n\n\tclient.options.LogInfo(\"Closing connection to beanstalk server %s (local=%s)\", client.conn.RemoteAddr().String(), client.conn.LocalAddr().String())\n\tclient.conn.Close()\n\tclient.conn = nil\n}\n\n\/\/ Bury a reserved job. This is done after being unable to process the job and\n\/\/ it is likely that other consumers won't either.\nfunc (client *Client) Bury(job *Job, priority uint32) error {\n\t_, _, err := client.requestResponse(\"bury %d %d\", job.ID, priority)\n\tif err == ErrBuried {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\n\/\/ Delete a reserved job. This is done after successful processing.\nfunc (client *Client) Delete(job *Job) error {\n\t_, _, err := client.requestResponse(\"delete %d\", job.ID)\n\treturn err\n}\n\n\/\/ Ignore removes an active tube from the watch list.\nfunc (client *Client) Ignore(tube string) error {\n\t_, _, err := client.requestResponse(\"ignore %s\", tube)\n\treturn err\n}\n\n\/\/ Put a new job into beanstalk.\nfunc (client *Client) Put(putRequest *PutRequest) (uint64, error) {\n\tid, _, err := client.requestResponse(\"put %d %d %d %d\\r\\n%s\",\n\t\tputRequest.Params.Priority,\n\t\tputRequest.Params.Delay\/time.Second,\n\t\tputRequest.Params.TTR\/time.Second,\n\t\tlen(putRequest.Body),\n\t\tputRequest.Body)\n\n\treturn id, err\n}\n\n\/\/ Release a reserved job. This is done after being unable to process the job,\n\/\/ but another consumer might be successful.\nfunc (client *Client) Release(job *Job, priority uint32, delay time.Duration) error {\n\t_, _, err := client.requestResponse(\"release %d %d %d\", job.ID, priority, delay\/time.Second)\n\treturn err\n}\n\n\/\/ Reserve retrieves a new job.\nfunc (client *Client) Reserve() (*Job, error) {\n\terr := client.request(\"reserve-with-timeout %d\", client.options.ReserveTimeout\/time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Set a read deadline that is slightly longer than the reserve timeout.\n\tif client.options.ReserveTimeout != 0 {\n\t\tclient.conn.SetReadDeadline(time.Now().Add(client.options.ReserveTimeout + time.Second))\n\t\tdefer client.conn.SetReadDeadline(time.Time{})\n\t}\n\n\tjob := &Job{TTR: time.Second}\n\tjob.ID, job.Body, err = client.response()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif job.ID == 0 {\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Fetch the TTR value for this job via stats-job. If this fails, ignore it.\n\tif _, yaml, err := client.requestResponse(\"stats-job %d\", job.ID); err == nil {\n\t\tif val, err := yamlValue(yaml, \"pri\"); err == nil {\n\t\t\tif prio, err := strconv.ParseUint(val, 10, 32); err == nil {\n\t\t\t\tjob.Priority = uint32(prio)\n\t\t\t}\n\t\t}\n\n\t\tif val, err := yamlValue(yaml, \"ttr\"); err == nil {\n\t\t\tif ttr, err := strconv.Atoi(val); err == nil {\n\t\t\t\tjob.TTR = time.Duration(ttr) * time.Second\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Shave off 100 milliseconds to have some room to play with between touches.\n\tjob.TTR -= 100 * time.Millisecond\n\n\treturn job, nil\n}\n\n\/\/ Touch a job to extend the TTR of the reserved job.\nfunc (client *Client) Touch(job *Job) error {\n\t_, _, err := client.requestResponse(\"touch %d\", job.ID)\n\treturn err\n}\n\n\/\/ Use the specified tube for the upcoming put requests.\nfunc (client *Client) Use(tube string) error {\n\t_, _, err := client.requestResponse(\"use %s\", tube)\n\treturn err\n}\n\n\/\/ Watch adds a tube to the watch list.\nfunc (client *Client) Watch(tube string) error {\n\t_, _, err := client.requestResponse(\"watch %s\", tube)\n\treturn err\n}\n\n\/\/ request sends a request to the beanstalk server.\nfunc (client *Client) request(format string, args ...interface{}) error {\n\tif client.options.ReadWriteTimeout != 0 {\n\t\tclient.conn.SetWriteDeadline(time.Now().Add(client.options.ReadWriteTimeout))\n\t\tdefer client.conn.SetWriteDeadline(time.Time{})\n\t}\n\n\tif err := client.textConn.PrintfLine(format, args...); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn ErrConnectionClosed\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ response reads and parses a response from the beanstalk server.\nfunc (client *Client) response() (uint64, []byte, error) {\n\tline, err := client.textConn.ReadLine()\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn 0, nil, ErrConnectionClosed\n\t\t}\n\t\treturn 0, nil, err\n\t}\n\n\titems := strings.SplitN(line, \" \", 2)\n\tif len(items[0]) == 0 {\n\t\treturn 0, nil, ErrUnexpectedResp\n\t}\n\n\tvar response, rest = items[0], \"\"\n\tif len(items) == 2 {\n\t\trest = items[1]\n\t}\n\n\tswitch response {\n\t\/\/ Simple successful responses.\n\tcase \"DELETED\", \"RELEASED\", \"TIMED_OUT\", \"TOUCHED\", \"USING\", \"WATCHING\":\n\t\treturn 0, nil, nil\n\n\t\/\/ BURIED can either be a successful response to a _bury_ command or an\n\t\/\/ unsuccessful response to the _put_ and _release_ commands.\n\tcase \"BURIED\":\n\t\tif rest != \"\" {\n\t\t\t\/\/ The response to the _put_ command provides an id of the job.\n\t\t\tif id, err := strconv.ParseUint(rest, 10, 64); err == nil {\n\t\t\t\treturn id, nil, ErrBuried\n\t\t\t}\n\t\t}\n\n\t\treturn 0, nil, ErrBuried\n\n\t\/\/ INSERTED is a successful response to a _put_ command.\n\tcase \"INSERTED\":\n\t\tif id, err := strconv.ParseUint(rest, 10, 64); err == nil {\n\t\t\treturn id, nil, nil\n\t\t}\n\n\t\/\/ OK is a successful response to a request that responds with YAML data.\n\tcase \"OK\":\n\t\tif size, err := strconv.Atoi(rest); err == nil {\n\t\t\tbody := make([]byte, size+2)\n\t\t\tif _, err := io.ReadFull(client.textConn.R, body); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\treturn 0, body[:size], nil\n\t\t}\n\n\t\/\/ A RESERVED response is a successful response to a _reserve_ command.\n\tcase \"RESERVED\":\n\t\tresInfo := strings.SplitN(rest, \" \", 2)\n\t\tif len(resInfo) != 2 {\n\t\t\tbreak\n\t\t}\n\n\t\tid, err := strconv.ParseUint(resInfo[0], 10, 64)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tsize, err := strconv.Atoi(resInfo[1])\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tbody := make([]byte, size+2)\n\t\tif _, err := io.ReadFull(client.textConn.R, body); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\treturn id, body[:size], nil\n\n\t\/\/ NOT_FOUND is a response to an unsuccessful _bury_, _delete_, _touch_ or\n\t\/\/ _release_ command.\n\tcase \"NOT_FOUND\":\n\t\treturn 0, nil, ErrNotFound\n\n\t\/\/ NOT_IGNORED is a response to an unsuccessful _ignore_ command.\n\tcase \"NOT_IGNORED\":\n\t\treturn 0, nil, ErrNotIgnored\n\n\t\/\/ The following responses can occur after an unsuccessful _put_ command.\n\tcase \"DRAINING\":\n\t\treturn 0, nil, ErrDraining\n\tcase \"EXPECTED_CRLF\":\n\t\treturn 0, nil, ErrExpectedCRLF\n\tcase \"JOB_TOO_BIG\":\n\t\treturn 0, nil, ErrJobTooBig\n\tcase \"OUT_OF_MEMORY\":\n\t\treturn 0, nil, ErrOutOfMemory\n\t}\n\n\treturn 0, nil, ErrUnexpectedResp\n}\n\n\/\/ requestResponse sends a request to the beanstalk server and then parses\n\/\/ and returns its response.\nfunc (client *Client) requestResponse(format string, args ...interface{}) (uint64, []byte, error) {\n\tif err := client.request(format, args...); err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif client.options.ReadWriteTimeout != 0 {\n\t\tclient.conn.SetReadDeadline(time.Now().Add(client.options.ReadWriteTimeout))\n\t\tdefer client.conn.SetReadDeadline(time.Time{})\n\t}\n\n\treturn client.response()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/xyproto\/browserspeak\"\n\t\"github.com\/xyproto\/genericsite\"\n\t\"github.com\/xyproto\/siteengines\"\n\t\"github.com\/xyproto\/web\"\n)\n\n\/\/ TODO: Norwegian everywhere\n\/\/ TODO: Different Redis database than the other sites\n\nconst JQUERY_VERSION = \"2.0.0\"\n\nfunc notFound2(ctx *web.Context, val string) {\n\tctx.ResponseWriter.WriteHeader(404)\n\tctx.ResponseWriter.Write([]byte(browserspeak.NotFound(ctx, val)))\n}\n\nfunc ServeEngines(userState *genericsite.UserState, mainMenuEntries genericsite.MenuEntries) {\n\t\/\/ The user engine\n\tuserEngine := siteengines.NewUserEngine(userState)\n\tuserEngine.ServePages()\n\n\t\/\/ The admin engine\n\tadminEngine := siteengines.NewAdminEngine(userState)\n\tadminEngine.ServePages(FTLSBaseCP, mainMenuEntries)\n\n\t\/\/ Wiki engine\n\twikiEngine := siteengines.NewWikiEngine(userState)\n\twikiEngine.ServePages(FTLSBaseCP, mainMenuEntries)\n}\n\n\/\/ TODO: Separate database for each site\nfunc main() {\n\n\t\/\/ UserState with a Redis Connection Pool\n\tuserState := genericsite.NewUserState()\n\tdefer userState.Close()\n\n\t\/\/ The archlinux.no webpage,\n\tmainMenuEntries := ServeFTLS(userState, \"\/js\/jquery-\"+JQUERY_VERSION+\".min.js\")\n\n\tServeEngines(userState, mainMenuEntries)\n\n\t\/\/ Compilation errors, vim-compatible filename\n\tweb.Get(\"\/error\", browserspeak.GenerateErrorHandle(\"errors.err\"))\n\tweb.Get(\"\/errors\", browserspeak.GenerateErrorHandle(\"errors.err\"))\n\n\t\/\/ Various .php and .asp urls that showed up in the log\n\tgenericsite.ServeForFun()\n\n\t\/\/ TODO: Incorporate this check into web.go, to only return\n\t\/\/ stuff in the header when the HEAD method is requested:\n\t\/\/ if ctx.Request.Method == \"HEAD\" { return }\n\t\/\/ See also: curl -I\n\n\t\/\/ Serve on port 3002 for the Nginx instance to use\n\tweb.Run(\"0.0.0.0:3002\")\n}\n<commit_msg>Minor changes<commit_after>package main\n\nimport (\n\t\"github.com\/xyproto\/browserspeak\"\n\t\"github.com\/xyproto\/genericsite\"\n\t\"github.com\/xyproto\/siteengines\"\n\t\"github.com\/xyproto\/web\"\n)\n\n\/\/ TODO: Norwegian everywhere\n\/\/ TODO: Different Redis database than the other sites\n\nconst JQUERY_VERSION = \"2.0.0\"\n\nfunc notFound2(ctx *web.Context, val string) {\n\tctx.ResponseWriter.WriteHeader(404)\n\tctx.ResponseWriter.Write([]byte(browserspeak.NotFound(ctx, val)))\n}\n\nfunc ServeEngines(userState *genericsite.UserState, mainMenuEntries genericsite.MenuEntries) {\n\t\/\/ The user engine\n\tuserEngine := siteengines.NewUserEngine(userState)\n\tuserEngine.ServePages(\"ftls2.roboticoverlords.org\")\n\n\t\/\/ The admin engine\n\tadminEngine := siteengines.NewAdminEngine(userState)\n\tadminEngine.ServePages(FTLSBaseCP, mainMenuEntries)\n\n\t\/\/ Wiki engine\n\twikiEngine := siteengines.NewWikiEngine(userState)\n\twikiEngine.ServePages(FTLSBaseCP, mainMenuEntries)\n}\n\n\/\/ TODO: Separate database for each site\nfunc main() {\n\n\t\/\/ UserState with a Redis Connection Pool\n\tuserState := genericsite.NewUserState()\n\tdefer userState.Close()\n\n\t\/\/ The archlinux.no webpage,\n\tmainMenuEntries := ServeFTLS(userState, \"\/js\/jquery-\"+JQUERY_VERSION+\".min.js\")\n\n\tServeEngines(userState, mainMenuEntries)\n\n\t\/\/ Compilation errors, vim-compatible filename\n\tweb.Get(\"\/error\", browserspeak.GenerateErrorHandle(\"errors.err\"))\n\tweb.Get(\"\/errors\", browserspeak.GenerateErrorHandle(\"errors.err\"))\n\n\t\/\/ Various .php and .asp urls that showed up in the log\n\tgenericsite.ServeForFun()\n\n\t\/\/ TODO: Incorporate this check into web.go, to only return\n\t\/\/ stuff in the header when the HEAD method is requested:\n\t\/\/ if ctx.Request.Method == \"HEAD\" { return }\n\t\/\/ See also: curl -I\n\n\t\/\/ Serve on port 3002 for the Nginx instance to use\n\tweb.Run(\"0.0.0.0:3002\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package prompter\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ Prompt simple prompting\nfunc Prompt(message, defaultAnswer string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tDefault: defaultAnswer,\n\t}).Prompt()\n}\n\n\/\/ YN y\/n choice\nfunc YN(message string, yes bool) bool {\n\tdefaultChoice := \"n\"\n\tif yes {\n\t\tdefaultChoice = \"y\"\n\t}\n\tinput := (&Prompter{\n\t\tMessage:    message,\n\t\tChoices:    []string{\"y\", \"n\"},\n\t\tIgnoreCase: true,\n\t\tDefault:    defaultChoice,\n\t}).Prompt()\n\n\treturn strings.ToLower(input) == \"y\"\n}\n\n\/\/ YesNo yes\/no choice\nfunc YesNo(message string, yes bool) bool {\n\tdefaultChoice := \"no\"\n\tif yes {\n\t\tdefaultChoice = \"yes\"\n\t}\n\tinput := (&Prompter{\n\t\tMessage:    message,\n\t\tChoices:    []string{\"yes\", \"no\"},\n\t\tIgnoreCase: true,\n\t\tDefault:    defaultChoice,\n\t}).Prompt()\n\n\treturn strings.ToLower(input) == \"yes\"\n}\n\n\/\/ Password asks password\nfunc Password(message string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tNoEcho:  true,\n\t}).Prompt()\n}\n\n\/\/ Choose make a choice\nfunc Choose(message string, choices []string, defaultChoice string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tChoices: choices,\n\t\tDefault: defaultChoice,\n\t}).Prompt()\n}\n\n\/\/ Regexp checks the answer by regexp\nfunc Regexp(message string, reg *regexp.Regexp, defaultAnswer string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tRegexp:  reg,\n\t\tDefault: defaultAnswer,\n\t}).Prompt()\n}\n<commit_msg>Make yes no prompts clearer<commit_after>package prompter\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ Prompt simple prompting\nfunc Prompt(message, defaultAnswer string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tDefault: defaultAnswer,\n\t}).Prompt()\n}\n\n\/\/ YN y\/n choice\nfunc YN(message string, defaultToYes bool) bool {\n\tdefaultChoice := \"n\"\n\tif defaultToYes {\n\t\tdefaultChoice = \"y\"\n\t}\n\tinput := (&Prompter{\n\t\tMessage:    message,\n\t\tChoices:    []string{\"y\", \"n\"},\n\t\tIgnoreCase: true,\n\t\tDefault:    defaultChoice,\n\t}).Prompt()\n\n\treturn strings.ToLower(input) == \"y\"\n}\n\n\/\/ YesNo yes\/no choice\nfunc YesNo(message string, defaultToYes bool) bool {\n\tdefaultChoice := \"no\"\n\tif defaultToYes {\n\t\tdefaultChoice = \"yes\"\n\t}\n\tinput := (&Prompter{\n\t\tMessage:    message,\n\t\tChoices:    []string{\"yes\", \"no\"},\n\t\tIgnoreCase: true,\n\t\tDefault:    defaultChoice,\n\t}).Prompt()\n\n\treturn strings.ToLower(input) == \"yes\"\n}\n\n\/\/ Password asks password\nfunc Password(message string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tNoEcho:  true,\n\t}).Prompt()\n}\n\n\/\/ Choose make a choice\nfunc Choose(message string, choices []string, defaultChoice string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tChoices: choices,\n\t\tDefault: defaultChoice,\n\t}).Prompt()\n}\n\n\/\/ Regexp checks the answer by regexp\nfunc Regexp(message string, reg *regexp.Regexp, defaultAnswer string) string {\n\treturn (&Prompter{\n\t\tMessage: message,\n\t\tRegexp:  reg,\n\t\tDefault: defaultAnswer,\n\t}).Prompt()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Go (cgo) interface to libgeoip *\/\npackage geoip\n\n\/*\n#cgo CFLAGS: -I\/opt\/local\/include -I\/usr\/local\/include -I\/usr\/include\n#cgo LDFLAGS: -lGeoIP -L\/opt\/local\/lib -L\/usr\/local\/lib -L\/usr\/lib\n#include <stdio.h>\n#include <errno.h>\n#include <GeoIP.h>\n#include <GeoIPCity.h>\n\n\/\/typedef GeoIP* GeoIP_pnt\n*\/\nimport \"C\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype GeoIP struct {\n\tdb *C.GeoIP\n\tmu sync.Mutex\n}\n\nfunc (gi *GeoIP) free() {\n\tif gi == nil {\n\t\treturn\n\t}\n\tif gi.db == nil {\n\t\tgi = nil\n\t\treturn\n\t}\n\tC.GeoIP_delete(gi.db)\n\tgi = nil\n\treturn\n}\n\n\/\/ Opens a GeoIP database by filename, all formats supported by libgeoip are\n\/\/ supported though there are only functions to access some of the databases in this API.\n\/\/ The database is opened in MEMORY_CACHE mode, if you need to optimize for memory\n\/\/ instead of performance you should change this.\n\/\/ If you don't pass a filename, it will try opening the database from\n\/\/ a list of common paths.\nfunc Open(files ...string) (*GeoIP, error) {\n\tif len(files) == 0 {\n\t\tfiles = []string{\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ Linux default\n\t\t\t\"\/usr\/share\/local\/GeoIP\/GeoIP.dat\", \/\/ source install?\n\t\t\t\"\/usr\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ FreeBSD\n\t\t\t\"\/opt\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ MacPorts\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ ArchLinux\n\t\t}\n\t}\n\n\tg := &GeoIP{}\n\truntime.SetFinalizer(g, (*GeoIP).free)\n\n\tvar err error\n\n\tfor _, file := range files {\n\n\t\t\/\/ libgeoip prints errors if it can't open the file, so check first\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcbase := C.CString(file)\n\t\tdefer C.free(unsafe.Pointer(cbase))\n\n\t\tg.db, err = C.GeoIP_open(cbase, C.GEOIP_MEMORY_CACHE)\n\t\tif g.db != nil && err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening GeoIP database (%s): %s\", files, err)\n\t}\n\n\tif g.db == nil {\n\t\treturn nil, fmt.Errorf(\"Didn't open GeoIP database (%s)\", files)\n\t}\n\n\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\treturn g, nil\n}\n\n\/\/ SetCustomDirectory sets the default location for the GeoIP .dat files used when\n\/\/ calling OpenType()\nfunc SetCustomDirectory(dir string) {\n\tcdir := C.CString(dir)\n\tdefer C.free(unsafe.Pointer(cdir))\n\tC.GeoIP_setup_custom_directory(cdir)\n}\n\n\/\/ OpenType opens a specified GeoIP database type in the default location. Constants\n\/\/ are defined for each database type (for example GEOIP_COUNTRY_EDITION).\nfunc OpenType(dbType int) (*GeoIP, error) {\n\tg := &GeoIP{}\n\truntime.SetFinalizer(g, (*GeoIP).free)\n\n\tvar err error\n\n\tg.db, err = C.GeoIP_open_type(C.int(dbType), C.GEOIP_MEMORY_CACHE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening GeoIP database (%d): %s\", dbType, err)\n\t}\n\n\tif g.db == nil {\n\t\treturn nil, fmt.Errorf(\"Didn't open GeoIP database (%d)\", dbType)\n\t}\n\n\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\n\treturn g, nil\n}\n\n\/\/ Takes an IPv4 address string and returns the organization name for that IP.\n\/\/ Requires the GeoIP organization database.\nfunc (gi *GeoIP) GetOrg(ip string) string {\n\tname, _ := gi.GetName(ip)\n\treturn name\n}\n\n\/\/ Works on the ASN, Netspeed, Organization and probably other\n\/\/ databases, takes and IP string and returns a \"name\" and the\n\/\/ netmask.\nfunc (gi *GeoIP) GetName(ip string) (name string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tcname := C.GeoIP_name_by_addr(gi.db, cip)\n\n\tif cname != nil {\n\t\tname = C.GoString(cname)\n\t\tdefer C.free(unsafe.Pointer(cname))\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\ntype GeoIPRecord struct {\n\tCountryCode  string\n\tCountryCode3 string\n\tCountryName  string\n\tRegion       string\n\tCity         string\n\tPostalCode   string\n\tLatitude     float32\n\tLongitude    float32\n\t\/\/ DMACode       int\n\tAreaCode      int\n\tCharSet       int\n\tContinentCode string\n}\n\n\/\/ Returns the \"City Record\" for an IP address. Requires the GeoCity(Lite)\n\/\/ database - http:\/\/www.maxmind.com\/en\/city\nfunc (gi *GeoIP) GetRecord(ip string) *GeoIPRecord {\n\tif gi.db == nil {\n\t\treturn nil\n\t}\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\trecord := C.GeoIP_record_by_addr(gi.db, cip)\n\tif record == nil {\n\t\treturn nil\n\t}\n\t\/\/ defer C.free(unsafe.Pointer(record))\n\tdefer C.GeoIPRecord_delete(record)\n\trec := new(GeoIPRecord)\n\trec.CountryCode = C.GoString(record.country_code)\n\trec.CountryCode3 = C.GoString(record.country_code3)\n\trec.CountryName = C.GoString(record.country_name)\n\trec.Region = C.GoString(record.region)\n\trec.City = C.GoString(record.city)\n\trec.PostalCode = C.GoString(record.postal_code)\n\trec.Latitude = float32(record.latitude)\n\trec.Longitude = float32(record.longitude)\n\trec.AreaCode = int(record.area_code)\n\trec.CharSet = int(record.charset)\n\trec.ContinentCode = C.GoString(record.continent_code)\n\n\treturn rec\n}\n\n\/\/ Returns the country code and region code for an IP address. Requires\n\/\/ the GeoIP Region database.\nfunc (gi *GeoIP) GetRegion(ip string) (string, string) {\n\tif gi.db == nil {\n\t\treturn \"\", \"\"\n\t}\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tregion := C.GeoIP_region_by_addr(gi.db, cip)\n\tif region == nil {\n\t\treturn \"\", \"\"\n\t}\n\n\tcountryCode := C.GoString(&region.country_code[0])\n\tregionCode := C.GoString(&region.region[0])\n\tdefer C.free(unsafe.Pointer(region))\n\n\treturn countryCode, regionCode\n}\n\n\/\/ Returns the region name given a country code and region code\nfunc GetRegionName(countryCode, regionCode string) string {\n\n\tcc := C.CString(countryCode)\n\tdefer C.free(unsafe.Pointer(cc))\n\n\trc := C.CString(regionCode)\n\tdefer C.free(unsafe.Pointer(rc))\n\n\tregion := C.GeoIP_region_name_by_code(cc, rc)\n\tif region == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ it's a static string constant, don't free this\n\tregionName := C.GoString(region)\n\n\treturn regionName\n}\n\n\/\/ Same as GetName() but for IPv6 addresses.\nfunc (gi *GeoIP) GetNameV6(ip string) (name string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tcname := C.GeoIP_name_by_addr_v6(gi.db, cip)\n\n\tif cname != nil {\n\t\tname = C.GoString(cname)\n\t\tdefer C.free(unsafe.Pointer(cname))\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ Takes an IPv4 address string and returns the country code for that IP\n\/\/ and the netmask for that IP range.\nfunc (gi *GeoIP) GetCountry(ip string) (cc string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock() \/\/ Lock to make sure we get the right result from GeoIP_last_netmask\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tccountry := C.GeoIP_country_code_by_addr(gi.db, cip)\n\n\tif ccountry != nil {\n\t\tcc = C.GoString(ccountry)\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ GetCountry_v6 works the same as GetCountry except for IPv6 addresses, be sure to\n\/\/ load a database with IPv6 data to get any results.\nfunc (gi *GeoIP) GetCountry_v6(ip string) (cc string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tccountry := C.GeoIP_country_code_by_addr_v6(gi.db, cip)\n\tif ccountry != nil {\n\t\tcc = C.GoString(ccountry)\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n<commit_msg>Fix SetCustomDirectory<commit_after>\/* Go (cgo) interface to libgeoip *\/\npackage geoip\n\n\/*\n#cgo CFLAGS: -I\/opt\/local\/include -I\/usr\/local\/include -I\/usr\/include\n#cgo LDFLAGS: -lGeoIP -L\/opt\/local\/lib -L\/usr\/local\/lib -L\/usr\/lib\n#include <stdio.h>\n#include <errno.h>\n#include <GeoIP.h>\n#include <GeoIPCity.h>\n\n\/\/typedef GeoIP* GeoIP_pnt\n*\/\nimport \"C\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype GeoIP struct {\n\tdb *C.GeoIP\n\tmu sync.Mutex\n}\n\nfunc (gi *GeoIP) free() {\n\tif gi == nil {\n\t\treturn\n\t}\n\tif gi.db == nil {\n\t\tgi = nil\n\t\treturn\n\t}\n\tC.GeoIP_delete(gi.db)\n\tgi = nil\n\treturn\n}\n\n\/\/ Opens a GeoIP database by filename, all formats supported by libgeoip are\n\/\/ supported though there are only functions to access some of the databases in this API.\n\/\/ The database is opened in MEMORY_CACHE mode, if you need to optimize for memory\n\/\/ instead of performance you should change this.\n\/\/ If you don't pass a filename, it will try opening the database from\n\/\/ a list of common paths.\nfunc Open(files ...string) (*GeoIP, error) {\n\tif len(files) == 0 {\n\t\tfiles = []string{\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ Linux default\n\t\t\t\"\/usr\/share\/local\/GeoIP\/GeoIP.dat\", \/\/ source install?\n\t\t\t\"\/usr\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ FreeBSD\n\t\t\t\"\/opt\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ MacPorts\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ ArchLinux\n\t\t}\n\t}\n\n\tg := &GeoIP{}\n\truntime.SetFinalizer(g, (*GeoIP).free)\n\n\tvar err error\n\n\tfor _, file := range files {\n\n\t\t\/\/ libgeoip prints errors if it can't open the file, so check first\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcbase := C.CString(file)\n\t\tdefer C.free(unsafe.Pointer(cbase))\n\n\t\tg.db, err = C.GeoIP_open(cbase, C.GEOIP_MEMORY_CACHE)\n\t\tif g.db != nil && err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening GeoIP database (%s): %s\", files, err)\n\t}\n\n\tif g.db == nil {\n\t\treturn nil, fmt.Errorf(\"Didn't open GeoIP database (%s)\", files)\n\t}\n\n\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\treturn g, nil\n}\n\n\/\/ SetCustomDirectory sets the default location for the GeoIP .dat files used when\n\/\/ calling OpenType()\nfunc SetCustomDirectory(dir string) {\n\tcdir := C.CString(dir)\n\t\/\/ GeoIP doesn't copy the string, so don't free it when we're done here.\n\t\/\/ defer C.free(unsafe.Pointer(cdir))\n\tC.GeoIP_setup_custom_directory(cdir)\n}\n\n\/\/ OpenType opens a specified GeoIP database type in the default location. Constants\n\/\/ are defined for each database type (for example GEOIP_COUNTRY_EDITION).\nfunc OpenType(dbType int) (*GeoIP, error) {\n\tg := &GeoIP{}\n\truntime.SetFinalizer(g, (*GeoIP).free)\n\n\tvar err error\n\n\tg.db, err = C.GeoIP_open_type(C.int(dbType), C.GEOIP_MEMORY_CACHE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening GeoIP database (%d): %s\", dbType, err)\n\t}\n\n\tif g.db == nil {\n\t\treturn nil, fmt.Errorf(\"Didn't open GeoIP database (%d)\", dbType)\n\t}\n\n\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\n\treturn g, nil\n}\n\n\/\/ Takes an IPv4 address string and returns the organization name for that IP.\n\/\/ Requires the GeoIP organization database.\nfunc (gi *GeoIP) GetOrg(ip string) string {\n\tname, _ := gi.GetName(ip)\n\treturn name\n}\n\n\/\/ Works on the ASN, Netspeed, Organization and probably other\n\/\/ databases, takes and IP string and returns a \"name\" and the\n\/\/ netmask.\nfunc (gi *GeoIP) GetName(ip string) (name string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tcname := C.GeoIP_name_by_addr(gi.db, cip)\n\n\tif cname != nil {\n\t\tname = C.GoString(cname)\n\t\tdefer C.free(unsafe.Pointer(cname))\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\ntype GeoIPRecord struct {\n\tCountryCode  string\n\tCountryCode3 string\n\tCountryName  string\n\tRegion       string\n\tCity         string\n\tPostalCode   string\n\tLatitude     float32\n\tLongitude    float32\n\t\/\/ DMACode       int\n\tAreaCode      int\n\tCharSet       int\n\tContinentCode string\n}\n\n\/\/ Returns the \"City Record\" for an IP address. Requires the GeoCity(Lite)\n\/\/ database - http:\/\/www.maxmind.com\/en\/city\nfunc (gi *GeoIP) GetRecord(ip string) *GeoIPRecord {\n\tif gi.db == nil {\n\t\treturn nil\n\t}\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\trecord := C.GeoIP_record_by_addr(gi.db, cip)\n\tif record == nil {\n\t\treturn nil\n\t}\n\t\/\/ defer C.free(unsafe.Pointer(record))\n\tdefer C.GeoIPRecord_delete(record)\n\trec := new(GeoIPRecord)\n\trec.CountryCode = C.GoString(record.country_code)\n\trec.CountryCode3 = C.GoString(record.country_code3)\n\trec.CountryName = C.GoString(record.country_name)\n\trec.Region = C.GoString(record.region)\n\trec.City = C.GoString(record.city)\n\trec.PostalCode = C.GoString(record.postal_code)\n\trec.Latitude = float32(record.latitude)\n\trec.Longitude = float32(record.longitude)\n\trec.AreaCode = int(record.area_code)\n\trec.CharSet = int(record.charset)\n\trec.ContinentCode = C.GoString(record.continent_code)\n\n\treturn rec\n}\n\n\/\/ Returns the country code and region code for an IP address. Requires\n\/\/ the GeoIP Region database.\nfunc (gi *GeoIP) GetRegion(ip string) (string, string) {\n\tif gi.db == nil {\n\t\treturn \"\", \"\"\n\t}\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tregion := C.GeoIP_region_by_addr(gi.db, cip)\n\tif region == nil {\n\t\treturn \"\", \"\"\n\t}\n\n\tcountryCode := C.GoString(&region.country_code[0])\n\tregionCode := C.GoString(&region.region[0])\n\tdefer C.free(unsafe.Pointer(region))\n\n\treturn countryCode, regionCode\n}\n\n\/\/ Returns the region name given a country code and region code\nfunc GetRegionName(countryCode, regionCode string) string {\n\n\tcc := C.CString(countryCode)\n\tdefer C.free(unsafe.Pointer(cc))\n\n\trc := C.CString(regionCode)\n\tdefer C.free(unsafe.Pointer(rc))\n\n\tregion := C.GeoIP_region_name_by_code(cc, rc)\n\tif region == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ it's a static string constant, don't free this\n\tregionName := C.GoString(region)\n\n\treturn regionName\n}\n\n\/\/ Same as GetName() but for IPv6 addresses.\nfunc (gi *GeoIP) GetNameV6(ip string) (name string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tcname := C.GeoIP_name_by_addr_v6(gi.db, cip)\n\n\tif cname != nil {\n\t\tname = C.GoString(cname)\n\t\tdefer C.free(unsafe.Pointer(cname))\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ Takes an IPv4 address string and returns the country code for that IP\n\/\/ and the netmask for that IP range.\nfunc (gi *GeoIP) GetCountry(ip string) (cc string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock() \/\/ Lock to make sure we get the right result from GeoIP_last_netmask\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tccountry := C.GeoIP_country_code_by_addr(gi.db, cip)\n\n\tif ccountry != nil {\n\t\tcc = C.GoString(ccountry)\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ GetCountry_v6 works the same as GetCountry except for IPv6 addresses, be sure to\n\/\/ load a database with IPv6 data to get any results.\nfunc (gi *GeoIP) GetCountry_v6(ip string) (cc string, netmask int) {\n\tif gi.db == nil {\n\t\treturn\n\t}\n\n\tgi.mu.Lock()\n\tdefer gi.mu.Unlock()\n\n\tcip := C.CString(ip)\n\tdefer C.free(unsafe.Pointer(cip))\n\tccountry := C.GeoIP_country_code_by_addr_v6(gi.db, cip)\n\tif ccountry != nil {\n\t\tcc = C.GoString(ccountry)\n\t\tnetmask = int(C.GeoIP_last_netmask(gi.db))\n\t\treturn\n\t}\n\treturn\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\/\/ SetSkips 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\n\/\/ NoOutput checks if there is any output recorded on Stdout or Stderr\nfunc NoOutput() bool {\n\treturn OutString() == \"\" && ErrString() == \"\"\n}\n\n\/\/ NoOutput checks if there is any output recorded on Stdout or Stderr\n\/\/ for a given pdbg instance.\nfunc (pdbg *Pdbg) NoOutput() bool {\n\treturn pdbg.OutString() == \"\" && pdbg.ErrString() == \"\"\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\/\/ Perrdbgf uses Stderr for printing strings, with indent and function name\nfunc Perrdbgf(format string, args ...interface{}) string {\n\treturn pdbg.pdbgfw(format, os.Stderr, 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\treturn pdbg.pdbgfw(format, pdbg.Err(), args...)\n}\n\nfunc (pdbg *Pdbg) pdbgfw(format string, iow io.Writer, 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\nvar r = regexp.MustCompile(`:\\d+[\\)\\]]`)\nvar r2 = regexp.MustCompile(`func\\.\\d+[\\)\\]]`)\n\n\/\/ ShouldEqualNL is a custom goconvey assertion to ignore differences\n\/\/ with func id and lines: `[globalPdbgExcludeTest:16] (func.019:167)` would\n\/\/ be equal to [globalPdbgExcludeTest] (func)\n\/\/ (see https:\/\/github.com\/smartystreets\/goconvey\/wiki\/Custom-Assertions)\nfunc ShouldEqualNL(actual interface{}, expected ...interface{}) string {\n\ta := actual.(string)\n\te := expected[0].(string)\n\ta = r.ReplaceAllStringFunc(a, func(s string) string { return s[len(s)-1:] })\n\te = r.ReplaceAllStringFunc(e, func(s string) string { return s[len(s)-1:] })\n\ta = r2.ReplaceAllStringFunc(a, func(s string) string { return \"func\" + s[len(s)-1:] })\n\te = r2.ReplaceAllStringFunc(e, func(s string) string { return \"func\" + s[len(s)-1:] })\n\ta = strings.TrimRight(a, \"\\r\\n\")\n\te = strings.TrimRight(e, \"\\r\\n\")\n\tif a == e {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"Extected: '%s'\\nActual:   '%s'\\n(Should be equal even with different lines and function ids)\", e, a)\n}\n<commit_msg>godbg pdbgfw actually uses the io.Writer passed<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\/\/ SetSkips 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\n\/\/ NoOutput checks if there is any output recorded on Stdout or Stderr\nfunc NoOutput() bool {\n\treturn OutString() == \"\" && ErrString() == \"\"\n}\n\n\/\/ NoOutput checks if there is any output recorded on Stdout or Stderr\n\/\/ for a given pdbg instance.\nfunc (pdbg *Pdbg) NoOutput() bool {\n\treturn pdbg.OutString() == \"\" && pdbg.ErrString() == \"\"\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\/\/ Perrdbgf uses Stderr for printing strings, with indent and function name\nfunc Perrdbgf(format string, args ...interface{}) string {\n\treturn pdbg.pdbgfw(format, os.Stderr, 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\treturn pdbg.pdbgfw(format, pdbg.Err(), args...)\n}\n\nfunc (pdbg *Pdbg) pdbgfw(format string, iow io.Writer, 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(iow, fmt.Sprint(msg))\n\treturn res\n}\n\nvar r = regexp.MustCompile(`:\\d+[\\)\\]]`)\nvar r2 = regexp.MustCompile(`func\\.\\d+[\\)\\]]`)\n\n\/\/ ShouldEqualNL is a custom goconvey assertion to ignore differences\n\/\/ with func id and lines: `[globalPdbgExcludeTest:16] (func.019:167)` would\n\/\/ be equal to [globalPdbgExcludeTest] (func)\n\/\/ (see https:\/\/github.com\/smartystreets\/goconvey\/wiki\/Custom-Assertions)\nfunc ShouldEqualNL(actual interface{}, expected ...interface{}) string {\n\ta := actual.(string)\n\te := expected[0].(string)\n\ta = r.ReplaceAllStringFunc(a, func(s string) string { return s[len(s)-1:] })\n\te = r.ReplaceAllStringFunc(e, func(s string) string { return s[len(s)-1:] })\n\ta = r2.ReplaceAllStringFunc(a, func(s string) string { return \"func\" + s[len(s)-1:] })\n\te = r2.ReplaceAllStringFunc(e, func(s string) string { return \"func\" + s[len(s)-1:] })\n\ta = strings.TrimRight(a, \"\\r\\n\")\n\te = strings.TrimRight(e, \"\\r\\n\")\n\tif a == e {\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"Extected: '%s'\\nActual:   '%s'\\n(Should be equal even with different lines and function ids)\", e, a)\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorle\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc encode(s string) string {\n\tcount := 1\n\tvar o bytes.Buffer\n\tvar i int\n\tfor i = 0; i < len(s)-1; i++ {\n\t\tif s[i] == s[i+1] {\n\t\t\tcount++\n\t\t} else {\n\t\t\to.WriteString(fmt.Sprintf(\"%d%c\", count, s[i]))\n\t\t\tcount = 1\n\t\t}\n\t}\n\to.WriteString(fmt.Sprintf(\"%d%c\", count, s[i]))\n\treturn o.String()\n}\n\nfunc decode(s string) string {\n\tvar o bytes.Buffer\n\tvar count string\n\tfor i := 0; i < len(s); i++ {\n\t\tif val, _ := strconv.Atoi(string(s[i])); val > 0 && val <= 9 {\n\t\t\tif countN, err := strconv.Atoi(count); err == nil {\n\t\t\t\tcount = fmt.Sprintf(\"%d%d\", countN, val)\n\t\t\t} else {\n\t\t\t\tcount = string(s[i])\n\t\t\t}\n\t\t} else {\n\t\t\tcount2, _ := strconv.Atoi(count)\n\t\t\tfor j := 0; j < count2; j++ {\n\t\t\t\to.WriteString(fmt.Sprintf(\"%c\", s[i]))\n\t\t\t}\n\t\t\tcount = \"\"\n\t\t}\n\t}\n\treturn o.String()\n}\n<commit_msg>Capitalized<commit_after>package gorle\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc Encode(s string) string {\n\tcount := 1\n\tvar o bytes.Buffer\n\tvar i int\n\tfor i = 0; i < len(s)-1; i++ {\n\t\tif s[i] == s[i+1] {\n\t\t\tcount++\n\t\t} else {\n\t\t\to.WriteString(fmt.Sprintf(\"%d%c\", count, s[i]))\n\t\t\tcount = 1\n\t\t}\n\t}\n\to.WriteString(fmt.Sprintf(\"%d%c\", count, s[i]))\n\treturn o.String()\n}\n\nfunc Decode(s string) string {\n\tvar o bytes.Buffer\n\tvar count string\n\tfor i := 0; i < len(s); i++ {\n\t\tif val, _ := strconv.Atoi(string(s[i])); val > 0 && val <= 9 {\n\t\t\tif countN, err := strconv.Atoi(count); err == nil {\n\t\t\t\tcount = fmt.Sprintf(\"%d%d\", countN, val)\n\t\t\t} else {\n\t\t\t\tcount = string(s[i])\n\t\t\t}\n\t\t} else {\n\t\t\tcount2, _ := strconv.Atoi(count)\n\t\t\tfor j := 0; j < count2; j++ {\n\t\t\t\to.WriteString(fmt.Sprintf(\"%c\", s[i]))\n\t\t\t}\n\t\t\tcount = \"\"\n\t\t}\n\t}\n\treturn o.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package gospy\n\nimport (\n\t\"reflect\"\n\t\"github.com\/cfmobile\/gmock\"\n\t\"fmt\"\n)\n\ntype ParamList []interface{}\n\ntype CallList []ParamList\n\ntype GoSpy struct {\n\tCalled  bool\n\tCalls   CallList\n\tmock   *gmock.GMock\n}\n\nfunc (self *GoSpy) Restore() {\n\tself.mock.Restore()\n}\n\nfunc (self *GoSpy) Reset() {\n\tself.Called = false\n\tself.Calls = nil\n}\n\nfunc (self *GoSpy) storeCall(arguments []reflect.Value) {\n\tself.Called = true;\n\n\tvar call ParamList\n\tfor _, arg := range arguments {\n\t\tcall = append(call, arg.Interface())\n\t}\n\n\tself.Calls = append(self.Calls, call)\n}\n\nfunc Spy(targetFuncVar interface{}) *GoSpy {\n\tspy := createSpy(targetFuncVar)\n\tdefaultFn := spy.getDefaultFn()\n\tspy.setTargetFn(defaultFn)\n\treturn spy\n}\n\nfunc SpyAndFake(targetFuncVar interface{}) *GoSpy {\n\treturn SpyAndFakeWithReturn(targetFuncVar) \/\/nil fakeReturnValues will create default\n}\n\nfunc SpyAndFakeWithReturn(targetFuncVar interface{}, fakeReturnValues ...interface{}) *GoSpy {\n\tspy := createSpy(targetFuncVar)\n\tfakeReturnFn := spy.getFnWithReturnValues(fakeReturnValues)\n\tspy.setTargetFn(fakeReturnFn)\n\treturn spy\n}\n\nfunc SpyAndFakeWithFunc(targetFuncVar interface{}, mockFunc interface{}) *GoSpy {\n\ttargetType := reflect.ValueOf(targetFuncVar).Type()\n\tmockFuncType := reflect.ValueOf(mockFunc).Type()\n\n\tif targetType != mockFuncType {\n\t\tpanic(fmt.Sprintf(\"Fake function has to have the same signature as the target [target: %+v, mock: %+v]\", targetType, mockFuncType))\n\t}\n\n\tspy := createSpy(targetFuncVar)\n\tfakeFuncFn := spy.getFnWithMockFunc(mockFunc)\n\tspy.setTargetFn(fakeFuncFn)\n\treturn spy\n}\n\nfunc (self *GoSpy) setTargetFn(fn func(args []reflect.Value) []reflect.Value) {\n\ttargetType := self.mock.GetTarget().Type()\n\twrapperFn := func(args []reflect.Value) []reflect.Value {\n\t\tself.storeCall(args)\n\t\treturn reflect.MakeFunc(targetType, fn).Call(args)\n\t}\n\n\ttargetFn := reflect.MakeFunc(targetType, wrapperFn)\n\tself.mock.Replace(targetFn.Interface())\n}\n\nfunc (self *GoSpy) getDefaultFn() (func(args []reflect.Value) []reflect.Value) {\n\treturn self.mock.GetOriginal().Call\n}\n\nfunc (self *GoSpy) getFnWithReturnValues(fakeReturnValues []interface{}) (func(args []reflect.Value) []reflect.Value) {\n\t\/\/ Gets the expected number of return values from the target\n\tvar numReturnValues = self.mock.GetTarget().Type().NumOut()\n\n\tif fakeReturnValues != nil && numReturnValues != len(fakeReturnValues) {\n\t\tpanic(\"Invalid number of return values. Either specify all or none\")\n\t}\n\n\treturn func(args []reflect.Value) (results []reflect.Value) {\n\t\t\/\/ Builds slice of return values, if required\n\t\ttargetType := self.mock.GetTarget().Type()\n\t\tfor i := 0; i < numReturnValues; i++ {\n\t\t\treturnItem := reflect.New(targetType.Out(i))\n\n\t\t\tvar returnElem = returnItem.Elem()\n\n\t\t\t\/\/ Gets value for return from fakeReturnValues, or leaves default constructed value if not available\n\t\t\tif fakeReturnValues != nil && fakeReturnValues[i] != nil {\n\t\t\t\treturnElem.Set(reflect.ValueOf(fakeReturnValues[i]))\n\t\t\t}\n\n\t\t\tresults = append(results, returnElem)\n\t\t}\n\n\t\treturn results\n\t}\n}\n\nfunc (self *GoSpy) getFnWithMockFunc(mockFunc interface{}) (func(args []reflect.Value) []reflect.Value) {\n\tmockFuncValue := reflect.ValueOf(mockFunc)\n\tif !mockFuncValue.IsValid() {\n\t\ttargetType := self.mock.GetTarget().Type()\n\t\tmockFuncValue = reflect.Zero(targetType)\n\t}\n\n\treturn mockFuncValue.Call\n}\n\nfunc createSpy(targetFuncPtr interface{}) *GoSpy {\n\tif !targetIsValid(targetFuncPtr) {\n\t\tpanic(\"Spy target has to be the pointer to a Func variable\")\n\t}\n\n\tspy := &GoSpy{Called: false, Calls: nil, mock: gmock.CreateMockWithTarget(targetFuncPtr)}\n\n\treturn spy\n}\n\nfunc targetIsValid(target interface{}) bool {\n\t\/\/ Target has to be a ptr to a function\n\ttargetValue := reflect.ValueOf(target)\n\treturn targetValue.Kind() == reflect.Ptr &&\n\t\t   targetValue.Elem().Kind() == reflect.Func\n}<commit_msg>RS - Renamed ParamList type to ArgList<commit_after>package gospy\n\nimport (\n\t\"reflect\"\n\t\"github.com\/cfmobile\/gmock\"\n\t\"fmt\"\n)\n\ntype ArgList []interface{}\n\ntype CallList []ArgList\n\ntype GoSpy struct {\n\tCalled  bool\n\tCalls   CallList\n\tmock   *gmock.GMock\n}\n\nfunc (self *GoSpy) Restore() {\n\tself.mock.Restore()\n}\n\nfunc (self *GoSpy) Reset() {\n\tself.Called = false\n\tself.Calls = nil\n}\n\nfunc (self *GoSpy) storeCall(arguments []reflect.Value) {\n\tself.Called = true;\n\n\tvar call ArgList\n\tfor _, arg := range arguments {\n\t\tcall = append(call, arg.Interface())\n\t}\n\n\tself.Calls = append(self.Calls, call)\n}\n\nfunc Spy(targetFuncVar interface{}) *GoSpy {\n\tspy := createSpy(targetFuncVar)\n\tdefaultFn := spy.getDefaultFn()\n\tspy.setTargetFn(defaultFn)\n\treturn spy\n}\n\nfunc SpyAndFake(targetFuncVar interface{}) *GoSpy {\n\treturn SpyAndFakeWithReturn(targetFuncVar) \/\/nil fakeReturnValues will create default\n}\n\nfunc SpyAndFakeWithReturn(targetFuncVar interface{}, fakeReturnValues ...interface{}) *GoSpy {\n\tspy := createSpy(targetFuncVar)\n\tfakeReturnFn := spy.getFnWithReturnValues(fakeReturnValues)\n\tspy.setTargetFn(fakeReturnFn)\n\treturn spy\n}\n\nfunc SpyAndFakeWithFunc(targetFuncVar interface{}, mockFunc interface{}) *GoSpy {\n\ttargetType := reflect.ValueOf(targetFuncVar).Type()\n\tmockFuncType := reflect.ValueOf(mockFunc).Type()\n\n\tif targetType != mockFuncType {\n\t\tpanic(fmt.Sprintf(\"Fake function has to have the same signature as the target [target: %+v, mock: %+v]\", targetType, mockFuncType))\n\t}\n\n\tspy := createSpy(targetFuncVar)\n\tfakeFuncFn := spy.getFnWithMockFunc(mockFunc)\n\tspy.setTargetFn(fakeFuncFn)\n\treturn spy\n}\n\nfunc (self *GoSpy) setTargetFn(fn func(args []reflect.Value) []reflect.Value) {\n\ttargetType := self.mock.GetTarget().Type()\n\twrapperFn := func(args []reflect.Value) []reflect.Value {\n\t\tself.storeCall(args)\n\t\treturn reflect.MakeFunc(targetType, fn).Call(args)\n\t}\n\n\ttargetFn := reflect.MakeFunc(targetType, wrapperFn)\n\tself.mock.Replace(targetFn.Interface())\n}\n\nfunc (self *GoSpy) getDefaultFn() (func(args []reflect.Value) []reflect.Value) {\n\treturn self.mock.GetOriginal().Call\n}\n\nfunc (self *GoSpy) getFnWithReturnValues(fakeReturnValues []interface{}) (func(args []reflect.Value) []reflect.Value) {\n\t\/\/ Gets the expected number of return values from the target\n\tvar numReturnValues = self.mock.GetTarget().Type().NumOut()\n\n\tif fakeReturnValues != nil && numReturnValues != len(fakeReturnValues) {\n\t\tpanic(\"Invalid number of return values. Either specify all or none\")\n\t}\n\n\treturn func(args []reflect.Value) (results []reflect.Value) {\n\t\t\/\/ Builds slice of return values, if required\n\t\ttargetType := self.mock.GetTarget().Type()\n\t\tfor i := 0; i < numReturnValues; i++ {\n\t\t\treturnItem := reflect.New(targetType.Out(i))\n\n\t\t\tvar returnElem = returnItem.Elem()\n\n\t\t\t\/\/ Gets value for return from fakeReturnValues, or leaves default constructed value if not available\n\t\t\tif fakeReturnValues != nil && fakeReturnValues[i] != nil {\n\t\t\t\treturnElem.Set(reflect.ValueOf(fakeReturnValues[i]))\n\t\t\t}\n\n\t\t\tresults = append(results, returnElem)\n\t\t}\n\n\t\treturn results\n\t}\n}\n\nfunc (self *GoSpy) getFnWithMockFunc(mockFunc interface{}) (func(args []reflect.Value) []reflect.Value) {\n\tmockFuncValue := reflect.ValueOf(mockFunc)\n\tif !mockFuncValue.IsValid() {\n\t\ttargetType := self.mock.GetTarget().Type()\n\t\tmockFuncValue = reflect.Zero(targetType)\n\t}\n\n\treturn mockFuncValue.Call\n}\n\nfunc createSpy(targetFuncPtr interface{}) *GoSpy {\n\tif !targetIsValid(targetFuncPtr) {\n\t\tpanic(\"Spy target has to be the pointer to a Func variable\")\n\t}\n\n\tspy := &GoSpy{Called: false, Calls: nil, mock: gmock.CreateMockWithTarget(targetFuncPtr)}\n\n\treturn spy\n}\n\nfunc targetIsValid(target interface{}) bool {\n\t\/\/ Target has to be a ptr to a function\n\ttargetValue := reflect.ValueOf(target)\n\treturn targetValue.Kind() == reflect.Ptr &&\n\t\t   targetValue.Elem().Kind() == reflect.Func\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 graph\n\n\/\/ All a node needs to do is identify itself. This allows the user to pass in nodes more\n\/\/ interesting than an int, but also allow us to reap the benefits of having a map-storable,\n\/\/ ==able type.\ntype Node interface {\n\tID() int\n}\n\n\/\/ Allows edges to do something more interesting that just be a group of nodes. While the methods\n\/\/ are called Head and Tail, they are not considered directed unless the given interface specifies\n\/\/ otherwise.\ntype Edge interface {\n\tHead() Node\n\tTail() Node\n}\n\n\/\/ A Graph implements the behavior of an undirected graph.\n\/\/\n\/\/ All methods in Graph are implicitly undirected. Graph algorithms that care about directionality\n\/\/ will intelligently choose the DirectedGraph behavior if that interface is also implemented,\n\/\/ even if the function itself only takes in a Graph (or a super-interface of graph).\ntype Graph interface {\n\t\/\/ NodeExists returns true when node is currently in the graph.\n\tNodeExists(Node) bool\n\n\t\/\/ NodeList returns a list of all nodes in no particular order, useful for\n\t\/\/ determining things like if a graph is fully connected. The caller is\n\t\/\/ free to modify this list. Implementations should construct a new list\n\t\/\/ and not return internal representation.\n\tNodeList() []Node\n\n\t\/\/ Neighbors returns all nodes connected by any edge to this node.\n\tNeighbors(Node) []Node\n\n\t\/\/ EdgeBetween returns an edge between node and neighbor such that\n\t\/\/ Head is one argument and Tail is the other. If no\n\t\/\/ such edge exists, this function returns nil.\n\tEdgeBetween(node, neighbor Node) Edge\n}\n\n\/\/ Directed graphs are characterized by having seperable Heads and Tails in their edges.\n\/\/ That is, if node1 goes to node2, that does not necessarily imply that node2 goes to node1.\n\/\/\n\/\/ While it's possible for a directed graph to have fully reciprocal edges (i.e. the graph is\n\/\/ symmetric) -- it is not required to be. The graph is also required to implement Graph\n\/\/ because in many cases it can be useful to know all neighbors regardless of direction.\ntype DirectedGraph interface {\n\tGraph\n\t\/\/ Successors gives the nodes connected by OUTBOUND edges.\n\t\/\/ If the graph is an undirected graph, this set is equal to Predecessors.\n\tSuccessors(Node) []Node\n\n\t\/\/ EdgeTo returns an edge between node and successor such that\n\t\/\/ Head returns node and Tail returns successor, if no\n\t\/\/ such edge exists, this function returns nil.\n\tEdgeTo(node, successor Node) Edge\n\n\t\/\/ Predecessors gives the nodes connected by INBOUND edges.\n\t\/\/ If the graph is an undirected graph, this set is equal to Successors.\n\tPredecessors(Node) []Node\n}\n\n\/\/ Returns all undirected edges in the graph\ntype EdgeLister interface {\n\tEdgeList() []Edge\n}\n\ntype EdgeListGraph interface {\n\tGraph\n\tEdgeLister\n}\n\n\/\/ Returns all directed edges in the graph.\ntype DirectedEdgeLister interface {\n\tDirectedEdgeList() []Edge\n}\n\ntype DirectedEdgeListGraph interface {\n\tGraph\n\tDirectedEdgeLister\n}\n\n\/\/ A crunch graph forces a sparse graph to become a dense graph. That is, if the node IDs are\n\/\/ [1,4,9,7] it would \"crunch\" the ids into the contiguous block [0,1,2,3]. Order is not\n\/\/ required to be preserved between the non-cruched and crunched instances (that means in\n\/\/ the example above 0 may correspond to 4 or 7 or 9, not necessarily 1).\n\/\/\n\/\/ All dense graphs must have the first ID as 0.\ntype CrunchGraph interface {\n\tGraph\n\tCrunch()\n}\n\n\/\/ A Graph that implements Coster has an actual cost between adjacent nodes, also known as a\n\/\/ weighted graph. If a graph implements coster and a function needs to read cost (e.g. A*),\n\/\/ this function will take precedence over the Uniform Cost function (all weights are 1) if \"nil\"\n\/\/ is passed in for the function argument.\n\/\/\n\/\/ If the argument is nil, or the edge is invalid for some reason, this should return math.Inf(1)\ntype Coster interface {\n\tCost(edge Edge) float64\n}\n\ntype CostGraph interface {\n\tCoster\n\tGraph\n}\n\ntype CostDirectedGraph interface {\n\tCoster\n\tDirectedGraph\n}\n\n\/\/ A graph that implements HeuristicCoster implements a heuristic between any two given nodes.\n\/\/ Like Coster, if a graph implements this and a function needs a heuristic cost (e.g. A*), this\n\/\/ function will take precedence over the Null Heuristic (always returns 0) if \"nil\" is passed in\n\/\/ for the function argument. If HeuristicCost is not intended to be used, it can be implemented as\n\/\/ the null heuristic (always returns 0.)\ntype HeuristicCoster interface {\n\t\/\/ HeuristicCost returns a heuristic cost between any two nodes.\n\tHeuristicCost(node1, node2 Node) float64\n}\n\n\/\/ A Mutable is a graph that can have arbitrary nodes and edges added or removed.\n\/\/\n\/\/ Anything implementing Mutable is required to store the actual argument. So if AddNode(myNode) is\n\/\/ called and later a user calls on the graph graph.NodeList(), the node added by AddNode must be\n\/\/ an the exact node, not a new node with the same ID.\n\/\/\n\/\/ In any case where conflict is possible (e.g. adding two nodes with the same ID), the later\n\/\/ call always supercedes the earlier one.\n\/\/\n\/\/ Functions will generally expect one of MutableGraph or MutableDirectedGraph and not Mutable\n\/\/ itself. That said, any function that takes Mutable[x], the destination mutable should\n\/\/ always be a different graph than the source.\ntype Mutable interface {\n\t\/\/ NewNode adds a node with an arbitrary ID and returns the new, unique ID\n\t\/\/ used.\n\tNewNode() Node\n\n\t\/\/ Adds a node to the graph. If this is called multiple times for the same ID, the newer node\n\t\/\/ overwrites the old one.\n\tAddNode(Node)\n\n\t\/\/ EmptyGraph clears the graph of all nodes and edges.\n\tEmptyGraph()\n\n\t\/\/ RemoveNode removes a node from the graph, as well as any edges\n\t\/\/ attached to it. If no such node exists, this is a no-op, not an error.\n\tRemoveNode(Node)\n}\n\n\/\/ MutableGraph is an interface ensuring the implementation of the ability to construct\n\/\/ an arbitrary undirected graph. It is very important to note that any implementation\n\/\/ of MutableGraph absolutely cannot safely implement the DirectedGraph interface.\n\/\/\n\/\/ A MutableGraph is required to store any Edge argument in the same way Mutable must\n\/\/ store a Node argument -- any retrieval call is required to return the exact supplied edge.\n\/\/ This is what makes it incompatible with DirectedGraph.\n\/\/\n\/\/ A call to AddEdgeBetween(Edge{head,tail}) make is so there is simply no way to safely\n\/\/ return EdgeTo(tail, head) since the edge returned will, by this contract, need to be\n\/\/ Head() == head and Tail() == tail when the reverse must be true to fulfill the\n\/\/ functionality guaranteed of EdgeTo.\ntype MutableGraph interface {\n\tCostGraph\n\tMutable\n\n\t\/\/ Like EdgeBetween in Graph, AddEdgeBetween adds an edge between two nodes.\n\t\/\/ If one or both nodes do not exist, the Graph is expected to add them.\n\tAddEdgeBetween(e Edge, cost float64)\n\n\t\/\/ RemoveEdge clears the stored edge between two nodes. Calling this will never\n\t\/\/ remove a node. If the edge does not exist this is a no-op, not an error.\n\tRemoveEdgeBetween(e Edge)\n}\n\n\/\/ MutableDirectedGraph is an interface that ensures one can construct an arbitrary directed\n\/\/ graph. Naturally, a MutableDirectedGraph works for both undirected and directed cases,\n\/\/ but simply using a MutableGraph may be cleaner. As the documentation for MutableGraph\n\/\/ notes, however, a graph cannot safely implement MutableGraph and MutableDirectedGraph\n\/\/ at the same time, because of the functionality of a EdgeTo in DirectedGraph.\ntype MutableDirectedGraph interface {\n\tCostDirectedGraph\n\tMutable\n\n\t\/\/ Adds an edge FROM e.Head TO e.Tail. Newer calls overwrite older ones.\n\t\/\/ If the nodes Head or Tail do not exist in the graph, this must add them.\n\tAddEdgeTo(e Edge, cost float64)\n\n\t\/\/ Removes an edge FROM e.Head TO e.Tail. If no such edge exists, this is a no-op,\n\t\/\/ not an error.\n\tRemoveEdgeTo(e Edge)\n}\n\n\/\/ A function that returns the cost of following an edge\ntype CostFunc func(Edge) float64\n\n\/\/ Estimates the cost of travelling between two nodes\ntype HeuristicCostFunc func(Node, Node) float64\n\n\/\/ Convenience constants for AddEdge and RemoveEdge\nconst (\n\tDirected   bool = true\n\tUndirected      = false\n)\n\n\/\/ Determines if a MutableGraph implements DirectedGraph and panics if it does.\n\/\/ This is a utility function to detect unsafe implementations. It's mostly for internal use,\n\/\/ but is exported since it may be useful to people who use the package for their own tests.\nfunc VetMutableGraph(g MutableGraph) {\n\tif _, ok := g.(DirectedGraph); ok {\n\t\tpanic(\"A MutableGraph implements DirectedGraph; this is unsafe!\")\n\t}\n}\n<commit_msg>Removed useless convenience constants<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 graph\n\n\/\/ All a node needs to do is identify itself. This allows the user to pass in nodes more\n\/\/ interesting than an int, but also allow us to reap the benefits of having a map-storable,\n\/\/ ==able type.\ntype Node interface {\n\tID() int\n}\n\n\/\/ Allows edges to do something more interesting that just be a group of nodes. While the methods\n\/\/ are called Head and Tail, they are not considered directed unless the given interface specifies\n\/\/ otherwise.\ntype Edge interface {\n\tHead() Node\n\tTail() Node\n}\n\n\/\/ A Graph implements the behavior of an undirected graph.\n\/\/\n\/\/ All methods in Graph are implicitly undirected. Graph algorithms that care about directionality\n\/\/ will intelligently choose the DirectedGraph behavior if that interface is also implemented,\n\/\/ even if the function itself only takes in a Graph (or a super-interface of graph).\ntype Graph interface {\n\t\/\/ NodeExists returns true when node is currently in the graph.\n\tNodeExists(Node) bool\n\n\t\/\/ NodeList returns a list of all nodes in no particular order, useful for\n\t\/\/ determining things like if a graph is fully connected. The caller is\n\t\/\/ free to modify this list. Implementations should construct a new list\n\t\/\/ and not return internal representation.\n\tNodeList() []Node\n\n\t\/\/ Neighbors returns all nodes connected by any edge to this node.\n\tNeighbors(Node) []Node\n\n\t\/\/ EdgeBetween returns an edge between node and neighbor such that\n\t\/\/ Head is one argument and Tail is the other. If no\n\t\/\/ such edge exists, this function returns nil.\n\tEdgeBetween(node, neighbor Node) Edge\n}\n\n\/\/ Directed graphs are characterized by having seperable Heads and Tails in their edges.\n\/\/ That is, if node1 goes to node2, that does not necessarily imply that node2 goes to node1.\n\/\/\n\/\/ While it's possible for a directed graph to have fully reciprocal edges (i.e. the graph is\n\/\/ symmetric) -- it is not required to be. The graph is also required to implement Graph\n\/\/ because in many cases it can be useful to know all neighbors regardless of direction.\ntype DirectedGraph interface {\n\tGraph\n\t\/\/ Successors gives the nodes connected by OUTBOUND edges.\n\t\/\/ If the graph is an undirected graph, this set is equal to Predecessors.\n\tSuccessors(Node) []Node\n\n\t\/\/ EdgeTo returns an edge between node and successor such that\n\t\/\/ Head returns node and Tail returns successor, if no\n\t\/\/ such edge exists, this function returns nil.\n\tEdgeTo(node, successor Node) Edge\n\n\t\/\/ Predecessors gives the nodes connected by INBOUND edges.\n\t\/\/ If the graph is an undirected graph, this set is equal to Successors.\n\tPredecessors(Node) []Node\n}\n\n\/\/ Returns all undirected edges in the graph\ntype EdgeLister interface {\n\tEdgeList() []Edge\n}\n\ntype EdgeListGraph interface {\n\tGraph\n\tEdgeLister\n}\n\n\/\/ Returns all directed edges in the graph.\ntype DirectedEdgeLister interface {\n\tDirectedEdgeList() []Edge\n}\n\ntype DirectedEdgeListGraph interface {\n\tGraph\n\tDirectedEdgeLister\n}\n\n\/\/ A crunch graph forces a sparse graph to become a dense graph. That is, if the node IDs are\n\/\/ [1,4,9,7] it would \"crunch\" the ids into the contiguous block [0,1,2,3]. Order is not\n\/\/ required to be preserved between the non-cruched and crunched instances (that means in\n\/\/ the example above 0 may correspond to 4 or 7 or 9, not necessarily 1).\n\/\/\n\/\/ All dense graphs must have the first ID as 0.\ntype CrunchGraph interface {\n\tGraph\n\tCrunch()\n}\n\n\/\/ A Graph that implements Coster has an actual cost between adjacent nodes, also known as a\n\/\/ weighted graph. If a graph implements coster and a function needs to read cost (e.g. A*),\n\/\/ this function will take precedence over the Uniform Cost function (all weights are 1) if \"nil\"\n\/\/ is passed in for the function argument.\n\/\/\n\/\/ If the argument is nil, or the edge is invalid for some reason, this should return math.Inf(1)\ntype Coster interface {\n\tCost(edge Edge) float64\n}\n\ntype CostGraph interface {\n\tCoster\n\tGraph\n}\n\ntype CostDirectedGraph interface {\n\tCoster\n\tDirectedGraph\n}\n\n\/\/ A graph that implements HeuristicCoster implements a heuristic between any two given nodes.\n\/\/ Like Coster, if a graph implements this and a function needs a heuristic cost (e.g. A*), this\n\/\/ function will take precedence over the Null Heuristic (always returns 0) if \"nil\" is passed in\n\/\/ for the function argument. If HeuristicCost is not intended to be used, it can be implemented as\n\/\/ the null heuristic (always returns 0.)\ntype HeuristicCoster interface {\n\t\/\/ HeuristicCost returns a heuristic cost between any two nodes.\n\tHeuristicCost(node1, node2 Node) float64\n}\n\n\/\/ A Mutable is a graph that can have arbitrary nodes and edges added or removed.\n\/\/\n\/\/ Anything implementing Mutable is required to store the actual argument. So if AddNode(myNode) is\n\/\/ called and later a user calls on the graph graph.NodeList(), the node added by AddNode must be\n\/\/ an the exact node, not a new node with the same ID.\n\/\/\n\/\/ In any case where conflict is possible (e.g. adding two nodes with the same ID), the later\n\/\/ call always supercedes the earlier one.\n\/\/\n\/\/ Functions will generally expect one of MutableGraph or MutableDirectedGraph and not Mutable\n\/\/ itself. That said, any function that takes Mutable[x], the destination mutable should\n\/\/ always be a different graph than the source.\ntype Mutable interface {\n\t\/\/ NewNode adds a node with an arbitrary ID and returns the new, unique ID\n\t\/\/ used.\n\tNewNode() Node\n\n\t\/\/ Adds a node to the graph. If this is called multiple times for the same ID, the newer node\n\t\/\/ overwrites the old one.\n\tAddNode(Node)\n\n\t\/\/ EmptyGraph clears the graph of all nodes and edges.\n\tEmptyGraph()\n\n\t\/\/ RemoveNode removes a node from the graph, as well as any edges\n\t\/\/ attached to it. If no such node exists, this is a no-op, not an error.\n\tRemoveNode(Node)\n}\n\n\/\/ MutableGraph is an interface ensuring the implementation of the ability to construct\n\/\/ an arbitrary undirected graph. It is very important to note that any implementation\n\/\/ of MutableGraph absolutely cannot safely implement the DirectedGraph interface.\n\/\/\n\/\/ A MutableGraph is required to store any Edge argument in the same way Mutable must\n\/\/ store a Node argument -- any retrieval call is required to return the exact supplied edge.\n\/\/ This is what makes it incompatible with DirectedGraph.\n\/\/\n\/\/ A call to AddEdgeBetween(Edge{head,tail}) make is so there is simply no way to safely\n\/\/ return EdgeTo(tail, head) since the edge returned will, by this contract, need to be\n\/\/ Head() == head and Tail() == tail when the reverse must be true to fulfill the\n\/\/ functionality guaranteed of EdgeTo.\ntype MutableGraph interface {\n\tCostGraph\n\tMutable\n\n\t\/\/ Like EdgeBetween in Graph, AddEdgeBetween adds an edge between two nodes.\n\t\/\/ If one or both nodes do not exist, the Graph is expected to add them.\n\tAddEdgeBetween(e Edge, cost float64)\n\n\t\/\/ RemoveEdge clears the stored edge between two nodes. Calling this will never\n\t\/\/ remove a node. If the edge does not exist this is a no-op, not an error.\n\tRemoveEdgeBetween(e Edge)\n}\n\n\/\/ MutableDirectedGraph is an interface that ensures one can construct an arbitrary directed\n\/\/ graph. Naturally, a MutableDirectedGraph works for both undirected and directed cases,\n\/\/ but simply using a MutableGraph may be cleaner. As the documentation for MutableGraph\n\/\/ notes, however, a graph cannot safely implement MutableGraph and MutableDirectedGraph\n\/\/ at the same time, because of the functionality of a EdgeTo in DirectedGraph.\ntype MutableDirectedGraph interface {\n\tCostDirectedGraph\n\tMutable\n\n\t\/\/ Adds an edge FROM e.Head TO e.Tail. Newer calls overwrite older ones.\n\t\/\/ If the nodes Head or Tail do not exist in the graph, this must add them.\n\tAddEdgeTo(e Edge, cost float64)\n\n\t\/\/ Removes an edge FROM e.Head TO e.Tail. If no such edge exists, this is a no-op,\n\t\/\/ not an error.\n\tRemoveEdgeTo(e Edge)\n}\n\n\/\/ A function that returns the cost of following an edge\ntype CostFunc func(Edge) float64\n\n\/\/ Estimates the cost of travelling between two nodes\ntype HeuristicCostFunc func(Node, Node) float64\n\n\/\/ Determines if a MutableGraph implements DirectedGraph and panics if it does.\n\/\/ This is a utility function to detect unsafe implementations. It's mostly for internal use,\n\/\/ but is exported since it may be useful to people who use the package for their own tests.\nfunc VetMutableGraph(g MutableGraph) {\n\tif _, ok := g.(DirectedGraph); ok {\n\t\tpanic(\"A MutableGraph implements DirectedGraph; this is unsafe!\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/stormcat24\/protodep\/helper\"\n\t\"github.com\/stormcat24\/protodep\/logger\"\n\t\"github.com\/stormcat24\/protodep\/service\"\n)\n\nvar (\n\tauthProvider helper.AuthProvider\n)\n\ntype protoResource struct {\n\tsource       string\n\trelativeDest string\n}\n\nvar upCmd = &cobra.Command{\n\tUse:   \"up\",\n\tShort: \"Populate .proto vendors existing protodep.toml and lock\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\tisForceUpdate, err := cmd.Flags().GetBool(\"force\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"force update = %t\", isForceUpdate)\n\n\t\tisCleanupCache, err := cmd.Flags().GetBool(\"cleanup\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"cleanup cache = %t\", isCleanupCache)\n\n\t\tidentityFile, err := cmd.Flags().GetString(\"identity-file\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"identity file = %s\", identityFile)\n\n\t\tpassword, err := cmd.Flags().GetString(\"password\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif password != \"\" {\n\t\t\tlogger.Info(\"password = %s\", strings.Repeat(\"x\", len(password))) \/\/ Do not display the password.\n\t\t}\n\n\t\tpwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\thomeDir, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tidentifyPath := filepath.Join(homeDir, \".ssh\", identityFile)\n\t\tisSSH, err := helper.IsAvailableSSH(identifyPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif isSSH {\n\t\t\tauthProvider = helper.NewAuthProvider(identifyPath, password)\n\t\t} else {\n\t\t\tauthProvider = helper.NewAuthProvider(\"\", \"\")\n\t\t}\n\n\t\tupdateService := service.NewSync(authProvider, homeDir, pwd, pwd)\n\t\treturn updateService.Resolve(isForceUpdate, isCleanupCache)\n\t},\n}\n\nfunc initDepCmd() {\n\tupCmd.PersistentFlags().BoolP(\"force\", \"f\", false, \"update locked file and .proto vendors\")\n\tupCmd.PersistentFlags().StringP(\"identity-file\", \"i\", \"id_rsa\", \"set the identity file for SSH\")\n\tupCmd.PersistentFlags().StringP(\"password\", \"p\", \"\", \"set the password for SSH\")\n\tupCmd.PersistentFlags().BoolP(\"cleanup\", \"c\", false, \"cleanup cache before exec.\")\n}\n<commit_msg>Add a CLI flag to get dependencies via HTTPS (#49)<commit_after>package cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/stormcat24\/protodep\/helper\"\n\t\"github.com\/stormcat24\/protodep\/logger\"\n\t\"github.com\/stormcat24\/protodep\/service\"\n)\n\nvar (\n\tauthProvider helper.AuthProvider\n)\n\ntype protoResource struct {\n\tsource       string\n\trelativeDest string\n}\n\nvar upCmd = &cobra.Command{\n\tUse:   \"up\",\n\tShort: \"Populate .proto vendors existing protodep.toml and lock\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\tisForceUpdate, err := cmd.Flags().GetBool(\"force\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"force update = %t\", isForceUpdate)\n\n\t\tisCleanupCache, err := cmd.Flags().GetBool(\"cleanup\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"cleanup cache = %t\", isCleanupCache)\n\n\t\tidentityFile, err := cmd.Flags().GetString(\"identity-file\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"identity file = %s\", identityFile)\n\n\t\tpassword, err := cmd.Flags().GetString(\"password\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif password != \"\" {\n\t\t\tlogger.Info(\"password = %s\", strings.Repeat(\"x\", len(password))) \/\/ Do not display the password.\n\t\t}\n\n\t\tuseHttps, err := cmd.Flags().GetBool(\"use-https\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlogger.Info(\"use https = %t\", useHttps)\n\n\t\tpwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\thomeDir, err := homedir.Dir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif useHttps {\n\t\t\tauthProvider = helper.NewAuthProvider(\"\", \"\")\n\t\t} else {\n\t\t\tidentifyPath := filepath.Join(homeDir, \".ssh\", identityFile)\n\t\t\tisSSH, err := helper.IsAvailableSSH(identifyPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif isSSH {\n\t\t\t\tauthProvider = helper.NewAuthProvider(identifyPath, password)\n\t\t\t} else {\n\t\t\t\tauthProvider = helper.NewAuthProvider(\"\", \"\")\n\t\t\t}\n\t\t}\n\n\t\tupdateService := service.NewSync(authProvider, homeDir, pwd, pwd)\n\t\treturn updateService.Resolve(isForceUpdate, isCleanupCache)\n\t},\n}\n\nfunc initDepCmd() {\n\tupCmd.PersistentFlags().BoolP(\"force\", \"f\", false, \"update locked file and .proto vendors\")\n\tupCmd.PersistentFlags().StringP(\"identity-file\", \"i\", \"id_rsa\", \"set the identity file for SSH\")\n\tupCmd.PersistentFlags().StringP(\"password\", \"p\", \"\", \"set the password for SSH\")\n\tupCmd.PersistentFlags().BoolP(\"cleanup\", \"c\", false, \"cleanup cache before exec.\")\n\tupCmd.PersistentFlags().BoolP(\"use-https\", \"u\", false, \"use HTTPS to get dependencies.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package ase\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"unicode\/utf16\"\n)\n\ntype Group struct {\n\tnameLen uint16\n\tName    string\n\tColors  []Color\n}\n\nfunc (group *Group) read(r io.Reader) (err error) {\n\tif err = group.readNameLen(r); err != nil {\n\t\treturn\n\t}\n\n\treturn group.readName(r)\n}\n\nfunc (group *Group) readNameLen(r io.Reader) error {\n\treturn binary.Read(r, binary.BigEndian, &group.nameLen)\n}\n\nfunc (group *Group) readName(r io.Reader) (err error) {\n\t\/\/\tmake array for our color name based on block length\n\tname := make([]uint16, group.nameLen)\n\tif err = binary.Read(r, binary.BigEndian, &name); err != nil {\n\t\treturn\n\t}\n\n\t\/\/\tdecode our name. we trim off the last byte since it's zero terminated\n\tgroup.Name = string(utf16.Decode(name[:len(name)-1]))\n\n\treturn\n}\n\nfunc (group *Group) write(w io.Writer) (err error) {\n\n\t\/\/ Write group start headers (block entry, block length,  nameLen, name)\n\tif err = group.writeBlockStart(w); err != nil {\n\t\treturn\n\t}\n\n\tif err = group.writeBlockLength(w); err != nil {\n\t\treturn\n\t}\n\n\tif err = group.writeNameLen(w); err != nil {\n\t\treturn\n\t}\n\tif err = group.writeName(w); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write group's colors\n\tfor _, color := range group.Colors {\n\t\tif err = color.write(w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Write the group's closing headers\n\tif err = group.writeBlockEnd(w); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}\n\n\/\/ Wrapper around writing a group start header.\nfunc (group *Group) writeBlockStart(w io.Writer) (err error) {\n\treturn binary.Write(w, binary.BigEndian, groupStart)\n}\n\n\/\/ Wrapper around writing a group end header.\nfunc (group *Group) writeBlockEnd(w io.Writer) (err error) {\n\t\/\/ First writes the groupEnd block followed by a terminating zero.\n\tbinary.Write(w, binary.BigEndian, groupEnd)\n\treturn binary.Write(w, binary.BigEndian, uint16(0x0000))\n}\n\n\/\/ Encode the color's name length.\nfunc (group *Group) writeNameLen(w io.Writer) (err error) {\n\t\/\/ Adding one to the name length accounts for the zero-terminated character.\n\treturn binary.Write(w, binary.BigEndian, group.NameLen()+1)\n}\n\n\/\/ Encode the group's name.\nfunc (group *Group) writeName(w io.Writer) (err error) {\n\tname := utf16.Encode([]rune(group.Name))\n\tname = append(name, uint16(0))\n\treturn binary.Write(w, binary.BigEndian, name)\n}\n\n\/\/ Helper function that returns the length of a group's name.\nfunc (group *Group) NameLen() uint16 {\n\treturn uint16(len(group.Name))\n}\n\n\/\/ Write color's block length as a part of the ASE encoding.\nfunc (group *Group) writeBlockLength(w io.Writer) (err error) {\n\tblockLength := group.calculateBlockLength()\n\tif err = binary.Write(w, binary.BigEndian, blockLength); err != nil {\n\t\treturn err\n\t}\n\treturn\n}\n\n\/\/ Calculates the block length to be written based on the color's attributes.\nfunc (group *Group) calculateBlockLength() int32 {\n\tbuf := new(bytes.Buffer)\n\tgroup.writeNameLen(buf)\n\tgroup.writeName(buf)\n\treturn int32(buf.Len())\n}\n<commit_msg>(encode) write two terminating zeros for group.writeBlockEnd()<commit_after>package ase\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"unicode\/utf16\"\n)\n\ntype Group struct {\n\tnameLen uint16\n\tName    string\n\tColors  []Color\n}\n\nfunc (group *Group) read(r io.Reader) (err error) {\n\tif err = group.readNameLen(r); err != nil {\n\t\treturn\n\t}\n\n\treturn group.readName(r)\n}\n\nfunc (group *Group) readNameLen(r io.Reader) error {\n\treturn binary.Read(r, binary.BigEndian, &group.nameLen)\n}\n\nfunc (group *Group) readName(r io.Reader) (err error) {\n\t\/\/\tmake array for our color name based on block length\n\tname := make([]uint16, group.nameLen)\n\tif err = binary.Read(r, binary.BigEndian, &name); err != nil {\n\t\treturn\n\t}\n\n\t\/\/\tdecode our name. we trim off the last byte since it's zero terminated\n\tgroup.Name = string(utf16.Decode(name[:len(name)-1]))\n\n\treturn\n}\n\nfunc (group *Group) write(w io.Writer) (err error) {\n\n\t\/\/ Write group start headers (block entry, block length,  nameLen, name)\n\tif err = group.writeBlockStart(w); err != nil {\n\t\treturn\n\t}\n\n\tif err = group.writeBlockLength(w); err != nil {\n\t\treturn\n\t}\n\n\tif err = group.writeNameLen(w); err != nil {\n\t\treturn\n\t}\n\tif err = group.writeName(w); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write group's colors\n\tfor _, color := range group.Colors {\n\t\tif err = color.write(w); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Write the group's closing headers\n\tif err = group.writeBlockEnd(w); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}\n\n\/\/ Wrapper around writing a group start header.\nfunc (group *Group) writeBlockStart(w io.Writer) (err error) {\n\treturn binary.Write(w, binary.BigEndian, groupStart)\n}\n\n\/\/ Wrapper around writing a group end header.\nfunc (group *Group) writeBlockEnd(w io.Writer) (err error) {\n\t\/\/ First writes the groupEnd block followed by two terminating zeroes.\n\tbinary.Write(w, binary.BigEndian, groupEnd)\n\tbinary.Write(w, binary.BigEndian, uint16(0x0000))\n\treturn binary.Write(w, binary.BigEndian, uint16(0x0000))\n}\n\n\/\/ Encode the color's name length.\nfunc (group *Group) writeNameLen(w io.Writer) (err error) {\n\t\/\/ Adding one to the name length accounts for the zero-terminated character.\n\treturn binary.Write(w, binary.BigEndian, group.NameLen()+1)\n}\n\n\/\/ Encode the group's name.\nfunc (group *Group) writeName(w io.Writer) (err error) {\n\tname := utf16.Encode([]rune(group.Name))\n\tname = append(name, uint16(0))\n\treturn binary.Write(w, binary.BigEndian, name)\n}\n\n\/\/ Helper function that returns the length of a group's name.\nfunc (group *Group) NameLen() uint16 {\n\treturn uint16(len(group.Name))\n}\n\n\/\/ Write color's block length as a part of the ASE encoding.\nfunc (group *Group) writeBlockLength(w io.Writer) (err error) {\n\tblockLength := group.calculateBlockLength()\n\tif err = binary.Write(w, binary.BigEndian, blockLength); err != nil {\n\t\treturn err\n\t}\n\treturn\n}\n\n\/\/ Calculates the block length to be written based on the color's attributes.\nfunc (group *Group) calculateBlockLength() int32 {\n\tbuf := new(bytes.Buffer)\n\tgroup.writeNameLen(buf)\n\tgroup.writeName(buf)\n\treturn int32(buf.Len())\n}\n<|endoftext|>"}
{"text":"<commit_before>package testhelpers\n\nimport(\n\t. \"github.com\/onsi\/gomega\"\n\t\"bytes\"\n  \"io\"\n\t\"os\"\n  \"strings\"\n  \"wall_street\"\n)\n\nfunc SimulatePipes(reader *wall_street.ReadlineReader, input string, block func()) []string {\n\tin, out, err := os.Pipe()\n\tExpect(err).NotTo(HaveOccurred())\n\treader.SetReadPipe(in)\n\n\tgo func() {\n\t\tdefer out.Close()\n\t\tout.Write([]byte(input))\n\t}()\n\n\treturn CaptureSTDOUT(reader, func() { block() })\n}\n\nfunc CaptureSTDOUT(reader *wall_street.ReadlineReader, block func()) []string {\n\tin, out, err := os.Pipe()\n\tExpect(err).ToNot(HaveOccurred())\n\n\treader.SetWritePipe(out)\n\n\tblock()\n\tout.Close()\n\n\tvar buf bytes.Buffer\n\tio.Copy(&buf, in)\n\tif len(buf.String()) == 0 {\n\t\treturn []string{}\n\t}\n\n\treturn strings.Split(buf.String(), \"\\n\")\n}\n<commit_msg>Add convenient newline to test helpers<commit_after>package testhelpers\n\nimport(\n\t. \"github.com\/onsi\/gomega\"\n\t\"bytes\"\n  \"io\"\n\t\"os\"\n  \"strings\"\n  \"wall_street\"\n)\n\nfunc SimulatePipes(reader *wall_street.ReadlineReader, input string, block func()) []string {\n\tin, out, err := os.Pipe()\n\tExpect(err).NotTo(HaveOccurred())\n\treader.SetReadPipe(in)\n\n\tgo func() {\n\t\tdefer out.Close()\n\t\tout.Write([]byte(input + \"\\n\"))\n\t}()\n\n\treturn CaptureSTDOUT(reader, func() { block() })\n}\n\nfunc CaptureSTDOUT(reader *wall_street.ReadlineReader, block func()) []string {\n\tin, out, err := os.Pipe()\n\tExpect(err).ToNot(HaveOccurred())\n\n\treader.SetWritePipe(out)\n\n\tblock()\n\tout.Close()\n\n\tvar buf bytes.Buffer\n\tio.Copy(&buf, in)\n\tif len(buf.String()) == 0 {\n\t\treturn []string{}\n\t}\n\n\treturn strings.Split(buf.String(), \"\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ package declared as executable, not lib\npackage main\n\n\/\/ an import\nimport \"fmt\"\n\n\/\/ entry point\nfunc main() {\n\t\/\/ call Printf function from fmt package\n\tfmt.Printf(\"hello, world\\n\")\n\n\t\/\/ call another function\n\tbeyondHello()\n\n}\n\nfunc beyondHello(){\n\t\/\/ variable should be declared before being used\n\tvar x int\n\t\/\/ assignation\n\tx = 3\n\n\t\/\/ type inference, declaration, assignation\n\ty := 4\n\n\t\/\/ a function returning 2 values\n\tsum, prod := learnMultiple(x, y)\n\tfmt.Println(\"sum:\", sum, \"prod:\", prod)\n\n\t\/\/ another function call\n\tlearnTypes()\n}\n\n\/\/ arguments x, y of type integers\n\/\/ this function returns 2 integers, sum & prod\nfunc learnMultiple(x, y int) (sum, prod int) {\n\t\/\/ two values returned\n\treturn x+y, x*y\n\n}\n\nfunc learnTypes(){\n\t\/\/ string inference\n\tstr := \"Learn go\"\n\ts2 := `string with\nnewline`\n\t\/\/ go source code use utf8 charset\n\t\/\/ rune type, for unicode char\n\tg := 'Σ'\n\n\t\/\/ float\n\tf := 3.14195\n\t\/\/ complex128 type, considered as float64 by compiler\n\tc := 3 + 4i\n\t\/\/ u declared as unsigned int\n\tvar u uint = 7\n\tvar pi float32 = 22. \/ 7\n\n\t\/\/ byte is an alias for uint8\n\tn := byte('\\n')\n\n\t\/\/ array are size fixed\n\tvar a4 [4]int \/\/ array size 4, int items 0, 0, 0, 0\n\ta3 := [...]int{3, 1, 5} \/\/ array size 3, int items 3, 1, 5\n\n\t\/\/ slices are size not fixed\n\ts3 := []int{4, 5, 9} \/\/ 3 ints slice\n\ts4 := make([]int, 4) \/\/ 4 ints slice initialized with zeros\n\tvar d2 [][]float64\n\tbs := []byte(\"a slice\")\n\n\t\/\/ add values to slice\n\ts3 = append(s3, 4, 5, 6)\n\ts3 = append(s3, []int{7,8,9}...)\n\tfmt.Println(s3)\n\n\n\n\t\/\/ declared & not used variables are errors\n\t\/\/ to ignore those unused values\n\t_, _, _, _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, c, u, pi, n, a3, a4, bs, d2, s4\n}\n<commit_msg>golang, control flow (1)<commit_after>\/\/ package declared as executable, not lib\npackage main\n\n\/\/ an import\nimport \"fmt\"\n\n\/\/ entry point\nfunc main() {\n\t\/\/ call Printf function from fmt package\n\tfmt.Printf(\"hello, world\\n\")\n\n\t\/\/ call another function\n\tbeyondHello()\n\n}\n\nfunc beyondHello() {\n\t\/\/ variable should be declared before being used\n\tvar x int\n\t\/\/ assignation\n\tx = 3\n\n\t\/\/ type inference, declaration, assignation\n\ty := 4\n\n\t\/\/ a function returning 2 values\n\tsum, prod := learnMultiple(x, y)\n\tfmt.Println(\"sum:\", sum, \"prod:\", prod)\n\n\t\/\/ another function call\n\tlearnTypes()\n}\n\n\/\/ arguments x, y of type integers\n\/\/ this function returns 2 integers, sum & prod\nfunc learnMultiple(x, y int) (sum, prod int) {\n\t\/\/ two values returned\n\treturn x + y, x * y\n\n}\n\nfunc learnTypes() {\n\t\/\/ string inference\n\tstr := \"Learn go\"\n\ts2 := `string with\nnewline`\n\t\/\/ go source code use utf8 charset\n\t\/\/ rune type, for unicode char\n\tg := 'Σ'\n\n\t\/\/ float\n\tf := 3.14195\n\t\/\/ complex128 type, considered as float64 by compiler\n\tc := 3 + 4i\n\t\/\/ u declared as unsigned int\n\tvar u uint = 7\n\tvar pi float32 = 22. \/ 7\n\n\t\/\/ byte is an alias for uint8\n\tn := byte('\\n')\n\n\t\/\/ array are size fixed\n\tvar a4 [4]int           \/\/ array size 4, int items 0, 0, 0, 0\n\ta3 := [...]int{3, 1, 5} \/\/ array size 3, int items 3, 1, 5\n\n\t\/\/ slices are size not fixed\n\ts3 := []int{4, 5, 9} \/\/ 3 ints slice\n\ts4 := make([]int, 4) \/\/ 4 ints slice initialized with zeros\n\tvar d2 [][]float64\n\tbs := []byte(\"a slice\")\n\n\t\/\/ add values to slice\n\ts3 = append(s3, 4, 5, 6)\n\ts3 = append(s3, []int{7, 8, 9}...)\n\tfmt.Println(s3)\n\n\t\/\/ maps are like python dictionaries\n\tm := map[string]int{\"score\": 5}\n\tm[\"distance\"] = 5\n\tfmt.Println(m)\n\n\t\/\/ declared & not used variables are errors\n\t\/\/ to ignore those unused values\n\t_, _, _, _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, c, u, pi, n, a3, a4, bs, d2, s4\n\tlearnFlowControl()\n}\n\nfunc learnFlowControl() {\n\tif true {\n\t\tfmt.Println(\"bim\")\n\t}\n\tif false {\n\t\t\/\/ if\n\t}else{\n\t\t\/\/ else\n\t}\n\t\/\/ switch case\n\tx := 42.0\n\tswitch x {\n\tcase 0:\n\tcase 1:\n\t\tfmt.Println(\"0 or 1\")\n\tcase 42:\n\t\tfmt.Println(\"42\")\n\tcase 43:\n\t\tfmt.Println(\"43\")\n\t}\n\n\t\/\/ for loop\n\tfor x:=0; x<3; x++ {\n\t\tfmt.Println(\"i: \", x)\n\t}\n\n\t\/\/ k,v will go through the different k,v pairs of the map\n\tfor k, v := range map[string]int{\"une\":1, \"deux\":2, \"trois\":3}{\n\t\tfmt.Printf(\"key=%s, value=%d\\n\", k, v)\n\t}\n\n\t\/\/\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\n\n func main() {\n   fmt.Println(\"Hello\")\nfmt.Println(\"bye forever\")\nfmt.Println(\"Whoops, I'm back!\")\n\n\tfmt.Println(\"Hello\")\n\tfmt.Println(\"Is it me you're looking for?\")\n\tfmt.Println(\"bye forever\")\n}\n<commit_msg>Please?<commit_after>package main\n\nimport \"fmt\"\n\n\n func main() {\n   fmt.Println(\"Hello\")\nfmt.Println(\"bye forever\")\nfmt.Println(\"Whoops, I'm back!\")\n\n\tfmt.Println(\"Hello\")\n\tfmt.Println(\"Is it me you're looking for?\")\n\tfmt.Println(\"bye forever\")\n\tfmt.Println(\"Forever and ever\")\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 privileges\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\/model\"\n\t\"github.com\/pingcap\/tidb\/mysql\"\n\t\"github.com\/pingcap\/tidb\/privilege\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\/variable\"\n\t\"github.com\/pingcap\/tidb\/util\/sqlexec\"\n)\n\nvar _ privilege.Checker = (*UserPrivileges)(nil)\n\ntype privileges struct {\n\tprivs map[mysql.PrivilegeType]bool\n}\n\nfunc (ps *privileges) contain(p mysql.PrivilegeType) bool {\n\tif ps.privs == nil {\n\t\treturn false\n\t}\n\t_, ok := ps.privs[p]\n\treturn ok\n}\n\nfunc (ps *privileges) add(p mysql.PrivilegeType) {\n\tif ps.privs == nil {\n\t\tps.privs = make(map[mysql.PrivilegeType]bool)\n\t}\n\tps.privs[p] = true\n}\n\ntype userPrivileges struct {\n\t\/\/ Global privileges\n\tGlobalPrivs *privileges\n\t\/\/ DBName-privileges\n\tDBPrivs map[string]*privileges\n\t\/\/ DBName-TableName-privileges\n\tTablePrivs map[string]map[string]*privileges\n}\n\n\/\/ UserPrivileges implements privilege.Checker interface.\n\/\/ This is used to check privilege for the current user.\ntype UserPrivileges struct {\n\tusername string\n\thost     string\n\tprivs    *userPrivileges\n}\n\n\/\/ Check implements Checker.Check interface.\nfunc (p *UserPrivileges) Check(ctx context.Context, db *model.DBInfo, tbl *model.TableInfo, privilege mysql.PrivilegeType) (bool, error) {\n\tif p.privs == nil {\n\t\t\/\/ Lazy load\n\t\terr := p.loadPrivileges(ctx)\n\t\tif err != nil {\n\t\t\treturn false, errors.Trace(err)\n\t\t}\n\t}\n\t\/\/ Check global scope privileges.\n\tok := p.privs.GlobalPrivs.contain(privilege)\n\tif ok {\n\t\treturn true, nil\n\t}\n\t\/\/ Check db scope privileges.\n\tdbp, ok := p.privs.DBPrivs[db.Name.O]\n\tif ok {\n\t\tok = dbp.contain(privilege)\n\t\tif ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\tif tbl == nil {\n\t\treturn false, nil\n\t}\n\t\/\/ Check table scope privileges.\n\tdbTbl, ok := p.privs.TablePrivs[db.Name.O]\n\tif !ok {\n\t\treturn false, nil\n\t}\n\ttblp, ok := dbTbl[tbl.Name.O]\n\tif !ok {\n\t\treturn false, nil\n\t}\n\treturn tblp.contain(privilege), nil\n}\n\nfunc (p *UserPrivileges) loadPrivileges(ctx context.Context) error {\n\tuser := variable.GetSessionVars(ctx).User\n\tstrs := strings.Split(user, \"@\")\n\tp.username, p.host = strs[0], strs[1]\n\tp.privs = &userPrivileges{}\n\t\/\/ Load privileges from mysql.User\/DB\/Table_privs\/Column_privs table\n\terr := p.loadGlobalPrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\terr = p.loadDBScopePrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\terr = p.loadTableScopePrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\t\/\/ TODO: consider column scope privilege latter.\n\treturn nil\n}\n\n\/\/ mysql.User\/mysql.DB table privilege columns start from index 3.\n\/\/ See: booststrap.go CreateUserTable\/CreateDBPrivTable\nconst userTablePrivColumnStartIndex = 3\nconst dbTablePrivColumnStartIndex = 3\n\nfunc (p *UserPrivileges) loadGlobalPrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.UserTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := &privileges{}\n\tfs, err := rs.Fields()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tfor i := userTablePrivColumnStartIndex; i < len(fs); i++ {\n\t\t\td := row.Data[i]\n\t\t\ted, ok := d.(mysql.Enum)\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Privilege should be mysql.Enum: %v(%T)\", d, d)\n\t\t\t}\n\t\t\tif ed.String() != \"Y\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf := fs[i]\n\t\t\tp, ok := mysql.Col2PrivType[f.Name]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps.add(p)\n\t\t}\n\t}\n\tp.privs.GlobalPrivs = ps\n\treturn nil\n}\n\nfunc (p *UserPrivileges) loadDBScopePrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.DBTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := make(map[string]*privileges)\n\tfs, err := rs.Fields()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ DB\n\t\tdb, ok := row.Data[1].(string)\n\t\tif !ok {\n\t\t\tpanic(\"This should be never happened!\")\n\t\t}\n\t\tps[db] = &privileges{}\n\t\tfor i := dbTablePrivColumnStartIndex; i < len(fs); i++ {\n\t\t\td := row.Data[i]\n\t\t\ted, ok := d.(mysql.Enum)\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Privilege should be mysql.Enum: %v(%T)\", d, d)\n\t\t\t}\n\t\t\tif ed.String() != \"Y\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf := fs[i]\n\t\t\tp, ok := mysql.Col2PrivType[f.Name]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps[db].add(p)\n\t\t}\n\t}\n\tp.privs.DBPrivs = ps\n\treturn nil\n}\n\nfunc (p *UserPrivileges) loadTableScopePrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.TablePrivTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := make(map[string]map[string]*privileges)\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ DB\n\t\tdb, ok := row.Data[1].(string)\n\t\tif !ok {\n\t\t\tpanic(\"This should be never happened!\")\n\t\t}\n\t\t\/\/ Table_name\n\t\ttbl, ok := row.Data[3].(string)\n\t\tif !ok {\n\t\t\tpanic(\"This should be never happened!\")\n\t\t}\n\t\t_, ok = ps[db]\n\t\tif !ok {\n\t\t\tps[db] = make(map[string]*privileges)\n\t\t}\n\t\tps[db][tbl] = &privileges{}\n\t\t\/\/ Table_priv\n\t\ttblPrivs, ok := row.Data[6].(mysql.Set)\n\t\tif !ok {\n\t\t\tpanic(\"This should be never happened!\")\n\t\t}\n\t\tpvs := strings.Split(tblPrivs.Name, \",\")\n\t\tfor _, d := range pvs {\n\t\t\tp, ok := mysql.SetStr2Priv[d]\n\t\t\tif !ok {\n\t\t\t\tpanic(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps[db][tbl].add(p)\n\t\t}\n\t}\n\tp.privs.TablePrivs = ps\n\treturn nil\n}\n<commit_msg>privileges: Replace panic with error.<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 privileges\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\/model\"\n\t\"github.com\/pingcap\/tidb\/mysql\"\n\t\"github.com\/pingcap\/tidb\/privilege\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\/variable\"\n\t\"github.com\/pingcap\/tidb\/util\/sqlexec\"\n)\n\nvar _ privilege.Checker = (*UserPrivileges)(nil)\n\ntype privileges struct {\n\tprivs map[mysql.PrivilegeType]bool\n}\n\nfunc (ps *privileges) contain(p mysql.PrivilegeType) bool {\n\tif ps.privs == nil {\n\t\treturn false\n\t}\n\t_, ok := ps.privs[p]\n\treturn ok\n}\n\nfunc (ps *privileges) add(p mysql.PrivilegeType) {\n\tif ps.privs == nil {\n\t\tps.privs = make(map[mysql.PrivilegeType]bool)\n\t}\n\tps.privs[p] = true\n}\n\ntype userPrivileges struct {\n\t\/\/ Global privileges\n\tGlobalPrivs *privileges\n\t\/\/ DBName-privileges\n\tDBPrivs map[string]*privileges\n\t\/\/ DBName-TableName-privileges\n\tTablePrivs map[string]map[string]*privileges\n}\n\n\/\/ UserPrivileges implements privilege.Checker interface.\n\/\/ This is used to check privilege for the current user.\ntype UserPrivileges struct {\n\tusername string\n\thost     string\n\tprivs    *userPrivileges\n}\n\n\/\/ Check implements Checker.Check interface.\nfunc (p *UserPrivileges) Check(ctx context.Context, db *model.DBInfo, tbl *model.TableInfo, privilege mysql.PrivilegeType) (bool, error) {\n\tif p.privs == nil {\n\t\t\/\/ Lazy load\n\t\terr := p.loadPrivileges(ctx)\n\t\tif err != nil {\n\t\t\treturn false, errors.Trace(err)\n\t\t}\n\t}\n\t\/\/ Check global scope privileges.\n\tok := p.privs.GlobalPrivs.contain(privilege)\n\tif ok {\n\t\treturn true, nil\n\t}\n\t\/\/ Check db scope privileges.\n\tdbp, ok := p.privs.DBPrivs[db.Name.O]\n\tif ok {\n\t\tok = dbp.contain(privilege)\n\t\tif ok {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\tif tbl == nil {\n\t\treturn false, nil\n\t}\n\t\/\/ Check table scope privileges.\n\tdbTbl, ok := p.privs.TablePrivs[db.Name.O]\n\tif !ok {\n\t\treturn false, nil\n\t}\n\ttblp, ok := dbTbl[tbl.Name.O]\n\tif !ok {\n\t\treturn false, nil\n\t}\n\treturn tblp.contain(privilege), nil\n}\n\nfunc (p *UserPrivileges) loadPrivileges(ctx context.Context) error {\n\tuser := variable.GetSessionVars(ctx).User\n\tstrs := strings.Split(user, \"@\")\n\tp.username, p.host = strs[0], strs[1]\n\tp.privs = &userPrivileges{}\n\t\/\/ Load privileges from mysql.User\/DB\/Table_privs\/Column_privs table\n\terr := p.loadGlobalPrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\terr = p.loadDBScopePrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\terr = p.loadTableScopePrivileges(ctx)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\t\/\/ TODO: consider column scope privilege latter.\n\treturn nil\n}\n\n\/\/ mysql.User\/mysql.DB table privilege columns start from index 3.\n\/\/ See: booststrap.go CreateUserTable\/CreateDBPrivTable\nconst userTablePrivColumnStartIndex = 3\nconst dbTablePrivColumnStartIndex = 3\n\nfunc (p *UserPrivileges) loadGlobalPrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.UserTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := &privileges{}\n\tfs, err := rs.Fields()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tfor i := userTablePrivColumnStartIndex; i < len(fs); i++ {\n\t\t\td := row.Data[i]\n\t\t\ted, ok := d.(mysql.Enum)\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Privilege should be mysql.Enum: %v(%T)\", d, d)\n\t\t\t}\n\t\t\tif ed.String() != \"Y\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf := fs[i]\n\t\t\tp, ok := mysql.Col2PrivType[f.Name]\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps.add(p)\n\t\t}\n\t}\n\tp.privs.GlobalPrivs = ps\n\treturn nil\n}\n\nfunc (p *UserPrivileges) loadDBScopePrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.DBTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := make(map[string]*privileges)\n\tfs, err := rs.Fields()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ DB\n\t\tdb, ok := row.Data[1].(string)\n\t\tif !ok {\n\t\t\terrors.Errorf(\"This should be never happened!\")\n\t\t}\n\t\tps[db] = &privileges{}\n\t\tfor i := dbTablePrivColumnStartIndex; i < len(fs); i++ {\n\t\t\td := row.Data[i]\n\t\t\ted, ok := d.(mysql.Enum)\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Privilege should be mysql.Enum: %v(%T)\", d, d)\n\t\t\t}\n\t\t\tif ed.String() != \"Y\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf := fs[i]\n\t\t\tp, ok := mysql.Col2PrivType[f.Name]\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps[db].add(p)\n\t\t}\n\t}\n\tp.privs.DBPrivs = ps\n\treturn nil\n}\n\nfunc (p *UserPrivileges) loadTableScopePrivileges(ctx context.Context) error {\n\tsql := fmt.Sprintf(`SELECT * FROM %s.%s WHERE User=\"%s\" AND (Host=\"%s\" OR Host=\"%%\");`, mysql.SystemDB, mysql.TablePrivTable, p.username, p.host)\n\trs, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer rs.Close()\n\tps := make(map[string]map[string]*privileges)\n\tfor {\n\t\trow, err := rs.Next()\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ DB\n\t\tdb, ok := row.Data[1].(string)\n\t\tif !ok {\n\t\t\treturn errors.Errorf(\"This should be never happened!\")\n\t\t}\n\t\t\/\/ Table_name\n\t\ttbl, ok := row.Data[3].(string)\n\t\tif !ok {\n\t\t\treturn errors.Errorf(\"This should be never happened!\")\n\t\t}\n\t\t_, ok = ps[db]\n\t\tif !ok {\n\t\t\tps[db] = make(map[string]*privileges)\n\t\t}\n\t\tps[db][tbl] = &privileges{}\n\t\t\/\/ Table_priv\n\t\ttblPrivs, ok := row.Data[6].(mysql.Set)\n\t\tif !ok {\n\t\t\terrors.Errorf(\"This should be never happened!\")\n\t\t}\n\t\tpvs := strings.Split(tblPrivs.Name, \",\")\n\t\tfor _, d := range pvs {\n\t\t\tp, ok := mysql.SetStr2Priv[d]\n\t\t\tif !ok {\n\t\t\t\treturn errors.Errorf(\"Unknown Privilege Type!\")\n\t\t\t}\n\t\t\tps[db][tbl].add(p)\n\t\t}\n\t}\n\tp.privs.TablePrivs = ps\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2017 Space Monkey, 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 httpsig\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ Rand is a hookable reader used as a random byte source.\n\tRand io.Reader = rand.Reader\n)\n\n\/\/ requestPath returns the :path pseudo header according to the HTTP\/2 spec.\nfunc requestPath(req *http.Request) string {\n\tpath := req.URL.Path\n\tif path == \"\" {\n\t\tpath = \"\/\"\n\t}\n\tif req.URL.RawQuery != \"\" {\n\t\tpath += \"?\" + req.URL.RawQuery\n\t}\n\treturn path\n}\n\n\/\/ BuildSignatureString constructs a signature string following section 2.3\nfunc BuildSignatureString(req *http.Request, headers []string) string {\n\tif len(headers) == 0 {\n\t\theaders = []string{\"date\"}\n\t}\n\tvalues := make([]string, 0, len(headers))\n\tfor _, h := range headers {\n\t\tswitch h {\n\t\tcase \"(request-target)\":\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s %s\",\n\t\t\t\th, strings.ToLower(req.Method), requestPath(req)))\n\t\tcase \"host\":\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s\", h, req.Host))\n\t\tcase \"date\":\n\t\t\tif req.Header.Get(h) == \"\" {\n\t\t\t\treq.Header.Set(h, time.Now().Format(time.RFC1123))\n\t\t\t}\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s\", h, req.Header.Get(h)))\n\t\tdefault:\n\t\t\tfor _, value := range req.Header[http.CanonicalHeaderKey(h)] {\n\t\t\t\tvalues = append(values,\n\t\t\t\t\tfmt.Sprintf(\"%s: %s\", h, strings.TrimSpace(value)))\n\t\t\t}\n\t\t}\n\t}\n\treturn strings.Join(values, \"\\n\")\n}\n\n\/\/ BuildSignatureData is a convenience wrapper around BuildSignatureString that\n\/\/ returns []byte instead of a string.\nfunc BuildSignatureData(req *http.Request, headers []string) []byte {\n\treturn []byte(BuildSignatureString(req, headers))\n}\n\nfunc toRSAPrivateKey(key interface{}) *rsa.PrivateKey {\n\tswitch k := key.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn k\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc toRSAPublicKey(key interface{}) *rsa.PublicKey {\n\tswitch k := key.(type) {\n\tcase *rsa.PublicKey:\n\t\treturn k\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc toHMACKey(key interface{}) []byte {\n\tswitch k := key.(type) {\n\tcase []byte:\n\t\treturn k\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc unsupportedAlgorithm(a Algorithm) error {\n\treturn fmt.Errorf(\"key does not support algorithm %q\", a.Name())\n}\n<commit_msg>Fix date format and timezone<commit_after>\/\/ Copyright (C) 2017 Space Monkey, 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 httpsig\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ Rand is a hookable reader used as a random byte source.\n\tRand io.Reader = rand.Reader\n)\n\n\/\/ requestPath returns the :path pseudo header according to the HTTP\/2 spec.\nfunc requestPath(req *http.Request) string {\n\tpath := req.URL.Path\n\tif path == \"\" {\n\t\tpath = \"\/\"\n\t}\n\tif req.URL.RawQuery != \"\" {\n\t\tpath += \"?\" + req.URL.RawQuery\n\t}\n\treturn path\n}\n\n\/\/ BuildSignatureString constructs a signature string following section 2.3\nfunc BuildSignatureString(req *http.Request, headers []string) string {\n\tif len(headers) == 0 {\n\t\theaders = []string{\"date\"}\n\t}\n\tvalues := make([]string, 0, len(headers))\n\tfor _, h := range headers {\n\t\tswitch h {\n\t\tcase \"(request-target)\":\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s %s\",\n\t\t\t\th, strings.ToLower(req.Method), requestPath(req)))\n\t\tcase \"host\":\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s\", h, req.Host))\n\t\tcase \"date\":\n\t\t\tif req.Header.Get(h) == \"\" {\n\t\t\t\treq.Header.Set(h, time.Now().UTC().Format(http.TimeFormat))\n\t\t\t}\n\t\t\tvalues = append(values, fmt.Sprintf(\"%s: %s\", h, req.Header.Get(h)))\n\t\tdefault:\n\t\t\tfor _, value := range req.Header[http.CanonicalHeaderKey(h)] {\n\t\t\t\tvalues = append(values,\n\t\t\t\t\tfmt.Sprintf(\"%s: %s\", h, strings.TrimSpace(value)))\n\t\t\t}\n\t\t}\n\t}\n\treturn strings.Join(values, \"\\n\")\n}\n\n\/\/ BuildSignatureData is a convenience wrapper around BuildSignatureString that\n\/\/ returns []byte instead of a string.\nfunc BuildSignatureData(req *http.Request, headers []string) []byte {\n\treturn []byte(BuildSignatureString(req, headers))\n}\n\nfunc toRSAPrivateKey(key interface{}) *rsa.PrivateKey {\n\tswitch k := key.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn k\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc toRSAPublicKey(key interface{}) *rsa.PublicKey {\n\tswitch k := key.(type) {\n\tcase *rsa.PublicKey:\n\t\treturn k\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc toHMACKey(key interface{}) []byte {\n\tswitch k := key.(type) {\n\tcase []byte:\n\t\treturn k\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc unsupportedAlgorithm(a Algorithm) error {\n\treturn fmt.Errorf(\"key does not support algorithm %q\", a.Name())\n}\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 btcwire\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"math\"\n)\n\n\/\/ Maximum payload size for a variable length integer.\nconst maxVarIntPayload = 9\n\n\/\/ readElement reads the next sequence of bytes from r using little endian\n\/\/ depending on the concrete type of element pointed to.\nfunc readElement(r io.Reader, element interface{}) error {\n\treturn binary.Read(r, binary.LittleEndian, element)\n}\n\n\/\/ readElements reads multiple items from r.  It is equivalent to multiple\n\/\/ calls to readElement.\nfunc readElements(r io.Reader, elements ...interface{}) error {\n\tfor _, element := range elements {\n\t\terr := readElement(r, element)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeElement writes the little endian representation of element to w.\nfunc writeElement(w io.Writer, element interface{}) error {\n\treturn binary.Write(w, binary.LittleEndian, element)\n}\n\n\/\/ writeElements writes multiple items to w.  It is equivalent to multiple\n\/\/ calls to writeElement.\nfunc writeElements(w io.Writer, elements ...interface{}) error {\n\tfor _, element := range elements {\n\t\terr := writeElement(w, element)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ readVarInt reads a variable length integer from r and returns it as a uint64.\nfunc readVarInt(r io.Reader, pver uint32) (uint64, error) {\n\tb := make([]byte, 1)\n\t_, err := r.Read(b)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar rv uint64\n\tdiscriminant := uint8(b[0])\n\tswitch discriminant {\n\tcase 0xff:\n\t\tvar u uint64\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = u\n\n\tcase 0xfe:\n\t\tvar u uint32\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = uint64(u)\n\n\tcase 0xfd:\n\t\tvar u uint16\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = uint64(u)\n\n\tdefault:\n\t\trv = uint64(discriminant)\n\t}\n\n\treturn rv, nil\n}\n\n\/\/ writeVarInt serializes val to w using a variable number of bytes depending\n\/\/ on its value.\nfunc writeVarInt(w io.Writer, pver uint32, val uint64) error {\n\tif val > math.MaxUint32 {\n\t\terr := writeElements(w, []byte{0xff}, uint64(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif val > math.MaxUint16 {\n\t\terr := writeElements(w, []byte{0xfe}, uint32(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif val >= 0xfd {\n\t\terr := writeElements(w, []byte{0xfd}, uint16(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn writeElement(w, uint8(val))\n}\n\n\/\/ readVarString reads a variable length string from r and returns it as a Go\n\/\/ string.  A varString is encoded as a varInt containing the length of the\n\/\/ string, and the bytes that represent the string itself.\nfunc readVarString(r io.Reader, pver uint32) (string, error) {\n\tslen, err := readVarInt(r, pver)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, slen)\n\terr = readElement(r, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\n\/\/ writeVarString serializes str to w as a varInt containing the length of the\n\/\/ string followed by the bytes that represent the string itself.\nfunc writeVarString(w io.Writer, pver uint32, str string) error {\n\terr := writeVarInt(w, pver, uint64(len(str)))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeElement(w, []byte(str))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ randomUint64 returns a cryptographically random uint64 value.  This\n\/\/ unexported version takes a reader primarily to ensure the error paths\n\/\/ can be properly tested by passing a fake reader in the tests.\nfunc randomUint64(r io.Reader) (uint64, error) {\n\tb := make([]byte, 8)\n\tn, err := r.Read(b)\n\tif n != len(b) {\n\t\treturn 0, io.ErrShortBuffer\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn binary.BigEndian.Uint64(b), nil\n}\n\n\/\/ RandomUint64 returns a cryptographically random uint64 value.\nfunc RandomUint64() (uint64, error) {\n\treturn randomUint64(rand.Reader)\n}\n\n\/\/ DoubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes.\nfunc DoubleSha256(b []byte) []byte {\n\thasher := sha256.New()\n\thasher.Write(b)\n\tsum := hasher.Sum(nil)\n\thasher.Reset()\n\thasher.Write(sum)\n\tsum = hasher.Sum(nil)\n\treturn sum\n}\n<commit_msg>Ensure readVarInt handles short buf on first byte.<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 btcwire\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"math\"\n)\n\n\/\/ Maximum payload size for a variable length integer.\nconst maxVarIntPayload = 9\n\n\/\/ readElement reads the next sequence of bytes from r using little endian\n\/\/ depending on the concrete type of element pointed to.\nfunc readElement(r io.Reader, element interface{}) error {\n\treturn binary.Read(r, binary.LittleEndian, element)\n}\n\n\/\/ readElements reads multiple items from r.  It is equivalent to multiple\n\/\/ calls to readElement.\nfunc readElements(r io.Reader, elements ...interface{}) error {\n\tfor _, element := range elements {\n\t\terr := readElement(r, element)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeElement writes the little endian representation of element to w.\nfunc writeElement(w io.Writer, element interface{}) error {\n\treturn binary.Write(w, binary.LittleEndian, element)\n}\n\n\/\/ writeElements writes multiple items to w.  It is equivalent to multiple\n\/\/ calls to writeElement.\nfunc writeElements(w io.Writer, elements ...interface{}) error {\n\tfor _, element := range elements {\n\t\terr := writeElement(w, element)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ readVarInt reads a variable length integer from r and returns it as a uint64.\nfunc readVarInt(r io.Reader, pver uint32) (uint64, error) {\n\tb := make([]byte, 1)\n\t_, err := io.ReadFull(r, b)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar rv uint64\n\tdiscriminant := uint8(b[0])\n\tswitch discriminant {\n\tcase 0xff:\n\t\tvar u uint64\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = u\n\n\tcase 0xfe:\n\t\tvar u uint32\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = uint64(u)\n\n\tcase 0xfd:\n\t\tvar u uint16\n\t\terr = binary.Read(r, binary.LittleEndian, &u)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\trv = uint64(u)\n\n\tdefault:\n\t\trv = uint64(discriminant)\n\t}\n\n\treturn rv, nil\n}\n\n\/\/ writeVarInt serializes val to w using a variable number of bytes depending\n\/\/ on its value.\nfunc writeVarInt(w io.Writer, pver uint32, val uint64) error {\n\tif val > math.MaxUint32 {\n\t\terr := writeElements(w, []byte{0xff}, uint64(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif val > math.MaxUint16 {\n\t\terr := writeElements(w, []byte{0xfe}, uint32(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif val >= 0xfd {\n\t\terr := writeElements(w, []byte{0xfd}, uint16(val))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\treturn writeElement(w, uint8(val))\n}\n\n\/\/ readVarString reads a variable length string from r and returns it as a Go\n\/\/ string.  A varString is encoded as a varInt containing the length of the\n\/\/ string, and the bytes that represent the string itself.\nfunc readVarString(r io.Reader, pver uint32) (string, error) {\n\tslen, err := readVarInt(r, pver)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, slen)\n\terr = readElement(r, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n\n\/\/ writeVarString serializes str to w as a varInt containing the length of the\n\/\/ string followed by the bytes that represent the string itself.\nfunc writeVarString(w io.Writer, pver uint32, str string) error {\n\terr := writeVarInt(w, pver, uint64(len(str)))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = writeElement(w, []byte(str))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ randomUint64 returns a cryptographically random uint64 value.  This\n\/\/ unexported version takes a reader primarily to ensure the error paths\n\/\/ can be properly tested by passing a fake reader in the tests.\nfunc randomUint64(r io.Reader) (uint64, error) {\n\tb := make([]byte, 8)\n\tn, err := r.Read(b)\n\tif n != len(b) {\n\t\treturn 0, io.ErrShortBuffer\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn binary.BigEndian.Uint64(b), nil\n}\n\n\/\/ RandomUint64 returns a cryptographically random uint64 value.\nfunc RandomUint64() (uint64, error) {\n\treturn randomUint64(rand.Reader)\n}\n\n\/\/ DoubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes.\nfunc DoubleSha256(b []byte) []byte {\n\thasher := sha256.New()\n\thasher.Write(b)\n\tsum := hasher.Sum(nil)\n\thasher.Reset()\n\thasher.Write(sum)\n\tsum = hasher.Sum(nil)\n\treturn sum\n}\n<|endoftext|>"}
{"text":"<commit_before>package QesyGo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype RandWeiht struct {\n\tName   string\n\tWeight int\n}\n\ntype RandWeihtArr []RandWeiht\n\nfunc Substr(str string, start int, end int) string {\n\tvar endNum int\n\ts := []byte(str)\n\tif end > 0 {\n\t\tendNum = start + end\n\t} else {\n\t\tendNum = len(str) + end\n\t}\n\treturn string(s[start:endNum])\n}\n\nfunc Rate(num int) bool {\n\trand := rand.Intn(100) + 1\n\tif rand <= num {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\n\/*\n* RandWeihtArr := &lib.RandWeihtArr{{\"user1\",8}, {\"user2\",1},{\"user3\",1}}\n* who := RandWeihtArr.RandWeight()\n *\/\nfunc (arr *RandWeihtArr) RandWeight() string {\n\tvar all int\n\tfor _, v := range *arr {\n\t\tall += v.Weight\n\t}\n\tplusNum := 0\n\ttempArr := make(map[string][2]int)\n\tfor _, v := range *arr {\n\t\tplusNum += v.Weight\n\t\ttempArr[v.Name] = [2]int{plusNum - v.Weight, plusNum}\n\t}\n\trandNum := rand.Intn(all) + 1\n\tvar ret string\n\tfor k, v := range tempArr {\n\t\tif randNum > v[0] && randNum <= v[1] {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc InArray(Arr interface{}, str string) bool {\n\tstrArr, ok := Arr.([]string)\n\tif ok {\n\t\tfor _, v := range strArr {\n\t\t\tif v == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tmapArr, ok := Arr.(map[string]string)\n\tif ok {\n\t\tfor _, v := range mapArr {\n\t\t\tif v == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tintArr, ok := Arr.([]int)\n\tif ok {\n\t\tfor _, v := range intArr {\n\t\t\tif strconv.Itoa(v) == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n\n}\n\nfunc ReadFile(str string) ([]byte, error) {\n\treturn ioutil.ReadFile(str)\n}\n\nfunc JsonEncode(arr interface{}) ([]byte, error) {\n\treturn json.Marshal(arr)\n}\n\nfunc JsonDecode(str []byte, jsonArr interface{}) error {\n\terr := json.Unmarshal(str, jsonArr)\n\treturn err\n\n}\n\nfunc Printf(format string, a ...interface{}) {\n\tfmt.Printf(format, a)\n}\n\nfunc Fprintf(w http.ResponseWriter, str string) {\n\tfmt.Fprintf(w, str)\n}\n\nfunc Die(v interface{}) {\n\tlog.Fatal(v)\n}\n\nfunc Implode(arr []string, sep string) string {\n\treturn strings.Join(arr, sep)\n}\n\nfunc Explode(str string, sep string) []string {\n\tif str == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(str, sep)\n}\n\nfunc Err(str string) error {\n\treturn errors.New(str)\n}\n\nfunc Println(str ...interface{}) {\n\tfmt.Println(str)\n}\n\nfunc Time(str string) int64 {\n\tnow := time.Now()\n\tt := now.UnixNano()\n\tswitch str {\n\tcase \"Millisecond\":\n\t\tt = now.UnixNano() \/ 1000\n\tcase \"Microsecond\":\n\t\tt = now.UnixNano() \/ 1000000\n\tcase \"Second\":\n\t\tt = now.UnixNano() \/ 1000000000\n\t}\n\treturn t\n}\n\n\/\/-- format : \"2006-01-02 03:04:05 PM\" --\n\/*\n月份 1,01,Jan,January\n日　 2,02,_2\n时　 3,03,15,PM,pm,AM,am\n分　 4,04\n秒　 5,05\n年　 06,2006\n周几 Mon,Monday\n时区时差表示 -07,-0700,Z0700,Z07:00,-07:00,MST\n时区字母缩写 MST\n*\/\nfunc Date(timestamp int64, format string) string {\n\ttm := time.Unix(timestamp, 0)\n\treturn tm.Format(format)\n}\n\n\/\/-- \"01\/02\/2006\", \"02\/08\/2015\" --\nfunc StrToTime(format string, input string) int64 {\n\ttm2, _ := time.Parse(format, input)\n\treturn tm2.Unix()\n}\n\nfunc Int64ToInt(num int64) (int, error) {\n\tstr := strconv.FormatInt(num, 10)\n\treturn strconv.Atoi(str)\n}\n\nfunc Unset(arr []string, str string) []string {\n\tnewArr := []string{}\n\tfor _, v := range arr {\n\t\tif v != str && v != \"\" {\n\t\t\tnewArr = append(newArr, v)\n\t\t}\n\t}\n\treturn newArr\n}\n<commit_msg>fix jsondecode<commit_after>package QesyGo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype RandWeiht struct {\n\tName   string\n\tWeight int\n}\n\ntype RandWeihtArr []RandWeiht\n\nfunc Substr(str string, start int, end int) string {\n\tvar endNum int\n\ts := []byte(str)\n\tif end > 0 {\n\t\tendNum = start + end\n\t} else {\n\t\tendNum = len(str) + end\n\t}\n\treturn string(s[start:endNum])\n}\n\nfunc Rate(num int) bool {\n\trand := rand.Intn(100) + 1\n\tif rand <= num {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\n\/*\n* RandWeihtArr := &lib.RandWeihtArr{{\"user1\",8}, {\"user2\",1},{\"user3\",1}}\n* who := RandWeihtArr.RandWeight()\n *\/\nfunc (arr *RandWeihtArr) RandWeight() string {\n\tvar all int\n\tfor _, v := range *arr {\n\t\tall += v.Weight\n\t}\n\tplusNum := 0\n\ttempArr := make(map[string][2]int)\n\tfor _, v := range *arr {\n\t\tplusNum += v.Weight\n\t\ttempArr[v.Name] = [2]int{plusNum - v.Weight, plusNum}\n\t}\n\trandNum := rand.Intn(all) + 1\n\tvar ret string\n\tfor k, v := range tempArr {\n\t\tif randNum > v[0] && randNum <= v[1] {\n\t\t\tret = k\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc InArray(Arr interface{}, str string) bool {\n\tstrArr, ok := Arr.([]string)\n\tif ok {\n\t\tfor _, v := range strArr {\n\t\t\tif v == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tmapArr, ok := Arr.(map[string]string)\n\tif ok {\n\t\tfor _, v := range mapArr {\n\t\t\tif v == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tintArr, ok := Arr.([]int)\n\tif ok {\n\t\tfor _, v := range intArr {\n\t\t\tif strconv.Itoa(v) == str {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n\n}\n\nfunc ReadFile(str string) ([]byte, error) {\n\treturn ioutil.ReadFile(str)\n}\n\nfunc JsonEncode(arr interface{}) ([]byte, error) {\n\treturn json.Marshal(arr)\n}\n\nfunc JsonDecode(str []byte, jsonArr interface{}) error {\n\tstrNew := string(str)\n\tif strNew == \"null\" || strNew == \"\" {\n\t\treturn nil\n\t}\n\terr := json.Unmarshal(str, jsonArr)\n\treturn err\n\n}\n\nfunc Printf(format string, a ...interface{}) {\n\tfmt.Printf(format, a)\n}\n\nfunc Fprintf(w http.ResponseWriter, str string) {\n\tfmt.Fprintf(w, str)\n}\n\nfunc Die(v interface{}) {\n\tlog.Fatal(v)\n}\n\nfunc Implode(arr []string, sep string) string {\n\treturn strings.Join(arr, sep)\n}\n\nfunc Explode(str string, sep string) []string {\n\tif str == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(str, sep)\n}\n\nfunc Err(str string) error {\n\treturn errors.New(str)\n}\n\nfunc Println(str ...interface{}) {\n\tfmt.Println(str)\n}\n\nfunc Time(str string) int64 {\n\tnow := time.Now()\n\tt := now.UnixNano()\n\tswitch str {\n\tcase \"Millisecond\":\n\t\tt = now.UnixNano() \/ 1000\n\tcase \"Microsecond\":\n\t\tt = now.UnixNano() \/ 1000000\n\tcase \"Second\":\n\t\tt = now.UnixNano() \/ 1000000000\n\t}\n\treturn t\n}\n\n\/\/-- format : \"2006-01-02 03:04:05 PM\" --\n\/*\n月份 1,01,Jan,January\n日　 2,02,_2\n时　 3,03,15,PM,pm,AM,am\n分　 4,04\n秒　 5,05\n年　 06,2006\n周几 Mon,Monday\n时区时差表示 -07,-0700,Z0700,Z07:00,-07:00,MST\n时区字母缩写 MST\n*\/\nfunc Date(timestamp int64, format string) string {\n\ttm := time.Unix(timestamp, 0)\n\treturn tm.Format(format)\n}\n\n\/\/-- \"01\/02\/2006\", \"02\/08\/2015\" --\nfunc StrToTime(format string, input string) int64 {\n\ttm2, _ := time.Parse(format, input)\n\treturn tm2.Unix()\n}\n\nfunc Int64ToInt(num int64) (int, error) {\n\tstr := strconv.FormatInt(num, 10)\n\treturn strconv.Atoi(str)\n}\n\nfunc Unset(arr []string, str string) []string {\n\tnewArr := []string{}\n\tfor _, v := range arr {\n\t\tif v != str && v != \"\" {\n\t\t\tnewArr = append(newArr, v)\n\t\t}\n\t}\n\treturn newArr\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"path\"\n\t\"reflect\"\n)\n\nfunc builtinImport(ss []sexpr) sexpr {\n\tif len(ss) != 1 {\n\t\tpanic(\"Invalid number of arguments\")\n\t}\n\n\tpkgPath, ok := ss[0].(string)\n\tif !ok {\n\t\tpanic(\"Invalid argument\")\n\t}\n\n\tpkgName := path.Base(pkgPath)\n\n\t\/\/ find the package in _go_imports\n\tpkg, found := _go_imports[pkgPath]\n\tif !found {\n\t\tpanic(\"Package not found\")\n\t}\n\n\t\/\/ import each item\n\tfor name, _go := range pkg {\n\t\tglobal[pkgName + \".\" + name] = wrapGo(_go)\n\t}\n\treturn Nil\n}\n\nfunc wrapGo(_go interface{}) sexpr {\n\ttyp := reflect.TypeOf(_go)\n\tkind := typ.Kind()\n\tswitch kind {\n\tcase reflect.Bool:\n\t\tb := _go.(bool)\n\t\tif b {\n\t\t\treturn float64(1)\n\t\t} else {\n\t\t\treturn Nil\n\t\t}\n\tcase reflect.Int:\n\t\treturn float64(_go.(int))\n\tcase reflect.Int8:\n\t\treturn float64(_go.(int8))\n\tcase reflect.Int16:\n\t\treturn float64(_go.(int16))\n\tcase reflect.Int32:\n\t\treturn float64(_go.(int32))\n\tcase reflect.Int64:\n\t\treturn float64(_go.(int64))\n\tcase reflect.Uint:\n\t\treturn float64(_go.(uint))\n\tcase reflect.Uint8:\n\t\treturn float64(_go.(uint8))\n\tcase reflect.Uint16:\n\t\treturn float64(_go.(uint16))\n\tcase reflect.Uint32:\n\t\treturn float64(_go.(uint32))\n\tcase reflect.Uint64:\n\t\treturn float64(_go.(uint64))\n\tcase reflect.Uintptr:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Float32:\n\t\treturn float64(_go.(float32))\n\tcase reflect.Float64:\n\t\treturn float64(_go.(float64))\n\tcase reflect.Complex64:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Complex128:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Array:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Chan:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Func:\n\t\treturn wrapFunc(_go)\n\tcase reflect.Interface:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Map:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Ptr:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Slice:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.String:\n\t\treturn _go.(string)\n\tcase reflect.Struct:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.UnsafePointer:\n\t\treturn Nil \/\/ can't handle this\n\t}\n\treturn Nil\n}\n\nfunc wrapFunc(f interface{}) func([]sexpr) sexpr {\n\t\/\/ TODO patch reflect so we can do type compatibility-checking\n\treturn func(ss []sexpr) sexpr {\n\t\tfun := reflect.ValueOf(f)\n\t\tvs := make([]reflect.Value, len(ss))\n\t\tfor i, s := range ss {\n\t\t\tvs[i] = reflect.ValueOf(s)\n\t\t}\n\t\tr := fun.Call(vs)\n\t\treturn wrapGo(r)\n\t}\n}\n<commit_msg>Adding TODO notice<commit_after>package main\n\nimport (\n\t\"path\"\n\t\"reflect\"\n)\n\nfunc builtinImport(ss []sexpr) sexpr {\n\tif len(ss) != 1 {\n\t\tpanic(\"Invalid number of arguments\")\n\t}\n\n\tpkgPath, ok := ss[0].(string)\n\tif !ok {\n\t\tpanic(\"Invalid argument\")\n\t}\n\n\tpkgName := path.Base(pkgPath)\n\n\t\/\/ find the package in _go_imports\n\tpkg, found := _go_imports[pkgPath]\n\tif !found {\n\t\tpanic(\"Package not found\")\n\t}\n\n\t\/\/ import each item\n\tfor name, _go := range pkg {\n\t\tglobal[pkgName + \".\" + name] = wrapGo(_go)\n\t}\n\treturn Nil\n}\n\nfunc wrapGo(_go interface{}) sexpr {\n\ttyp := reflect.TypeOf(_go)\n\tkind := typ.Kind()\n\tswitch kind {\n\tcase reflect.Bool:\n\t\tb := _go.(bool)\n\t\tif b {\n\t\t\treturn float64(1)\n\t\t} else {\n\t\t\treturn Nil\n\t\t}\n\tcase reflect.Int:\n\t\treturn float64(_go.(int))\n\tcase reflect.Int8:\n\t\treturn float64(_go.(int8))\n\tcase reflect.Int16:\n\t\treturn float64(_go.(int16))\n\tcase reflect.Int32:\n\t\treturn float64(_go.(int32))\n\tcase reflect.Int64:\n\t\treturn float64(_go.(int64))\n\tcase reflect.Uint:\n\t\treturn float64(_go.(uint))\n\tcase reflect.Uint8:\n\t\treturn float64(_go.(uint8))\n\tcase reflect.Uint16:\n\t\treturn float64(_go.(uint16))\n\tcase reflect.Uint32:\n\t\treturn float64(_go.(uint32))\n\tcase reflect.Uint64:\n\t\treturn float64(_go.(uint64))\n\tcase reflect.Uintptr:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Float32:\n\t\treturn float64(_go.(float32))\n\tcase reflect.Float64:\n\t\treturn float64(_go.(float64))\n\tcase reflect.Complex64:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Complex128:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Array:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Chan:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Func:\n\t\treturn wrapFunc(_go)\n\tcase reflect.Interface:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Map:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Ptr:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.Slice:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.String:\n\t\treturn _go.(string)\n\tcase reflect.Struct:\n\t\treturn Nil \/\/ TODO\n\tcase reflect.UnsafePointer:\n\t\treturn Nil \/\/ can't handle this\n\t}\n\treturn Nil\n}\n\nfunc wrapFunc(f interface{}) func([]sexpr) sexpr {\n\t\/\/ TODO patch reflect so we can do type compatibility-checking\n\treturn func(ss []sexpr) sexpr {\n\t\tfun := reflect.ValueOf(f)\n\t\tvs := make([]reflect.Value, len(ss))\n\t\tfor i, s := range ss {\n\t\t\t\/\/ TODO convert any cons and function arguments\n\t\t\tvs[i] = reflect.ValueOf(s)\n\t\t}\n\t\tr := fun.Call(vs)\n\t\treturn wrapGo(r)\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 nvim\n\nimport (\n\t\"go\/scanner\"\n\n\t\"github.com\/garyburd\/neovim-go\/vim\"\n)\n\n\/\/ QuickfixError represents an item in a quickfix list.\ntype LoclistError struct {\n\t\/\/ Buffer number\n\tBufnr int `msgpack:\"bufnr,omitempty\"`\n\t\/\/ Name of a file; only used when bufnr is not present or it is invalid.\n\tFileName string `msgpack:\"filename,omitempty\"`\n\t\/\/ Line number in the file.\n\tLNum int `msgpack:\"lnum,omitempty\"`\n\t\/\/ Column number (first column is 1).\n\tCol int `msgpack:\"col,omitempty\"`\n\t\/\/ When Vcol is != 0,  Col is visual column.\n\tVCol int `msgpack:\"vcol,omitempty\"`\n\t\/\/ Error number.\n\tNr int `msgpack:\"nr,omitempty\"`\n\t\/\/ Search pattern used to locate the error.\n\tPattern string `msgpack:\"pattern,omitempty\"`\n\t\/\/ Description of the error.\n\tText string `msgpack:\"text,omitempty\"`\n\t\/\/ Single-character error type, 'E', 'W', etc.\n\tType string `msgpack:\"type,omitempty\"`\n\t\/\/ Valid is non-zero if this is a recognized error message.\n\tValid int `msgpack:\"valid,omitempty\"`\n}\n\nfunc LoclistErrors(v *vim.Vim, b vim.Buffer, errors error) error {\n\tvar loclist []*LoclistError\n\n\tif e, ok := errors.(scanner.Error); ok {\n\t\tloclist = append(loclist, &LoclistError{\n\t\t\tLNum: e.Pos.Line,\n\t\t\tCol:  e.Pos.Column,\n\t\t\tText: e.Msg,\n\t\t})\n\t} else if el, ok := errors.(scanner.ErrorList); ok {\n\t\tfor _, e := range el {\n\t\t\tloclist = append(loclist, &LoclistError{\n\t\t\t\tLNum: e.Pos.Line,\n\t\t\t\tCol:  e.Pos.Column,\n\t\t\t\tText: e.Msg,\n\t\t\t})\n\t\t}\n\t}\n\n\tif len(loclist) == 0 {\n\t\treturn errors\n\t}\n\n\tbufnr, err := v.BufferNumber(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor i := range loclist {\n\t\tloclist[i].Bufnr = bufnr\n\t}\n\n\t\/\/ setloclist({nr}, {list} [, {action}])\n\t\/\/ Call(fname string, result interface{}, args ...interface{}) error\n\tif err := v.Call(\"setloclist\", nil, 0, loclist); err != nil {\n\t\treturn err\n\t}\n\n\treturn v.Command(\"lopen\")\n}\n\nfunc LoclistClose(v *vim.Vim) error {\n\treturn v.Command(\"lclose\")\n}\n<commit_msg>Fix LocationList utility<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 nvim\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/garyburd\/neovim-go\/vim\"\n)\n\n\/\/ Loclist represents an item in a quickfix list.\ntype LoclistData struct {\n\t\/\/ Buffer number\n\tBufnr int `msgpack:\"bufnr,omitempty\"`\n\t\/\/ Name of a file; only used when bufnr is not present or it is invalid.\n\tFileName string `msgpack:\"filename,omitempty\"`\n\t\/\/ Line number in the file.\n\tLNum int `msgpack:\"lnum,omitempty\"`\n\t\/\/ Column number (first column is 1).\n\tCol int `msgpack:\"col,omitempty\"`\n\t\/\/ When Vcol is != 0,  Col is visual column.\n\tVCol int `msgpack:\"vcol,omitempty\"`\n\t\/\/ Error number.\n\tNr int `msgpack:\"nr,omitempty\"`\n\t\/\/ Search pattern used to locate the error.\n\tPattern string `msgpack:\"pattern,omitempty\"`\n\t\/\/ Description of the error.\n\tText string `msgpack:\"text,omitempty\"`\n\t\/\/ Single-character error type, 'E', 'W', etc.\n\tType string `msgpack:\"type,omitempty\"`\n\t\/\/ Valid is non-zero if this is a recognized error message.\n\tValid int `msgpack:\"valid,omitempty\"`\n}\n\nfunc Loclist(v *vim.Vim, b vim.Buffer, loclist []*LoclistData, open bool) error {\n\t\/\/ setloclist({nr}, {list} [, {action}])\n\t\/\/ Call(fname string, result interface{}, args ...interface{}) error\n\tif err := v.Call(\"setloclist\", nil, 0, loclist); err != nil {\n\t\treturn err\n\t}\n\n\tif open {\n\t\treturn v.Command(\"lopen\")\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc LoclistClose(v *vim.Vim) error {\n\treturn v.Command(\"lclose\")\n}\n\nfunc SplitPos(pos string) (string, int, int) {\n\tfile := strings.Split(pos, \":\")\n\tline, _ := strconv.ParseInt(file[1], 10, 64)\n\tcol, _ := strconv.ParseInt(file[2], 10, 64)\n\n\treturn file[0], int(line), int(col)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\".\/prompt\"\n\t\"fmt\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Config struct {\n\tDirectory []string `yaml:\"Directory\"`\n}\n\nfunc removeDirectories(directories []string) {\n\tif ok := prompt.Confirm(\"Directories\\n%s\\n\\nAre you sure you want to delete directories? \", strings.Join(directories, \"\\n\")); !ok {\n\t\tprintln(\"Do nothing\")\n\t\treturn\n\t}\n\n\tfor _, directory := range directories {\n\t\tif err := os.RemoveAll(directory); err != nil {\n\t\t\tfmt.Println(err)\n\t\t} else {\n\t\t\tos.Mkdir(directory, 0775)\n\t\t}\n\t}\n\tfmt.Println(\"Have cleaned\")\n}\n\nfunc readConfigFile() Config {\n\tconfigFile := os.Getenv(\"HOME\") + \"\/.houki.yml\"\n\n\tbuf, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar parsedMap Config\n\tif err = yaml.Unmarshal(buf, &parsedMap); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn parsedMap\n}\n\nfunc main() {\n\tconfig := readConfigFile()\n\tremoveDirectories(config.Directory)\n\n}\n<commit_msg>use goroutine for remove directory<commit_after>package main\n\nimport (\n\t\".\/prompt\"\n\t\"fmt\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Config struct {\n\tDirectory []string `yaml:\"Directory\"`\n}\n\nfunc reCreateDirectory(directory string) {\n\tif err := os.RemoveAll(directory); err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tos.Mkdir(directory, 0775)\n\t}\n}\n\nfunc removeDirectories(directories []string) {\n\tif ok := prompt.Confirm(\"Directories\\n%s\\n\\nAre you sure you want to delete directories? \", strings.Join(directories, \"\\n\")); !ok {\n\t\tprintln(\"Do nothing\")\n\t\treturn\n\t}\n\n\tfor _, directory := range directories {\n\t\tgo reCreateDirectory(directory)\n\t}\n\tfmt.Println(\"Have cleaned\")\n}\n\nfunc readConfigFile() Config {\n\tconfigFile := os.Getenv(\"HOME\") + \"\/.houki.yml\"\n\n\tbuf, err := ioutil.ReadFile(configFile)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar parsedMap Config\n\tif err = yaml.Unmarshal(buf, &parsedMap); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn parsedMap\n}\n\nfunc main() {\n\tconfig := readConfigFile()\n\tremoveDirectories(config.Directory)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013-2014 Unknown\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\/\/ Package Hacker View provides APIs to analyze Go projects and generate AST-based source code view.\npackage hv\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/Unknwon\/com\"\n)\n\n\/\/ Render renders source code to HTML.\n\/\/ Note that you have to call Build before you call this method.\nfunc (w *Walker) Render() (map[string][]byte, error) {\n\thtmls := make(map[string][]byte)\n\tfiles := make(map[string]File)\n\tsrcs := w.SrcFiles\n\timports := make([]string, 0, 10)\n\n\tfor name, src := range srcs {\n\t\tpkg, err := w.Build(&WalkRes{\n\t\t\tWalkDepth: WD_All,\n\t\t\tWalkType:  WT_Memory,\n\t\t\tWalkMode:  WM_NoReadme | WM_NoExample,\n\t\t\tSrcs:      []*Source{src},\n\t\t\tBuildAll:  true,\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"hv.Walker.Render -> \" + err.Error())\n\t\t}\n\n\t\tfiles[name] = pkg.File\n\n\t\tfor _, v := range w.Pdoc.Imports {\n\t\t\timports = com.AppendStr(imports, v)\n\t\t}\n\t}\n\n\tr := Render{\n\t\tLinks:     GetLinks(w.Pdoc.ImportPath, imports, files),\n\t\tFilteList: make(map[string]bool),\n\t}\n\n\tfor name := range srcs {\n\t\thtmls[name] = r.Render(name, srcs[name].Data())\n\t\t\/\/com.SaveFile(name+\".hmtl\", htmls[name])\n\t}\n\treturn htmls, nil\n}\n\n\/\/ A link describes the (HTML) link information for an identifier.\n\/\/ The zero value of a link represents \"no link\".\ntype Link struct {\n\tPath, Name, Comment string\n}\n\ntype localVar struct {\n\tname, tp string\n}\n\n\/\/ A Render describles a code render.\ntype Render struct {\n\trecv       localVar\n\tblockLevel int\n\n\tLinks     []*Link\n\tFilteList map[string]bool\n}\n\n\/\/ Render highlights code.\nfunc (r *Render) Render(name string, data []byte) []byte {\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\n\tcode := string(data)\n\tl := len(code)\n\n\tbuf := new(bytes.Buffer)\n\t\/\/buf.WriteString(\"<pre>\")\n\n\tstrTag := uint8(0)\n\tisComment := false\n\tisBlockComment := false\n\tisString := false\n\tisFuncDecl := false\n\tisFuncBlock := false\n\tisHasRecv := false\n\tisTypeDecl := false\n\tlast := 0\n\tpos := 0\n\n\tfor {\n\tCutWords:\n\t\tfor {\n\t\t\tcurChar := code[pos]\n\t\t\tif !com.IsLetter(curChar) {\n\t\t\t\tif isComment {\n\t\t\t\t\t\/\/ Comment.\n\t\t\t\t\tif isBlockComment {\n\t\t\t\t\t\t\/\/ Check if in end of block comment.\n\t\t\t\t\t\tif curChar == '\/' && code[pos-1] == '*' {\n\t\t\t\t\t\t\tbreak CutWords\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ Check if in start of block comment.\n\t\t\t\t\t\tif curChar == '*' && code[pos-1] == '\/' {\n\t\t\t\t\t\t\tisBlockComment = true\n\t\t\t\t\t\t} else if curChar == '\\n' {\n\t\t\t\t\t\t\tbreak CutWords\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ String.\n\t\t\t\t\tif curChar == '\\'' || curChar == '\"' || curChar == '`' {\n\t\t\t\t\t\tif !isString {\n\t\t\t\t\t\t\t\/\/ Set string tag.\n\t\t\t\t\t\t\tstrTag = curChar\n\t\t\t\t\t\t\tisString = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ Check if it is end of string or escaped character.\n\t\t\t\t\t\t\tif (code[pos-1] == '\\\\' && code[pos-2] == '\\\\') || code[pos-1] != '\\\\' {\n\t\t\t\t\t\t\t\t\/\/ Check string tag.\n\t\t\t\t\t\t\t\tif curChar == strTag {\n\t\t\t\t\t\t\t\t\t\/\/ Handle string highlight.\n\t\t\t\t\t\t\t\t\tbreak CutWords\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\n\t\t\t\t\tif !isString {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase curChar == '\/' && (code[pos+1] == '\/' || code[pos+1] == '*'):\n\t\t\t\t\t\t\tisComment = true\n\t\t\t\t\t\tcase curChar > 47 && curChar < 58: \/\/ Ends with number.\n\t\t\t\t\t\tcase curChar == '_' && code[pos-1] != ' ': \/\/ Underline: _.\n\t\t\t\t\t\tcase (curChar != '.' || curChar == '\\n'):\n\t\t\t\t\t\t\tbreak CutWords\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 pos == l-1 {\n\t\t\t\tbreak CutWords\n\t\t\t}\n\t\t\tpos++\n\t\t}\n\n\t\tseg := code[last : pos+1]\n\tCheckLink:\n\t\tswitch {\n\t\tcase isComment:\n\t\t\tisComment = false\n\t\t\tisBlockComment = false\n\t\t\tfmt.Fprintf(buf, `<span class=\"com\">%s<\/span>`, seg)\n\t\tcase isString:\n\t\t\tisString = false\n\t\t\tfmt.Fprintf(buf, `<span class=\"str\">%s<\/span>`, template.HTMLEscapeString(seg))\n\t\tcase seg == \"\\t\":\n\t\t\tfmt.Fprintf(buf, `%s`, \"    \")\n\t\tcase seg == \"{\":\n\t\t\tif isFuncDecl {\n\t\t\t\tisFuncDecl = false\n\t\t\t\tisFuncBlock = true\n\t\t\t}\n\n\t\t\tif isFuncBlock {\n\t\t\t\tr.blockLevel++\n\t\t\t}\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\tcase seg == \"}\":\n\t\t\tif isFuncBlock {\n\t\t\t\tr.blockLevel--\n\t\t\t}\n\t\t\tif r.blockLevel == 0 {\n\t\t\t\tisFuncBlock = false\n\t\t\t\tr.recv.name = \"\"\n\t\t\t}\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\tcase isFuncDecl:\n\t\t\tif isHasRecv {\n\t\t\t\tif seg != \"(\" && seg != \" \" && seg != \"*\" {\n\t\t\t\t\tif len(r.recv.name) == 0 {\n\t\t\t\t\t\tr.recv.name = seg[:len(seg)-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr.recv.tp = seg[:len(seg)-1]\n\t\t\t\t\t\tisHasRecv = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if len(seg) > 1 && code[pos] == '(' {\n\t\t\t\tif len(r.recv.name) > 0 {\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s_%s\\\">%s<\/span>(\", r.recv.tp, seg[:len(seg)-1], seg[:len(seg)-1])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s\\\">%s<\/span>(\", seg[:len(seg)-1], seg[:len(seg)-1])\n\t\t\t\t}\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase pos-last > 1:\n\t\t\t\/\/ Check if the last word of the paragraphy.\n\t\t\tl := len(seg)\n\t\t\tkeyword := seg\n\t\t\tif !com.IsLetter(seg[l-1]) {\n\t\t\t\tkeyword = seg[:l-1]\n\t\t\t} else {\n\t\t\t\tl++\n\t\t\t}\n\n\t\t\t\/\/ Check keywords.\n\t\t\tswitch keyword {\n\t\t\tcase \"return\", \"break\":\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"ret\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\tcase \"func\":\n\t\t\t\tisFuncDecl = true\n\t\t\t\tif code[pos+1] == '(' {\n\t\t\t\t\tisHasRecv = true\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"package\", \"import\", \"range\", \"for\", \"if\", \"else\", \"type\", \"struct\", \"select\", \"case\", \"var\", \"const\", \"switch\", \"default\", \"continue\":\n\t\t\t\tif keyword == \"type\" {\n\t\t\t\t\tisTypeDecl = true\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"key\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\tcase \"new\", \"append\", \"make\", \"panic\", \"recover\", \"len\", \"cap\", \"copy\", \"close\", \"delete\", \"defer\":\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"bui\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\n\t\t\tif isPredeclared(keyword) {\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"boo\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\n\t\t\t\/\/ Check links.\n\t\t\tlink, ok := r.findType(seg)\n\t\t\tif ok {\n\t\t\t\tswitch {\n\t\t\t\tcase strings.HasSuffix(link.Path, name) && len(link.Name) > 0: \/\/ Current file.\n\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"int\" title=\"%s\" href=\"#%s\">%s<\/a>%s`,\n\t\t\t\t\t\tlink.Comment, link.Name, link.Name, seg[l-1:])\n\t\t\t\tcase len(link.Path) > 0 && len(link.Name) > 0:\n\t\t\t\t\tif strings.HasPrefix(link.Path, \"#\") {\n\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" href=\"%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, seg[l-1:])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif strings.Index(link.Path, \"#\") > -1 {\n\t\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" target=\"_blank\" href=\"%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, seg[l-1:])\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" target=\"_blank\" href=\"\/%s#%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, link.Name, seg[l-1:])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if seg[len(seg)-1] == ' ' || seg[len(seg)-1] == '\\n' {\n\t\t\t\tif isFuncDecl || isTypeDecl {\n\t\t\t\t\tisTypeDecl = false\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s\\\">%s<\/span>%s\", seg[:len(seg)-1], seg[:len(seg)-1], seg[l-1:])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t}\n\n\t\tlast = pos + 1\n\t\tpos++\n\t\t\/\/ End of code.\n\t\tif pos == l {\n\t\t\tfmt.Fprintf(buf, \"%s\", code[last:])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}\n\nfunc (r *Render) findType(name string) (*Link, bool) {\n\tif !com.IsLetter(name[0]) {\n\t\treturn nil, false\n\t}\n\n\t\/\/ We cannot deal with struct field now.\n\tif name[len(name)-1] == '[' || name[len(name)-1] == ']' ||\n\t\tname[len(name)-1] == ' ' || name[len(name)-1] == ':' {\n\t\treturn nil, false\n\t}\n\n\t\/\/ We cannot deal with chain operation.\n\tif name[0] == '.' {\n\t\treturn nil, false\n\t}\n\n\tname = name[:len(name)-1]\n\n\t\/\/ This is for functions and types from imported packages.\n\ti := strings.Index(name, \".\")\n\t\/\/ We cannot deal with struct field or chain operation now.\n\tif i != strings.LastIndex(name, \".\") {\n\t\treturn nil, false\n\t}\n\n\tif filte := r.FilteList[name]; filte {\n\t\treturn nil, false\n\t}\n\n\tvar left, right string\n\tif i > -1 {\n\t\tleft = name[:i+1]\n\t\tright = name[i+1:]\n\t}\n\n\tfor _, l := range r.Links {\n\t\tif i == -1 {\n\t\t\t\/\/ Exported types and functions in current package.\n\t\t\tif l.Name == name {\n\t\t\t\treturn l, true\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Functions and types from imported packages.\n\t\t\tif l.Name == left {\n\t\t\t\tif len(l.Path) > 0 {\n\t\t\t\t\treturn &Link{Name: name, Path: \"\/\" + l.Path + \"#\" + right}, true\n\t\t\t\t} else {\n\t\t\t\t\treturn &Link{Name: name, Path: \"#\" + right}, true\n\t\t\t\t}\n\t\t\t} else if r.recv.name == left[:len(left)-1] {\n\t\t\t\t\/\/ fmt.Println(r.recv.tp + \".\" + right)\n\t\t\t\t\/\/ fmt.Println(r.findType(r.recv.tp + \".\" + right))\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t}\n\n\tr.FilteList[name] = true\n\treturn nil, false\n}\n\n\/\/ GetLinks returns objects with its jump link.\nfunc GetLinks(prefix string, imports []string, files map[string]File) []*Link {\n\tprefix += \"?f=\"\n\tlinks := make([]*Link, 0, len(imports)+len(files)*20+10)\n\tfor fname, f := range files {\n\t\t\/\/ Get all types, functions and import packages.\n\t\tfor _, t := range f.Types {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    t.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(t.Doc),\n\t\t\t})\n\n\t\t\tfor _, f := range t.Funcs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor _, f := range t.IFuncs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor _, t := range f.Itypes {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    t.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(t.Doc),\n\t\t\t})\n\n\t\t\tfor _, f := range t.Funcs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor _, f := range t.IFuncs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor _, f := range f.Funcs {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    f.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t})\n\t\t}\n\n\t\tfor _, f := range f.Ifuncs {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    f.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, v := range imports {\n\t\tif v != \"C\" {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName: path.Base(v) + \".\",\n\t\t\t\tPath: v,\n\t\t\t})\n\t\t}\n\t}\n\treturn links\n}\n\nfunc isPredeclared(name string) bool {\n\t_, ok := predeclared[name]\n\treturn ok\n}\n<commit_msg>try to fix bug<commit_after>\/\/ Copyright 2013-2014 Unknown\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\/\/ Package Hacker View provides APIs to analyze Go projects and generate AST-based source code view.\npackage hv\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/Unknwon\/com\"\n)\n\n\/\/ Render renders source code to HTML.\n\/\/ Note that you have to call Build before you call this method.\nfunc (w *Walker) Render() (map[string][]byte, error) {\n\thtmls := make(map[string][]byte)\n\tfiles := make(map[string]File)\n\tsrcs := w.SrcFiles\n\timports := make([]string, 0, 10)\n\n\tfor name, src := range srcs {\n\t\tpkg, err := w.Build(&WalkRes{\n\t\t\tWalkDepth: WD_All,\n\t\t\tWalkType:  WT_Memory,\n\t\t\tWalkMode:  WM_NoReadme | WM_NoExample,\n\t\t\tSrcs:      []*Source{src},\n\t\t\tBuildAll:  true,\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"hv.Walker.Render -> \" + err.Error())\n\t\t}\n\n\t\tfiles[name] = pkg.File\n\n\t\tfor _, v := range w.Pdoc.Imports {\n\t\t\timports = com.AppendStr(imports, v)\n\t\t}\n\t}\n\n\tr := Render{\n\t\tLinks:     GetLinks(w.Pdoc.ImportPath, imports, files),\n\t\tFilteList: make(map[string]bool),\n\t}\n\n\tfor name := range srcs {\n\t\thtmls[name] = r.Render(name, srcs[name].Data())\n\t\t\/\/com.SaveFile(name+\".hmtl\", htmls[name])\n\t}\n\treturn htmls, nil\n}\n\n\/\/ A link describes the (HTML) link information for an identifier.\n\/\/ The zero value of a link represents \"no link\".\ntype Link struct {\n\tPath, Name, Comment string\n}\n\ntype localVar struct {\n\tname, tp string\n}\n\n\/\/ A Render describles a code render.\ntype Render struct {\n\trecv       localVar\n\tblockLevel int\n\n\tLinks     []*Link\n\tFilteList map[string]bool\n}\n\n\/\/ Render highlights code.\nfunc (r *Render) Render(name string, data []byte) []byte {\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\n\tcode := string(data)\n\tl := len(code)\n\n\tbuf := new(bytes.Buffer)\n\t\/\/buf.WriteString(\"<pre>\")\n\n\tstrTag := uint8(0)\n\tisComment := false\n\tisBlockComment := false\n\tisString := false\n\tisFuncDecl := false\n\tisFuncBlock := false\n\tisHasRecv := false\n\tisTypeDecl := false\n\tlast := 0\n\tpos := 0\n\n\tfor {\n\tCutWords:\n\t\tfor {\n\t\t\tcurChar := code[pos]\n\t\t\tif !com.IsLetter(curChar) {\n\t\t\t\tif isComment {\n\t\t\t\t\t\/\/ Comment.\n\t\t\t\t\tif isBlockComment {\n\t\t\t\t\t\t\/\/ Check if in end of block comment.\n\t\t\t\t\t\tif curChar == '\/' && code[pos-1] == '*' {\n\t\t\t\t\t\t\tbreak CutWords\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ Check if in start of block comment.\n\t\t\t\t\t\tif curChar == '*' && code[pos-1] == '\/' {\n\t\t\t\t\t\t\tisBlockComment = true\n\t\t\t\t\t\t} else if curChar == '\\n' {\n\t\t\t\t\t\t\tbreak CutWords\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ String.\n\t\t\t\t\tif curChar == '\\'' || curChar == '\"' || curChar == '`' {\n\t\t\t\t\t\tif !isString {\n\t\t\t\t\t\t\t\/\/ Set string tag.\n\t\t\t\t\t\t\tstrTag = curChar\n\t\t\t\t\t\t\tisString = true\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ Check if it is end of string or escaped character.\n\t\t\t\t\t\t\tif (code[pos-1] == '\\\\' && code[pos-2] == '\\\\') || code[pos-1] != '\\\\' {\n\t\t\t\t\t\t\t\t\/\/ Check string tag.\n\t\t\t\t\t\t\t\tif curChar == strTag {\n\t\t\t\t\t\t\t\t\t\/\/ Handle string highlight.\n\t\t\t\t\t\t\t\t\tbreak CutWords\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\n\t\t\t\t\t\/\/ FIXME: index out of range\n\t\t\t\t\tif len(code) <= pos {\n\t\t\t\t\t\tbreak CutWords\n\t\t\t\t\t}\n\t\t\t\t\tif !isString {\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase curChar == '\/' && (code[pos+1] == '\/' || code[pos+1] == '*'):\n\t\t\t\t\t\t\tisComment = true\n\t\t\t\t\t\tcase curChar > 47 && curChar < 58: \/\/ Ends with number.\n\t\t\t\t\t\tcase curChar == '_' && code[pos-1] != ' ': \/\/ Underline: _.\n\t\t\t\t\t\tcase (curChar != '.' || curChar == '\\n'):\n\t\t\t\t\t\t\tbreak CutWords\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 pos == l-1 {\n\t\t\t\tbreak CutWords\n\t\t\t}\n\t\t\tpos++\n\t\t}\n\n\t\tseg := code[last : pos+1]\n\tCheckLink:\n\t\tswitch {\n\t\tcase isComment:\n\t\t\tisComment = false\n\t\t\tisBlockComment = false\n\t\t\tfmt.Fprintf(buf, `<span class=\"com\">%s<\/span>`, seg)\n\t\tcase isString:\n\t\t\tisString = false\n\t\t\tfmt.Fprintf(buf, `<span class=\"str\">%s<\/span>`, template.HTMLEscapeString(seg))\n\t\tcase seg == \"\\t\":\n\t\t\tfmt.Fprintf(buf, `%s`, \"    \")\n\t\tcase seg == \"{\":\n\t\t\tif isFuncDecl {\n\t\t\t\tisFuncDecl = false\n\t\t\t\tisFuncBlock = true\n\t\t\t}\n\n\t\t\tif isFuncBlock {\n\t\t\t\tr.blockLevel++\n\t\t\t}\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\tcase seg == \"}\":\n\t\t\tif isFuncBlock {\n\t\t\t\tr.blockLevel--\n\t\t\t}\n\t\t\tif r.blockLevel == 0 {\n\t\t\t\tisFuncBlock = false\n\t\t\t\tr.recv.name = \"\"\n\t\t\t}\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\tcase isFuncDecl:\n\t\t\tif isHasRecv {\n\t\t\t\tif seg != \"(\" && seg != \" \" && seg != \"*\" {\n\t\t\t\t\tif len(r.recv.name) == 0 {\n\t\t\t\t\t\tr.recv.name = seg[:len(seg)-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr.recv.tp = seg[:len(seg)-1]\n\t\t\t\t\t\tisHasRecv = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if len(seg) > 1 && code[pos] == '(' {\n\t\t\t\tif len(r.recv.name) > 0 {\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s_%s\\\">%s<\/span>(\", r.recv.tp, seg[:len(seg)-1], seg[:len(seg)-1])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s\\\">%s<\/span>(\", seg[:len(seg)-1], seg[:len(seg)-1])\n\t\t\t\t}\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase pos-last > 1:\n\t\t\t\/\/ Check if the last word of the paragraphy.\n\t\t\tl := len(seg)\n\t\t\tkeyword := seg\n\t\t\tif !com.IsLetter(seg[l-1]) {\n\t\t\t\tkeyword = seg[:l-1]\n\t\t\t} else {\n\t\t\t\tl++\n\t\t\t}\n\n\t\t\t\/\/ Check keywords.\n\t\t\tswitch keyword {\n\t\t\tcase \"return\", \"break\":\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"ret\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\tcase \"func\":\n\t\t\t\tisFuncDecl = true\n\t\t\t\tif code[pos+1] == '(' {\n\t\t\t\t\tisHasRecv = true\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"package\", \"import\", \"range\", \"for\", \"if\", \"else\", \"type\", \"struct\", \"select\", \"case\", \"var\", \"const\", \"switch\", \"default\", \"continue\":\n\t\t\t\tif keyword == \"type\" {\n\t\t\t\t\tisTypeDecl = true\n\t\t\t\t}\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"key\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\tcase \"new\", \"append\", \"make\", \"panic\", \"recover\", \"len\", \"cap\", \"copy\", \"close\", \"delete\", \"defer\":\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"bui\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\n\t\t\tif isPredeclared(keyword) {\n\t\t\t\tfmt.Fprintf(buf, `<span class=\"boo\">%s<\/span>%s`, keyword, seg[l-1:])\n\t\t\t\tbreak CheckLink\n\t\t\t}\n\n\t\t\t\/\/ Check links.\n\t\t\tlink, ok := r.findType(seg)\n\t\t\tif ok {\n\t\t\t\tswitch {\n\t\t\t\tcase strings.HasSuffix(link.Path, name) && len(link.Name) > 0: \/\/ Current file.\n\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"int\" title=\"%s\" href=\"#%s\">%s<\/a>%s`,\n\t\t\t\t\t\tlink.Comment, link.Name, link.Name, seg[l-1:])\n\t\t\t\tcase len(link.Path) > 0 && len(link.Name) > 0:\n\t\t\t\t\tif strings.HasPrefix(link.Path, \"#\") {\n\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" href=\"%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, seg[l-1:])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif strings.Index(link.Path, \"#\") > -1 {\n\t\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" target=\"_blank\" href=\"%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, seg[l-1:])\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Fprintf(buf, `<a class=\"ext\" title=\"%s\" target=\"_blank\" href=\"\/%s#%s\">%s<\/a>%s`,\n\t\t\t\t\t\t\t\tlink.Comment, link.Path, link.Name, link.Name, seg[l-1:])\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if seg[len(seg)-1] == ' ' || seg[len(seg)-1] == '\\n' {\n\t\t\t\tif isFuncDecl || isTypeDecl {\n\t\t\t\t\tisTypeDecl = false\n\t\t\t\t\tfmt.Fprintf(buf, \"<span id=\\\"%s\\\">%s<\/span>%s\", seg[:len(seg)-1], seg[:len(seg)-1], seg[l-1:])\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Fprintf(buf, \"%s\", seg)\n\t\t}\n\n\t\tlast = pos + 1\n\t\tpos++\n\t\t\/\/ End of code.\n\t\tif pos == l {\n\t\t\tfmt.Fprintf(buf, \"%s\", code[last:])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn buf.Bytes()\n}\n\nfunc (r *Render) findType(name string) (*Link, bool) {\n\tif !com.IsLetter(name[0]) {\n\t\treturn nil, false\n\t}\n\n\t\/\/ We cannot deal with struct field now.\n\tif name[len(name)-1] == '[' || name[len(name)-1] == ']' ||\n\t\tname[len(name)-1] == ' ' || name[len(name)-1] == ':' {\n\t\treturn nil, false\n\t}\n\n\t\/\/ We cannot deal with chain operation.\n\tif name[0] == '.' {\n\t\treturn nil, false\n\t}\n\n\tname = name[:len(name)-1]\n\n\t\/\/ This is for functions and types from imported packages.\n\ti := strings.Index(name, \".\")\n\t\/\/ We cannot deal with struct field or chain operation now.\n\tif i != strings.LastIndex(name, \".\") {\n\t\treturn nil, false\n\t}\n\n\tif filte := r.FilteList[name]; filte {\n\t\treturn nil, false\n\t}\n\n\tvar left, right string\n\tif i > -1 {\n\t\tleft = name[:i+1]\n\t\tright = name[i+1:]\n\t}\n\n\tfor _, l := range r.Links {\n\t\tif i == -1 {\n\t\t\t\/\/ Exported types and functions in current package.\n\t\t\tif l.Name == name {\n\t\t\t\treturn l, true\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Functions and types from imported packages.\n\t\t\tif l.Name == left {\n\t\t\t\tif len(l.Path) > 0 {\n\t\t\t\t\treturn &Link{Name: name, Path: \"\/\" + l.Path + \"#\" + right}, true\n\t\t\t\t} else {\n\t\t\t\t\treturn &Link{Name: name, Path: \"#\" + right}, true\n\t\t\t\t}\n\t\t\t} else if r.recv.name == left[:len(left)-1] {\n\t\t\t\t\/\/ fmt.Println(r.recv.tp + \".\" + right)\n\t\t\t\t\/\/ fmt.Println(r.findType(r.recv.tp + \".\" + right))\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t}\n\n\tr.FilteList[name] = true\n\treturn nil, false\n}\n\n\/\/ GetLinks returns objects with its jump link.\nfunc GetLinks(prefix string, imports []string, files map[string]File) []*Link {\n\tprefix += \"?f=\"\n\tlinks := make([]*Link, 0, len(imports)+len(files)*20+10)\n\tfor fname, f := range files {\n\t\t\/\/ Get all types, functions and import packages.\n\t\tfor _, t := range f.Types {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    t.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(t.Doc),\n\t\t\t})\n\n\t\t\tfor _, f := range t.Funcs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor _, f := range t.IFuncs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor _, t := range f.Itypes {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    t.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(t.Doc),\n\t\t\t})\n\n\t\t\tfor _, f := range t.Funcs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tfor _, f := range t.IFuncs {\n\t\t\t\tlinks = append(links, &Link{\n\t\t\t\t\tName:    f.Name,\n\t\t\t\t\tPath:    prefix + fname,\n\t\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfor _, f := range f.Funcs {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    f.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t})\n\t\t}\n\n\t\tfor _, f := range f.Ifuncs {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName:    f.Name,\n\t\t\t\tPath:    prefix + fname,\n\t\t\t\tComment: template.HTMLEscapeString(f.Doc),\n\t\t\t})\n\t\t}\n\t}\n\n\tfor _, v := range imports {\n\t\tif v != \"C\" {\n\t\t\tlinks = append(links, &Link{\n\t\t\t\tName: path.Base(v) + \".\",\n\t\t\t\tPath: v,\n\t\t\t})\n\t\t}\n\t}\n\treturn links\n}\n\nfunc isPredeclared(name string) bool {\n\t_, ok := predeclared[name]\n\treturn ok\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"encoding\/json\"\nimport \"flag\"\nimport \"fmt\"\nimport \"io\/ioutil\"\nimport \"math\/rand\"\nimport \"time\"\nimport \"os\"\nimport \"runtime\"\n\nfunc main() {\n\tnumRenderJobs := flag.Int(\n\t\t\"j\", runtime.NumCPU(), \"how many render jobs to spawn\")\n\n\tflag.Parse()\n\n\truntime.GOMAXPROCS(*numRenderJobs)\n\n\tseed := time.Now().UTC().UnixNano()\n\trng := rand.New(rand.NewSource(seed))\n\n\tif flag.NArg() < 1 {\n\t\tfmt.Fprintf(\n\t\t\tos.Stderr, \"%s [options] [scene.json...]\\n\",\n\t\t\tos.Args[0])\n\t\tflag.PrintDefaults()\n\t\tos.Exit(-1)\n\t}\n\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\tinputPath := flag.Arg(i)\n\t\tfmt.Printf(\n\t\t\t\"Processing %s (%d\/%d)...\\n\",\n\t\t\tinputPath, i+1, flag.NArg())\n\t\tconfigBytes, err := ioutil.ReadFile(inputPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tvar config map[string]interface{}\n\t\terr = json.Unmarshal(configBytes, &config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tsceneConfig := config[\"scene\"].(map[string]interface{})\n\t\tscene := MakeScene(sceneConfig)\n\t\trendererConfig := config[\"renderer\"].(map[string]interface{})\n\t\trenderer := MakeRenderer(rendererConfig)\n\t\trenderer.Render(*numRenderJobs, rng, &scene)\n\t}\n}\n<commit_msg>Add flag to write a CPU profile<commit_after>package main\n\nimport \"encoding\/json\"\nimport \"flag\"\nimport \"fmt\"\nimport \"io\/ioutil\"\nimport \"math\/rand\"\nimport \"time\"\nimport \"os\"\nimport \"runtime\"\nimport \"runtime\/pprof\"\n\nfunc main() {\n\tnumRenderJobs := flag.Int(\n\t\t\"j\", runtime.NumCPU(), \"how many render jobs to spawn\")\n\n\tprofilePath := flag.String(\n\t\t\"p\", \"\", \"if non-empty, path to write the cpu profile to\")\n\n\tflag.Parse()\n\n\tif len(*profilePath) > 0 {\n\t\tf, err := os.Create(*profilePath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer func() {\n\t\t\tif err := f.Close(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\n\t\tpprof.StartCPUProfile(f)\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\n\truntime.GOMAXPROCS(*numRenderJobs)\n\n\tseed := time.Now().UTC().UnixNano()\n\trng := rand.New(rand.NewSource(seed))\n\n\tif flag.NArg() < 1 {\n\t\tfmt.Fprintf(\n\t\t\tos.Stderr, \"%s [options] [scene.json...]\\n\",\n\t\t\tos.Args[0])\n\t\tflag.PrintDefaults()\n\t\tos.Exit(-1)\n\t}\n\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\tinputPath := flag.Arg(i)\n\t\tfmt.Printf(\n\t\t\t\"Processing %s (%d\/%d)...\\n\",\n\t\t\tinputPath, i+1, flag.NArg())\n\t\tconfigBytes, err := ioutil.ReadFile(inputPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tvar config map[string]interface{}\n\t\terr = json.Unmarshal(configBytes, &config)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tsceneConfig := config[\"scene\"].(map[string]interface{})\n\t\tscene := MakeScene(sceneConfig)\n\t\trendererConfig := config[\"renderer\"].(map[string]interface{})\n\t\trenderer := MakeRenderer(rendererConfig)\n\t\trenderer.Render(*numRenderJobs, rng, &scene)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package indexer\n\nimport (\n\t\"sync\"\n\t\"sort\"\n)\n\n\/\/ Index is a single index.\ntype Index struct {\n\tkeys []IndexElement\n\tm sync.RWMutex\n}\n\n\/\/NewIndex creates an Index instance\nfunc NewIndex() *Index {\n\tindex := new(Index)\n\tindex.keys = []IndexElement{}\n\treturn index\n}\n\n\/\/Len returns length of the index\nfunc (in *Index) Len() int {\n\treturn len(in.keys)\n}\n\n\/\/Less inompares values\nfunc (in *Index) Less(i, j int) bool {\n\treturn in.keys[i].Less(in.keys[j])\n}\n\n\/\/Swap swaps IndexElements in list\nfunc (in *Index) Swap(i, j int) {\n\tin.keys[i], in.keys[j] = in.keys[j], in.keys[i]\n}\n\n\/\/Add adds a single IndexElement\nfunc (in *Index) Add(element IndexElement) {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tlocation := 0\n\tfor key, index := range in.keys {\n\t\tif element.Less(index) {\n\t\t\tlocation = key\n\t\t} else {\n\t\t\tin.keys = append(in.keys[:location], element, in.keys[key:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Remove deletes a single IndexElement\nfunc (in *Index) Remove(element IndexElement) {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tfor key, index := range in.keys {\n\t\tif element.Key() == index.Key() {\n\t\t\tin.keys = append(in.keys[:key], in.keys[key+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Sort sorts IndexElement list\nfunc (in *Index) Sort() {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tsort.Sort(in)\n}\n<commit_msg>Fix \"too many arguments to append\" error<commit_after>package indexer\n\nimport (\n\t\"sync\"\n\t\"sort\"\n)\n\n\/\/ Index is a single index.\ntype Index struct {\n\tkeys []IndexElement\n\tm sync.RWMutex\n}\n\n\/\/NewIndex creates an Index instance\nfunc NewIndex() *Index {\n\tindex := new(Index)\n\tindex.keys = []IndexElement{}\n\treturn index\n}\n\n\/\/Len returns length of the index\nfunc (in *Index) Len() int {\n\treturn len(in.keys)\n}\n\n\/\/Less inompares values\nfunc (in *Index) Less(i, j int) bool {\n\treturn in.keys[i].Less(in.keys[j])\n}\n\n\/\/Swap swaps IndexElements in list\nfunc (in *Index) Swap(i, j int) {\n\tin.keys[i], in.keys[j] = in.keys[j], in.keys[i]\n}\n\n\/\/Add adds a single IndexElement\nfunc (in *Index) Add(element IndexElement) {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tlocation := 0\n\tfor key, index := range in.keys {\n\t\tif element.Less(index) {\n\t\t\tlocation = key\n\t\t} else {\n\t\t\tbefore := append(in.keys[:location], element)\n\t\t\tin.keys = append(before, in.keys[key:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Remove deletes a single IndexElement\nfunc (in *Index) Remove(element IndexElement) {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tfor key, index := range in.keys {\n\t\tif element.Key() == index.Key() {\n\t\t\tin.keys = append(in.keys[:key], in.keys[key+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Sort sorts IndexElement list\nfunc (in *Index) Sort() {\n\tin.m.Lock()\n\tdefer in.m.Unlock()\n\tsort.Sort(in)\n}\n<|endoftext|>"}
{"text":"<commit_before>package git\n\n\/*\n#cgo pkg-config: libgit2\n#include <git2.h>\n#include <git2\/errors.h>\n*\/\nimport \"C\"\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\t\"unsafe\"\n)\n\ntype Index struct {\n\tptr *C.git_index\n}\n\ntype IndexEntry struct {\n\tCtime time.Time\n\tMtime time.Time\n\tMode  uint\n\tUid   uint\n\tGid   uint\n\tSize  uint\n\tOid   *Oid\n\tPath  string\n}\n\nfunc newIndexFromC(ptr *C.git_index) *Index {\n\tidx := &Index{ptr}\n\truntime.SetFinalizer(idx, (*Index).Free)\n\treturn idx\n}\n\nfunc (v *Index) AddByPath(path string) error {\n\tcstr := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cstr))\n\n\tret := C.git_index_add_bypath(v.ptr, cstr)\n\tif ret < 0 {\n\t\treturn LastError()\n\t}\n\n\treturn nil\n}\n\nfunc (v *Index) WriteTree() (*Oid, error) {\n\toid := new(Oid)\n\tret := C.git_index_write_tree(oid.toC(), v.ptr)\n\tif ret < 0 {\n\t\treturn nil, LastError()\n\t}\n\n\treturn oid, nil\n}\n\nfunc (v *Index) Free() {\n\truntime.SetFinalizer(v, nil)\n\tC.git_index_free(v.ptr)\n}\n\nfunc (v *Index) EntryCount() uint {\n\treturn uint(C.git_index_entrycount(v.ptr))\n}\n\nfunc newIndexEntryFromC(entry *C.git_index_entry) *IndexEntry {\n\treturn &IndexEntry{\n\t\ttime.Unix(int64(entry.ctime.seconds), int64(entry.ctime.nanoseconds)),\n\t\ttime.Unix(int64(entry.mtime.seconds), int64(entry.mtime.nanoseconds)),\n\t\tuint(entry.mode),\n\t\tuint(entry.uid),\n\t\tuint(entry.gid),\n\t\tuint(entry.file_size),\n\t\tnewOidFromC(&entry.oid),\n\t\tC.GoString(entry.path),\n\t}\n}\n\nfunc (v *Index) EntryByIndex(index uint) (*IndexEntry, error) {\n\tcentry := C.git_index_get_byindex(v.ptr, C.size_t(index))\n\tif centry == nil {\n\t\treturn nil, fmt.Errorf(\"Index out of Bounds\")\n\t}\n\treturn newIndexEntryFromC(centry), nil\n}\n<commit_msg>Adjust to oid -> id<commit_after>package git\n\n\/*\n#cgo pkg-config: libgit2\n#include <git2.h>\n#include <git2\/errors.h>\n*\/\nimport \"C\"\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\t\"unsafe\"\n)\n\ntype Index struct {\n\tptr *C.git_index\n}\n\ntype IndexEntry struct {\n\tCtime time.Time\n\tMtime time.Time\n\tMode  uint\n\tUid   uint\n\tGid   uint\n\tSize  uint\n\tId   *Oid\n\tPath  string\n}\n\nfunc newIndexFromC(ptr *C.git_index) *Index {\n\tidx := &Index{ptr}\n\truntime.SetFinalizer(idx, (*Index).Free)\n\treturn idx\n}\n\nfunc (v *Index) AddByPath(path string) error {\n\tcstr := C.CString(path)\n\tdefer C.free(unsafe.Pointer(cstr))\n\n\tret := C.git_index_add_bypath(v.ptr, cstr)\n\tif ret < 0 {\n\t\treturn LastError()\n\t}\n\n\treturn nil\n}\n\nfunc (v *Index) WriteTree() (*Oid, error) {\n\toid := new(Oid)\n\tret := C.git_index_write_tree(oid.toC(), v.ptr)\n\tif ret < 0 {\n\t\treturn nil, LastError()\n\t}\n\n\treturn oid, nil\n}\n\nfunc (v *Index) Free() {\n\truntime.SetFinalizer(v, nil)\n\tC.git_index_free(v.ptr)\n}\n\nfunc (v *Index) EntryCount() uint {\n\treturn uint(C.git_index_entrycount(v.ptr))\n}\n\nfunc newIndexEntryFromC(entry *C.git_index_entry) *IndexEntry {\n\treturn &IndexEntry{\n\t\ttime.Unix(int64(entry.ctime.seconds), int64(entry.ctime.nanoseconds)),\n\t\ttime.Unix(int64(entry.mtime.seconds), int64(entry.mtime.nanoseconds)),\n\t\tuint(entry.mode),\n\t\tuint(entry.uid),\n\t\tuint(entry.gid),\n\t\tuint(entry.file_size),\n\t\tnewOidFromC(&entry.id),\n\t\tC.GoString(entry.path),\n\t}\n}\n\nfunc (v *Index) EntryByIndex(index uint) (*IndexEntry, error) {\n\tcentry := C.git_index_get_byindex(v.ptr, C.size_t(index))\n\tif centry == nil {\n\t\treturn nil, fmt.Errorf(\"Index out of Bounds\")\n\t}\n\treturn newIndexEntryFromC(centry), nil\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\/\/ This package implements the PEM data encoding, which originated in Privacy\n\/\/ Enhanced Mail. The most common use of PEM encoding today is in TLS keys and\n\/\/ certificates. See RFC 1421.\npackage pem\n\nimport (\n\t\"bytes\";\n\t\"encoding\/base64\";\n\t\"strings\";\n)\n\n\/\/ A Block represents a PEM encoded structure.\n\/\/\n\/\/ The encoded form is:\n\/\/    -----BEGIN Type-----\n\/\/    Headers\n\/\/    base64-encoded Bytes\n\/\/    -----END Type-----\n\/\/ where Headers is a possibly empty sequence of Key: Value lines.\ntype Block struct {\n\tType\tstring;\t\t\t\/\/ The type, taken from the preamble (i.e. \"RSA PRIVATE KEY\").\n\tHeaders\tmap[string]string;\t\/\/ Optional headers.\n\tBytes\t[]byte;\t\t\t\/\/ The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.\n}\n\n\/\/ getLine results the first \\r\\n or \\n delineated line from the given byte\n\/\/ array. The line does not include the \\r\\n or \\n. The remainder of the byte\n\/\/ array (also not including the new line bytes) is also returned and this will\n\/\/ always be smaller than the original argument.\nfunc getLine(data []byte) (line, rest []byte) {\n\ti := bytes.Index(data, []byte{'\\n'});\n\tvar j int;\n\tif i < 0 {\n\t\ti = len(data);\n\t\tj = i;\n\t} else {\n\t\tj = i+1;\n\t\tif i > 0 && data[i-1] == '\\r' {\n\t\t\ti--;\n\t\t}\n\t}\n\treturn data[0:i], data[j:len(data)];\n}\n\n\/\/ removeWhitespace returns a copy of its input with all spaces, tab and\n\/\/ newline characters removed.\nfunc removeWhitespace(data []byte) []byte {\n\tresult := make([]byte, len(data));\n\tn := 0;\n\n\tfor _, b := range data {\n\t\tif b == ' ' || b == '\\t' || b == '\\r' || b == '\\n' {\n\t\t\tcontinue;\n\t\t}\n\t\tresult[n] = b;\n\t\tn++;\n\t}\n\n\treturn result[0:n];\n}\n\nvar pemStart = strings.Bytes(\"\\n-----BEGIN \")\nvar pemEnd = strings.Bytes(\"\\n-----END \")\nvar pemEndOfLine = strings.Bytes(\"-----\")\n\n\/\/ Decode will find the next PEM formatted block (certificate, private key\n\/\/ etc) in the input. It returns that block and the remainder of the input. If\n\/\/ no PEM data is found, p is nil and the whole of the input is returned in \/\/ rest.\nfunc Decode(data []byte) (p *Block, rest []byte) {\n\t\/\/ pemStart begins with a newline. However, at the very beginning of\n\t\/\/ the byte array, we'll accept the start string without it.\n\trest = data;\n\tif bytes.HasPrefix(data, pemStart[1:len(pemStart)]) {\n\t\trest = rest[len(pemStart)-1 : len(data)];\n\t} else if i := bytes.Index(data, pemStart); i >= 0 {\n\t\trest = rest[i+len(pemStart) : len(data)];\n\t} else {\n\t\treturn nil, data;\n\t}\n\n\ttypeLine, rest := getLine(rest);\n\tif !bytes.HasSuffix(typeLine, pemEndOfLine) {\n\t\tgoto Error;\n\t}\n\ttypeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)];\n\n\tp = &Block{\n\t\tHeaders: make(map[string]string),\n\t\tType: string(typeLine),\n\t};\n\n\tfor {\n\t\t\/\/ This loop terminates because getLine's second result is\n\t\t\/\/ always smaller than it's argument.\n\t\tif len(rest) == 0 {\n\t\t\treturn nil, data;\n\t\t}\n\t\tline, next := getLine(rest);\n\n\t\ti := bytes.Index(line, []byte{':'});\n\t\tif i == -1 {\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ TODO(agl): need to cope with values that spread across lines.\n\t\tkey, val := line[0:i], line[i+1 : len(line)];\n\t\tkey = bytes.TrimSpace(key);\n\t\tval = bytes.TrimSpace(val);\n\t\tp.Headers[string(key)] = string(val);\n\t\trest = next;\n\t}\n\n\ti := bytes.Index(rest, pemEnd);\n\tif i < 0 {\n\t\tgoto Error;\n\t}\n\tbase64Data := removeWhitespace(rest[0:i]);\n\n\tp.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data)));\n\tn, err := base64.StdEncoding.Decode(base64Data, p.Bytes);\n\tif err != nil {\n\t\tgoto Error;\n\t}\n\tp.Bytes = p.Bytes[0:n];\n\n\t_, rest = getLine(rest[i+len(pemEnd) : len(rest)]);\n\n\treturn;\n\nError:\n\t\/\/ If we get here then we have rejected a likely looking, but\n\t\/\/ ultimately invalid PEM block. We need to start over from a new\n\t\/\/ position.  We have consumed the preamble line and will have consumed\n\t\/\/ any lines which could be header lines. However, a valid preamble\n\t\/\/ line is not a valid header line, therefore we cannot have consumed\n\t\/\/ the preamble line for the any subsequent block. Thus, we will always\n\t\/\/ find any valid block, no matter what bytes preceed it.\n\t\/\/\n\t\/\/ For example, if the input is\n\t\/\/\n\t\/\/    -----BEGIN MALFORMED BLOCK-----\n\t\/\/    junk that may look like header lines\n\t\/\/   or data lines, but no END line\n\t\/\/\n\t\/\/    -----BEGIN ACTUAL BLOCK-----\n\t\/\/    realdata\n\t\/\/    -----END ACTUAL BLOCK-----\n\t\/\/\n\t\/\/ we've failed to parse using the first BEGIN line\n\t\/\/ and now will try again, using the second BEGIN line.\n\tp, rest = Decode(rest);\n\tif p == nil {\n\t\trest = data;\n\t}\n\treturn;\n}\n<commit_msg>Fix typo in 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\/\/ This package implements the PEM data encoding, which originated in Privacy\n\/\/ Enhanced Mail. The most common use of PEM encoding today is in TLS keys and\n\/\/ certificates. See RFC 1421.\npackage pem\n\nimport (\n\t\"bytes\";\n\t\"encoding\/base64\";\n\t\"strings\";\n)\n\n\/\/ A Block represents a PEM encoded structure.\n\/\/\n\/\/ The encoded form is:\n\/\/    -----BEGIN Type-----\n\/\/    Headers\n\/\/    base64-encoded Bytes\n\/\/    -----END Type-----\n\/\/ where Headers is a possibly empty sequence of Key: Value lines.\ntype Block struct {\n\tType\tstring;\t\t\t\/\/ The type, taken from the preamble (i.e. \"RSA PRIVATE KEY\").\n\tHeaders\tmap[string]string;\t\/\/ Optional headers.\n\tBytes\t[]byte;\t\t\t\/\/ The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.\n}\n\n\/\/ getLine results the first \\r\\n or \\n delineated line from the given byte\n\/\/ array. The line does not include the \\r\\n or \\n. The remainder of the byte\n\/\/ array (also not including the new line bytes) is also returned and this will\n\/\/ always be smaller than the original argument.\nfunc getLine(data []byte) (line, rest []byte) {\n\ti := bytes.Index(data, []byte{'\\n'});\n\tvar j int;\n\tif i < 0 {\n\t\ti = len(data);\n\t\tj = i;\n\t} else {\n\t\tj = i+1;\n\t\tif i > 0 && data[i-1] == '\\r' {\n\t\t\ti--;\n\t\t}\n\t}\n\treturn data[0:i], data[j:len(data)];\n}\n\n\/\/ removeWhitespace returns a copy of its input with all spaces, tab and\n\/\/ newline characters removed.\nfunc removeWhitespace(data []byte) []byte {\n\tresult := make([]byte, len(data));\n\tn := 0;\n\n\tfor _, b := range data {\n\t\tif b == ' ' || b == '\\t' || b == '\\r' || b == '\\n' {\n\t\t\tcontinue;\n\t\t}\n\t\tresult[n] = b;\n\t\tn++;\n\t}\n\n\treturn result[0:n];\n}\n\nvar pemStart = strings.Bytes(\"\\n-----BEGIN \")\nvar pemEnd = strings.Bytes(\"\\n-----END \")\nvar pemEndOfLine = strings.Bytes(\"-----\")\n\n\/\/ Decode will find the next PEM formatted block (certificate, private key\n\/\/ etc) in the input. It returns that block and the remainder of the input. If\n\/\/ no PEM data is found, p is nil and the whole of the input is returned in\n\/\/ rest.\nfunc Decode(data []byte) (p *Block, rest []byte) {\n\t\/\/ pemStart begins with a newline. However, at the very beginning of\n\t\/\/ the byte array, we'll accept the start string without it.\n\trest = data;\n\tif bytes.HasPrefix(data, pemStart[1:len(pemStart)]) {\n\t\trest = rest[len(pemStart)-1 : len(data)];\n\t} else if i := bytes.Index(data, pemStart); i >= 0 {\n\t\trest = rest[i+len(pemStart) : len(data)];\n\t} else {\n\t\treturn nil, data;\n\t}\n\n\ttypeLine, rest := getLine(rest);\n\tif !bytes.HasSuffix(typeLine, pemEndOfLine) {\n\t\tgoto Error;\n\t}\n\ttypeLine = typeLine[0 : len(typeLine)-len(pemEndOfLine)];\n\n\tp = &Block{\n\t\tHeaders: make(map[string]string),\n\t\tType: string(typeLine),\n\t};\n\n\tfor {\n\t\t\/\/ This loop terminates because getLine's second result is\n\t\t\/\/ always smaller than it's argument.\n\t\tif len(rest) == 0 {\n\t\t\treturn nil, data;\n\t\t}\n\t\tline, next := getLine(rest);\n\n\t\ti := bytes.Index(line, []byte{':'});\n\t\tif i == -1 {\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ TODO(agl): need to cope with values that spread across lines.\n\t\tkey, val := line[0:i], line[i+1 : len(line)];\n\t\tkey = bytes.TrimSpace(key);\n\t\tval = bytes.TrimSpace(val);\n\t\tp.Headers[string(key)] = string(val);\n\t\trest = next;\n\t}\n\n\ti := bytes.Index(rest, pemEnd);\n\tif i < 0 {\n\t\tgoto Error;\n\t}\n\tbase64Data := removeWhitespace(rest[0:i]);\n\n\tp.Bytes = make([]byte, base64.StdEncoding.DecodedLen(len(base64Data)));\n\tn, err := base64.StdEncoding.Decode(base64Data, p.Bytes);\n\tif err != nil {\n\t\tgoto Error;\n\t}\n\tp.Bytes = p.Bytes[0:n];\n\n\t_, rest = getLine(rest[i+len(pemEnd) : len(rest)]);\n\n\treturn;\n\nError:\n\t\/\/ If we get here then we have rejected a likely looking, but\n\t\/\/ ultimately invalid PEM block. We need to start over from a new\n\t\/\/ position.  We have consumed the preamble line and will have consumed\n\t\/\/ any lines which could be header lines. However, a valid preamble\n\t\/\/ line is not a valid header line, therefore we cannot have consumed\n\t\/\/ the preamble line for the any subsequent block. Thus, we will always\n\t\/\/ find any valid block, no matter what bytes preceed it.\n\t\/\/\n\t\/\/ For example, if the input is\n\t\/\/\n\t\/\/    -----BEGIN MALFORMED BLOCK-----\n\t\/\/    junk that may look like header lines\n\t\/\/   or data lines, but no END line\n\t\/\/\n\t\/\/    -----BEGIN ACTUAL BLOCK-----\n\t\/\/    realdata\n\t\/\/    -----END ACTUAL BLOCK-----\n\t\/\/\n\t\/\/ we've failed to parse using the first BEGIN line\n\t\/\/ and now will try again, using the second BEGIN line.\n\tp, rest = Decode(rest);\n\tif p == nil {\n\t\trest = data;\n\t}\n\treturn;\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\/\/ Utility functions.\n\npackage ioutil\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n)\n\n\/\/ ReadAll reads from r until an error or EOF and returns the data it read.\nfunc ReadAll(r io.Reader) ([]byte, os.Error) {\n\tvar buf bytes.Buffer\n\t_, err := io.Copy(&buf, r)\n\treturn buf.Bytes(), err\n}\n\n\/\/ ReadFile reads the file named by filename and returns the contents.\nfunc ReadFile(filename string) ([]byte, os.Error) {\n\tf, err := os.Open(filename, os.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\t\/\/ It's a good but not certain bet that Stat will tell us exactly how much to\n\t\/\/ read, so let's try it but be prepared for the answer to be wrong.\n\tdir, err := f.Stat()\n\tvar n uint64\n\tif err != nil && dir.Size < 2e9 { \/\/ Don't preallocate a huge buffer, just in case.\n\t\tn = dir.Size\n\t}\n\t\/\/ Add a little extra in case Size is zero, and to avoid another allocation after\n\t\/\/ Read has filled the buffer.\n\tn += bytes.MinRead\n\t\/\/ Pre-allocate the correct size of buffer, then set its size to zero.  The\n\t\/\/ Buffer will read into the allocated space cheaply.  If the size was wrong,\n\t\/\/ we'll either waste some space off the end or reallocate as needed, but\n\t\/\/ in the overwhelmingly common case we'll get it just right.\n\tbuf := bytes.NewBuffer(make([]byte, 0, n))\n\t_, err = buf.ReadFrom(f)\n\treturn buf.Bytes(), err\n}\n\n\/\/ WriteFile writes data to a file named by filename.\n\/\/ If the file does not exist, WriteFile creates it with permissions perm;\n\/\/ otherwise WriteFile truncates it before writing.\nfunc WriteFile(filename string, data []byte, perm int) os.Error {\n\tf, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn, err := f.Write(data)\n\tf.Close()\n\tif err == nil && n < len(data) {\n\t\terr = io.ErrShortWrite\n\t}\n\treturn err\n}\n\n\/\/ A dirList implements sort.Interface.\ntype dirList []*os.Dir\n\nfunc (d dirList) Len() int           { return len(d) }\nfunc (d dirList) Less(i, j int) bool { return d[i].Name < d[j].Name }\nfunc (d dirList) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\n\n\/\/ ReadDir reads the directory named by dirname and returns\n\/\/ a list of sorted directory entries.\nfunc ReadDir(dirname string) ([]*os.Dir, os.Error) {\n\tf, err := os.Open(dirname, os.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist, err := f.Readdir(-1)\n\tf.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdirs := make(dirList, len(list))\n\tfor i := range list {\n\t\tdirs[i] = &list[i]\n\t}\n\tsort.Sort(dirs)\n\treturn dirs, nil\n}\n<commit_msg>io\/ioutil: fix bug in ReadFile when Open succeeds but Stat fails<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\/\/ Utility functions.\n\npackage ioutil\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n)\n\n\/\/ ReadAll reads from r until an error or EOF and returns the data it read.\nfunc ReadAll(r io.Reader) ([]byte, os.Error) {\n\tvar buf bytes.Buffer\n\t_, err := io.Copy(&buf, r)\n\treturn buf.Bytes(), err\n}\n\n\/\/ ReadFile reads the file named by filename and returns the contents.\nfunc ReadFile(filename string) ([]byte, os.Error) {\n\tf, err := os.Open(filename, os.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\t\/\/ It's a good but not certain bet that Stat will tell us exactly how much to\n\t\/\/ read, so let's try it but be prepared for the answer to be wrong.\n\tdir, err := f.Stat()\n\tvar n uint64\n\tif err == nil && dir.Size < 2e9 { \/\/ Don't preallocate a huge buffer, just in case.\n\t\tn = dir.Size\n\t}\n\t\/\/ Add a little extra in case Size is zero, and to avoid another allocation after\n\t\/\/ Read has filled the buffer.\n\tn += bytes.MinRead\n\t\/\/ Pre-allocate the correct size of buffer, then set its size to zero.  The\n\t\/\/ Buffer will read into the allocated space cheaply.  If the size was wrong,\n\t\/\/ we'll either waste some space off the end or reallocate as needed, but\n\t\/\/ in the overwhelmingly common case we'll get it just right.\n\tbuf := bytes.NewBuffer(make([]byte, 0, n))\n\t_, err = buf.ReadFrom(f)\n\treturn buf.Bytes(), err\n}\n\n\/\/ WriteFile writes data to a file named by filename.\n\/\/ If the file does not exist, WriteFile creates it with permissions perm;\n\/\/ otherwise WriteFile truncates it before writing.\nfunc WriteFile(filename string, data []byte, perm int) os.Error {\n\tf, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tn, err := f.Write(data)\n\tf.Close()\n\tif err == nil && n < len(data) {\n\t\terr = io.ErrShortWrite\n\t}\n\treturn err\n}\n\n\/\/ A dirList implements sort.Interface.\ntype dirList []*os.Dir\n\nfunc (d dirList) Len() int           { return len(d) }\nfunc (d dirList) Less(i, j int) bool { return d[i].Name < d[j].Name }\nfunc (d dirList) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }\n\n\/\/ ReadDir reads the directory named by dirname and returns\n\/\/ a list of sorted directory entries.\nfunc ReadDir(dirname string) ([]*os.Dir, os.Error) {\n\tf, err := os.Open(dirname, os.O_RDONLY, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist, err := f.Readdir(-1)\n\tf.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdirs := make(dirList, len(list))\n\tfor i := range list {\n\t\tdirs[i] = &list[i]\n\t}\n\tsort.Sort(dirs)\n\treturn dirs, nil\n}\n<|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 net_test\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n)\n\nfunc ExampleListener() {\n\t\/\/ Listen on TCP port 2000 on all interfaces.\n\tl, err := net.Listen(\"tcp\", \":2000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor {\n\t\t\/\/ Wait for a connection.\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ Handle the connection in a new goroutine.\n\t\t\/\/ The loop then returns to accepting, so that\n\t\t\/\/ multiple connections may be served concurrently.\n\t\tgo func(c net.Conn) {\n\t\t\t\/\/ Echo all incoming data.\n\t\t\tio.Copy(c, c)\n\t\t\t\/\/ Shut down the connection.\n\t\t\tc.Close()\n\t\t}(conn)\n\t}\n}\n<commit_msg>net: close TCPListener in example<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 net_test\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n)\n\nfunc ExampleListener() {\n\t\/\/ Listen on TCP port 2000 on all interfaces.\n\tl, err := net.Listen(\"tcp\", \":2000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer l.Close()\n\tfor {\n\t\t\/\/ Wait for a connection.\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ Handle the connection in a new goroutine.\n\t\t\/\/ The loop then returns to accepting, so that\n\t\t\/\/ multiple connections may be served concurrently.\n\t\tgo func(c net.Conn) {\n\t\t\t\/\/ Echo all incoming data.\n\t\t\tio.Copy(c, c)\n\t\t\t\/\/ Shut down the connection.\n\t\t\tc.Close()\n\t\t}(conn)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.cloudfoundry.org\/bytefmt\"\n\t\"net\"\n\t\"time\"\n)\n\nvar last_ring_time time.Time\n\ntype busyFunc func() bool\n\n\/\/ Is the network connection inbound or outbound\nconst (\n\tINBOUND = iota\n\tOUTBOUND\n)\n\n\/\/ Interface specification for a connection\ntype connection interface {\n\tRead(p []byte) (int, error)\n\tWrite(p []byte) (int, error)\n\tClose() error\n\tRemoteAddr() net.Addr\n\tDirection() int \/\/ INBOUND or OUTBOUND\n\tMode() bool      \/\/ What command mode to be in after connection\n\tSetMode(bool)\n\tStats() (uint64, uint64)\n\tString() string\n\tSetDeadline(t time.Time) error\n}\n\n\n\/\/ How many rings before giving up\nconst __MAX_RINGS = 15\n\n\/\/ How long to wait for the remote to answer.  6 seconds is the default\n\/\/ ring-silence time\nconst __CONNECT_TIMEOUT = __MAX_RINGS * 6 * time.Second\n\nfunc answerIncomming(conn connection) bool {\n\tconst __DELAY_MS = 20\n\n\tzero := make([]byte, 1)\n\tzero[0] = 0\n\n\tr := registers\n\tfor i := 0; i < __MAX_RINGS; i++ {\n\t\tlast_ring_time = time.Now()\n\t\tconn.Write([]byte(\"Ringing...\\n\\r\"))\n\t\tlogger.Print(\"Ringing\")\n\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\tgoto answered\n\t\t}\n\n\t\t\/\/ Simulate the \"2-4\" pattern for POTS ring signal (2\n\t\t\/\/ seconds of high voltage ring signal, 4 seconds\n\t\t\/\/ of silence)\n\n\t\t\/\/ Ring for 2s\n\t\td := 0\n\t\traiseRI()\n\t\tfor onHook() && d < 2000 {\n\t\t\tif _, err := conn.Write(zero); err != nil {\n\t\t\t\tgoto no_answer\n\t\t\t}\n\t\t\ttime.Sleep(__DELAY_MS * time.Millisecond)\n\t\t\td += __DELAY_MS\n\t\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\t\tgoto answered\n\t\t\t}\n\t\t}\n\t\tlowerRI()\n\n\t\t\/\/ By verification, the Hayes Ultra 96 displays the\n\t\t\/\/ \"RING\" text \/after\/ the RI signal is lowered.  So\n\t\t\/\/ do this here so we behave the same.\n\t\tserial.Println(RING)\n\n\t\t\/\/ If Auto Answer is enabled and we've exceeded the\n\t\t\/\/ configured number of rings to wait before\n\t\t\/\/ answering, answer the call.  We do this here before\n\t\t\/\/ the 4s delay as I think it feels more correct.\n\t\tringCount := r.Inc(REG_RING_COUNT)\n\t\taaCount := r.Read(REG_AUTO_ANSWER)\n\t\tif aaCount > 0 {\n\t\t\tif ringCount >= aaCount {\n\t\t\t\tlogger.Print(\"Auto answering\")\n\t\t\t\tanswer()\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Silence for 4s\n\t\td = 0\n\t\tfor onHook() && d < 4000 {\n\t\t\t\/\/ Test for closed connection\n\t\t\tif _, err := conn.Write(zero); err != nil {\n\t\t\t\tgoto no_answer\n\t\t\t}\n\n\t\t\ttime.Sleep(__DELAY_MS * time.Millisecond)\n\t\t\td += __DELAY_MS\n\t\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\t\tgoto answered\n\t\t\t}\n\t\t}\n\t}\n\nno_answer:\n\t\/\/ At this point we've not answered and have timed out, or the\n\t\/\/ caller hung up before we answered.\n\tlogger.Print(\"No answer\")\n\tconn.Write([]byte(\"No answer, closing connection\\n\\r\"))\n\tlowerRI()\n\treturn false\n\nanswered:\n\t\/\/ if we're here, the computer answered.\n\tlogger.Print(\"Answered\")\n\tconn.Write([]byte(\"Answered\\n\\r\"))\n\tregisters.Write(REG_RING_COUNT, 0)\n\tlowerRI()\n\treturn true\n}\n\nfunc startAcceptingCalls() {\n\tstarted_ok := make(chan error)\n\n\tif flags.skipTelnet {\n\t\tlogger.Print(\"Telnet server not started by command line flag\")\n\t} else {\n\t\tgo acceptTelnet(callChannel, checkBusy, logger, started_ok)\n\t\tif err := <-started_ok; err != nil {\n\t\t\tlogger.Printf(\"Telnet server failed to start: %s\", err)\n\t\t} else {\n\t\t\tlogger.Print(\"Telnet server started\")\n\t\t}\n\t}\n\n\n\tif flags.skipSSH {\n\t\tlogger.Print(\"SSH server not started by command line flag\")\n\t} else {\n\t\tgo acceptSSH(callChannel, flags.privateKey, checkBusy, logger,\n\t\t\tstarted_ok)\n\t\tif err := <-started_ok; err != nil {\n\t\t\tlogger.Printf(\"SSH server failed to start: %s\", err)\n\t\t} else {\n\t\t\tlogger.Print(\"SSH server started\")\n\t\t}\n\t}\n}\n\n\n\/\/ Clear the ring counter after 8s\n\/\/ Must be a goroutine\nfunc clearRingCounter() {\n\tdelay := 8 * time.Second\n\tt := time.Tick(delay)\n\tfor range t { \n\t\tif time.Since(last_ring_time) >= delay {\n\t\t\tregisters.Write(REG_RING_COUNT, 0)\n\t\t}\n\t}\n}\n\n\/\/ Pass bytes from the remote dialer to the serial port (for now,\n\/\/ stdout) as long as we're offhook, we're in DATA MODE and we have\n\/\/ valid carrier (m.comm != nil)\nfunc serviceConnection() {\n\tvar t time.Time\n\tvar timeout time.Duration\n\n\tlogger.Printf(\"Servicing connection with remote %s\", m.conn.RemoteAddr())\n\n\tbuf := make([]byte, 1)\n\tfor {\n\t\t\/\/ If S30 is non-zero, set a timeout\n\t\tb := registers.Read(REG_INACTIVITY_TIMER)\n\t\ttimeout = time.Duration(b) * 10 * time.Second\n\t\tif timeout == time.Duration(0) {\n\t\t\tt = time.Time{}\n\t\t} else {\n\t\t\tt = time.Now().Add(timeout)\n\t\t}\n\t\tif err := m.conn.SetDeadline(t); err != nil {\n\t\t\tlogger.Printf(\"conn.SetDeadline(): %s\", err)\n\t\t\treturn\n\t\t}\n\t\t\n\t\tif _, err := m.conn.Read(buf); err != nil { \/\/ Remote hung up or ...\n\t\t\tnerr, ok := err.(net.Error)\t    \/\/ we timed out.\n\t\t\tswitch {\n\t\t\tcase ok && nerr.Timeout():\n\t\t\t\tlogger.Printf(\"conn.Read(): S30 timeout: %s\",\n\t\t\t\t\ttimeout)\n\t\t\tcase ok && nerr.Temporary():\n\t\t\t\tlogger.Printf(\"conn.Read(): temporary errory\")\n\t\t\t\tcontinue\n\t\t\tdefault: \n\t\t\t\tlogger.Print(\"conn.Read(): \", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif m.dcd == false {\n\t\t\tlogger.Print(\"conn.Read(): No carrier at network read\")\n\t\t\treturn\n\t\t}\n\n\t\tif onHook() {\n\t\t\tlogger.Print(\"conn.Read(): On hook at network read\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Send the byte to the DTE, blink the RD LED\n\t\tif m.mode == DATAMODE {\n\t\t\tled_RD_on()\n\t\t\tserial.Write(buf)\n\t\t\tled_RD_off()\n\t\t}\n\t}\n}\n\n\/\/ Accept connection's from dial*() and accept*() functions.\nfunc handleCalls() {\n\tgo clearRingCounter()\n\tstartAcceptingCalls()\n\n\t\/\/ Wait for a connection.  If it's an incoming call, answer\n\t\/\/ it.  If it's an outgoing call or an answered incoming call,\n\t\/\/ service it\n\tvar conn connection\n\tfor {\n\t\tconn = <-callChannel\n\t\tsetLineBusy(true)\n\n\t\tswitch conn.Direction() {\n\t\tcase INBOUND:\n\t\t\tlogger.Printf(\"Incomming call from %s\", conn.RemoteAddr())\n\t\t\tif !answerIncomming(conn) {\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase OUTBOUND:\n\t\t\tlogger.Printf(\"Outgoing call to %s \", conn.RemoteAddr())\n\t\t}\n\n\t\t\/\/ We now have an established connection (either answered or dialed)\n\t\t\/\/ so service it.\n\t\tm.conn = conn\n\t\tm.mode = conn.Mode()\n\t\tm.connectSpeed = 38400\n\t\tm.dcd = true\t\/\/ Force DCD \"up\" here.\n\t\tserviceConnection()\n\n\t\tif m.dcd == true { \/\/ User didn't hang up, so print status\n\t\t\tserial.Printf(\"\\n\")\n\t\t\tprstatus(NO_CARRIER)\n\t\t}\n\t\tsent, recv := m.conn.Stats()\n\t\tconn.Close()\n\t\tm.conn = nil\n\t\thangup()\n\t\tsetLineBusy(false)\n\t\tlogger.Printf(\"Connection closed, sent %s recv %s\",\n\t\t\tbytefmt.ByteSize(sent), bytefmt.ByteSize(recv))\n\n\t}\n}\n<commit_msg>Proposed fix for issue #36, untested<commit_after>package main\n\nimport (\n\t\"code.cloudfoundry.org\/bytefmt\"\n\t\"net\"\n\t\"time\"\n)\n\nvar last_ring_time time.Time\n\ntype busyFunc func() bool\n\n\/\/ Is the network connection inbound or outbound\nconst (\n\tINBOUND = iota\n\tOUTBOUND\n)\n\n\/\/ Interface specification for a connection\ntype connection interface {\n\tRead(p []byte) (int, error)\n\tWrite(p []byte) (int, error)\n\tClose() error\n\tRemoteAddr() net.Addr\n\tDirection() int \/\/ INBOUND or OUTBOUND\n\tMode() bool      \/\/ What command mode to be in after connection\n\tSetMode(bool)\n\tStats() (uint64, uint64)\n\tString() string\n\tSetDeadline(t time.Time) error\n}\n\n\n\/\/ How many rings before giving up\nconst __MAX_RINGS = 15\n\n\/\/ How long to wait for the remote to answer.  6 seconds is the default\n\/\/ ring-silence time\nconst __CONNECT_TIMEOUT = __MAX_RINGS * 6 * time.Second\n\nfunc answerIncomming(conn connection) bool {\n\tconst __DELAY_MS = 20\n\n\tzero := make([]byte, 1)\n\tzero[0] = 0\n\n\tr := registers\n\tfor i := 0; i < __MAX_RINGS; i++ {\n\t\tlast_ring_time = time.Now()\n\t\tconn.Write([]byte(\"Ringing...\\n\\r\"))\n\t\tlogger.Print(\"Ringing\")\n\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\tgoto answered\n\t\t}\n\n\t\t\/\/ Simulate the \"2-4\" pattern for POTS ring signal (2\n\t\t\/\/ seconds of high voltage ring signal, 4 seconds\n\t\t\/\/ of silence)\n\n\t\t\/\/ Ring for 2s\n\t\td := 0\n\t\traiseRI()\n\t\tfor onHook() && d < 2000 {\n\t\t\tif _, err := conn.Write(zero); err != nil {\n\t\t\t\tgoto no_answer\n\t\t\t}\n\t\t\ttime.Sleep(__DELAY_MS * time.Millisecond)\n\t\t\td += __DELAY_MS\n\t\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\t\tgoto answered\n\t\t\t}\n\t\t}\n\t\tlowerRI()\n\n\t\t\/\/ By verification, the Hayes Ultra 96 displays the\n\t\t\/\/ \"RING\" text \/after\/ the RI signal is lowered.  So\n\t\t\/\/ do this here so we behave the same.\n\t\tserial.Println(RING)\n\n\t\t\/\/ If Auto Answer is enabled and we've exceeded the\n\t\t\/\/ configured number of rings to wait before\n\t\t\/\/ answering, answer the call.  We do this here before\n\t\t\/\/ the 4s delay as I think it feels more correct.\n\t\tringCount := r.Inc(REG_RING_COUNT)\n\t\taaCount := r.Read(REG_AUTO_ANSWER)\n\t\tif aaCount > 0 {\n\t\t\tif ringCount >= aaCount {\n\t\t\t\tlogger.Print(\"Auto answering\")\n\t\t\t\tanswer()\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Silence for 4s\n\t\td = 0\n\t\tfor onHook() && d < 4000 {\n\t\t\t\/\/ Test for closed connection\n\t\t\tif _, err := conn.Write(zero); err != nil {\n\t\t\t\tgoto no_answer\n\t\t\t}\n\n\t\t\ttime.Sleep(__DELAY_MS * time.Millisecond)\n\t\t\td += __DELAY_MS\n\t\t\tif offHook() { \/\/ computer has issued 'ATA'\n\t\t\t\tgoto answered\n\t\t\t}\n\t\t}\n\t}\n\nno_answer:\n\t\/\/ At this point we've not answered and have timed out, or the\n\t\/\/ caller hung up before we answered.\n\tlogger.Print(\"No answer\")\n\tconn.Write([]byte(\"No answer, closing connection\\n\\r\"))\n\tlowerRI()\n\treturn false\n\nanswered:\n\t\/\/ if we're here, the computer answered.\n\tlogger.Print(\"Answered\")\n\tconn.Write([]byte(\"Answered\\n\\r\"))\n\tregisters.Write(REG_RING_COUNT, 0)\n\tlowerRI()\n\traiseDSR()\n\traiseCTS()\n\treturn true\n}\n\nfunc startAcceptingCalls() {\n\tstarted_ok := make(chan error)\n\n\tif flags.skipTelnet {\n\t\tlogger.Print(\"Telnet server not started by command line flag\")\n\t} else {\n\t\tgo acceptTelnet(callChannel, checkBusy, logger, started_ok)\n\t\tif err := <-started_ok; err != nil {\n\t\t\tlogger.Printf(\"Telnet server failed to start: %s\", err)\n\t\t} else {\n\t\t\tlogger.Print(\"Telnet server started\")\n\t\t}\n\t}\n\n\n\tif flags.skipSSH {\n\t\tlogger.Print(\"SSH server not started by command line flag\")\n\t} else {\n\t\tgo acceptSSH(callChannel, flags.privateKey, checkBusy, logger,\n\t\t\tstarted_ok)\n\t\tif err := <-started_ok; err != nil {\n\t\t\tlogger.Printf(\"SSH server failed to start: %s\", err)\n\t\t} else {\n\t\t\tlogger.Print(\"SSH server started\")\n\t\t}\n\t}\n}\n\n\n\/\/ Clear the ring counter after 8s\n\/\/ Must be a goroutine\nfunc clearRingCounter() {\n\tdelay := 8 * time.Second\n\tt := time.Tick(delay)\n\tfor range t { \n\t\tif time.Since(last_ring_time) >= delay {\n\t\t\tregisters.Write(REG_RING_COUNT, 0)\n\t\t}\n\t}\n}\n\n\/\/ Pass bytes from the remote dialer to the serial port (for now,\n\/\/ stdout) as long as we're offhook, we're in DATA MODE and we have\n\/\/ valid carrier (m.comm != nil)\nfunc serviceConnection() {\n\tvar t time.Time\n\tvar timeout time.Duration\n\n\tlogger.Printf(\"Servicing connection with remote %s\", m.conn.RemoteAddr())\n\n\tbuf := make([]byte, 1)\n\tfor {\n\t\t\/\/ If S30 is non-zero, set a timeout\n\t\tb := registers.Read(REG_INACTIVITY_TIMER)\n\t\ttimeout = time.Duration(b) * 10 * time.Second\n\t\tif timeout == time.Duration(0) {\n\t\t\tt = time.Time{}\n\t\t} else {\n\t\t\tt = time.Now().Add(timeout)\n\t\t}\n\t\tif err := m.conn.SetDeadline(t); err != nil {\n\t\t\tlogger.Printf(\"conn.SetDeadline(): %s\", err)\n\t\t\treturn\n\t\t}\n\t\t\n\t\tif _, err := m.conn.Read(buf); err != nil { \/\/ Remote hung up or ...\n\t\t\tnerr, ok := err.(net.Error)\t    \/\/ we timed out.\n\t\t\tswitch {\n\t\t\tcase ok && nerr.Timeout():\n\t\t\t\tlogger.Printf(\"conn.Read(): S30 timeout: %s\",\n\t\t\t\t\ttimeout)\n\t\t\tcase ok && nerr.Temporary():\n\t\t\t\tlogger.Printf(\"conn.Read(): temporary errory\")\n\t\t\t\tcontinue\n\t\t\tdefault: \n\t\t\t\tlogger.Print(\"conn.Read(): \", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif m.dcd == false {\n\t\t\tlogger.Print(\"conn.Read(): No carrier at network read\")\n\t\t\treturn\n\t\t}\n\n\t\tif onHook() {\n\t\t\tlogger.Print(\"conn.Read(): On hook at network read\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Send the byte to the DTE, blink the RD LED\n\t\tif m.mode == DATAMODE {\n\t\t\tled_RD_on()\n\t\t\tserial.Write(buf)\n\t\t\tled_RD_off()\n\t\t}\n\t}\n}\n\n\/\/ Accept connection's from dial*() and accept*() functions.\nfunc handleCalls() {\n\tgo clearRingCounter()\n\tstartAcceptingCalls()\n\n\t\/\/ Wait for a connection.  If it's an incoming call, answer\n\t\/\/ it.  If it's an outgoing call or an answered incoming call,\n\t\/\/ service it\n\tvar conn connection\n\tfor {\n\t\tconn = <-callChannel\n\t\tsetLineBusy(true)\n\n\t\tswitch conn.Direction() {\n\t\tcase INBOUND:\n\t\t\tlogger.Printf(\"Incomming call from %s\", conn.RemoteAddr())\n\t\t\tif !answerIncomming(conn) {\n\t\t\t\tconn.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase OUTBOUND:\n\t\t\tlogger.Printf(\"Outgoing call to %s \", conn.RemoteAddr())\n\t\t}\n\n\t\t\/\/ We now have an established connection (either answered or dialed)\n\t\t\/\/ so service it.\n\t\tm.conn = conn\n\t\tm.mode = conn.Mode()\n\t\tm.connectSpeed = 38400\n\t\tm.dcd = true\t\/\/ Force DCD \"up\" here.\n\t\tserviceConnection()\n\n\t\tif m.dcd == true { \/\/ User didn't hang up, so print status\n\t\t\tserial.Printf(\"\\n\")\n\t\t\tprstatus(NO_CARRIER)\n\t\t}\n\t\tsent, recv := m.conn.Stats()\n\t\tconn.Close()\n\t\tm.conn = nil\n\t\thangup()\n\t\tsetLineBusy(false)\n\t\tlogger.Printf(\"Connection closed, sent %s recv %s\",\n\t\t\tbytefmt.ByteSize(sent), bytefmt.ByteSize(recv))\n\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 build gathers information about Go packages.\n\/\/\n\/\/ Go Path\n\/\/\n\/\/ The Go path is a list of directory trees containing Go source code.\n\/\/ It is consulted to resolve imports that cannot be found in the standard\n\/\/ Go tree.  The default path is the value of the GOPATH environment\n\/\/ variable, interpreted as a path list appropriate to the operating system\n\/\/ (on Unix, the variable is a colon-separated string;\n\/\/ on Windows, a semicolon-separated string;\n\/\/ on Plan 9, a list).\n\/\/\n\/\/ Each directory listed in the Go path must have a prescribed structure:\n\/\/\n\/\/ The src\/ directory holds source code.  The path below 'src' determines\n\/\/ the import path or executable name.\n\/\/\n\/\/ The pkg\/ directory holds installed package objects.\n\/\/ As in the Go tree, each target operating system and\n\/\/ architecture pair has its own subdirectory of pkg\n\/\/ (pkg\/GOOS_GOARCH).\n\/\/ \n\/\/ If DIR is a directory listed in the Go path, a package with\n\/\/ source in DIR\/src\/foo\/bar can be imported as \"foo\/bar\" and\n\/\/ has its compiled form installed to \"DIR\/pkg\/GOOS_GOARCH\/foo\/bar.a\"\n\/\/ (or, for gccgo, \"DIR\/pkg\/gccgo\/foo\/libbar.a\").\n\/\/ \n\/\/ The bin\/ directory holds compiled commands.\n\/\/ Each command is named for its source directory, but only\n\/\/ using the final element, not the entire path.  That is, the\n\/\/ command with source in DIR\/src\/foo\/quux is installed into\n\/\/ DIR\/bin\/quux, not DIR\/bin\/foo\/quux.  The foo\/ is stripped\n\/\/ so that you can add DIR\/bin to your PATH to get at the\n\/\/ installed commands.\n\/\/ \n\/\/ Here's an example directory layout:\n\/\/ \n\/\/\tGOPATH=\/home\/user\/gocode\n\/\/ \n\/\/\t\/home\/user\/gocode\/\n\/\/\t    src\/\n\/\/\t        foo\/\n\/\/\t            bar\/               (go code in package bar)\n\/\/\t                x.go\n\/\/\t            quux\/              (go code in package main)\n\/\/\t                y.go\n\/\/\t    bin\/\n\/\/\t        quux                   (installed command)\n\/\/\t    pkg\/\n\/\/\t        linux_amd64\/\n\/\/\t            foo\/\n\/\/\t                bar.a          (installed package object)\n\/\/\n\/\/ Build Constraints\n\/\/\n\/\/ A build constraint is a line comment beginning with the directive +build\n\/\/ that lists the conditions under which a file should be included in the package.\n\/\/ Constraints may appear in any kind of source file (not just Go), but\n\/\/ they must be appear near the top of the file, preceded\n\/\/ only by blank lines and other line comments.\n\/\/\n\/\/ A build constraint is evaluated as the OR of space-separated options;\n\/\/ each option evaluates as the AND of its comma-separated terms;\n\/\/ and each term is an alphanumeric word or, preceded by !, its negation.\n\/\/ That is, the build constraint:\n\/\/\n\/\/\t\/\/ +build linux,386 darwin,!cgo\n\/\/\n\/\/ corresponds to the boolean formula:\n\/\/\n\/\/\t(linux AND 386) OR (darwin AND (NOT cgo))\n\/\/\n\/\/ During a particular build, the following words are satisfied:\n\/\/\n\/\/\t- the target operating system, as spelled by runtime.GOOS\n\/\/\t- the target architecture, as spelled by runtime.GOARCH\n\/\/\t- \"cgo\", if ctxt.CgoEnabled is true\n\/\/\t- any additional words listed in ctxt.BuildTags\n\/\/\n\/\/ If a file's name, after stripping the extension and a possible _test suffix,\n\/\/ matches *_GOOS, *_GOARCH, or *_GOOS_GOARCH for any known operating\n\/\/ system and architecture values, then the file is considered to have an implicit\n\/\/ build constraint requiring those terms.\n\/\/\n\/\/ To keep a file from being considered for the build:\n\/\/\n\/\/\t\/\/ +build ignore\n\/\/\n\/\/ (any other unsatisfied word will work as well, but ``ignore'' is conventional.)\n\/\/\n\/\/ To build a file only when using cgo, and only on Linux and OS X:\n\/\/\n\/\/\t\/\/ +build linux,cgo darwin,cgo\n\/\/\n\/\/ Such a file is usually paired with another file implementing the\n\/\/ default functionality for other systems, which in this case would\n\/\/ carry the constraint:\n\/\/\n\/\/\t\/\/ +build !linux !darwin !cgo\n\/\/\n\/\/ Naming a file dns_windows.go will cause it to be included only when\n\/\/ building the package for Windows; similarly, math_386.s will be included\n\/\/ only when building the package for 32-bit x86.\n\/\/\npackage build\n<commit_msg>go\/build: fix boolean negation<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 build gathers information about Go packages.\n\/\/\n\/\/ Go Path\n\/\/\n\/\/ The Go path is a list of directory trees containing Go source code.\n\/\/ It is consulted to resolve imports that cannot be found in the standard\n\/\/ Go tree.  The default path is the value of the GOPATH environment\n\/\/ variable, interpreted as a path list appropriate to the operating system\n\/\/ (on Unix, the variable is a colon-separated string;\n\/\/ on Windows, a semicolon-separated string;\n\/\/ on Plan 9, a list).\n\/\/\n\/\/ Each directory listed in the Go path must have a prescribed structure:\n\/\/\n\/\/ The src\/ directory holds source code.  The path below 'src' determines\n\/\/ the import path or executable name.\n\/\/\n\/\/ The pkg\/ directory holds installed package objects.\n\/\/ As in the Go tree, each target operating system and\n\/\/ architecture pair has its own subdirectory of pkg\n\/\/ (pkg\/GOOS_GOARCH).\n\/\/ \n\/\/ If DIR is a directory listed in the Go path, a package with\n\/\/ source in DIR\/src\/foo\/bar can be imported as \"foo\/bar\" and\n\/\/ has its compiled form installed to \"DIR\/pkg\/GOOS_GOARCH\/foo\/bar.a\"\n\/\/ (or, for gccgo, \"DIR\/pkg\/gccgo\/foo\/libbar.a\").\n\/\/ \n\/\/ The bin\/ directory holds compiled commands.\n\/\/ Each command is named for its source directory, but only\n\/\/ using the final element, not the entire path.  That is, the\n\/\/ command with source in DIR\/src\/foo\/quux is installed into\n\/\/ DIR\/bin\/quux, not DIR\/bin\/foo\/quux.  The foo\/ is stripped\n\/\/ so that you can add DIR\/bin to your PATH to get at the\n\/\/ installed commands.\n\/\/ \n\/\/ Here's an example directory layout:\n\/\/ \n\/\/\tGOPATH=\/home\/user\/gocode\n\/\/ \n\/\/\t\/home\/user\/gocode\/\n\/\/\t    src\/\n\/\/\t        foo\/\n\/\/\t            bar\/               (go code in package bar)\n\/\/\t                x.go\n\/\/\t            quux\/              (go code in package main)\n\/\/\t                y.go\n\/\/\t    bin\/\n\/\/\t        quux                   (installed command)\n\/\/\t    pkg\/\n\/\/\t        linux_amd64\/\n\/\/\t            foo\/\n\/\/\t                bar.a          (installed package object)\n\/\/\n\/\/ Build Constraints\n\/\/\n\/\/ A build constraint is a line comment beginning with the directive +build\n\/\/ that lists the conditions under which a file should be included in the package.\n\/\/ Constraints may appear in any kind of source file (not just Go), but\n\/\/ they must be appear near the top of the file, preceded\n\/\/ only by blank lines and other line comments.\n\/\/\n\/\/ A build constraint is evaluated as the OR of space-separated options;\n\/\/ each option evaluates as the AND of its comma-separated terms;\n\/\/ and each term is an alphanumeric word or, preceded by !, its negation.\n\/\/ That is, the build constraint:\n\/\/\n\/\/\t\/\/ +build linux,386 darwin,!cgo\n\/\/\n\/\/ corresponds to the boolean formula:\n\/\/\n\/\/\t(linux AND 386) OR (darwin AND (NOT cgo))\n\/\/\n\/\/ During a particular build, the following words are satisfied:\n\/\/\n\/\/\t- the target operating system, as spelled by runtime.GOOS\n\/\/\t- the target architecture, as spelled by runtime.GOARCH\n\/\/\t- \"cgo\", if ctxt.CgoEnabled is true\n\/\/\t- any additional words listed in ctxt.BuildTags\n\/\/\n\/\/ If a file's name, after stripping the extension and a possible _test suffix,\n\/\/ matches *_GOOS, *_GOARCH, or *_GOOS_GOARCH for any known operating\n\/\/ system and architecture values, then the file is considered to have an implicit\n\/\/ build constraint requiring those terms.\n\/\/\n\/\/ To keep a file from being considered for the build:\n\/\/\n\/\/\t\/\/ +build ignore\n\/\/\n\/\/ (any other unsatisfied word will work as well, but ``ignore'' is conventional.)\n\/\/\n\/\/ To build a file only when using cgo, and only on Linux and OS X:\n\/\/\n\/\/\t\/\/ +build linux,cgo darwin,cgo\n\/\/\n\/\/ Such a file is usually paired with another file implementing the\n\/\/ default functionality for other systems, which in this case would\n\/\/ carry the constraint:\n\/\/\n\/\/\t\/\/ +build !linux,!darwin !cgo\n\/\/\n\/\/ Naming a file dns_windows.go will cause it to be included only when\n\/\/ building the package for Windows; similarly, math_386.s will be included\n\/\/ only when building the package for 32-bit x86.\n\/\/\npackage build\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\/\/ +build !netgo\n\/\/ +build darwin dragonfly freebsd linux netbsd openbsd\n\npackage net\n\n\/*\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n*\/\nimport \"C\"\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc cgoLookupHost(name string) (addrs []string, err error, completed bool) {\n\tip, err, completed := cgoLookupIP(name)\n\tfor _, p := range ip {\n\t\taddrs = append(addrs, p.String())\n\t}\n\treturn\n}\n\nfunc cgoLookupPort(net, service string) (port int, err error, completed bool) {\n\tacquireThread()\n\tdefer releaseThread()\n\n\tvar res *C.struct_addrinfo\n\tvar hints C.struct_addrinfo\n\n\tswitch net {\n\tcase \"\":\n\t\t\/\/ no hints\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\thints.ai_socktype = C.SOCK_STREAM\n\t\thints.ai_protocol = C.IPPROTO_TCP\n\tcase \"udp\", \"udp4\", \"udp6\":\n\t\thints.ai_socktype = C.SOCK_DGRAM\n\t\thints.ai_protocol = C.IPPROTO_UDP\n\tdefault:\n\t\treturn 0, UnknownNetworkError(net), true\n\t}\n\tif len(net) >= 4 {\n\t\tswitch net[3] {\n\t\tcase '4':\n\t\t\thints.ai_family = C.AF_INET\n\t\tcase '6':\n\t\t\thints.ai_family = C.AF_INET6\n\t\t}\n\t}\n\n\ts := C.CString(service)\n\tdefer C.free(unsafe.Pointer(s))\n\tif C.getaddrinfo(nil, s, &hints, &res) == 0 {\n\t\tdefer C.freeaddrinfo(res)\n\t\tfor r := res; r != nil; r = r.ai_next {\n\t\t\tswitch r.ai_family {\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\tcase C.AF_INET:\n\t\t\t\tsa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))\n\t\t\t\tp := (*[2]byte)(unsafe.Pointer(&sa.Port))\n\t\t\t\treturn int(p[0])<<8 | int(p[1]), nil, true\n\t\t\tcase C.AF_INET6:\n\t\t\t\tsa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))\n\t\t\t\tp := (*[2]byte)(unsafe.Pointer(&sa.Port))\n\t\t\t\treturn int(p[0])<<8 | int(p[1]), nil, true\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, &AddrError{\"unknown port\", net + \"\/\" + service}, true\n}\n\nfunc cgoLookupIPCNAME(name string) (addrs []IP, cname string, err error, completed bool) {\n\tacquireThread()\n\tdefer releaseThread()\n\n\tvar res *C.struct_addrinfo\n\tvar hints C.struct_addrinfo\n\n\thints.ai_flags = cgoAddrInfoFlags()\n\thints.ai_socktype = C.SOCK_STREAM\n\n\th := C.CString(name)\n\tdefer C.free(unsafe.Pointer(h))\n\tgerrno, err := C.getaddrinfo(h, nil, &hints, &res)\n\tif gerrno != 0 {\n\t\tvar str string\n\t\tif gerrno == C.EAI_NONAME {\n\t\t\tstr = noSuchHost\n\t\t} else if gerrno == C.EAI_SYSTEM {\n\t\t\tstr = err.Error()\n\t\t} else {\n\t\t\tstr = C.GoString(C.gai_strerror(gerrno))\n\t\t}\n\t\treturn nil, \"\", &DNSError{Err: str, Name: name}, true\n\t}\n\tdefer C.freeaddrinfo(res)\n\tif res != nil {\n\t\tcname = C.GoString(res.ai_canonname)\n\t\tif cname == \"\" {\n\t\t\tcname = name\n\t\t}\n\t\tif len(cname) > 0 && cname[len(cname)-1] != '.' {\n\t\t\tcname += \".\"\n\t\t}\n\t}\n\tfor r := res; r != nil; r = r.ai_next {\n\t\t\/\/ We only asked for SOCK_STREAM, but check anyhow.\n\t\tif r.ai_socktype != C.SOCK_STREAM {\n\t\t\tcontinue\n\t\t}\n\t\tswitch r.ai_family {\n\t\tdefault:\n\t\t\tcontinue\n\t\tcase C.AF_INET:\n\t\t\tsa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))\n\t\t\taddrs = append(addrs, copyIP(sa.Addr[:]))\n\t\tcase C.AF_INET6:\n\t\t\tsa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))\n\t\t\taddrs = append(addrs, copyIP(sa.Addr[:]))\n\t\t}\n\t}\n\treturn addrs, cname, nil, true\n}\n\nfunc cgoLookupIP(name string) (addrs []IP, err error, completed bool) {\n\taddrs, _, err, completed = cgoLookupIPCNAME(name)\n\treturn\n}\n\nfunc cgoLookupCNAME(name string) (cname string, err error, completed bool) {\n\t_, cname, err, completed = cgoLookupIPCNAME(name)\n\treturn\n}\n\nfunc copyIP(x IP) IP {\n\ty := make(IP, len(x))\n\tcopy(y, x)\n\treturn y\n}\n<commit_msg>net: defend against broken getaddrinfo on 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\n\/\/ +build !netgo\n\/\/ +build darwin dragonfly freebsd linux netbsd openbsd\n\npackage net\n\n\/*\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n*\/\nimport \"C\"\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nfunc cgoLookupHost(name string) (addrs []string, err error, completed bool) {\n\tip, err, completed := cgoLookupIP(name)\n\tfor _, p := range ip {\n\t\taddrs = append(addrs, p.String())\n\t}\n\treturn\n}\n\nfunc cgoLookupPort(net, service string) (port int, err error, completed bool) {\n\tacquireThread()\n\tdefer releaseThread()\n\n\tvar res *C.struct_addrinfo\n\tvar hints C.struct_addrinfo\n\n\tswitch net {\n\tcase \"\":\n\t\t\/\/ no hints\n\tcase \"tcp\", \"tcp4\", \"tcp6\":\n\t\thints.ai_socktype = C.SOCK_STREAM\n\t\thints.ai_protocol = C.IPPROTO_TCP\n\tcase \"udp\", \"udp4\", \"udp6\":\n\t\thints.ai_socktype = C.SOCK_DGRAM\n\t\thints.ai_protocol = C.IPPROTO_UDP\n\tdefault:\n\t\treturn 0, UnknownNetworkError(net), true\n\t}\n\tif len(net) >= 4 {\n\t\tswitch net[3] {\n\t\tcase '4':\n\t\t\thints.ai_family = C.AF_INET\n\t\tcase '6':\n\t\t\thints.ai_family = C.AF_INET6\n\t\t}\n\t}\n\n\ts := C.CString(service)\n\tdefer C.free(unsafe.Pointer(s))\n\tif C.getaddrinfo(nil, s, &hints, &res) == 0 {\n\t\tdefer C.freeaddrinfo(res)\n\t\tfor r := res; r != nil; r = r.ai_next {\n\t\t\tswitch r.ai_family {\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\tcase C.AF_INET:\n\t\t\t\tsa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))\n\t\t\t\tp := (*[2]byte)(unsafe.Pointer(&sa.Port))\n\t\t\t\treturn int(p[0])<<8 | int(p[1]), nil, true\n\t\t\tcase C.AF_INET6:\n\t\t\t\tsa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))\n\t\t\t\tp := (*[2]byte)(unsafe.Pointer(&sa.Port))\n\t\t\t\treturn int(p[0])<<8 | int(p[1]), nil, true\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, &AddrError{\"unknown port\", net + \"\/\" + service}, true\n}\n\nfunc cgoLookupIPCNAME(name string) (addrs []IP, cname string, err error, completed bool) {\n\tacquireThread()\n\tdefer releaseThread()\n\n\tvar res *C.struct_addrinfo\n\tvar hints C.struct_addrinfo\n\n\thints.ai_flags = cgoAddrInfoFlags()\n\thints.ai_socktype = C.SOCK_STREAM\n\n\th := C.CString(name)\n\tdefer C.free(unsafe.Pointer(h))\n\tgerrno, err := C.getaddrinfo(h, nil, &hints, &res)\n\tif gerrno != 0 {\n\t\tvar str string\n\t\tif gerrno == C.EAI_NONAME {\n\t\t\tstr = noSuchHost\n\t\t} else if gerrno == C.EAI_SYSTEM {\n\t\t\tif err == nil {\n\t\t\t\t\/\/ err should not be nil, but sometimes getaddrinfo returns\n\t\t\t\t\/\/ gerrno == C.EAI_SYSTEM with err == nil on Linux.\n\t\t\t\t\/\/ The report claims that it happens when we have too many\n\t\t\t\t\/\/ open files, so use syscall.EMFILE (too many open files in system).\n\t\t\t\t\/\/ Most system calls would return ENFILE (too many open files),\n\t\t\t\t\/\/ so at the least EMFILE should be easy to recognize if this\n\t\t\t\t\/\/ comes up again. golang.org\/issue\/6232.\n\t\t\t\terr = syscall.EMFILE\n\t\t\t}\n\t\t\tstr = err.Error()\n\t\t} else {\n\t\t\tstr = C.GoString(C.gai_strerror(gerrno))\n\t\t}\n\t\treturn nil, \"\", &DNSError{Err: str, Name: name}, true\n\t}\n\tdefer C.freeaddrinfo(res)\n\tif res != nil {\n\t\tcname = C.GoString(res.ai_canonname)\n\t\tif cname == \"\" {\n\t\t\tcname = name\n\t\t}\n\t\tif len(cname) > 0 && cname[len(cname)-1] != '.' {\n\t\t\tcname += \".\"\n\t\t}\n\t}\n\tfor r := res; r != nil; r = r.ai_next {\n\t\t\/\/ We only asked for SOCK_STREAM, but check anyhow.\n\t\tif r.ai_socktype != C.SOCK_STREAM {\n\t\t\tcontinue\n\t\t}\n\t\tswitch r.ai_family {\n\t\tdefault:\n\t\t\tcontinue\n\t\tcase C.AF_INET:\n\t\t\tsa := (*syscall.RawSockaddrInet4)(unsafe.Pointer(r.ai_addr))\n\t\t\taddrs = append(addrs, copyIP(sa.Addr[:]))\n\t\tcase C.AF_INET6:\n\t\t\tsa := (*syscall.RawSockaddrInet6)(unsafe.Pointer(r.ai_addr))\n\t\t\taddrs = append(addrs, copyIP(sa.Addr[:]))\n\t\t}\n\t}\n\treturn addrs, cname, nil, true\n}\n\nfunc cgoLookupIP(name string) (addrs []IP, err error, completed bool) {\n\taddrs, _, err, completed = cgoLookupIPCNAME(name)\n\treturn\n}\n\nfunc cgoLookupCNAME(name string) (cname string, err error, completed bool) {\n\t_, cname, err, completed = cgoLookupIPCNAME(name)\n\treturn\n}\n\nfunc copyIP(x IP) IP {\n\ty := make(IP, len(x))\n\tcopy(y, x)\n\treturn y\n}\n<|endoftext|>"}
{"text":"<commit_before>package task\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com\/satori\/go.uuid\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\ntype mockedStorage struct {\n\tmock.Mock\n}\n\nfunc newMockedStorage() *mockedStorage {\n\treturn &mockedStorage{}\n}\n\nfunc (m *mockedStorage) Save(task *Task) error {\n\targs := m.Called(task)\n\treturn args.Error(0)\n}\n\nfunc (m *mockedStorage) Load(uuid uuid.UUID) (*Task, error) {\n\targs := m.Called(uuid)\n\treturn args.Get(0).(*Task), args.Error(1)\n}\n\nfunc Test_SavedToStorage(t *testing.T) {\n\ttask := NewTask(\"T\", nil, nil, dumpDoFunc, nil)\n\tstorage := new(mockedStorage)\n\tstorage.On(\"Save\", task).Return(nil)\n\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tDo(ctx, cancelFunc, task, storage)\n\n\tstorage.AssertExpectations(t)\n}\n<commit_msg>Default mocked storage creation fixed<commit_after>package task\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com\/satori\/go.uuid\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\ntype mockedStorage struct {\n\tmock.Mock\n}\n\nfunc newMockedStorage() *mockedStorage {\n\tstorage := mockedStorage{}\n\tstorage.On(\"Save\", mock.Anything).Return(nil)\n\treturn &storage\n}\n\nfunc (m *mockedStorage) Save(task *Task) error {\n\targs := m.Called(task)\n\treturn args.Error(0)\n}\n\nfunc (m *mockedStorage) Load(uuid uuid.UUID) (*Task, error) {\n\targs := m.Called(uuid)\n\treturn args.Get(0).(*Task), args.Error(1)\n}\n\nfunc Test_SavedToStorage(t *testing.T) {\n\ttask := NewTask(\"T\", nil, nil, dumpDoFunc, nil)\n\tstorage := new(mockedStorage)\n\tstorage.On(\"Save\", task).Return(nil)\n\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tDo(ctx, cancelFunc, task, storage)\n\n\tstorage.AssertExpectations(t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package taskpool\n\nimport (\n\t\"context\"\n\t\"log\"\n)\n\ntype task func() error\n\n\/\/ TaskPool manages concurrent processes. No more than size tasks run at once,\n\/\/ and when a task returns an error, the Pool's context is cancelled.\ntype TaskPool struct {\n\tadd  chan task\n\twait chan error\n}\n\n\/\/ New returns a TaskPool waiting for tasks to run.\nfunc New(ctx context.Context, size int) (TaskPool, context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tt := TaskPool{\n\t\tadd:  make(chan task),\n\t\twait: make(chan error),\n\t}\n\tgo t.start(ctx, cancel, size)\n\treturn t, ctx\n}\n\nfunc (tp TaskPool) start(ctx context.Context, cancel context.CancelFunc, size int) {\n\tresult := make(chan error)\n\tworkerC := make(chan task)\n\n\tdefer cancel()\n\tdefer close(workerC) \/\/ Make sure worker goroutines get cleaned up\n\tdefer close(tp.add)  \/\/ Closing this is pointless unless there's a bug\n\n\t\/\/ Start worker pool\n\tfor i := 0; i < size; i++ {\n\t\tgo func() {\n\t\t\tfor t := range workerC {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlog.Println(\"37\")\n\t\t\t\t\treturn\n\t\t\t\tcase result <- t():\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tvar (\n\t\tnextTask task\n\t\ttasks    []task\n\t\ttaskC    chan task\n\t\twaitC    = tp.wait\n\t\trunning  int\n\t)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ttp.wait <- ctx.Err()\n\t\t\tlog.Println(\"58\")\n\t\t\treturn\n\n\t\tcase t := <-tp.add:\n\t\t\ttasks = append(tasks, t)\n\n\t\tcase taskC <- nextTask:\n\t\t\ttasks = tasks[1:]\n\t\t\trunning++\n\n\t\tcase waitC <- nil:\n\t\t\treturn\n\n\t\tcase err := <-result:\n\t\t\tif err != nil {\n\t\t\t\ttp.wait <- err\n\t\t\t\tlog.Println(\"72\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trunning--\n\t\t}\n\n\t\twaitC = nil\n\t\tif len(tasks) > 0 {\n\t\t\tnextTask = tasks[0]\n\t\t\ttaskC = workerC\n\t\t} else {\n\t\t\tif running == 0 {\n\t\t\t\twaitC = tp.wait\n\t\t\t}\n\t\t\tnextTask = nil\n\t\t\ttaskC = nil\n\t\t}\n\t}\n}\n\n\/\/ Go adds a task to the pool of tasks to complete.\nfunc (tp TaskPool) Go(t func() error) {\n\ttp.add <- t\n}\n\n\/\/ Wait waits for all tasks added to the pool to finish running.\nfunc (tp TaskPool) Wait() error {\n\treturn <-tp.wait\n}\n<commit_msg>Taskpool: remove stray debug logging<commit_after>package taskpool\n\nimport (\n\t\"context\"\n\t\"log\"\n)\n\ntype task func() error\n\n\/\/ TaskPool manages concurrent processes. No more than size tasks run at once,\n\/\/ and when a task returns an error, the Pool's context is cancelled.\ntype TaskPool struct {\n\tadd  chan task\n\twait chan error\n}\n\n\/\/ New returns a TaskPool waiting for tasks to run.\nfunc New(ctx context.Context, size int) (TaskPool, context.Context) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\tt := TaskPool{\n\t\tadd:  make(chan task),\n\t\twait: make(chan error),\n\t}\n\tgo t.start(ctx, cancel, size)\n\treturn t, ctx\n}\n\nfunc (tp TaskPool) start(ctx context.Context, cancel context.CancelFunc, size int) {\n\tresult := make(chan error)\n\tworkerC := make(chan task)\n\n\tdefer cancel()\n\tdefer close(workerC) \/\/ Make sure worker goroutines get cleaned up\n\tdefer close(tp.add)  \/\/ Closing this is pointless unless there's a bug\n\n\t\/\/ Start worker pool\n\tfor i := 0; i < size; i++ {\n\t\tgo func() {\n\t\t\tfor t := range workerC {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tlog.Println(\"37\")\n\t\t\t\t\treturn\n\t\t\t\tcase result <- t():\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tvar (\n\t\tnextTask task\n\t\ttasks    []task\n\t\ttaskC    chan task\n\t\twaitC    = tp.wait\n\t\trunning  int\n\t)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ttp.wait <- ctx.Err()\n\t\t\treturn\n\n\t\tcase t := <-tp.add:\n\t\t\ttasks = append(tasks, t)\n\n\t\tcase taskC <- nextTask:\n\t\t\ttasks = tasks[1:]\n\t\t\trunning++\n\n\t\tcase waitC <- nil:\n\t\t\treturn\n\n\t\tcase err := <-result:\n\t\t\tif err != nil {\n\t\t\t\ttp.wait <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\trunning--\n\t\t}\n\n\t\twaitC = nil\n\t\tif len(tasks) > 0 {\n\t\t\tnextTask = tasks[0]\n\t\t\ttaskC = workerC\n\t\t} else {\n\t\t\tif running == 0 {\n\t\t\t\twaitC = tp.wait\n\t\t\t}\n\t\t\tnextTask = nil\n\t\t\ttaskC = nil\n\t\t}\n\t}\n}\n\n\/\/ Go adds a task to the pool of tasks to complete.\nfunc (tp TaskPool) Go(t func() error) {\n\ttp.add <- t\n}\n\n\/\/ Wait waits for all tasks added to the pool to finish running.\nfunc (tp TaskPool) Wait() error {\n\treturn <-tp.wait\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorma\n\nimport \"github.com\/raphael\/goa\/design\"\n\n\/\/ Validate tests whether the StorageGroup definition is consistent\nfunc (a *StorageGroupDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\n\ta.IterateStores(func(store *RelationalStoreDefinition) error {\n\t\tverr.Merge(store.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalStore definition is consistent\nfunc (a *RelationalStoreDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\n\ta.IterateModels(func(model *RelationalModelDefinition) error {\n\t\tverr.Merge(model.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalModel definition is consistent\nfunc (a *RelationalModelDefinition) Validate() *design.ValidationErrors {\n\n\tverr := new(goa.ValidationErrors)\n\n\ta.IterateFields(func(field *RelationalFieldDefinition) error {\n\t\tverr.Merge(field.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalField definition is consistent\nfunc (a *RelationalFieldDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\tif field.Name == \"\" {\n\t\tverr.Add(a, \"field name not defined\")\n\t}\n\treturn verr.AsError()\n}\n<commit_msg>WIP Standalone DSL<commit_after>package gorma\n\nimport \"github.com\/raphael\/goa\/design\"\n\n\/\/ Validate tests whether the StorageGroup definition is consistent\nfunc (a *StorageGroupDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\n\ta.IterateStores(func(store *RelationalStoreDefinition) error {\n\t\tverr.Merge(store.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalStore definition is consistent\nfunc (a *RelationalStoreDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\n\ta.IterateModels(func(model *RelationalModelDefinition) error {\n\t\tverr.Merge(model.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalModel definition is consistent\nfunc (a *RelationalModelDefinition) Validate() *design.ValidationErrors {\n\n\tverr := new(goa.ValidationErrors)\n\tif a.Name == \"\" {\n\t\tverr.Add(a, \"model name not defined\")\n\t}\n\ta.IterateFields(func(field *RelationalFieldDefinition) error {\n\t\tverr.Merge(field.Validate())\n\t})\n\n\treturn verr.AsError()\n}\n\n\/\/ Validate tests whether the RelationalField definition is consistent\nfunc (a *RelationalFieldDefinition) Validate() *design.ValidationErrors {\n\tverr := new(goa.ValidationErrors)\n\tif field.Name == \"\" {\n\t\tverr.Add(a, \"field name not defined\")\n\t}\n\treturn verr.AsError()\n}\n<|endoftext|>"}
{"text":"<commit_before>package weed_server\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/stats\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n\n\t_ \"github.com\/chrislusf\/seaweedfs\/weed\/statik\"\n\t\"github.com\/gorilla\/mux\"\n\tstatik \"github.com\/rakyll\/statik\/fs\"\n)\n\nvar serverStats *stats.ServerStats\nvar startTime = time.Now()\nvar statikFS http.FileSystem\n\nfunc init() {\n\tserverStats = stats.NewServerStats()\n\tgo serverStats.Start()\n\tstatikFS, _ = statik.New()\n}\n\nfunc writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {\n\tvar bytes []byte\n\tif r.FormValue(\"pretty\") != \"\" {\n\t\tbytes, err = json.MarshalIndent(obj, \"\", \"  \")\n\t} else {\n\t\tbytes, err = json.Marshal(obj)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tcallback := r.FormValue(\"callback\")\n\tif callback == \"\" {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(httpStatus)\n\t\t_, err = w.Write(bytes)\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application\/javascript\")\n\t\tw.WriteHeader(httpStatus)\n\t\tif _, err = w.Write([]uint8(callback)); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif _, err = w.Write([]uint8(\"(\")); err != nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bytes))\n\t\tif _, err = w.Write([]uint8(\")\")); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ wrapper for writeJson - just logs errors\nfunc writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {\n\tif err := writeJson(w, r, httpStatus, obj); err != nil {\n\t\tglog.V(0).Infof(\"error writing JSON %+v status %d: %v\", obj, httpStatus, err)\n\t}\n}\nfunc writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {\n\tm := make(map[string]interface{})\n\tm[\"error\"] = err.Error()\n\twriteJsonQuiet(w, r, httpStatus, m)\n}\n\nfunc debug(params ...interface{}) {\n\tglog.V(4).Infoln(params...)\n}\n\nfunc submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string, grpcDialOption grpc.DialOption) {\n\tm := make(map[string]interface{})\n\tif r.Method != \"POST\" {\n\t\twriteJsonError(w, r, http.StatusMethodNotAllowed, errors.New(\"Only submit via POST!\"))\n\t\treturn\n\t}\n\n\tdebug(\"parsing upload file...\")\n\tfname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.ParseUpload(r)\n\tif pe != nil {\n\t\twriteJsonError(w, r, http.StatusBadRequest, pe)\n\t\treturn\n\t}\n\n\tdebug(\"assigning file id for\", fname)\n\tr.ParseForm()\n\tcount := uint64(1)\n\tif r.FormValue(\"count\") != \"\" {\n\t\tcount, pe = strconv.ParseUint(r.FormValue(\"count\"), 10, 32)\n\t\tif pe != nil {\n\t\t\twriteJsonError(w, r, http.StatusBadRequest, pe)\n\t\t\treturn\n\t\t}\n\t}\n\tar := &operation.VolumeAssignRequest{\n\t\tCount:       count,\n\t\tReplication: r.FormValue(\"replication\"),\n\t\tCollection:  r.FormValue(\"collection\"),\n\t\tTtl:         r.FormValue(\"ttl\"),\n\t}\n\tassignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar)\n\tif ae != nil {\n\t\twriteJsonError(w, r, http.StatusInternalServerError, ae)\n\t\treturn\n\t}\n\n\turl := \"http:\/\/\" + assignResult.Url + \"\/\" + assignResult.Fid\n\tif lastModified != 0 {\n\t\turl = url + \"?ts=\" + strconv.FormatUint(lastModified, 10)\n\t}\n\n\tdebug(\"upload file to store\", url)\n\tuploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth)\n\tif err != nil {\n\t\twriteJsonError(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tm[\"fileName\"] = fname\n\tm[\"fid\"] = assignResult.Fid\n\tm[\"fileUrl\"] = assignResult.PublicUrl + \"\/\" + assignResult.Fid\n\tm[\"size\"] = originalDataSize\n\tm[\"eTag\"] = uploadResult.ETag\n\twriteJsonQuiet(w, r, http.StatusCreated, m)\n\treturn\n}\n\nfunc parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {\n\tswitch strings.Count(path, \"\/\") {\n\tcase 3:\n\t\tparts := strings.Split(path, \"\/\")\n\t\tvid, fid, filename = parts[1], parts[2], parts[3]\n\t\text = filepath.Ext(filename)\n\tcase 2:\n\t\tparts := strings.Split(path, \"\/\")\n\t\tvid, fid = parts[1], parts[2]\n\t\tdotIndex := strings.LastIndex(fid, \".\")\n\t\tif dotIndex > 0 {\n\t\t\text = fid[dotIndex:]\n\t\t\tfid = fid[0:dotIndex]\n\t\t}\n\tdefault:\n\t\tsepIndex := strings.LastIndex(path, \"\/\")\n\t\tcommaIndex := strings.LastIndex(path[sepIndex:], \",\")\n\t\tif commaIndex <= 0 {\n\t\t\tvid, isVolumeIdOnly = path[sepIndex+1:], true\n\t\t\treturn\n\t\t}\n\t\tdotIndex := strings.LastIndex(path[sepIndex:], \".\")\n\t\tvid = path[sepIndex+1 : commaIndex]\n\t\tfid = path[commaIndex+1:]\n\t\text = \"\"\n\t\tif dotIndex > 0 {\n\t\t\tfid = path[commaIndex+1 : dotIndex]\n\t\t\text = path[dotIndex:]\n\t\t}\n\t}\n\treturn\n}\n\nfunc statsHealthHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\nfunc statsCounterHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\tm[\"Counters\"] = serverStats\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\n\nfunc statsMemoryHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\tm[\"Memory\"] = stats.MemStat()\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\n\nfunc handleStaticResources(defaultMux *http.ServeMux) {\n\tdefaultMux.Handle(\"\/favicon.ico\", http.FileServer(statikFS))\n\tdefaultMux.Handle(\"\/seaweedfsstatic\/\", http.StripPrefix(\"\/seaweedfsstatic\", http.FileServer(statikFS)))\n}\n\nfunc handleStaticResources2(r *mux.Router) {\n\tr.Handle(\"\/favicon.ico\", http.FileServer(statikFS))\n\tr.PathPrefix(\"\/seaweedfsstatic\/\").Handler(http.StripPrefix(\"\/seaweedfsstatic\", http.FileServer(statikFS)))\n}\n<commit_msg>skip writing content if not modified<commit_after>package weed_server\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/stats\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n\n\t_ \"github.com\/chrislusf\/seaweedfs\/weed\/statik\"\n\t\"github.com\/gorilla\/mux\"\n\tstatik \"github.com\/rakyll\/statik\/fs\"\n)\n\nvar serverStats *stats.ServerStats\nvar startTime = time.Now()\nvar statikFS http.FileSystem\n\nfunc init() {\n\tserverStats = stats.NewServerStats()\n\tgo serverStats.Start()\n\tstatikFS, _ = statik.New()\n}\n\nfunc writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {\n\tvar bytes []byte\n\tif r.FormValue(\"pretty\") != \"\" {\n\t\tbytes, err = json.MarshalIndent(obj, \"\", \"  \")\n\t} else {\n\t\tbytes, err = json.Marshal(obj)\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tcallback := r.FormValue(\"callback\")\n\tif callback == \"\" {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(httpStatus)\n\t\tif httpStatus == http.StatusNotModified {\n\t\t\treturn\n\t\t}\n\t\t_, err = w.Write(bytes)\n\t} else {\n\t\tw.Header().Set(\"Content-Type\", \"application\/javascript\")\n\t\tw.WriteHeader(httpStatus)\n\t\tif httpStatus == http.StatusNotModified {\n\t\t\treturn\n\t\t}\n\t\tif _, err = w.Write([]uint8(callback)); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif _, err = w.Write([]uint8(\"(\")); err != nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprint(w, string(bytes))\n\t\tif _, err = w.Write([]uint8(\")\")); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ wrapper for writeJson - just logs errors\nfunc writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {\n\tif err := writeJson(w, r, httpStatus, obj); err != nil {\n\t\tglog.V(0).Infof(\"error writing JSON %+v status %d: %v\", obj, httpStatus, err)\n\t}\n}\nfunc writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {\n\tm := make(map[string]interface{})\n\tm[\"error\"] = err.Error()\n\twriteJsonQuiet(w, r, httpStatus, m)\n}\n\nfunc debug(params ...interface{}) {\n\tglog.V(4).Infoln(params...)\n}\n\nfunc submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string, grpcDialOption grpc.DialOption) {\n\tm := make(map[string]interface{})\n\tif r.Method != \"POST\" {\n\t\twriteJsonError(w, r, http.StatusMethodNotAllowed, errors.New(\"Only submit via POST!\"))\n\t\treturn\n\t}\n\n\tdebug(\"parsing upload file...\")\n\tfname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.ParseUpload(r)\n\tif pe != nil {\n\t\twriteJsonError(w, r, http.StatusBadRequest, pe)\n\t\treturn\n\t}\n\n\tdebug(\"assigning file id for\", fname)\n\tr.ParseForm()\n\tcount := uint64(1)\n\tif r.FormValue(\"count\") != \"\" {\n\t\tcount, pe = strconv.ParseUint(r.FormValue(\"count\"), 10, 32)\n\t\tif pe != nil {\n\t\t\twriteJsonError(w, r, http.StatusBadRequest, pe)\n\t\t\treturn\n\t\t}\n\t}\n\tar := &operation.VolumeAssignRequest{\n\t\tCount:       count,\n\t\tReplication: r.FormValue(\"replication\"),\n\t\tCollection:  r.FormValue(\"collection\"),\n\t\tTtl:         r.FormValue(\"ttl\"),\n\t}\n\tassignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar)\n\tif ae != nil {\n\t\twriteJsonError(w, r, http.StatusInternalServerError, ae)\n\t\treturn\n\t}\n\n\turl := \"http:\/\/\" + assignResult.Url + \"\/\" + assignResult.Fid\n\tif lastModified != 0 {\n\t\turl = url + \"?ts=\" + strconv.FormatUint(lastModified, 10)\n\t}\n\n\tdebug(\"upload file to store\", url)\n\tuploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth)\n\tif err != nil {\n\t\twriteJsonError(w, r, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tm[\"fileName\"] = fname\n\tm[\"fid\"] = assignResult.Fid\n\tm[\"fileUrl\"] = assignResult.PublicUrl + \"\/\" + assignResult.Fid\n\tm[\"size\"] = originalDataSize\n\tm[\"eTag\"] = uploadResult.ETag\n\twriteJsonQuiet(w, r, http.StatusCreated, m)\n\treturn\n}\n\nfunc parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly bool) {\n\tswitch strings.Count(path, \"\/\") {\n\tcase 3:\n\t\tparts := strings.Split(path, \"\/\")\n\t\tvid, fid, filename = parts[1], parts[2], parts[3]\n\t\text = filepath.Ext(filename)\n\tcase 2:\n\t\tparts := strings.Split(path, \"\/\")\n\t\tvid, fid = parts[1], parts[2]\n\t\tdotIndex := strings.LastIndex(fid, \".\")\n\t\tif dotIndex > 0 {\n\t\t\text = fid[dotIndex:]\n\t\t\tfid = fid[0:dotIndex]\n\t\t}\n\tdefault:\n\t\tsepIndex := strings.LastIndex(path, \"\/\")\n\t\tcommaIndex := strings.LastIndex(path[sepIndex:], \",\")\n\t\tif commaIndex <= 0 {\n\t\t\tvid, isVolumeIdOnly = path[sepIndex+1:], true\n\t\t\treturn\n\t\t}\n\t\tdotIndex := strings.LastIndex(path[sepIndex:], \".\")\n\t\tvid = path[sepIndex+1 : commaIndex]\n\t\tfid = path[commaIndex+1:]\n\t\text = \"\"\n\t\tif dotIndex > 0 {\n\t\t\tfid = path[commaIndex+1 : dotIndex]\n\t\t\text = path[dotIndex:]\n\t\t}\n\t}\n\treturn\n}\n\nfunc statsHealthHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\nfunc statsCounterHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\tm[\"Counters\"] = serverStats\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\n\nfunc statsMemoryHandler(w http.ResponseWriter, r *http.Request) {\n\tm := make(map[string]interface{})\n\tm[\"Version\"] = util.VERSION\n\tm[\"Memory\"] = stats.MemStat()\n\twriteJsonQuiet(w, r, http.StatusOK, m)\n}\n\nfunc handleStaticResources(defaultMux *http.ServeMux) {\n\tdefaultMux.Handle(\"\/favicon.ico\", http.FileServer(statikFS))\n\tdefaultMux.Handle(\"\/seaweedfsstatic\/\", http.StripPrefix(\"\/seaweedfsstatic\", http.FileServer(statikFS)))\n}\n\nfunc handleStaticResources2(r *mux.Router) {\n\tr.Handle(\"\/favicon.ico\", http.FileServer(statikFS))\n\tr.PathPrefix(\"\/seaweedfsstatic\/\").Handler(http.StripPrefix(\"\/seaweedfsstatic\", http.FileServer(statikFS)))\n}\n<|endoftext|>"}
{"text":"<commit_before>package model_test\n\n\n<commit_msg>Start of test framework<commit_after>package model_test\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/crezam\/actions-on-google-golang\/model\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestRequestParsing(t *testing.T) {\n\n\tvar req model.ApiAiRequest\n\n\tfile, _ := os.Open(\".\/data\/sample_request1.json\")\n\tdec := json.NewDecoder(file)\n\n\tif err := dec.Decode(&req); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif resolvedQuery := req.Result.ResolvedQuery; resolvedQuery != \"Hi, my name is Sam!\" {\n\t\tt.Fatal(\"Failed parsing resolved query\")\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package wikifier\n\ntype tocBlock struct {\n\t*parserBlock\n}\n\nfunc newTocBlock(name string, b *parserBlock) block {\n\treturn &tocBlock{b}\n}\n\nfunc (toc *tocBlock) html(page *Page, el element) {\n\tel.setTag(\"ul\")\n\tel.addHTML(HTML(\"<strong>Contents<\/strong>\"))\n\t\/\/ add each top-level section\n\tfor _, child := range page.main.blockContent() {\n\t\tif sec, ok := child.(*secBlock); ok {\n\t\t\ttocAdd(sec, el)\n\t\t}\n\t}\n}\n\nfunc tocAdd(sec *secBlock, addTo element) {\n\n\t\/\/ create an item for this section\n\tvar subList element\n\tif !sec.isIntro {\n\t\tli := addTo.createChild(\"li\", \"\")\n\t\ta := li.createChild(\"a\", \"link-internal\")\n\t\ta.setAttr(\"href\", \"#\"+sec.headingID)\n\t\ta.addHTML(sec.fmtTitle)\n\t\taddTo = li\n\t} else {\n\t\tsubList = addTo\n\t}\n\n\t\/\/ create a sub-list for each section underneath\n\tfor _, child := range sec.blockContent() {\n\t\tif secChild, ok := child.(*secBlock); ok {\n\t\t\tif subList == nil {\n\t\t\t\tsubList = addTo.createChild(\"ul\", \"\")\n\t\t\t}\n\t\t\ttocAdd(secChild, subList)\n\t\t}\n\t}\n}\n<commit_msg>seems fmtTitle isn't yet defined so format it now<commit_after>package wikifier\n\ntype tocBlock struct {\n\t*parserBlock\n}\n\nfunc newTocBlock(name string, b *parserBlock) block {\n\treturn &tocBlock{b}\n}\n\nfunc (toc *tocBlock) html(page *Page, el element) {\n\tel.setTag(\"ul\")\n\tel.addHTML(HTML(\"<strong>Contents<\/strong>\"))\n\t\/\/ add each top-level section\n\tfor _, child := range page.main.blockContent() {\n\t\tif sec, ok := child.(*secBlock); ok {\n\t\t\ttocAdd(sec, el, page)\n\t\t}\n\t}\n}\n\nfunc tocAdd(sec *secBlock, addTo element, page *Page) {\n\n\t\/\/ create an item for this section\n\tvar subList element\n\tif !sec.isIntro {\n\t\tli := addTo.createChild(\"li\", \"\")\n\t\ta := li.createChild(\"a\", \"link-internal\")\n\t\ta.setAttr(\"href\", \"#\"+sec.headingID)\n\t\ta.addHTML(page.formatTextOpts(sec.title, fmtOpt{pos: sec.openPos}))\n\t\taddTo = li\n\t} else {\n\t\tsubList = addTo\n\t}\n\n\t\/\/ create a sub-list for each section underneath\n\tfor _, child := range sec.blockContent() {\n\t\tif secChild, ok := child.(*secBlock); ok {\n\t\t\tif subList == nil {\n\t\t\t\tsubList = addTo.createChild(\"ul\", \"\")\n\t\t\t}\n\t\t\ttocAdd(secChild, subList, page)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package worker\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\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\/service\/sqs\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sqs\/sqsiface\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\ntype mockedSqsClient struct {\n\tConfig   *aws.Config\n\tResponse sqs.ReceiveMessageOutput\n\tsqsiface.SQSAPI\n\tmock.Mock\n}\n\nfunc (c *mockedSqsClient) GetQueueUrl(urlInput *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) {\n\turl := fmt.Sprintf(\"https:\/\/sqs.%v.amazonaws.com\/123456789\/%v\", *c.Config.Region, *urlInput.QueueName)\n\n\treturn &sqs.GetQueueUrlOutput{QueueUrl: &url}, nil\n}\n\nfunc (c *mockedSqsClient) ReceiveMessage(input *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) {\n\tc.Called(input)\n\n\treturn &c.Response, nil\n}\n\nfunc (c *mockedSqsClient) DeleteMessage(input *sqs.DeleteMessageInput) (*sqs.DeleteMessageOutput, error) {\n\tc.Called(input)\n\tc.Response = sqs.ReceiveMessageOutput{}\n\n\treturn &sqs.DeleteMessageOutput{}, nil\n}\n\ntype mockedHandler struct {\n\tmock.Mock\n}\n\nfunc (mh *mockedHandler) HandleMessage(foo string, qux string) {\n\tmh.Called(foo, qux)\n}\n\ntype sqsEvent struct {\n\tFoo string `json:\"foo\"`\n\tQux string `json:\"qux\"`\n}\n\nfunc TestStart(t *testing.T) {\n\tregion := \"eu-west-1\"\n\tawsConfig := &aws.Config{Region: &region}\n\tworkerConfig := &Config{QueueName: \"my-sqs-queue\"}\n\tclient := setupMockedSqsClient(awsConfig)\n\tworker := New(client, workerConfig)\n\n\tctx, cancel := contextAndCancel()\n\tdefer cancel()\n\n\thandler := new(mockedHandler)\n\thandlerFunc := HandlerFunc(func(msg *sqs.Message) (err error) {\n\t\tevent := &sqsEvent{}\n\n\t\tjson.Unmarshal([]byte(aws.StringValue(msg.Body)), event)\n\n\t\thandler.HandleMessage(event.Foo, event.Qux)\n\n\t\treturn\n\t})\n\n\tt.Run(\"the worker has correct configuration\", func(t *testing.T) {\n\t\tassert.Equal(t, worker.Config.QueueName, \"my-sqs-queue\", \"QueueName has been set properly\")\n\t\tassert.Equal(t, worker.Config.QueueURL, \"https:\/\/sqs.eu-west-1.amazonaws.com\/123456789\/my-sqs-queue\", \"QueueURL has been set properly\")\n\t\tassert.Equal(t, worker.Config.MaxNumberOfMessage, int64(10), \"MaxNumberOfMessage has been set properly\")\n\t\tassert.Equal(t, worker.Config.WaitTimeSecond, int64(20), \"WaitTimeSecond has been set properly\")\n\t})\n\n\tt.Run(\"the worker successfully processes a message\", func(t *testing.T) {\n\t\tsetupClientSpies(client)\n\t\thandler.On(\"HandleMessage\", \"bar\", \"baz\").Return().Once()\n\t\tworker.Start(ctx, handlerFunc)\n\n\t\tclient.AssertExpectations(t)\n\t\thandler.AssertExpectations(t)\n\t})\n}\n\nfunc contextAndCancel() (context.Context, context.CancelFunc) {\n\tdelay := time.Now().Add(1 * time.Millisecond)\n\n\treturn context.WithDeadline(context.Background(), delay)\n}\n\nfunc setupMockedSqsClient(awsConfig *aws.Config) *mockedSqsClient {\n\tsqsMessage := &sqs.Message{Body: aws.String(`{ \"foo\": \"bar\", \"qux\": \"baz\" }`)}\n\tsqsResponse := sqs.ReceiveMessageOutput{\n\t\tMessages: []*sqs.Message{sqsMessage},\n\t}\n\n\treturn &mockedSqsClient{Response: sqsResponse, Config: awsConfig}\n}\n\nfunc setupClientSpies(client *mockedSqsClient) {\n\turl := aws.String(\"https:\/\/sqs.eu-west-1.amazonaws.com\/123456789\/my-sqs-queue\")\n\treceiveInput := &sqs.ReceiveMessageInput{\n\t\tQueueUrl:            url,\n\t\tMaxNumberOfMessages: aws.Int64(10),\n\t\tAttributeNames: []*string{\n\t\t\taws.String(\"All\"),\n\t\t},\n\t\tWaitTimeSeconds: aws.Int64(20),\n\t}\n\tclient.On(\"ReceiveMessage\", receiveInput).Return()\n\n\tdeleteInput := &sqs.DeleteMessageInput{\n\t\tQueueUrl: url,\n\t}\n\tclient.On(\"DeleteMessage\", deleteInput).Return()\n}\n<commit_msg>Add tests for different configuration settings (#10)<commit_after>package worker\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\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\/service\/sqs\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sqs\/sqsiface\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/mock\"\n)\n\ntype mockedSqsClient struct {\n\tConfig   *aws.Config\n\tResponse sqs.ReceiveMessageOutput\n\tsqsiface.SQSAPI\n\tmock.Mock\n}\n\nfunc (c *mockedSqsClient) GetQueueUrl(urlInput *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) {\n\turl := fmt.Sprintf(\"https:\/\/sqs.%v.amazonaws.com\/123456789\/%v\", *c.Config.Region, *urlInput.QueueName)\n\n\treturn &sqs.GetQueueUrlOutput{QueueUrl: &url}, nil\n}\n\nfunc (c *mockedSqsClient) ReceiveMessage(input *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) {\n\tc.Called(input)\n\n\treturn &c.Response, nil\n}\n\nfunc (c *mockedSqsClient) DeleteMessage(input *sqs.DeleteMessageInput) (*sqs.DeleteMessageOutput, error) {\n\tc.Called(input)\n\tc.Response = sqs.ReceiveMessageOutput{}\n\n\treturn &sqs.DeleteMessageOutput{}, nil\n}\n\ntype mockedHandler struct {\n\tmock.Mock\n}\n\nfunc (mh *mockedHandler) HandleMessage(foo string, qux string) {\n\tmh.Called(foo, qux)\n}\n\ntype sqsEvent struct {\n\tFoo string `json:\"foo\"`\n\tQux string `json:\"qux\"`\n}\n\nconst maxNumberOfMessages = 1984\nconst waitTimeSecond = 1337\n\nfunc TestStart(t *testing.T) {\n\tregion := \"eu-west-1\"\n\tawsConfig := &aws.Config{Region: &region}\n\tworkerConfig := &Config{\n\t\tMaxNumberOfMessage: maxNumberOfMessages,\n\t\tQueueName:          \"my-sqs-queue\",\n\t\tWaitTimeSecond:     waitTimeSecond,\n\t}\n\n\tclientParams := buildClientParams()\n\tsqsMessage := &sqs.Message{Body: aws.String(`{ \"foo\": \"bar\", \"qux\": \"baz\" }`)}\n\tsqsResponse := sqs.ReceiveMessageOutput{Messages: []*sqs.Message{sqsMessage}}\n\tclient := &mockedSqsClient{Response: sqsResponse, Config: awsConfig}\n\tdeleteInput := &sqs.DeleteMessageInput{QueueUrl: clientParams.QueueUrl}\n\n\tworker := New(client, workerConfig)\n\n\tctx, cancel := contextAndCancel()\n\tdefer cancel()\n\n\thandler := new(mockedHandler)\n\thandlerFunc := HandlerFunc(func(msg *sqs.Message) (err error) {\n\t\tevent := &sqsEvent{}\n\n\t\tjson.Unmarshal([]byte(aws.StringValue(msg.Body)), event)\n\n\t\thandler.HandleMessage(event.Foo, event.Qux)\n\n\t\treturn\n\t})\n\n\tt.Run(\"the worker has correct configuration\", func(t *testing.T) {\n\t\tassert.Equal(t, worker.Config.QueueName, \"my-sqs-queue\", \"QueueName has been set properly\")\n\t\tassert.Equal(t, worker.Config.QueueURL, \"https:\/\/sqs.eu-west-1.amazonaws.com\/123456789\/my-sqs-queue\", \"QueueURL has been set properly\")\n\t\tassert.Equal(t, worker.Config.MaxNumberOfMessage, int64(maxNumberOfMessages), \"MaxNumberOfMessage has been set properly\")\n\t\tassert.Equal(t, worker.Config.WaitTimeSecond, int64(waitTimeSecond), \"WaitTimeSecond has been set properly\")\n\t})\n\n\tt.Run(\"the worker has correct default configuration\", func(t *testing.T) {\n\t\tminimumConfig := &Config{\n\t\t\tQueueName: \"my-sqs-queue\",\n\t\t}\n\t\tworker := New(client, minimumConfig)\n\n\t\tassert.Equal(t, worker.Config.QueueName, \"my-sqs-queue\", \"QueueName has been set properly\")\n\t\tassert.Equal(t, worker.Config.QueueURL, \"https:\/\/sqs.eu-west-1.amazonaws.com\/123456789\/my-sqs-queue\", \"QueueURL has been set properly\")\n\t\tassert.Equal(t, worker.Config.MaxNumberOfMessage, int64(10), \"MaxNumberOfMessage has been set by default\")\n\t\tassert.Equal(t, worker.Config.WaitTimeSecond, int64(20), \"WaitTimeSecond has been set by default\")\n\t})\n\n\tt.Run(\"the worker successfully processes a message\", func(t *testing.T) {\n\t\tclient.On(\"ReceiveMessage\", clientParams).Return()\n\t\tclient.On(\"DeleteMessage\", deleteInput).Return()\n\t\thandler.On(\"HandleMessage\", \"bar\", \"baz\").Return().Once()\n\n\t\tworker.Start(ctx, handlerFunc)\n\n\t\tclient.AssertExpectations(t)\n\t\thandler.AssertExpectations(t)\n\t})\n}\n\nfunc contextAndCancel() (context.Context, context.CancelFunc) {\n\tdelay := time.Now().Add(1 * time.Millisecond)\n\n\treturn context.WithDeadline(context.Background(), delay)\n}\n\nfunc buildClientParams() *sqs.ReceiveMessageInput {\n\turl := aws.String(\"https:\/\/sqs.eu-west-1.amazonaws.com\/123456789\/my-sqs-queue\")\n\n\treturn &sqs.ReceiveMessageInput{\n\t\tQueueUrl:            url,\n\t\tMaxNumberOfMessages: aws.Int64(maxNumberOfMessages),\n\t\tAttributeNames:      []*string{aws.String(\"All\")},\n\t\tWaitTimeSeconds:     aws.Int64(waitTimeSecond),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package simulator\n\n\/\/ Simulator is the object that coordanates workers for the game computations\ntype Simulator struct {\n\tkillChan    chan struct{}\n\tworkerQueue chan *Worker\n\tnumWorkers,\n\tmaxWorkers int\n\tJobChan chan *Job\n}\n\n\/\/ ListenAndServer listen for new requrests and serve the responses\nfunc (s *Simulator) ListenAndServer() {\n\tfor {\n\n\t\tselect {\n\n\t\tcase tmp := <-s.JobChan:\n\t\t\t\/\/ see if there is an open worker\n\t\t\tselect {\n\t\t\t\/\/ if there is an open worker, assign the job to that worker and run the job\n\t\t\tcase w := <-s.workerQueue:\n\t\t\t\tw.job = tmp\n\t\t\t\tgo w.job.run()\n\t\t\t\/\/ if there is no open worker, but the max number of workers has not been reaches, create a new worker and assign it the job\n\t\t\tdefault:\n\t\t\t\tif s.numWorkers < s.maxWorkers {\n\t\t\t\t\tw := NewWorker(s)\n\t\t\t\t\tw.job = tmp\n\t\t\t\t\tgo w.job.run()\n\t\t\t\t\ts.numWorkers += 1\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ if a new worker cannot be created, block until worker is ready\n\t\t\t\t\tw := <-s.workerQueue\n\t\t\t\t\tw.job = tmp\n\t\t\t\t\tgo w.job.run()\n\t\t\t\t}\n\t\t\t}\n\t\t\/\/ If signal on killChan is recieved, close all channels and return the function.\n\t\tcase <-s.killChan:\n\t\t\tclose(s.JobChan)\n\t\t\tclose(s.killChan)\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>the worker now calles the run function<commit_after>package simulator\n\n\/\/ Simulator is the object that coordanates workers for the game computations\ntype Simulator struct {\n\tkillChan    chan struct{}\n\tworkerQueue chan *Worker\n\tnumWorkers,\n\tmaxWorkers int\n\tJobChan chan *Job\n}\n\n\/\/ ListenAndServer listen for new requrests and serve the responses\nfunc (s *Simulator) ListenAndServer() {\n\tfor {\n\n\t\tselect {\n\n\t\tcase tmp := <-s.JobChan:\n\t\t\t\/\/ see if there is an open worker\n\t\t\tselect {\n\t\t\t\/\/ if there is an open worker, assign the job to that worker and run the job\n\t\t\tcase w := <-s.workerQueue:\n\t\t\t\tw.job = tmp\n\t\t\t\tgo w.job.run()\n\t\t\t\/\/ if there is no open worker, but the max number of workers has not been reaches, create a new worker and assign it the job\n\t\t\tdefault:\n\t\t\t\tif s.numWorkers < s.maxWorkers {\n\t\t\t\t\tw := NewWorker(s)\n\t\t\t\t\tw.job = tmp\n\t\t\t\t\tgo w.Run()\n\t\t\t\t\ts.numWorkers += 1\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ if a new worker cannot be created, block until a worker is ready\n\t\t\t\t\tw := <-s.workerQueue\n\t\t\t\t\tw.job = tmp\n\t\t\t\t\tgo w.Run()\n\t\t\t\t}\n\t\t\t}\n\t\t\/\/ If signal on killChan is recieved, close all channels and return the function.\n\t\tcase <-s.killChan:\n\t\t\tclose(s.JobChan)\n\t\t\tclose(s.killChan)\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package ws provides components for building web services and automating the processing of web service requests.\npackage handler\n\nimport (\n\t\"github.com\/graniticio\/granitic\/logging\"\n\t\"github.com\/graniticio\/granitic\/ws\"\n\t\"net\/http\"\n\t\"regexp\"\n)\n\n\/\/Implements HttpEndpointProvider\ntype WsHandler struct {\n\tAccessChecker         ws.WsAccessChecker \/\/\n\tAllowDirectHTTPAccess bool \/\/ Whether or not the underlying HTTP request and response writer should be made available to request Logic.\n\tAutoBindQuery         bool \/\/ Whether or not query parameters should be automatically injected into the request body.\n\tBindPathParams        []string \/\/ A list of fields on the request body that should be populated using elements of the request path.\n\tCheckAccessAfterParse bool \/\/ Check caller's permissions after request has been parsed (true) or before parsing (false).\n\tDeferFrameworkErrors  bool \/\/ If true, do not automatically return an error response if errors are found during the automated phases of request processing.\n\tDisableQueryParsing   bool \/\/ If true, discard the request's query parameters.\n\tDisablePathParsing    bool \/\/ If true, discard any path parameters found by match the request URI against the PathMatchPattern regex.\n\tErrorFinder           ws.ServiceErrorFinder \/\/ An object that provides access to application defined error messages for use during validation.\n\tFieldQueryParam       map[string]string \/\/ A map of fields on the request body object and the names of query parameters that should be used to populate them\n\tFrameworkErrors       *ws.FrameworkErrorGenerator \/\/ An object that provides access to built-in error messages to use when an error is found during the automated phases of request processing.\n\tHttpMethod            string \/\/ The HTTP method (GET, POST etc) that this handler supports.\n\tLog                   logging.Logger \/\/\n\tLogic                 ws.WsRequestProcessor \/\/ The object representing the 'logic' behind this handler.\n\tParamBinder           *ws.ParamBinder \/\/\n\tPathMatchPattern      string \/\/ A regex that will be matched against inbound request paths to check if this handler should be used to service the request.\n\tResponseWriter        ws.WsResponseWriter \/\/\n\tRequireAuthentication bool \/\/ Whether on not the caller needs to be authenticated (using a ws.WsIdentifier) in order to access the logic behind this handler.\n\tUnmarshaller          ws.WsUnmarshaller \/\/\n\tUserIdentifier        ws.WsIdentifier \/\/\n\tbindPathParams        bool\n\tbindQuery             bool\n\thttpMethods           []string\n\tcomponentName         string\n\tpathRegex             *regexp.Regexp\n\tvalidate              bool\n\tvalidator             ws.WsRequestValidator\n}\n\nfunc (wh *WsHandler) ProvideErrorFinder(finder ws.ServiceErrorFinder) {\n\twh.ErrorFinder = finder\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) ServeHTTP(w *ws.WsHTTPResponseWriter, req *http.Request) ws.WsIdentity {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twh.Log.LogErrorfWithTrace(\"Panic recovered while trying process a request or write its response %s\", r)\n\t\t\twh.writePanicResponse(r, w)\n\t\t}\n\t}()\n\n\twsReq := new(ws.WsRequest)\n\twsReq.HttpMethod = req.Method\n\n\tif wh.AllowDirectHTTPAccess {\n\t\tda := new(ws.DirectHTTPAccess)\n\t\tda.Request = req\n\t\tda.ResponseWriter = w\n\n\t\twsReq.UnderlyingHTTP = da\n\t}\n\n\n\t\/\/Try to identify and\/or authenticate the caller\n\tif !wh.identifyAndAuthenticate(w, req, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Check caller has permission to use this resource\n\tif !wh.CheckAccessAfterParse && !wh.checkAccess(w, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Unmarshall body, query parameters and path parameters\n\twh.unmarshall(req, wsReq)\n\twh.processQueryParams(req, wsReq)\n\twh.processPathParams(req, wsReq)\n\n\tif wsReq.HasFrameworkErrors() && !wh.DeferFrameworkErrors {\n\t\twh.handleFrameworkErrors(w, wsReq)\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Check caller has permission to use this resource\n\tif wh.CheckAccessAfterParse && !wh.checkAccess(w, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Validate request\n\tvar errors ws.ServiceErrors\n\terrors.ErrorFinder = wh.ErrorFinder\n\n\tif wh.validate {\n\t\twh.validator.Validate(&errors, wsReq)\n\t}\n\n\tif errors.HasErrors() {\n\t\twh.writeErrorResponse(&errors, w)\n\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Execute logic\n\twh.process(wsReq, w)\n\n\treturn wsReq.UserIdentity\n}\n\nfunc (wh *WsHandler) unmarshall(req *http.Request, wsReq *ws.WsRequest) {\n\n\ttargetSource, found := wh.Logic.(ws.WsUnmarshallTarget)\n\n\tif found {\n\t\ttarget := targetSource.UnmarshallTarget()\n\t\twsReq.RequestBody = target\n\n\t\tif req.ContentLength == 0 {\n\t\t\treturn\n\t\t}\n\n\t\terr := wh.Unmarshaller.Unmarshall(req, wsReq)\n\n\t\tif err != nil {\n\n\t\t\twh.Log.LogDebugf(\"Error unmarshalling request body for %s %s %s\", req.URL.Path, req.Method, err)\n\n\t\t\tm, c := wh.FrameworkErrors.MessageCode(ws.UnableToParseRequest)\n\n\t\t\tf := ws.NewUnmarshallWsFrameworkError(m, c)\n\t\t\twsReq.AddFrameworkError(f)\n\t\t}\n\n\t}\n}\n\nfunc (wh *WsHandler) processPathParams(req *http.Request, wsReq *ws.WsRequest) {\n\n\tif wh.DisablePathParsing {\n\t\treturn\n\t}\n\n\tre := wh.pathRegex\n\tparams := re.FindStringSubmatch(req.URL.Path)\n\twsReq.PathParams = params[1:]\n\n\tif wh.bindPathParams && len(wsReq.PathParams) > 0 {\n\t\tpp := ws.NewWsParamsForPath(wh.BindPathParams, wsReq.PathParams)\n\t\twh.ParamBinder.AutoBindPathParameters(wsReq, pp)\n\t}\n\n}\n\nfunc (wh *WsHandler) processQueryParams(req *http.Request, wsReq *ws.WsRequest) {\n\n\tif wh.DisableQueryParsing {\n\t\treturn\n\t}\n\n\tvalues := req.URL.Query()\n\twsReq.QueryParams = ws.NewWsParamsForQuery(values)\n\n\tif wh.bindQuery {\n\t\tif wsReq.RequestBody == nil {\n\t\t\twh.Log.LogErrorf(\"Query parameter binding is enabled, but no target available to bind into. Does your Logic component implement the WsUnmarshallTarget interface?\")\n\t\t\treturn\n\t\t}\n\n\t\tif wh.AutoBindQuery {\n\t\t\twh.ParamBinder.AutoBindQueryParameters(wsReq)\n\t\t} else {\n\t\t\twh.ParamBinder.BindQueryParameters(wsReq, wh.FieldQueryParam)\n\t\t}\n\n\t}\n\n}\n\nfunc (wh *WsHandler) checkAccess(w *ws.WsHTTPResponseWriter, wsReq *ws.WsRequest) bool {\n\n\tac := wh.AccessChecker\n\n\tif ac == nil {\n\t\treturn true\n\t}\n\n\tallowed := ac.Allowed(wsReq)\n\n\tif allowed {\n\t\treturn true\n\t} else {\n\t\twh.ResponseWriter.WriteAbnormalStatus(http.StatusForbidden, w)\n\t\treturn false\n\t}\n}\n\nfunc (wh *WsHandler) identifyAndAuthenticate(w *ws.WsHTTPResponseWriter, req *http.Request, wsReq *ws.WsRequest) bool {\n\n\tif wh.UserIdentifier != nil {\n\t\ti := wh.UserIdentifier.Identify(req)\n\t\twsReq.UserIdentity = i\n\n\t\tif wh.RequireAuthentication && !i.Authenticated() {\n\t\t\twh.ResponseWriter.WriteAbnormalStatus(http.StatusUnauthorized, w)\n\t\t\treturn false\n\t\t}\n\n\t}\n\n\tif wsReq.UserIdentity == nil {\n\t\twsReq.UserIdentity = ws.NewAnonymousIdentity()\n\t}\n\n\treturn true\n\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) SupportedHttpMethods() []string {\n\tif len(wh.httpMethods) > 0 {\n\t\treturn wh.httpMethods\n\t} else {\n\t\treturn []string{wh.HttpMethod}\n\t}\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) RegexPattern() string {\n\treturn wh.PathMatchPattern\n}\n\nfunc (wh *WsHandler) handleFrameworkErrors(w *ws.WsHTTPResponseWriter, wsReq *ws.WsRequest) {\n\n\tvar se ws.ServiceErrors\n\tse.HttpStatus = http.StatusBadRequest\n\n\tfor _, fe := range wsReq.FrameworkErrors {\n\t\tse.AddNewError(ws.Client, fe.Code, fe.Message)\n\t}\n\n\twh.writeErrorResponse(&se, w)\n\n}\n\nfunc (wh *WsHandler) process(jsonReq *ws.WsRequest, w *ws.WsHTTPResponseWriter) {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twh.Log.LogErrorfWithTrace(\"Panic recovered while trying process a request or write its response %s\", r)\n\t\t\twh.writePanicResponse(r, w)\n\t\t}\n\t}()\n\n\twsRes := ws.NewWsResponse(wh.ErrorFinder)\n\twh.Logic.Process(jsonReq, wsRes)\n\n\twh.ResponseWriter.Write(wsRes, w)\n\n}\n\nfunc (wh *WsHandler) writeErrorResponse(errors *ws.ServiceErrors, w *ws.WsHTTPResponseWriter) {\n\n\tl := wh.Log\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tl.LogErrorfWithTrace(\"Panic recovered while trying to write a response that was already in error %s\", r)\n\t\t}\n\t}()\n\n\terr := wh.ResponseWriter.WriteErrors(errors, w)\n\n\tif err != nil {\n\t\tl.LogErrorf(\"Problem writing an HTTP response that was already in error\", err)\n\t}\n\n}\n\nfunc (wh *WsHandler) writePanicResponse(r interface{}, w *ws.WsHTTPResponseWriter) {\n\n\twh.ResponseWriter.WriteAbnormalStatus(http.StatusInternalServerError, w)\n\n\twh.Log.LogErrorf(\"Panic recovered but error response served. %s\", r)\n\n}\n\nfunc (wh *WsHandler) StartComponent() error {\n\n\tvalidator, found := wh.Logic.(ws.WsRequestValidator)\n\n\twh.validate = found\n\n\tif found {\n\t\twh.validator = validator\n\t}\n\n\twh.bindQuery = wh.AutoBindQuery || (wh.FieldQueryParam != nil && len(wh.FieldQueryParam) > 0)\n\n\tif !wh.DisablePathParsing {\n\n\t\twh.bindPathParams = len(wh.BindPathParams) > 0\n\n\t\tr, err := regexp.Compile(wh.PathMatchPattern)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\twh.pathRegex = r\n\t\t}\n\n\t}\n\n\treturn nil\n\n}\n\nfunc (wh *WsHandler) ComponentName() string {\n\treturn wh.componentName\n}\n\nfunc (wh *WsHandler) SetComponentName(name string) {\n\twh.componentName = name\n}\n\n<commit_msg>Refactoring packaging of WsHandler<commit_after>package handler\n\nimport (\n\t\"github.com\/graniticio\/granitic\/logging\"\n\t\"github.com\/graniticio\/granitic\/ws\"\n\t\"net\/http\"\n\t\"regexp\"\n)\n\n\/\/Implements HttpEndpointProvider\ntype WsHandler struct {\n\tAccessChecker         ws.WsAccessChecker \/\/\n\tAllowDirectHTTPAccess bool \/\/ Whether or not the underlying HTTP request and response writer should be made available to request Logic.\n\tAutoBindQuery         bool \/\/ Whether or not query parameters should be automatically injected into the request body.\n\tBindPathParams        []string \/\/ A list of fields on the request body that should be populated using elements of the request path.\n\tCheckAccessAfterParse bool \/\/ Check caller's permissions after request has been parsed (true) or before parsing (false).\n\tDeferFrameworkErrors  bool \/\/ If true, do not automatically return an error response if errors are found during the automated phases of request processing.\n\tDisableQueryParsing   bool \/\/ If true, discard the request's query parameters.\n\tDisablePathParsing    bool \/\/ If true, discard any path parameters found by match the request URI against the PathMatchPattern regex.\n\tErrorFinder           ws.ServiceErrorFinder \/\/ An object that provides access to application defined error messages for use during validation.\n\tFieldQueryParam       map[string]string \/\/ A map of fields on the request body object and the names of query parameters that should be used to populate them\n\tFrameworkErrors       *ws.FrameworkErrorGenerator \/\/ An object that provides access to built-in error messages to use when an error is found during the automated phases of request processing.\n\tHttpMethod            string \/\/ The HTTP method (GET, POST etc) that this handler supports.\n\tLog                   logging.Logger \/\/\n\tLogic                 ws.WsRequestProcessor \/\/ The object representing the 'logic' behind this handler.\n\tParamBinder           *ws.ParamBinder \/\/\n\tPathMatchPattern      string \/\/ A regex that will be matched against inbound request paths to check if this handler should be used to service the request.\n\tResponseWriter        ws.WsResponseWriter \/\/\n\tRequireAuthentication bool \/\/ Whether on not the caller needs to be authenticated (using a ws.WsIdentifier) in order to access the logic behind this handler.\n\tUnmarshaller          ws.WsUnmarshaller \/\/\n\tUserIdentifier        ws.WsIdentifier \/\/\n\tbindPathParams        bool\n\tbindQuery             bool\n\thttpMethods           []string\n\tcomponentName         string\n\tpathRegex             *regexp.Regexp\n\tvalidate              bool\n\tvalidator             ws.WsRequestValidator\n}\n\nfunc (wh *WsHandler) ProvideErrorFinder(finder ws.ServiceErrorFinder) {\n\twh.ErrorFinder = finder\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) ServeHTTP(w *ws.WsHTTPResponseWriter, req *http.Request) ws.WsIdentity {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twh.Log.LogErrorfWithTrace(\"Panic recovered while trying process a request or write its response %s\", r)\n\t\t\twh.writePanicResponse(r, w)\n\t\t}\n\t}()\n\n\twsReq := new(ws.WsRequest)\n\twsReq.HttpMethod = req.Method\n\n\tif wh.AllowDirectHTTPAccess {\n\t\tda := new(ws.DirectHTTPAccess)\n\t\tda.Request = req\n\t\tda.ResponseWriter = w\n\n\t\twsReq.UnderlyingHTTP = da\n\t}\n\n\n\t\/\/Try to identify and\/or authenticate the caller\n\tif !wh.identifyAndAuthenticate(w, req, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Check caller has permission to use this resource\n\tif !wh.CheckAccessAfterParse && !wh.checkAccess(w, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Unmarshall body, query parameters and path parameters\n\twh.unmarshall(req, wsReq)\n\twh.processQueryParams(req, wsReq)\n\twh.processPathParams(req, wsReq)\n\n\tif wsReq.HasFrameworkErrors() && !wh.DeferFrameworkErrors {\n\t\twh.handleFrameworkErrors(w, wsReq)\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Check caller has permission to use this resource\n\tif wh.CheckAccessAfterParse && !wh.checkAccess(w, wsReq) {\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Validate request\n\tvar errors ws.ServiceErrors\n\terrors.ErrorFinder = wh.ErrorFinder\n\n\tif wh.validate {\n\t\twh.validator.Validate(&errors, wsReq)\n\t}\n\n\tif errors.HasErrors() {\n\t\twh.writeErrorResponse(&errors, w)\n\n\t\treturn wsReq.UserIdentity\n\t}\n\n\t\/\/Execute logic\n\twh.process(wsReq, w)\n\n\treturn wsReq.UserIdentity\n}\n\nfunc (wh *WsHandler) unmarshall(req *http.Request, wsReq *ws.WsRequest) {\n\n\ttargetSource, found := wh.Logic.(ws.WsUnmarshallTarget)\n\n\tif found {\n\t\ttarget := targetSource.UnmarshallTarget()\n\t\twsReq.RequestBody = target\n\n\t\tif req.ContentLength == 0 {\n\t\t\treturn\n\t\t}\n\n\t\terr := wh.Unmarshaller.Unmarshall(req, wsReq)\n\n\t\tif err != nil {\n\n\t\t\twh.Log.LogDebugf(\"Error unmarshalling request body for %s %s %s\", req.URL.Path, req.Method, err)\n\n\t\t\tm, c := wh.FrameworkErrors.MessageCode(ws.UnableToParseRequest)\n\n\t\t\tf := ws.NewUnmarshallWsFrameworkError(m, c)\n\t\t\twsReq.AddFrameworkError(f)\n\t\t}\n\n\t}\n}\n\nfunc (wh *WsHandler) processPathParams(req *http.Request, wsReq *ws.WsRequest) {\n\n\tif wh.DisablePathParsing {\n\t\treturn\n\t}\n\n\tre := wh.pathRegex\n\tparams := re.FindStringSubmatch(req.URL.Path)\n\twsReq.PathParams = params[1:]\n\n\tif wh.bindPathParams && len(wsReq.PathParams) > 0 {\n\t\tpp := ws.NewWsParamsForPath(wh.BindPathParams, wsReq.PathParams)\n\t\twh.ParamBinder.AutoBindPathParameters(wsReq, pp)\n\t}\n\n}\n\nfunc (wh *WsHandler) processQueryParams(req *http.Request, wsReq *ws.WsRequest) {\n\n\tif wh.DisableQueryParsing {\n\t\treturn\n\t}\n\n\tvalues := req.URL.Query()\n\twsReq.QueryParams = ws.NewWsParamsForQuery(values)\n\n\tif wh.bindQuery {\n\t\tif wsReq.RequestBody == nil {\n\t\t\twh.Log.LogErrorf(\"Query parameter binding is enabled, but no target available to bind into. Does your Logic component implement the WsUnmarshallTarget interface?\")\n\t\t\treturn\n\t\t}\n\n\t\tif wh.AutoBindQuery {\n\t\t\twh.ParamBinder.AutoBindQueryParameters(wsReq)\n\t\t} else {\n\t\t\twh.ParamBinder.BindQueryParameters(wsReq, wh.FieldQueryParam)\n\t\t}\n\n\t}\n\n}\n\nfunc (wh *WsHandler) checkAccess(w *ws.WsHTTPResponseWriter, wsReq *ws.WsRequest) bool {\n\n\tac := wh.AccessChecker\n\n\tif ac == nil {\n\t\treturn true\n\t}\n\n\tallowed := ac.Allowed(wsReq)\n\n\tif allowed {\n\t\treturn true\n\t} else {\n\t\twh.ResponseWriter.WriteAbnormalStatus(http.StatusForbidden, w)\n\t\treturn false\n\t}\n}\n\nfunc (wh *WsHandler) identifyAndAuthenticate(w *ws.WsHTTPResponseWriter, req *http.Request, wsReq *ws.WsRequest) bool {\n\n\tif wh.UserIdentifier != nil {\n\t\ti := wh.UserIdentifier.Identify(req)\n\t\twsReq.UserIdentity = i\n\n\t\tif wh.RequireAuthentication && !i.Authenticated() {\n\t\t\twh.ResponseWriter.WriteAbnormalStatus(http.StatusUnauthorized, w)\n\t\t\treturn false\n\t\t}\n\n\t}\n\n\tif wsReq.UserIdentity == nil {\n\t\twsReq.UserIdentity = ws.NewAnonymousIdentity()\n\t}\n\n\treturn true\n\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) SupportedHttpMethods() []string {\n\tif len(wh.httpMethods) > 0 {\n\t\treturn wh.httpMethods\n\t} else {\n\t\treturn []string{wh.HttpMethod}\n\t}\n}\n\n\/\/HttpEndpointProvider\nfunc (wh *WsHandler) RegexPattern() string {\n\treturn wh.PathMatchPattern\n}\n\nfunc (wh *WsHandler) handleFrameworkErrors(w *ws.WsHTTPResponseWriter, wsReq *ws.WsRequest) {\n\n\tvar se ws.ServiceErrors\n\tse.HttpStatus = http.StatusBadRequest\n\n\tfor _, fe := range wsReq.FrameworkErrors {\n\t\tse.AddNewError(ws.Client, fe.Code, fe.Message)\n\t}\n\n\twh.writeErrorResponse(&se, w)\n\n}\n\nfunc (wh *WsHandler) process(jsonReq *ws.WsRequest, w *ws.WsHTTPResponseWriter) {\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\twh.Log.LogErrorfWithTrace(\"Panic recovered while trying process a request or write its response %s\", r)\n\t\t\twh.writePanicResponse(r, w)\n\t\t}\n\t}()\n\n\twsRes := ws.NewWsResponse(wh.ErrorFinder)\n\twh.Logic.Process(jsonReq, wsRes)\n\n\twh.ResponseWriter.Write(wsRes, w)\n\n}\n\nfunc (wh *WsHandler) writeErrorResponse(errors *ws.ServiceErrors, w *ws.WsHTTPResponseWriter) {\n\n\tl := wh.Log\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tl.LogErrorfWithTrace(\"Panic recovered while trying to write a response that was already in error %s\", r)\n\t\t}\n\t}()\n\n\terr := wh.ResponseWriter.WriteErrors(errors, w)\n\n\tif err != nil {\n\t\tl.LogErrorf(\"Problem writing an HTTP response that was already in error\", err)\n\t}\n\n}\n\nfunc (wh *WsHandler) writePanicResponse(r interface{}, w *ws.WsHTTPResponseWriter) {\n\n\twh.ResponseWriter.WriteAbnormalStatus(http.StatusInternalServerError, w)\n\n\twh.Log.LogErrorf(\"Panic recovered but error response served. %s\", r)\n\n}\n\nfunc (wh *WsHandler) StartComponent() error {\n\n\tvalidator, found := wh.Logic.(ws.WsRequestValidator)\n\n\twh.validate = found\n\n\tif found {\n\t\twh.validator = validator\n\t}\n\n\twh.bindQuery = wh.AutoBindQuery || (wh.FieldQueryParam != nil && len(wh.FieldQueryParam) > 0)\n\n\tif !wh.DisablePathParsing {\n\n\t\twh.bindPathParams = len(wh.BindPathParams) > 0\n\n\t\tr, err := regexp.Compile(wh.PathMatchPattern)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\twh.pathRegex = r\n\t\t}\n\n\t}\n\n\treturn nil\n\n}\n\nfunc (wh *WsHandler) ComponentName() string {\n\treturn wh.componentName\n}\n\nfunc (wh *WsHandler) SetComponentName(name string) {\n\twh.componentName = name\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package ari\n\n\/\/ Bridge represents a communication path to an\n\/\/ Asterisk server for working with bridge resources\ntype Bridge interface {\n\n\t\/\/ Create creates a bridge\n\tCreate(id string, btype string, name string) (*BridgeHandle, error)\n\n\t\/\/ Get gets the BridgeHandle\n\tGet(id string) *BridgeHandle\n\n\t\/\/ Lists returns the lists of bridges in asterisk\n\tList() ([]*BridgeHandle, error)\n\n\t\/\/ Data gets the bridge data\n\tData(id string) (BridgeData, error)\n\n\t\/\/ AddChannel adds a channel to the bridge\n\tAddChannel(bridgeID string, channelID string) error\n\n\t\/\/ RemoveChannel removes a channel from the bridge\n\tRemoveChannel(bridgeID string, channelID string) error\n\n\t\/\/ Delete deletes the bridge\n\tDelete(id string) error\n\n\t\/\/ Play plays the media URI to the bridge\n\tPlay(id string, playbackID string, mediaURI string) (*PlaybackHandle, error)\n\n\t\/\/ Record records the bridge\n\tRecord(id string, name string, opts *RecordingOptions) (*LiveRecordingHandle, error)\n\n\t\/\/ Subscribe subscribes the given bridge events events\n\tSubscribe(id string, n ...string) Subscription\n}\n\n\/\/ BridgeData describes an Asterisk Bridge, the entity which merges media from\n\/\/ one or more channels into a common audio output\ntype BridgeData struct {\n\tID         string   `json:\"id\"`           \/\/ Unique Id for this bridge\n\tClass      string   `json:\"bridge_class\"` \/\/ Class of the bridge\n\tType       string   `json:\"bridge_type\"`  \/\/ Type of bridge (mixing, holding, dtmf_events, proxy_media)\n\tChannelIDs []string `json:\"channels\"`     \/\/ List of pariticipating channel ids\n\tCreator    string   `json:\"creator\"`      \/\/ Creating entity of the bridge\n\tName       string   `json:\"name\"`         \/\/ The name of the bridge\n\tTechnology string   `json:\"technology\"`   \/\/ Name of the bridging technology\n}\n\n\/\/ NewBridgeHandle creates a new bridge handle\nfunc NewBridgeHandle(id string, b Bridge) *BridgeHandle {\n\treturn &BridgeHandle{\n\t\tid: id,\n\t\tb:  b,\n\t}\n}\n\n\/\/ BridgeHandle is the handle to a bridge for performing operations\ntype BridgeHandle struct {\n\tid string\n\tb  Bridge\n}\n\n\/\/ ID returns the identifier for the bridge\nfunc (bh *BridgeHandle) ID() string {\n\treturn bh.id\n}\n\n\/\/ AddChannel adds a channel to the bridge\nfunc (bh *BridgeHandle) AddChannel(channelID string) (err error) {\n\terr = bh.b.AddChannel(bh.id, channelID)\n\treturn\n}\n\n\/\/ RemoveChannel removes a channel from the bridge\nfunc (bh *BridgeHandle) RemoveChannel(channelID string) (err error) {\n\terr = bh.b.RemoveChannel(bh.id, channelID)\n\treturn\n}\n\n\/\/ Delete deletes the bridge\nfunc (bh *BridgeHandle) Delete(channelID string) (err error) {\n\terr = bh.b.Delete(bh.id)\n\treturn\n}\n\n\/\/ Data gets the bridge data\nfunc (bh *BridgeHandle) Data() (bd BridgeData, err error) {\n\tbd, err = bh.b.Data(bh.id)\n\treturn\n}\n\n\/\/ Play initiates playback of the specified media uri\n\/\/ to the bridge, returning the Playback handle\nfunc (bh *BridgeHandle) Play(id string, mediaURI string) (ph *PlaybackHandle, err error) {\n\tph, err = bh.b.Play(bh.id, id, mediaURI)\n\treturn\n}\n\n\/\/ Record records the bridge to the given filename\nfunc (bh *BridgeHandle) Record(name string, opts *RecordingOptions) (rh *LiveRecordingHandle, err error) {\n\trh, err = bh.b.Record(bh.id, name, opts)\n\treturn\n}\n\n\/\/ Playback returns the playback transport\nfunc (bh *BridgeHandle) Playback() Playback {\n\tif pb, ok := bh.b.(Playbacker); ok {\n\t\treturn pb.Playback()\n\t}\n\treturn nil\n}\n\n\/\/ Subscribe creates a subscription to the list of events\nfunc (bh *BridgeHandle) Subscribe(n ...string) Subscription {\n\tif bh == nil {\n\t\treturn nil\n\t}\n\treturn bh.b.Subscribe(bh.id, n...)\n}\n\n\/\/ Match returns true if the event matches the bridge\nfunc (bh *BridgeHandle) Match(e Event) bool {\n\tbridgeEvent, ok := e.(BridgeEvent)\n\tif !ok {\n\t\treturn false\n\t}\n\tbridgeIDs := bridgeEvent.GetBridgeIDs()\n\tfor _, i := range bridgeIDs {\n\t\tif i == bh.id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>bh.Delete should not take an argument<commit_after>package ari\n\n\/\/ Bridge represents a communication path to an\n\/\/ Asterisk server for working with bridge resources\ntype Bridge interface {\n\n\t\/\/ Create creates a bridge\n\tCreate(id string, btype string, name string) (*BridgeHandle, error)\n\n\t\/\/ Get gets the BridgeHandle\n\tGet(id string) *BridgeHandle\n\n\t\/\/ Lists returns the lists of bridges in asterisk\n\tList() ([]*BridgeHandle, error)\n\n\t\/\/ Data gets the bridge data\n\tData(id string) (BridgeData, error)\n\n\t\/\/ AddChannel adds a channel to the bridge\n\tAddChannel(bridgeID string, channelID string) error\n\n\t\/\/ RemoveChannel removes a channel from the bridge\n\tRemoveChannel(bridgeID string, channelID string) error\n\n\t\/\/ Delete deletes the bridge\n\tDelete(id string) error\n\n\t\/\/ Play plays the media URI to the bridge\n\tPlay(id string, playbackID string, mediaURI string) (*PlaybackHandle, error)\n\n\t\/\/ Record records the bridge\n\tRecord(id string, name string, opts *RecordingOptions) (*LiveRecordingHandle, error)\n\n\t\/\/ Subscribe subscribes the given bridge events events\n\tSubscribe(id string, n ...string) Subscription\n}\n\n\/\/ BridgeData describes an Asterisk Bridge, the entity which merges media from\n\/\/ one or more channels into a common audio output\ntype BridgeData struct {\n\tID         string   `json:\"id\"`           \/\/ Unique Id for this bridge\n\tClass      string   `json:\"bridge_class\"` \/\/ Class of the bridge\n\tType       string   `json:\"bridge_type\"`  \/\/ Type of bridge (mixing, holding, dtmf_events, proxy_media)\n\tChannelIDs []string `json:\"channels\"`     \/\/ List of pariticipating channel ids\n\tCreator    string   `json:\"creator\"`      \/\/ Creating entity of the bridge\n\tName       string   `json:\"name\"`         \/\/ The name of the bridge\n\tTechnology string   `json:\"technology\"`   \/\/ Name of the bridging technology\n}\n\n\/\/ NewBridgeHandle creates a new bridge handle\nfunc NewBridgeHandle(id string, b Bridge) *BridgeHandle {\n\treturn &BridgeHandle{\n\t\tid: id,\n\t\tb:  b,\n\t}\n}\n\n\/\/ BridgeHandle is the handle to a bridge for performing operations\ntype BridgeHandle struct {\n\tid string\n\tb  Bridge\n}\n\n\/\/ ID returns the identifier for the bridge\nfunc (bh *BridgeHandle) ID() string {\n\treturn bh.id\n}\n\n\/\/ AddChannel adds a channel to the bridge\nfunc (bh *BridgeHandle) AddChannel(channelID string) (err error) {\n\terr = bh.b.AddChannel(bh.id, channelID)\n\treturn\n}\n\n\/\/ RemoveChannel removes a channel from the bridge\nfunc (bh *BridgeHandle) RemoveChannel(channelID string) (err error) {\n\terr = bh.b.RemoveChannel(bh.id, channelID)\n\treturn\n}\n\n\/\/ Delete deletes the bridge\nfunc (bh *BridgeHandle) Delete() (err error) {\n\terr = bh.b.Delete(bh.id)\n\treturn\n}\n\n\/\/ Data gets the bridge data\nfunc (bh *BridgeHandle) Data() (bd BridgeData, err error) {\n\tbd, err = bh.b.Data(bh.id)\n\treturn\n}\n\n\/\/ Play initiates playback of the specified media uri\n\/\/ to the bridge, returning the Playback handle\nfunc (bh *BridgeHandle) Play(id string, mediaURI string) (ph *PlaybackHandle, err error) {\n\tph, err = bh.b.Play(bh.id, id, mediaURI)\n\treturn\n}\n\n\/\/ Record records the bridge to the given filename\nfunc (bh *BridgeHandle) Record(name string, opts *RecordingOptions) (rh *LiveRecordingHandle, err error) {\n\trh, err = bh.b.Record(bh.id, name, opts)\n\treturn\n}\n\n\/\/ Playback returns the playback transport\nfunc (bh *BridgeHandle) Playback() Playback {\n\tif pb, ok := bh.b.(Playbacker); ok {\n\t\treturn pb.Playback()\n\t}\n\treturn nil\n}\n\n\/\/ Subscribe creates a subscription to the list of events\nfunc (bh *BridgeHandle) Subscribe(n ...string) Subscription {\n\tif bh == nil {\n\t\treturn nil\n\t}\n\treturn bh.b.Subscribe(bh.id, n...)\n}\n\n\/\/ Match returns true if the event matches the bridge\nfunc (bh *BridgeHandle) Match(e Event) bool {\n\tbridgeEvent, ok := e.(BridgeEvent)\n\tif !ok {\n\t\treturn false\n\t}\n\tbridgeIDs := bridgeEvent.GetBridgeIDs()\n\tfor _, i := range bridgeIDs {\n\t\tif i == bh.id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package golis\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n)\n\n\/\/自定义缓存\ntype Buffer struct {\n\tb    []byte\n\trOff int \/\/读取位置\n\twOff int \/\/写入位置\n}\n\n\/\/创建Buffer\nfunc NewBuffer() *Buffer {\n\treturn new(Buffer)\n}\n\n\/\/获取缓存当前容量\nfunc (b *Buffer) Cap() int {\n\treturn cap(b.b)\n}\n\n\/\/当前可读长度\nfunc (b *Buffer) Length() int {\n\treturn b.wOff\n}\n\n\/\/重置读取位 置\nfunc (b *Buffer) ResetRead() {\n\tb.rOff = 0\n}\n\n\/\/重置写入位置\nfunc (b *Buffer) ResetWrite() {\n\tb.wOff = 0\n}\n\n\/\/写入bytes数据\nfunc (b *Buffer) PutBytes(buffer []byte) {\n\tb.b = append(b.b, buffer...)\n\tb.wOff = len(buffer) + b.wOff\n}\n\n\/\/指定位置写入,如果指定写入位置超出了wOff位置,则抛出异常\n\/\/如果指定位置已经存在数据并写入数据超出wOff位置则覆盖之前数据，wOff变更最新\n\/\/如果指定位置已经存在数据并写入数据没有超出wOff位置则覆盖之前数据，wOff不变\nfunc (b *Buffer) PutBytesAt(pos int, buffer []byte) error {\n\twillPos := pos + len(buffer)\n\tif pos > b.wOff {\n\t\treturn errors.New(\"pos is out of wOff\")\n\t}\n\tif willPos > b.wOff {\n\t\tcopy(b.b[b.wOff:], buffer)\n\t\tb.wOff = willPos\n\t} else {\n\t\tcopy(b.b[b.wOff:], buffer)\n\t}\n\treturn nil\n}\n\n\/\/将int数据存入缓存\nfunc (b *Buffer) PutInt(i int) {\n\tx := int32(i)\n\tbytesBuffer := bytes.NewBuffer([]byte{})\n\tbinary.Write(bytesBuffer, binary.BigEndian, x)\n\tb.PutBytes(bytesBuffer.Bytes())\n}\n\n\/\/将uint32数据放入内存\nfunc (b *Buffer) PutUint32(i uint32) {\n\tbytesBuffer := bytes.NewBuffer([]byte{})\n\tbinary.Write(bytesBuffer, binary.BigEndian, i)\n\tb.PutBytes(bytesBuffer.Bytes())\n}\n\n\/\/将字符串存入buffer\nfunc (b *Buffer) PutString(s string) {\n\tb.PutBytes([]byte(s))\n}\n\n\/\/读取指定位置开始，指定长度的bytes数据\n\/\/如果读取数据位置超出了写入数据的位置，则返回错误\nfunc (b *Buffer) ReadBytesAt(pos, length int) ([]byte, error) {\n\tif pos > b.wOff {\n\t\treturn nil, errors.New(\"pos is out of wOff\")\n\t}\n\tbuffer := make([]byte, length)\n\tif pos+length > b.wOff {\n\t\tcopy(buffer, b.b[pos:b.wOff])\n\t\tb.rOff = b.wOff\n\t} else {\n\t\tp := pos + length\n\t\tcopy(buffer, b.b[pos:p])\n\t\tb.rOff = p\n\t}\n\n\treturn buffer, nil\n}\n\nfunc (b *Buffer) ReadBytes(length int) ([]byte, error) {\n\trpos := b.rOff + length\n\tif rpos > b.wOff {\n\t\treturn nil, errors.New(\"ReadBytes out off wOff\")\n\t}\n\tbuf := make([]byte, length)\n\tcopy(buf, b.b[b.rOff:rpos])\n\tb.rOff = rpos\n\treturn buf, nil\n}\n\n\/\/读取int\nfunc (b *Buffer) ReadInt() (int, error) {\n\trpos := b.rOff + 4\n\tif rpos > b.wOff {\n\t\treturn 0, errors.New(\"ReadInt out off wOff\")\n\t}\n\tbytesBuffer := bytes.NewBuffer(b.b[b.rOff:rpos])\n\tvar x int32\n\tbinary.Read(bytesBuffer, binary.BigEndian, &x)\n\tb.rOff = rpos\n\treturn int(x), nil\n}\n\n\/\/读取uint32数据\nfunc (b *Buffer) ReadUint32() (uint32, error) {\n\trpos := b.rOff + 4\n\tif rpos > b.wOff {\n\t\treturn 0, errors.New(\"ReadUint32 out off wOff\")\n\t}\n\tbytesBuffer := bytes.NewBuffer(b.b[b.rOff:rpos])\n\tvar x uint32\n\tbinary.Read(bytesBuffer, binary.BigEndian, &x)\n\tb.rOff = rpos\n\treturn x, nil\n}\n\n\/\/读取字符串\nfunc (b *Buffer) ReadString(length int) (string, error) {\n\trpos := b.rOff + length\n\tif rpos > b.wOff {\n\t\treturn \"\", errors.New(\"ReadString out of wOff\")\n\t}\n\ts := string(b.b[b.rOff:rpos])\n\tb.rOff = rpos\n\treturn s, nil\n}\n<commit_msg>修改buffer调用<commit_after>package golis\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n)\n\n\/\/自定义缓存\ntype Buffer struct {\n\tb    []byte\n\trOff int \/\/读取位置\n\twOff int \/\/写入位置\n}\n\n\/\/创建Buffer\nfunc NewBuffer() *Buffer {\n\treturn new(Buffer)\n}\n\n\/\/获取缓存当前容量\nfunc (b *Buffer) Cap() int {\n\treturn cap(b.b)\n}\n\n\/\/当前可读长度\nfunc (b *Buffer) ReadLength() int {\n\treturn b.wOff - b.rOff\n}\n\n\/\/重置读取位置\nfunc (b *Buffer) ResetRead() {\n\tb.rOff = 0\n}\n\n\/\/获取读取位置\nfunc (b *Buffer) GetReadPos() int {\n\treturn b.rOff\n}\n\nfunc (b *Buffer) SetReadPos(pos int) error {\n\tif pos > b.wOff {\n\t\treturn errors.New(\"ResetReadAt is out of error\")\n\t}\n\tb.rOff = pos\n\treturn nil\n}\n\n\/\/重置写入位置\nfunc (b *Buffer) ResetWrite() {\n\tb.wOff = 0\n}\n\n\/\/写入bytes数据\nfunc (b *Buffer) PutBytes(buffer []byte) {\n\tb.b = append(b.b, buffer...)\n\tb.wOff = len(buffer) + b.wOff\n}\n\n\/\/指定位置写入,如果指定写入位置超出了wOff位置,则抛出异常\n\/\/如果指定位置已经存在数据并写入数据超出wOff位置则覆盖之前数据，wOff变更最新\n\/\/如果指定位置已经存在数据并写入数据没有超出wOff位置则覆盖之前数据，wOff不变\nfunc (b *Buffer) PutBytesAt(pos int, buffer []byte) error {\n\twillPos := pos + len(buffer)\n\tif pos > b.wOff {\n\t\treturn errors.New(\"pos is out of wOff\")\n\t}\n\tif willPos > b.wOff {\n\t\tcopy(b.b[b.wOff:], buffer)\n\t\tb.wOff = willPos\n\t} else {\n\t\tcopy(b.b[b.wOff:], buffer)\n\t}\n\treturn nil\n}\n\n\/\/将int数据存入缓存\nfunc (b *Buffer) PutInt(i int) {\n\tx := int32(i)\n\tbytesBuffer := bytes.NewBuffer([]byte{})\n\tbinary.Write(bytesBuffer, binary.BigEndian, x)\n\tb.PutBytes(bytesBuffer.Bytes())\n}\n\n\/\/将uint32数据放入内存\nfunc (b *Buffer) PutUint32(i uint32) {\n\tbytesBuffer := bytes.NewBuffer([]byte{})\n\tbinary.Write(bytesBuffer, binary.BigEndian, i)\n\tb.PutBytes(bytesBuffer.Bytes())\n}\n\n\/\/将字符串存入buffer\nfunc (b *Buffer) PutString(s string) {\n\tb.PutBytes([]byte(s))\n}\n\n\/\/读取指定位置开始，指定长度的bytes数据\n\/\/如果读取数据位置超出了写入数据的位置，则返回错误\nfunc (b *Buffer) ReadBytesAt(pos, length int) ([]byte, error) {\n\tif pos > b.wOff {\n\t\treturn nil, errors.New(\"pos is out of wOff\")\n\t}\n\tbuffer := make([]byte, length)\n\tif pos+length > b.wOff {\n\t\tcopy(buffer, b.b[pos:b.wOff])\n\t\tb.rOff = b.wOff\n\t} else {\n\t\tp := pos + length\n\t\tcopy(buffer, b.b[pos:p])\n\t\tb.rOff = p\n\t}\n\n\treturn buffer, nil\n}\n\nfunc (b *Buffer) ReadBytes(length int) ([]byte, error) {\n\trpos := b.rOff + length\n\tif rpos > b.wOff {\n\t\treturn nil, errors.New(\"ReadBytes out off wOff\")\n\t}\n\tbuf := make([]byte, length)\n\tcopy(buf, b.b[b.rOff:rpos])\n\tb.rOff = rpos\n\treturn buf, nil\n}\n\n\/\/读取int\nfunc (b *Buffer) ReadInt() (int, error) {\n\trpos := b.rOff + 4\n\tif rpos > b.wOff {\n\t\treturn 0, errors.New(\"ReadInt out off wOff\")\n\t}\n\tbytesBuffer := bytes.NewBuffer(b.b[b.rOff:rpos])\n\tvar x int32\n\tbinary.Read(bytesBuffer, binary.BigEndian, &x)\n\tb.rOff = rpos\n\treturn int(x), nil\n}\n\n\/\/读取uint32数据\nfunc (b *Buffer) ReadUint32() (uint32, error) {\n\trpos := b.rOff + 4\n\tif rpos > b.wOff {\n\t\treturn 0, errors.New(\"ReadUint32 out off wOff\")\n\t}\n\tbytesBuffer := bytes.NewBuffer(b.b[b.rOff:rpos])\n\tvar x uint32\n\tbinary.Read(bytesBuffer, binary.BigEndian, &x)\n\tb.rOff = rpos\n\treturn x, nil\n}\n\n\/\/读取字符串\nfunc (b *Buffer) ReadString(length int) (string, error) {\n\trpos := b.rOff + length\n\tif rpos > b.wOff {\n\t\treturn \"\", errors.New(\"ReadString out of wOff\")\n\t}\n\ts := string(b.b[b.rOff:rpos])\n\tb.rOff = rpos\n\treturn s, nil\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\"bytes\"\n\t\"encoding\/gob\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/heketi\/heketi\/tests\"\n\t\"github.com\/heketi\/heketi\/utils\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc init() {\n\t\/\/ turn off logging\n\tlogger.SetLevel(utils.LEVEL_NOLOG)\n}\n\nfunc TestClusterCreateBadJsonRequest(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n\t\tsome really bad json code\n    }`)\n\n\t\/\/ Post nothing\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, err == nil)\n\ttests.Assert(t, r.StatusCode == 422)\n\n}\n\nfunc TestClusterCreateEmptyRequest(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n    }`)\n\n\t\/\/ Post nothing\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, err == nil)\n\ttests.Assert(t, r.StatusCode == http.StatusCreated)\n\n\t\/\/ Read JSON\n\tvar msg ClusterInfoResponse\n\terr = utils.GetJsonFromResponse(r, &msg)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Test JSON\n\ttests.Assert(t, msg.Id == msg.Name)\n\ttests.Assert(t, len(msg.Nodes) == 0)\n\ttests.Assert(t, len(msg.Volumes) == 0)\n\n\t\/\/ Check that the data on the database is recorded correctly\n\tvar entrybytes []byte\n\terr = app.db.View(func(tx *bolt.Tx) error {\n\t\tentrybytes = tx.Bucket([]byte(BOLTDB_BUCKET_CLUSTER)).Get([]byte(msg.Id))\n\t\treturn nil\n\t})\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Unmarshal\n\tvar entry ClusterEntry\n\tdec := gob.NewDecoder(bytes.NewReader(entrybytes))\n\terr = dec.Decode(&entry)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Make sure they entries are euqal\n\ttests.Assert(t, entry.Info.Id == msg.Id)\n\ttests.Assert(t, entry.Info.Name == msg.Name)\n\ttests.Assert(t, len(entry.Info.Volumes) == 0)\n\ttests.Assert(t, len(entry.Info.Nodes) == 0)\n}\n\nfunc TestClusterCreateWithName(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n        \"name\" : \"test_name\"\n    }`)\n\n\t\/\/ Request\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, r.StatusCode == http.StatusCreated)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Read JSON\n\tvar msg ClusterInfoResponse\n\terr = utils.GetJsonFromResponse(r, &msg)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Test JSON\n\ttests.Assert(t, msg.Id != msg.Name)\n\ttests.Assert(t, \"test_name\" == msg.Name)\n\ttests.Assert(t, len(msg.Nodes) == 0)\n\ttests.Assert(t, len(msg.Volumes) == 0)\n\n\t\/\/ Check that the data on the database is recorded correctly\n\tvar entrybytes []byte\n\terr = app.db.View(func(tx *bolt.Tx) error {\n\t\tentrybytes = tx.Bucket([]byte(BOLTDB_BUCKET_CLUSTER)).Get([]byte(msg.Id))\n\t\treturn nil\n\t})\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Unmarshal\n\tvar entry ClusterEntry\n\tdec := gob.NewDecoder(bytes.NewReader(entrybytes))\n\terr = dec.Decode(&entry)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Make sure they entries are euqal\n\ttests.Assert(t, entry.Info.Id == msg.Id)\n\ttests.Assert(t, entry.Info.Name == msg.Name)\n\ttests.Assert(t, len(entry.Info.Volumes) == 0)\n\ttests.Assert(t, len(entry.Info.Nodes) == 0)\n}\n<commit_msg>ClusterList unittest<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\"bytes\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/heketi\/heketi\/tests\"\n\t\"github.com\/heketi\/heketi\/utils\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc init() {\n\t\/\/ turn off logging\n\tlogger.SetLevel(utils.LEVEL_NOLOG)\n}\n\nfunc TestClusterCreateBadJsonRequest(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n\t\tsome really bad json code\n    }`)\n\n\t\/\/ Post nothing\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, err == nil)\n\ttests.Assert(t, r.StatusCode == 422)\n\n}\n\nfunc TestClusterCreateEmptyRequest(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n    }`)\n\n\t\/\/ Post nothing\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, err == nil)\n\ttests.Assert(t, r.StatusCode == http.StatusCreated)\n\n\t\/\/ Read JSON\n\tvar msg ClusterInfoResponse\n\terr = utils.GetJsonFromResponse(r, &msg)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Test JSON\n\ttests.Assert(t, msg.Id == msg.Name)\n\ttests.Assert(t, len(msg.Nodes) == 0)\n\ttests.Assert(t, len(msg.Volumes) == 0)\n\n\t\/\/ Check that the data on the database is recorded correctly\n\tvar entrybytes []byte\n\terr = app.db.View(func(tx *bolt.Tx) error {\n\t\tentrybytes = tx.Bucket([]byte(BOLTDB_BUCKET_CLUSTER)).Get([]byte(msg.Id))\n\t\treturn nil\n\t})\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Unmarshal\n\tvar entry ClusterEntry\n\tdec := gob.NewDecoder(bytes.NewReader(entrybytes))\n\terr = dec.Decode(&entry)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Make sure they entries are euqal\n\ttests.Assert(t, entry.Info.Id == msg.Id)\n\ttests.Assert(t, entry.Info.Name == msg.Name)\n\ttests.Assert(t, len(entry.Info.Volumes) == 0)\n\ttests.Assert(t, len(entry.Info.Nodes) == 0)\n}\n\nfunc TestClusterCreateWithName(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ ClusterCreate JSON Request\n\trequest := []byte(`{\n        \"name\" : \"test_name\"\n    }`)\n\n\t\/\/ Request\n\tr, err := http.Post(ts.URL+\"\/clusters\", \"application\/json\", bytes.NewBuffer(request))\n\ttests.Assert(t, r.StatusCode == http.StatusCreated)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Read JSON\n\tvar msg ClusterInfoResponse\n\terr = utils.GetJsonFromResponse(r, &msg)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Test JSON\n\ttests.Assert(t, msg.Id != msg.Name)\n\ttests.Assert(t, \"test_name\" == msg.Name)\n\ttests.Assert(t, len(msg.Nodes) == 0)\n\ttests.Assert(t, len(msg.Volumes) == 0)\n\n\t\/\/ Check that the data on the database is recorded correctly\n\tvar entrybytes []byte\n\terr = app.db.View(func(tx *bolt.Tx) error {\n\t\tentrybytes = tx.Bucket([]byte(BOLTDB_BUCKET_CLUSTER)).Get([]byte(msg.Id))\n\t\treturn nil\n\t})\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Unmarshal\n\tvar entry ClusterEntry\n\tdec := gob.NewDecoder(bytes.NewReader(entrybytes))\n\terr = dec.Decode(&entry)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Make sure they entries are euqal\n\ttests.Assert(t, entry.Info.Id == msg.Id)\n\ttests.Assert(t, entry.Info.Name == msg.Name)\n\ttests.Assert(t, len(entry.Info.Volumes) == 0)\n\ttests.Assert(t, len(entry.Info.Nodes) == 0)\n}\n\nfunc TestClusterList(t *testing.T) {\n\ttmpfile := tests.Tempfile()\n\tdefer os.Remove(tmpfile)\n\n\t\/\/ Patch dbfilename so that it is restored at the end of the tests\n\tdefer tests.Patch(&dbfilename, tmpfile).Restore()\n\n\t\/\/ Create the app\n\tapp := NewApp()\n\tdefer app.Close()\n\trouter := mux.NewRouter()\n\tapp.SetRoutes(router)\n\n\t\/\/ Setup the server\n\tts := httptest.NewServer(router)\n\tdefer ts.Close()\n\n\t\/\/ Save some objects in the database\n\tnumclusters := 5\n\terr := app.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BOLTDB_BUCKET_CLUSTER))\n\t\tif b == nil {\n\t\t\treturn errors.New(\"Unable to open bucket\")\n\t\t}\n\n\t\tfor i := 0; i < numclusters; i++ {\n\t\t\tvar buffer bytes.Buffer\n\t\t\tvar entry ClusterEntry\n\n\t\t\tentry.Info.Id = fmt.Sprintf(\"%v\", 5000+i)\n\t\t\tentry.Info.Name = entry.Info.Id\n\n\t\t\tenc := gob.NewEncoder(&buffer)\n\t\t\terr := enc.Encode(entry)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = b.Put([]byte(entry.Info.Id), buffer.Bytes())\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\n\t})\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Now that we have some data in the database, we can\n\t\/\/ make a request for the clutser list\n\tr, err := http.Get(ts.URL + \"\/clusters\")\n\ttests.Assert(t, r.StatusCode == http.StatusOK)\n\ttests.Assert(t, err == nil)\n\ttests.Assert(t, r.Header.Get(\"Content-Type\") == \"application\/json; charset=UTF-8\")\n\n\t\/\/ Read response\n\tvar msg ClusterListResponse\n\terr = utils.GetJsonFromResponse(r, &msg)\n\ttests.Assert(t, err == nil)\n\n\t\/\/ Thanks to BoltDB they come back in order\n\tmockid := 5000 \/\/ This is the mock id value we set above\n\tfor _, id := range msg.Clusters {\n\t\ttests.Assert(t, id == fmt.Sprintf(\"%v\", mockid))\n\t\tmockid++\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\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\"text\/template\"\n\t\"launchpad.net\/goyaml\"\n\n\t\"github.com\/shxsun\/flags\"\n\t\"github.com\/shxsun\/go-sh\"\n)\n\ntype Option struct {\n\tTemplate string `short:\"t\" long:\"template\" default:\"shxsun\/gails-default\" description:\"use which template(templale should on github)\"`\n}\n\nvar (\n\tmycnf   = &Option{}\n\targs    []string\n\tfuncMap template.FuncMap\n)\n\n\/\/ ORMName, Type, Name\n\/*\nvar tmpl = `\n\t\t\/* XXXX\n\t\t{{ range . }}v.{{.Name}} = this.Get{{.Type|title}}(\"{{.ORMName}}\")\n\t\t{{ end }}\n\n\t\ttype Book struct {\n\t\t\tID int64 json\n\t\t\t{{ range . }}{{.Name}}  {{.Type}} xorm:\"{{.ORMName}}\"\n\t\t\t{{ end }}\n\t\t}\n\t\tXXXX *\/\n\ntype Column struct {\n\tName    string\n\tType    string\n\tORMName string\n}\n\nfunc ignore(info os.FileInfo) bool {\n\tif info.IsDir() {\n\t\tif info.Name() != \".\" && info.Name() != \"..\" &&\n\t\t\tstrings.HasPrefix(info.Name(), \".\") { \/\/ ignore hidden dir\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\treturn strings.HasPrefix(info.Name(), \".\")\n\t}\n\treturn false\n}\n\nfunc pathWalk(path string, depth int) (files []string, err error) {\n\tfiles = make([]string, 0)\n\tbaseNumSeps := strings.Count(path, string(os.PathSeparator))\n\terr = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\tif info.IsDir() {\n\t\t\tpathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps\n\t\t\tif pathDepth > depth {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\tif ignore(info) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t} else if info.Mode().IsRegular() && !ignore(info) {\n\t\t\tfiles = append(files, path)\n\t\t\t\/\/if matched, _ := regexp.Match(mycnf.Include, []byte(info.Name())); matched { \/\/}\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n\tvar err error\n\targs, err = flags.Parse(mycnf)\n\tif len(args) < 2 {\n\t\tprogram := filepath.Base(os.Args[0])\n\t\tfmt.Printf(`Usage:\n\t%s <table> <col:type> [col:type ...]\nExample:\n\t%s book name:string\n`, program, program)\n\t\tos.Exit(1)\n\t}\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc main() {\n\t\/\/ prepare arguments\n\tpatten := regexp.MustCompile(`^(\\w+):(string|int)$`)\n\tvs := make(map[string]interface{}, 0)\n\tcols := make([]Column, 0)\n\tvs[\"Table\"] = args[0]\n\tfor _, s := range args[1:] {\n\t\tvs := patten.FindStringSubmatch(s)\n\t\tif vs == nil {\n\t\t\tlog.Fatalf(\"invalid format: %s\", strconv.Quote(s))\n\t\t}\n\t\tc := Column{}\n\t\tc.ORMName, c.Type = vs[1], vs[2]\n\t\tc.Name = strings.Title(c.ORMName)\n\t\tcols = append(cols, c)\n\t}\n\tvs[\"Cols\"] = cols\n\tpwd, _ := os.Getwd()\n\tvs[\"PWD\"] = pwd\n\tvs[\"PkgPath\"] = pwd[len(os.Getenv(\"GOPATH\")+\"\/src\/\"):]\n\tvs[\"AppName\"] = filepath.Base(pwd)\n\n\t\/\/ render template\n\ttmpdir, err := ioutil.TempDir(\".\/\", \"tmp.gails.\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\tlog.Println(\"use template\", mycnf.Template)\n\t\/\/sh.Command(\"git\", \"clone\", \"https:\/\/github.com\/\"+mycnf.Template, tmpdir).Run()\n\tsh.Command(\"git\", \"clone\", \"\/Users\/skyblue\/goproj\/src\/github.com\/shxsun\/gails-default\", tmpdir).Run()\n\n\tfiles, err := pathWalk(tmpdir, 1)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ newName func, eg: user.go -- rename -> book.go\n\tpjoin := func(p string) string { return filepath.Join(tmpdir, p) }\n\tfilemap := readGailsYml(pjoin(\".gails.yml\"))\n\tnewName := func(file string) string {\n\t\tt, ok := filemap[file]\n\t\tif !ok {\n\t\t\treturn file\n\t\t}\n\t\ts, err := renderString(t, vs)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn s\n\t}\n\n\t\/\/ format code\n\tsession := sh.NewSession()\n\tsession.ShowCMD = true\n\tfor _, src := range files {\n\t\t\/\/fmt.Println(file)\n\t\torig := src[len(tmpdir)+1:]\n\t\tdst := newName(orig)\n\t\tif _, exists := fileExists(dst); !exists {\n\t\t\tdstDir := filepath.Dir(dst)\n\t\t\tos.MkdirAll(dstDir, 0755)\n\t\t\tfmt.Println(\"git:\/\/\"+orig, \"-->\", dst)\n\t\t\tif err = renderFile(dst, src, vs); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tsh.Command(\"cp\", \"-v\", src, dst).Run()\n\t\t\t}\n\t\t\t\/\/ format code\n\t\t\tif strings.HasSuffix(dst, \".go\") {\n\t\t\t\t\/\/session.Command(\"go\", \"fmt\", file).Run()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc init() {\n\tfuncMap = template.FuncMap{\n\t\t\"title\": strings.Title,\n\t}\n}\n\nfunc fileExists(file string) (os.FileInfo, bool) {\n\tfi, err := os.Stat(file)\n\treturn fi, err == nil\n}\nfunc readGailsYml(file string) (m map[string]string) {\n\tm = make(map[string]string)\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tm[\".gitignore\"] = \".gitignore\"\n\t\t}\n\t}()\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = goyaml.Unmarshal(data, m)\n\treturn\n}\n\nfunc renderString(tmplstr string, v interface{}) (out string, err error) {\n\tmytmpl := template.New(\"rdstr\").Funcs(funcMap)\n\tt, err := mytmpl.Parse(tmplstr)\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\terr = t.Execute(buf, v)\n\treturn string(buf.Bytes()), err\n}\n\nfunc renderFile(dst string, src string, v interface{}) (err error) {\n\tfmt.Println(src)\n\tt, err := template.ParseFiles(src)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\terr = t.Funcs(funcMap).Execute(buf, v)\n\tif err != nil {\n\t\treturn\n\t}\n\txxxx := regexp.MustCompile(`.*\\s+XXXX.*\\n`)\n\tfi, _ := os.Stat(src)\n\tout := xxxx.ReplaceAll(buf.Bytes(), []byte(\"\"))\n\terr = ioutil.WriteFile(dst, out, fi.Mode())\n\treturn\n}\n\nfunc deleteXXXX(filename string) (err error) {\n\txxxx := regexp.MustCompile(`.*\\s+XXXX.*\\n`)\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tfi, _ := os.Stat(filename)\n\tout := xxxx.ReplaceAll(content, []byte(\"\"))\n\terr = ioutil.WriteFile(filename, out, fi.Mode())\n\treturn\n}\n<commit_msg>lunch<commit_after>package main\n\nimport (\n\t\"bytes\"\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\"text\/template\"\n\t\"launchpad.net\/goyaml\"\n\n\t\"github.com\/shxsun\/flags\"\n\t\"github.com\/shxsun\/go-sh\"\n)\n\ntype Option struct {\n\tTemplate string `short:\"t\" long:\"template\" default:\"shxsun\/gails-default\" description:\"use which template(templale should on github)\"`\n}\n\nvar (\n\tmycnf   = &Option{}\n\targs    []string\n\tfuncMap template.FuncMap\n)\n\n\/\/ ORMName, Type, Name\n\/*\nvar tmpl = `\n\t\t\/* XXXX\n\t\t{{ range . }}v.{{.Name}} = this.Get{{.Type|title}}(\"{{.ORMName}}\")\n\t\t{{ end }}\n\n\t\ttype Book struct {\n\t\t\tID int64 json\n\t\t\t{{ range . }}{{.Name}}  {{.Type}} xorm:\"{{.ORMName}}\"\n\t\t\t{{ end }}\n\t\t}\n\t\tXXXX *\/\n\ntype Column struct {\n\tName    string\n\tType    string\n\tORMName string\n}\n\nfunc ignore(info os.FileInfo) bool {\n\tif info.IsDir() {\n\t\tif info.Name() != \".\" && info.Name() != \"..\" &&\n\t\t\tstrings.HasPrefix(info.Name(), \".\") { \/\/ ignore hidden dir\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\treturn strings.HasPrefix(info.Name(), \".\")\n\t}\n\treturn false\n}\n\nfunc pathWalk(path string, depth int) (files []string, err error) {\n\tfiles = make([]string, 0)\n\tbaseNumSeps := strings.Count(path, string(os.PathSeparator))\n\terr = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {\n\t\tif info.IsDir() {\n\t\t\tpathDepth := strings.Count(path, string(os.PathSeparator)) - baseNumSeps\n\t\t\tif pathDepth > depth {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\tif ignore(info) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t} else if info.Mode().IsRegular() && !ignore(info) {\n\t\t\tfiles = append(files, path)\n\t\t\t\/\/if matched, _ := regexp.Match(mycnf.Include, []byte(info.Name())); matched { \/\/}\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}\n\nfunc init() {\n\tlog.SetFlags(log.Lshortfile | log.LstdFlags)\n\tvar err error\n\targs, err = flags.Parse(mycnf)\n\tif len(args) < 2 {\n\t\tprogram := filepath.Base(os.Args[0])\n\t\tfmt.Printf(`Usage:\n\t%s <table> <col:type> [col:type ...]\nExample:\n\t%s book name:string\n`, program, program)\n\t\tos.Exit(1)\n\t}\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc main() {\n\t\/\/ prepare arguments\n\tpatten := regexp.MustCompile(`^(\\w+):(string|int)$`)\n\tvs := make(map[string]interface{}, 0)\n\tcols := make([]Column, 0)\n\tvs[\"Table\"] = args[0]\n\tfor _, s := range args[1:] {\n\t\tvs := patten.FindStringSubmatch(s)\n\t\tif vs == nil {\n\t\t\tlog.Fatalf(\"invalid format: %s\", strconv.Quote(s))\n\t\t}\n\t\tc := Column{}\n\t\tc.ORMName, c.Type = vs[1], vs[2]\n\t\tc.Name = strings.Title(c.ORMName)\n\t\tcols = append(cols, c)\n\t}\n\tvs[\"Cols\"] = cols\n\tpwd, _ := os.Getwd()\n\tvs[\"PWD\"] = pwd\n\tvs[\"PkgPath\"] = pwd[len(os.Getenv(\"GOPATH\")+\"\/src\/\"):]\n\tvs[\"AppName\"] = filepath.Base(pwd)\n\n\t\/\/ render template\n\ttmpdir, err := ioutil.TempDir(\".\/\", \"tmp.gails.\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\tlog.Println(\"use template\", mycnf.Template)\n\t\/\/sh.Command(\"git\", \"clone\", \"https:\/\/github.com\/\"+mycnf.Template, tmpdir).Run()\n\tsh.Command(\"git\", \"clone\", \"\/Users\/skyblue\/goproj\/src\/github.com\/shxsun\/gails-default\", tmpdir).Run()\n\n\tfiles, err := pathWalk(tmpdir, 1)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ newName func, eg: user.go -- rename -> book.go\n\tpjoin := func(p string) string { return filepath.Join(tmpdir, p) }\n\tfilemap := readGailsYml(pjoin(\".gails.yml\"))\n\tnewName := func(file string) string {\n\t\tt, ok := filemap[file]\n\t\tif !ok {\n\t\t\treturn file\n\t\t}\n\t\ts, err := renderString(t, vs)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn s\n\t}\n\n\t\/\/ format code\n\tsession := sh.NewSession()\n\tsession.ShowCMD = true\n\tfor _, src := range files {\n\t\t\/\/fmt.Println(file)\n\t\torig := src[len(tmpdir)+1:]\n\t\tdst := newName(orig)\n\t\tif _, exists := fileExists(dst); !exists {\n\t\t\tdstDir := filepath.Dir(dst)\n\t\t\tos.MkdirAll(dstDir, 0755)\n\t\t\tfmt.Println(\"git:\/\/\"+orig, \"-->\", dst)\n\t\t\tif err = renderFile(dst, src, vs); err != nil {\n\t\t\t\tsh.Command(\"cp\", \"-v\", src, dst).Run()\n\t\t\t}\n\t\t\t\/\/ format code\n\t\t\tif strings.HasSuffix(dst, \".go\") {\n\t\t\t\tsession.Command(\"go\", \"fmt\", dst).Run()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc init() {\n\tfuncMap = template.FuncMap{\n\t\t\"title\": strings.Title,\n\t}\n}\n\nfunc fileExists(file string) (os.FileInfo, bool) {\n\tfi, err := os.Stat(file)\n\treturn fi, err == nil\n}\nfunc readGailsYml(file string) (m map[string]string) {\n\tm = make(map[string]string)\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tm[\".gitignore\"] = \".gitignore\"\n\t\t}\n\t}()\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = goyaml.Unmarshal(data, m)\n\treturn\n}\n\nfunc renderString(tmplstr string, v interface{}) (out string, err error) {\n\tmytmpl := template.New(\"rdstr\").Funcs(funcMap)\n\tt, err := mytmpl.Parse(tmplstr)\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\terr = t.Execute(buf, v)\n\treturn string(buf.Bytes()), err\n}\n\nfunc renderFile(dst string, src string, v interface{}) (err error) {\n\tfmt.Println(src)\n\txxxx := regexp.MustCompile(`[^\\n]*XXXX[^\\n]*\\n`)\n\tnnnn := regexp.MustCompile(`.*NNNN`)\n\ts, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\treturn\n\t}\n\tout := xxxx.ReplaceAll(s, []byte(\"\"))\n\tout = nnnn.ReplaceAll(out, []byte(\"\"))\n\n\tt, err := template.New(\"rdfile\").Funcs(funcMap).Parse(string(out))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tbuf := bytes.NewBuffer(nil)\n\terr = t.Execute(buf, v)\n\tif err != nil {\n\t\treturn\n\t}\n\tfi, _ := os.Stat(src)\n\terr = ioutil.WriteFile(dst, buf.Bytes(), fi.Mode())\n\treturn\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 consumererror\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io\/collector\/consumer\/pdata\"\n)\n\n\/\/ Traces is an error that may carry associated Trace data for a subset of received data\n\/\/ that faiiled to be processed or sent.\ntype Traces struct {\n\terror\n\tfailed pdata.Traces\n}\n\n\/\/ NewTraces creates a Traces that can encapsulate received data that failed to be processed or sent.\nfunc NewTraces(err error, failed pdata.Traces) error {\n\treturn Traces{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsTraces finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsTraces(err error, target *Traces) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetTraces returns failed traces from the associated error.\nfunc (err Traces) GetTraces() pdata.Traces {\n\treturn err.failed\n}\n\n\/\/ Logs is an error that may carry associated Log data for a subset of received data\n\/\/ that faiiled to be processed or sent.\ntype Logs struct {\n\terror\n\tfailed pdata.Logs\n}\n\n\/\/ NewLogs creates a Logs that can encapsulate received data that failed to be processed or sent.\nfunc NewLogs(err error, failed pdata.Logs) error {\n\treturn Logs{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsLogs finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsLogs(err error, target *Logs) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetLogs returns failed logs from the associated error.\nfunc (err Logs) GetLogs() pdata.Logs {\n\treturn err.failed\n}\n\n\/\/ Metrics is an error that may carry associated Metrics data for a subset of received data\n\/\/ that faiiled to be processed or sent.\ntype Metrics struct {\n\terror\n\tfailed pdata.Metrics\n}\n\n\/\/ NewMetrics creates a Metrics that can encapsulate received data that failed to be processed or sent.\nfunc NewMetrics(err error, failed pdata.Metrics) error {\n\treturn Metrics{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsMetrics finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsMetrics(err error, target *Metrics) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetMetrics returns failed metrics from the associated error.\nfunc (err Metrics) GetMetrics() pdata.Metrics {\n\treturn err.failed\n}\n<commit_msg>Small typos in consumererror (#2933)<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 consumererror\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io\/collector\/consumer\/pdata\"\n)\n\n\/\/ Traces is an error that may carry associated Trace data for a subset of received data\n\/\/ that failed to be processed or sent.\ntype Traces struct {\n\terror\n\tfailed pdata.Traces\n}\n\n\/\/ NewTraces creates a Traces that can encapsulate received data that failed to be processed or sent.\nfunc NewTraces(err error, failed pdata.Traces) error {\n\treturn Traces{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsTraces finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsTraces(err error, target *Traces) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetTraces returns failed traces from the associated error.\nfunc (err Traces) GetTraces() pdata.Traces {\n\treturn err.failed\n}\n\n\/\/ Logs is an error that may carry associated Log data for a subset of received data\n\/\/ that failed to be processed or sent.\ntype Logs struct {\n\terror\n\tfailed pdata.Logs\n}\n\n\/\/ NewLogs creates a Logs that can encapsulate received data that failed to be processed or sent.\nfunc NewLogs(err error, failed pdata.Logs) error {\n\treturn Logs{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsLogs finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsLogs(err error, target *Logs) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetLogs returns failed logs from the associated error.\nfunc (err Logs) GetLogs() pdata.Logs {\n\treturn err.failed\n}\n\n\/\/ Metrics is an error that may carry associated Metrics data for a subset of received data\n\/\/ that failed to be processed or sent.\ntype Metrics struct {\n\terror\n\tfailed pdata.Metrics\n}\n\n\/\/ NewMetrics creates a Metrics that can encapsulate received data that failed to be processed or sent.\nfunc NewMetrics(err error, failed pdata.Metrics) error {\n\treturn Metrics{\n\t\terror:  err,\n\t\tfailed: failed,\n\t}\n}\n\n\/\/ AsMetrics finds the first error in err's chain that can be assigned to target. If such an error is found\n\/\/ it is assigned to target and true is returned, otherwise false is returned.\nfunc AsMetrics(err error, target *Metrics) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, target)\n}\n\n\/\/ GetMetrics returns failed metrics from the associated error.\nfunc (err Metrics) GetMetrics() pdata.Metrics {\n\treturn err.failed\n}\n<|endoftext|>"}
{"text":"<commit_before>package gring_test\n\nimport (\n\t\"container\/ring\"\n\t\"github.com\/gogf\/gf\/g\"\n\t\"github.com\/gogf\/gf\/g\/container\/gring\"\n\t\"github.com\/gogf\/gf\/g\/test\/gtest\"\n\t\"testing\"\n)\ntype Student struct {\n\tposition int\n\tname    string\n\tupgrade bool\n}\n\nfunc TestRing_Val(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\t\/\/定义cap 为3的ring类型数据\n\t\tr := gring.New(3, true)\n\t\t\/\/分别给3个元素初始化赋值\n\t\tr.Put(&Student{1,\"jimmy\", true})\n\t\tr.Put(&Student{2,\"tom\", true})\n\t\tr.Put(&Student{3,\"alon\", false})\n\n\t\t\/\/元素取值并判断和预设值是否相等\n\t\tgtest.Assert(r.Val().(*Student).name,\"jimmy\")\n\t\t\/\/从当前位置往后移两个元素\n\t\tr.Move(2)\n\t\tgtest.Assert(r.Val().(*Student).name,\"alon\")\n\t\t\/\/更新元素值\n\t\t\/\/测试 value == nil\n\t\tr.Set(nil)\n\t\tgtest.Assert(r.Val(),nil)\n\t\t\/\/测试value != nil\n\t\tr.Set(&Student{3, \"jack\", true})\n\t})\n}\nfunc TestRing_CapLen(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(10)\n\t\tr.Put(\"goframe\")\n\t\t\/\/cap长度 10\n\t\tgtest.Assert(r.Cap(), 10)\n\t\t\/\/已有数据项 1\n\t\tgtest.Assert(r.Len(), 1)\n\t})\n}\n\nfunc TestRing_Position(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(2)\n\t\tr.Put(1)\n\t\tr.Put(2)\n\t\t\/\/往后移动1个元素\n\t\tr.Next()\n\t\tgtest.Assert(r.Val(),2)\n\t\t\/\/往前移动1个元素\n\t\tr.Prev()\n\t\tgtest.Assert(r.Val(),1)\n\n\t})\n}\n\nfunc TestRing_Link(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(3)\n\t\tr.Put(1)\n\t\tr.Put(2)\n\t\tr.Put(3)\n\t\ts := gring.New(2)\n\t\ts.Put(\"a\")\n\t\ts.Put(\"b\")\n\n\t\trs := r.Link(s)\n\t\tgtest.Assert(rs.Move(2).Val(), \"b\")\n\n\t})\n}\n\nfunc TestRing_Unlink(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(5)\n\t\tfor i := 0; i< 5; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\t\t\/\/ 1 2 3 4 5\n\t\t\/\/ 删除当前位置往后的2个数据，返回被删除的数据\n\t\t\/\/ 重新计算s len\n\t\ts := r.Unlink(2)\t\t\/\/ 2 3\n\t\tgtest.Assert(s.Val(), 2)\n\t\tgtest.Assert(s.Len(), 1)\n\t})\n}\n\nfunc TestRing_Slice(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\t\tr.Move(2)\t\/\/ 3\n\t\tarray := r.SliceNext()\t\t\/\/ [3 4 5 1 2]\n\t\tgtest.Assert(array[0], 3)\n\t\tgtest.Assert(len(array), 5)\n\n\t\t\/\/判断array是否等于[3 4 5 1 2]\n\t\tra := []int{3,4,5,1,2}\n\t\tgtest.Assert(ra, array)\n\n\t\t\/\/第3个元素设为nil\n\t\tr.Set(nil)\n\t\tarray2 := r.SliceNext() \t\/\/[4 5 1 2]\n\t\t\/\/返回当前位置往后不为空的元素数组，长度为4\n\t\tgtest.Assert(array2, g.Slice{4,5,1,2})\n\n\t\tarray3 := r.SlicePrev() \t\/\/[2 1 5 4]\n\t\tgtest.Assert(array3, g.Slice{2,1,5,4})\n\n\t\ts := gring.New(ringLen)\n\t\tarray4 := s.SlicePrev()\t\/\/ []\n\t\tgtest.Assert(array4, g.Slice{})\n\n\t})\n}\n\nfunc TestRing_RLockIterator(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\n\t\t\/\/ring不存在有值元素\n\t\tr.RLockIteratorNext(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), nil)\n\t\t\treturn true\n\t\t})\n\n\n\t\tr.RLockIteratorPrev(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), nil)\n\t\t\treturn true\n\t\t})\n\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\n\t\t\/\/回调函数返回true,RLockIteratorNext遍历5次\n\t\tr.RLockIteratorNext(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), 1)\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/RLockIteratorPrev遍历3次返回 false,退出遍历\n\t\tr.RLockIteratorPrev(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), 1)\n\t\t\treturn false\n\t\t})\n\n\t})\n}\n\nfunc TestRing_LockIterator(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\n\t\t\/\/不存在有值元素\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn true\n\t\t})\n\n\t\tr.LockIteratorPrev(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/ring初始化元素值\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\n\t\t\/\/往后遍历组成数据 [1,2,3,4,5]\n\t\tarray1 := g.Slice{1,2,3,4,5}\n\t\tii := 0\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\t\/\/校验每一次遍历取值是否是期望值\n\t\t\tgtest.Assert(item.Value, array1[ii])\n\t\t\tii++;\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/往后取3个元素组成数组\n\t\t\/\/获得 [1,5,4]\n\t\ti := 0\n\t\ta := g.Slice{1,5,4}\n\t\tr.LockIteratorPrev(func(item *ring.Ring) bool {\n\t\t\tif i > 2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tgtest.Assert(item.Value, a[i])\n\t\t\ti++;\n\t\t\treturn true\n\t\t})\n\n\n\t})\n}<commit_msg>Update unit test for gring<commit_after>package gring_test\n\nimport (\n\t\"container\/ring\"\n\t\"github.com\/gogf\/gf\/g\"\n\t\"github.com\/gogf\/gf\/g\/container\/gring\"\n\t\"github.com\/gogf\/gf\/g\/test\/gtest\"\n\t\"testing\"\n)\ntype Student struct {\n\tposition int\n\tname    string\n\tupgrade bool\n}\n\nfunc TestRing_Val(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\t\/\/定义cap 为3的ring类型数据\n\t\tr := gring.New(3, true)\n\t\t\/\/分别给3个元素初始化赋值\n\t\tr.Put(&Student{1,\"jimmy\", true})\n\t\tr.Put(&Student{2,\"tom\", true})\n\t\tr.Put(&Student{3,\"alon\", false})\n\n\t\t\/\/元素取值并判断和预设值是否相等\n\t\tgtest.Assert(r.Val().(*Student).name,\"jimmy\")\n\t\t\/\/从当前位置往后移两个元素\n\t\tr.Move(2)\n\t\tgtest.Assert(r.Val().(*Student).name,\"alon\")\n\t\t\/\/更新元素值\n\t\t\/\/测试 value == nil\n\t\tr.Set(nil)\n\t\tgtest.Assert(r.Val(),nil)\n\t\t\/\/测试value != nil\n\t\tr.Set(&Student{3, \"jack\", true})\n\t})\n}\nfunc TestRing_CapLen(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(10)\n\t\tr.Put(\"goframe\")\n\t\t\/\/cap长度 10\n\t\tgtest.Assert(r.Cap(), 10)\n\t\t\/\/已有数据项 1\n\t\tgtest.Assert(r.Len(), 1)\n\t})\n}\n\nfunc TestRing_Position(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(2)\n\t\tr.Put(1)\n\t\tr.Put(2)\n\t\t\/\/往后移动1个元素\n\t\tr.Next()\n\t\tgtest.Assert(r.Val(),2)\n\t\t\/\/往前移动1个元素\n\t\tr.Prev()\n\t\tgtest.Assert(r.Val(),1)\n\n\t})\n}\n\nfunc TestRing_Link(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(3)\n\t\tr.Put(1)\n\t\tr.Put(2)\n\t\tr.Put(3)\n\t\ts := gring.New(2)\n\t\ts.Put(\"a\")\n\t\ts.Put(\"b\")\n\n\t\trs := r.Link(s)\n\t\tgtest.Assert(rs.Move(2).Val(), \"b\")\n\n\t})\n}\n\nfunc TestRing_Unlink(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tr := gring.New(5)\n\t\tfor i := 0; i< 5; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\t\t\/\/ 1 2 3 4\n\t\t\/\/ 删除当前位置往后的2个数据，返回被删除的数据\n\t\t\/\/ 重新计算s len\n\t\ts := r.Unlink(2)\t\t\/\/ 2 3\n\t\tgtest.Assert(s.Val(), 2)\n\t\tgtest.Assert(s.Len(), 1)\n\t})\n}\n\nfunc TestRing_Slice(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\t\tr.Move(2)\t\/\/ 3\n\t\tarray := r.SliceNext()\t\t\/\/ [3 4 5 1 2]\n\t\tgtest.Assert(array[0], 3)\n\t\tgtest.Assert(len(array), 5)\n\n\t\t\/\/判断array是否等于[3 4 5 1 2]\n\t\tra := []int{3,4,5,1,2}\n\t\tgtest.Assert(ra, array)\n\n\t\t\/\/第3个元素设为nil\n\t\tr.Set(nil)\n\t\tarray2 := r.SliceNext() \t\/\/[4 5 1 2]\n\t\t\/\/返回当前位置往后不为空的元素数组，长度为4\n\t\tgtest.Assert(array2, g.Slice{4,5,1,2})\n\n\t\tarray3 := r.SlicePrev() \t\/\/[2 1 5 4]\n\t\tgtest.Assert(array3, g.Slice{2,1,5,4})\n\n\t\ts := gring.New(ringLen)\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\ts.Put(i+1)\n\t\t}\n\t\tarray4 := s.SlicePrev()\t\/\/ []\n\t\tgtest.Assert(array4, g.Slice{1,5,4,3,2})\n\n\t})\n}\n\nfunc TestRing_RLockIterator(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\n\t\t\/\/ring不存在有值元素\n\t\tr.RLockIteratorNext(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), nil)\n\t\t\treturn false\n\t\t})\n\t\tr.RLockIteratorNext(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), nil)\n\t\t\treturn true\n\t\t})\n\n\t\tr.RLockIteratorPrev(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), nil)\n\t\t\treturn true\n\t\t})\n\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\n\t\t\/\/回调函数返回true,RLockIteratorNext遍历5次\n\t\tr.RLockIteratorNext(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), 1)\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/RLockIteratorPrev遍历3次返回 false,退出遍历\n\t\tr.RLockIteratorPrev(func(value interface{}) bool {\n\t\t\tgtest.Assert(r.Val(), 1)\n\t\t\treturn false\n\t\t})\n\n\t})\n}\n\nfunc TestRing_LockIterator(t *testing.T) {\n\tgtest.Case(t, func() {\n\t\tringLen := 5\n\t\tr := gring.New(ringLen)\n\n\t\t\/\/不存在有值元素\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn false\n\t\t})\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn false\n\t\t})\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn true\n\t\t})\n\n\t\tr.LockIteratorPrev(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn false\n\t\t})\n\t\tr.LockIteratorPrev(func(item *ring.Ring) bool {\n\t\t\tgtest.Assert(item.Value, nil)\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/ring初始化元素值\n\t\tfor i := 0; i< ringLen; i++  {\n\t\t\tr.Put(i+1)\n\t\t}\n\n\t\t\/\/往后遍历组成数据 [1,2,3,4,5]\n\t\tarray1 := g.Slice{1,2,3,4,5}\n\t\tii := 0\n\t\tr.LockIteratorNext(func(item *ring.Ring) bool {\n\t\t\t\/\/校验每一次遍历取值是否是期望值\n\t\t\tgtest.Assert(item.Value, array1[ii])\n\t\t\tii++;\n\t\t\treturn true\n\t\t})\n\n\t\t\/\/往后取3个元素组成数组\n\t\t\/\/获得 [1,5,4]\n\t\ti := 0\n\t\ta := g.Slice{1,5,4}\n\t\tr.LockIteratorPrev(func(item *ring.Ring) bool {\n\t\t\tif i > 2 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tgtest.Assert(item.Value, a[i])\n\t\t\ti++;\n\t\t\treturn true\n\t\t})\n\n\n\t})\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/ryanuber\/go-license\"\n)\n\ntype response struct {\n\tLicense string\n\tFile    string\n}\n\nfunc getLicense(input chan string, output chan response) {\n\tfor file := range input {\n\t\tl, err := license.NewFromFile(file)\n\t\tsplitFile := strings.Split(file, \"\/\")\n\t\tnewFile := splitFile[1 : len(splitFile)-1]\n\t\tfile = strings.Join(newFile, \"\/\")\n\t\tif err != nil {\n\t\t\toutput <- response{File: file, License: err.Error()}\n\t\t} else {\n\t\t\toutput <- response{File: file, License: l.Type}\n\t\t}\n\t}\n}\n\nfunc main() {\n\troot := \"vendor\/\"\n\ti := 0\n\tinput := make(chan string)\n\toutput := make(chan response)\n\n\tfor a := 0; a < 5; a++ {\n\t\tgo getLicense(input, output)\n\t}\n\tvar files []string\n\tfilepath.Walk(root, func(path string, f os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tfmt.Println(\"No vendor folder found. Aborting..\")\n\t\t\treturn err\n\t\t}\n\t\tif !f.IsDir() {\n\t\t\tsplitPath := strings.Split(path, \"\/\")\n\t\t\trawPath := splitPath[len(splitPath)-1]\n\t\t\tif strings.Contains(strings.ToUpper(rawPath), \"LICENSE\") {\n\t\t\t\tfiles = append(files, path)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\tif len(files) == 0 {\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tfor _, v := range files {\n\t\t\tinput <- v\n\t\t}\n\t}()\n\tfor out := range output {\n\t\tfmt.Printf(\"%v =======> %v\\n\", out.File, out.License)\n\t\ti++\n\t\tif i == len(files)-1 || len(files) == 1 {\n\t\t\tbreak\n\t\t}\n\n\t}\n}\n<commit_msg>Check for COPYING as part of license file<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/ryanuber\/go-license\"\n)\n\ntype response struct {\n\tLicense string\n\tFile    string\n}\n\nfunc getLicense(input chan string, output chan response) {\n\tfor file := range input {\n\t\tl, err := license.NewFromFile(file)\n\t\tsplitFile := strings.Split(file, \"\/\")\n\t\tnewFile := splitFile[1 : len(splitFile)-1]\n\t\tfile = strings.Join(newFile, \"\/\")\n\t\tif err != nil {\n\t\t\toutput <- response{File: file, License: err.Error()}\n\t\t} else {\n\t\t\toutput <- response{File: file, License: l.Type}\n\t\t}\n\t}\n}\nfunc scan(path string) bool {\n\tpath = strings.ToUpper(path)\n\treturn strings.Contains(path, \"LICENSE\") || strings.Contains(path, \"COPYING\")\n}\n\nfunc main() {\n\troot := \"vendor\/\"\n\ti := 0\n\tinput := make(chan string)\n\toutput := make(chan response)\n\n\tfor a := 0; a < 5; a++ {\n\t\tgo getLicense(input, output)\n\t}\n\tvar files []string\n\tfilepath.Walk(root, func(path string, f os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\tfmt.Println(\"No vendor folder found. Aborting..\")\n\t\t\treturn err\n\t\t}\n\t\tif !f.IsDir() {\n\t\t\tsplitPath := strings.Split(path, \"\/\")\n\t\t\trawPath := splitPath[len(splitPath)-1]\n\t\t\tif scan(rawPath) {\n\t\t\t\tfiles = append(files, path)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\tif len(files) == 0 {\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tfor _, v := range files {\n\t\t\tinput <- v\n\t\t}\n\t}()\n\tfor out := range output {\n\t\tfmt.Printf(\"%v =======> %v\\n\", out.File, out.License)\n\t\ti++\n\t\tif i == len(files)-1 || len(files) == 1 {\n\t\t\tbreak\n\t\t}\n\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gobls\n\nimport \"bufio\"\n\n\/\/ const DefaultBufferSize = 16 * 1024\nconst DefaultBufferSize = bufio.MaxScanTokenSize\n\n\/\/ Scanner provides an interface for reading newline-delimited lines\n\/\/ of text. It is similar to `bufio.Scanner`, but wraps\n\/\/ `bufio.ReadLine` so lines of arbitrary length can be\n\/\/ scanned. Successive calls to the Scan method will step through the\n\/\/ lines of a file, skipping the newline whitespace between lines.\n\/\/\n\/\/ Scanning stops unrecoverably at EOF, or at the first I\/O\n\/\/ error. Unlike `bufio.Scanner`, howver, attempting to scan a line\n\/\/ longer than `bufio.MaxScanTokenSize` will not result in an error,\n\/\/ but will return the long line.\n\/\/\n\/\/ It is not necessary to check for errors by calling the Err method\n\/\/ until after scanning stops, when the Scan method returns false.\ntype Scanner interface {\n\tBytes() []byte\n\tErr() error\n\tScan() bool\n\tText() string\n}\n<commit_msg>uses 16K buffers by default<commit_after>package gobls\n\nconst DefaultBufferSize = 16 * 1024\n\n\/\/ Scanner provides an interface for reading newline-delimited lines\n\/\/ of text. It is similar to `bufio.Scanner`, but wraps\n\/\/ `bufio.ReadLine` so lines of arbitrary length can be\n\/\/ scanned. Successive calls to the Scan method will step through the\n\/\/ lines of a file, skipping the newline whitespace between lines.\n\/\/\n\/\/ Scanning stops unrecoverably at EOF, or at the first I\/O\n\/\/ error. Unlike `bufio.Scanner`, howver, attempting to scan a line\n\/\/ longer than `bufio.MaxScanTokenSize` will not result in an error,\n\/\/ but will return the long line.\n\/\/\n\/\/ It is not necessary to check for errors by calling the Err method\n\/\/ until after scanning stops, when the Scan method returns false.\ntype Scanner interface {\n\tBytes() []byte\n\tErr() error\n\tScan() bool\n\tText() string\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)\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\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\t\/\/ Used for the counter chan.\n\tinc = true\n\tdec = false\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 indicate that a Close is requested preventing further Accept. It will\n\t\/\/ also wait for the active connections to be terminated before returning.\n\t\/\/ Note, this won't actually do the close, and is provided as part of the\n\t\/\/ public API for cases where the socket must not be closed (such as systemd\n\t\/\/ activation).\n\tCloseRequest()\n\n\t\/\/ Will return the underlying file representing this Listener.\n\tFile() (f *os.File, err error)\n}\n\n\/\/ A FileListener is a file backed net.Listener.\ntype FileListener interface {\n\tnet.Listener\n\n\t\/\/ Will return the underlying file representing this Listener.\n\tFile() (f *os.File, err error)\n}\n\n\/\/ A goroutine based counter that provides graceful Close for listeners.\ntype listener struct {\n\tFileListener\n\tclosed       bool      \/\/ Indicates we're already closed.\n\tcloseRequest chan bool \/\/ Send a bool here to indicate we want to Close.\n\tallClosed    chan bool \/\/ Receive from here will indicate a clean Close.\n\tcounter      chan bool \/\/ Use the inc\/dec counters.\n}\n\n\/\/ Allows for us to notice when the connection is closed.\ntype conn struct {\n\tnet.Conn\n\tcounter chan bool\n}\n\nfunc (c conn) Close() error {\n\tc.counter <- dec\n\treturn c.Conn.Close()\n}\n\n\/\/ Wraps an existing File listener to provide a graceful Close() process.\nfunc NewListener(l FileListener) Listener {\n\ti := &listener{\n\t\tFileListener: l,\n\t\tcloseRequest: make(chan bool),\n\t\tallClosed:    make(chan bool),\n\t\tcounter:      make(chan bool),\n\t}\n\tgo i.enabler()\n\treturn i\n}\n\nfunc (l *listener) enabler() {\n\tvar counter uint64\n\tvar change bool\n\tfor {\n\t\tselect {\n\t\tcase <-l.closeRequest:\n\t\t\tl.closed = true\n\t\tcase change = <-l.counter:\n\t\t\tif change == inc {\n\t\t\t\tcounter++\n\t\t\t} else {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t}\n\t\tif l.closed && counter == 0 {\n\t\t\tl.allClosed <- true\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (l *listener) CloseRequest() {\n\tif l.closed == true {\n\t\treturn\n\t}\n\tl.closeRequest <- true\n\t<-l.allClosed\n}\n\nfunc (l *listener) Close() error {\n\tl.CloseRequest()\n\treturn l.FileListener.Close()\n}\n\nfunc (l *listener) Accept() (net.Conn, error) {\n\tif l.closed == true {\n\t\treturn nil, ErrAlreadyClosed\n\t}\n\tc, err := l.FileListener.Accept()\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), errClosed) {\n\t\t\treturn nil, ErrAlreadyClosed\n\t\t}\n\t\treturn nil, err\n\t}\n\tl.counter <- inc\n\treturn conn{\n\t\tConn:    c,\n\t\tcounter: l.counter,\n\t}, 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\tif os.Getppid() == 1 { \/\/ init provided sockets dont actually close\n\t\t\t\t\t\tl.CloseRequest()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcErr := l.Close()\n\t\t\t\t\t\tif cErr != nil {\n\t\t\t\t\t\t\terr = cErr\n\t\t\t\t\t\t}\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\tpanic(\"not reached\")\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>remove some duplication<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)\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\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\t\/\/ Used for the counter chan.\n\tinc = true\n\tdec = false\n)\n\n\/\/ A FileListener is a file backed net.Listener.\ntype FileListener interface {\n\tnet.Listener\n\n\t\/\/ Will return the underlying file representing this Listener.\n\tFile() (f *os.File, err error)\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\tFileListener\n\n\t\/\/ Will indicate that a Close is requested preventing further Accept. It will\n\t\/\/ also wait for the active connections to be terminated before returning.\n\t\/\/ Note, this won't actually do the close, and is provided as part of the\n\t\/\/ public API for cases where the socket must not be closed (such as systemd\n\t\/\/ activation).\n\tCloseRequest()\n}\n\n\/\/ A goroutine based counter that provides graceful Close for listeners.\ntype listener struct {\n\tFileListener\n\tclosed       bool      \/\/ Indicates we're already closed.\n\tcloseRequest chan bool \/\/ Send a bool here to indicate we want to Close.\n\tallClosed    chan bool \/\/ Receive from here will indicate a clean Close.\n\tcounter      chan bool \/\/ Use the inc\/dec counters.\n}\n\n\/\/ Allows for us to notice when the connection is closed.\ntype conn struct {\n\tnet.Conn\n\tcounter chan bool\n}\n\nfunc (c conn) Close() error {\n\tc.counter <- dec\n\treturn c.Conn.Close()\n}\n\n\/\/ Wraps an existing File listener to provide a graceful Close() process.\nfunc NewListener(l FileListener) Listener {\n\ti := &listener{\n\t\tFileListener: l,\n\t\tcloseRequest: make(chan bool),\n\t\tallClosed:    make(chan bool),\n\t\tcounter:      make(chan bool),\n\t}\n\tgo i.enabler()\n\treturn i\n}\n\nfunc (l *listener) enabler() {\n\tvar counter uint64\n\tvar change bool\n\tfor {\n\t\tselect {\n\t\tcase <-l.closeRequest:\n\t\t\tl.closed = true\n\t\tcase change = <-l.counter:\n\t\t\tif change == inc {\n\t\t\t\tcounter++\n\t\t\t} else {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t}\n\t\tif l.closed && counter == 0 {\n\t\t\tl.allClosed <- true\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (l *listener) CloseRequest() {\n\tif l.closed == true {\n\t\treturn\n\t}\n\tl.closeRequest <- true\n\t<-l.allClosed\n}\n\nfunc (l *listener) Close() error {\n\tl.CloseRequest()\n\treturn l.FileListener.Close()\n}\n\nfunc (l *listener) Accept() (net.Conn, error) {\n\tif l.closed == true {\n\t\treturn nil, ErrAlreadyClosed\n\t}\n\tc, err := l.FileListener.Accept()\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), errClosed) {\n\t\t\treturn nil, ErrAlreadyClosed\n\t\t}\n\t\treturn nil, err\n\t}\n\tl.counter <- inc\n\treturn conn{\n\t\tConn:    c,\n\t\tcounter: l.counter,\n\t}, 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\tif os.Getppid() == 1 { \/\/ init provided sockets dont actually close\n\t\t\t\t\t\tl.CloseRequest()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcErr := l.Close()\n\t\t\t\t\t\tif cErr != nil {\n\t\t\t\t\t\t\terr = cErr\n\t\t\t\t\t\t}\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\tpanic(\"not reached\")\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 continuous\n\n\/\/ MorphologicalComputationW [...]\nfunc MorphologicalComputationW(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationA [...]\nfunc MorphologicalComputationA(w2a1w1 [][]float64, w2Indices, a1Indices, w1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2a1w1, w2Indices, a1Indices, w1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationCW1 [...]\nfunc MorphologicalComputationCW(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger1(w2w1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger1(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationCW2 [...]\nfunc MorphologicalComputationCW(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger2(w2w1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger2(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWA1 = I(W;{W,A}) - I(W';A)\nfunc MorphologicalComputationWA(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false) - KraskovStoegbauerGrassberger1(w2a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWA2 = I(W;{W,A}) - I(W';A)\nfunc MorphologicalComputationWA(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false) - KraskovStoegbauerGrassberger2(w2a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWS = I(W;{W,S}) - I(W';S)\nfunc MorphologicalComputationWS(w2w1s1 [][]float64, w2Indices, w1Indices, s1Idices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1s1, w2Indices, w1Indices, s1Indices, k, false) - KraskovStoegbauerGrassberger(w2s1, w2Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWS1 = I(W;{W,S}) - I(W';S)\nfunc MorphologicalComputationWS(w2w1s1 [][]float64, w2Indices, w1Indices, s1Idices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1s1, w2Indices, w1Indices, s1Indices, k, false) - KraskovStoegbauerGrassberger1(w2s1, w2Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWS2 = I(W;{W,S}) - I(W';S)\nfunc MorphologicalComputationWS(w2w1s1 [][]float64, w2Indices, w1Indices, s1Idices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1s1, w2Indices, w1Indices, s1Indices, k, false) - KraskovStoegbauerGrassberger2(w2s1, w2Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationMI1 [...]\nfunc MorphologicalComputationMI(w2w1s1a1 [][]float64, w2Indices, w1Indices, s1Idices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger1(w2w1s1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger1(a1s1, a1Indices, s1Idices, k, false)\n}\n\n\/\/ MorphologicalComputationMI2 [...]\nfunc MorphologicalComputationMI(w2w1s1a1 [][]float64, w2Indices, w1Indices, s1Idices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger2(w2w1s1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger2(a1s1, a1Indices, s1Idices, k, false)\n}\n<commit_msg>Fixed test cases<commit_after>package continuous\n\n\/\/ MorphologicalComputationW [...]\nfunc MorphologicalComputationW(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationA [...]\nfunc MorphologicalComputationA(w2a1w1 [][]float64, w2Indices, a1Indices, w1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2a1w1, w2Indices, a1Indices, w1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationCW1 [...]\nfunc MorphologicalComputationCW1(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger1(w2w1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger1(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationCW2 [...]\nfunc MorphologicalComputationCW2(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger2(w2w1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger2(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWA1 = I(W;{W,A}) - I(W';A)\nfunc MorphologicalComputationWA1(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false) - KraskovStoegbauerGrassberger1(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWA2 = I(W;{W,A}) - I(W';A)\nfunc MorphologicalComputationWA(w2w1a1 [][]float64, w2Indices, w1Indices, a1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1a1, w2Indices, w1Indices, a1Indices, k, false) - KraskovStoegbauerGrassberger2(w2w1a1, w2Indices, a1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWS1 = I(W;{W,S}) - I(W';S)\nfunc MorphologicalComputationWS1(w2w1s1 [][]float64, w2Indices, w1Indices, s1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1s1, w2Indices, w1Indices, s1Indices, k, false) - KraskovStoegbauerGrassberger1(w2w1s1, w2Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationWS2 = I(W;{W,S}) - I(W';S)\nfunc MorphologicalComputationWS2(w2w1s1 [][]float64, w2Indices, w1Indices, s1Indices []int, k int) float64 {\n\treturn FrenzelPompe(w2w1s1, w2Indices, w1Indices, s1Indices, k, false) - KraskovStoegbauerGrassberger2(w2w1s1, w2Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationMI1 [...]\nfunc MorphologicalComputationMI1(w2w1s1a1 [][]float64, w2Indices, w1Indices, s1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger1(w2w1s1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger1(w2w1s1a1, a1Indices, s1Indices, k, false)\n}\n\n\/\/ MorphologicalComputationMI2 [...]\nfunc MorphologicalComputationMI2(w2w1s1a1 [][]float64, w2Indices, w1Indices, s1Indices, a1Indices []int, k int) float64 {\n\treturn KraskovStoegbauerGrassberger2(w2w1s1a1, w2Indices, w1Indices, k, false) - KraskovStoegbauerGrassberger2(w2w1s1a1, a1Indices, s1Indices, k, false)\n}\n<|endoftext|>"}
{"text":"<commit_before>package docker\n\nimport (\n\t\"fmt\"\n\t\"github.com\/dotcloud\/docker\/utils\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Graph is a store for versioned filesystem images and the relationship between them.\ntype Graph struct {\n\tRoot    string\n\tidIndex *utils.TruncIndex\n}\n\n\/\/ NewGraph instantiates a new graph at the given root path in the filesystem.\n\/\/ `root` will be created if it doesn't exist.\nfunc NewGraph(root string) (*Graph, error) {\n\tabspath, err := filepath.Abs(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Create the root directory if it doesn't exists\n\tif err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {\n\t\treturn nil, err\n\t}\n\tgraph := &Graph{\n\t\tRoot:    abspath,\n\t\tidIndex: utils.NewTruncIndex(),\n\t}\n\tif err := graph.restore(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn graph, nil\n}\n\nfunc (graph *Graph) restore() error {\n\tdir, err := ioutil.ReadDir(graph.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, v := range dir {\n\t\tid := v.Name()\n\t\tgraph.idIndex.Add(id)\n\t}\n\treturn nil\n}\n\n\/\/ FIXME: Implement error subclass instead of looking at the error text\n\/\/ Note: This is the way golang implements os.IsNotExists on Plan9\nfunc (graph *Graph) IsNotExist(err error) bool {\n\treturn err != nil && (strings.Contains(err.Error(), \"does not exist\") || strings.Contains(err.Error(), \"No such\"))\n}\n\n\/\/ Exists returns true if an image is registered at the given id.\n\/\/ If the image doesn't exist or if an error is encountered, false is returned.\nfunc (graph *Graph) Exists(id string) bool {\n\tif _, err := graph.Get(id); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Get returns the image with the given id, or an error if the image doesn't exist.\nfunc (graph *Graph) Get(name string) (*Image, error) {\n\tid, err := graph.idIndex.Get(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ FIXME: return nil when the image doesn't exist, instead of an error\n\timg, err := LoadImage(graph.imageRoot(id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif img.ID != id {\n\t\treturn nil, fmt.Errorf(\"Image stored at '%s' has wrong id '%s'\", id, img.ID)\n\t}\n\timg.graph = graph\n\tif img.Size == 0 {\n\t\troot, err := img.root()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := StoreSize(img, root); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn img, nil\n}\n\n\/\/ Create creates a new image and registers it in the graph.\nfunc (graph *Graph) Create(layerData Archive, container *Container, comment, author string, config *Config) (*Image, error) {\n\timg := &Image{\n\t\tID:            GenerateID(),\n\t\tComment:       comment,\n\t\tCreated:       time.Now(),\n\t\tDockerVersion: VERSION,\n\t\tAuthor:        author,\n\t\tConfig:        config,\n\t\tArchitecture:  \"x86_64\",\n\t}\n\tif container != nil {\n\t\timg.Parent = container.Image\n\t\timg.Container = container.ID\n\t\timg.ContainerConfig = *container.Config\n\t}\n\tif err := graph.Register(nil, layerData, img); err != nil {\n\t\treturn nil, err\n\t}\n\treturn img, nil\n}\n\n\/\/ Register imports a pre-existing image into the graph.\n\/\/ FIXME: pass img as first argument\nfunc (graph *Graph) Register(jsonData []byte, layerData Archive, img *Image) error {\n\tif err := ValidateID(img.ID); err != nil {\n\t\treturn err\n\t}\n\t\/\/ (This is a convenience to save time. Race conditions are taken care of by os.Rename)\n\tif graph.Exists(img.ID) {\n\t\treturn fmt.Errorf(\"Image %s already exists\", img.ID)\n\t}\n\ttmp, err := graph.Mktemp(\"\")\n\tdefer os.RemoveAll(tmp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Mktemp failed: %s\", err)\n\t}\n\tif err := StoreImage(img, jsonData, layerData, tmp); err != nil {\n\t\treturn err\n\t}\n\t\/\/ Commit\n\tif err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil {\n\t\treturn err\n\t}\n\timg.graph = graph\n\tgraph.idIndex.Add(img.ID)\n\treturn nil\n}\n\n\/\/ TempLayerArchive creates a temporary archive of the given image's filesystem layer.\n\/\/   The archive is stored on disk and will be automatically deleted as soon as has been read.\n\/\/   If output is not nil, a human-readable progress bar will be written to it.\n\/\/   FIXME: does this belong in Graph? How about MktempFile, let the caller use it for archives?\nfunc (graph *Graph) TempLayerArchive(id string, compression Compression, sf *utils.StreamFormatter, output io.Writer) (*TempArchive, error) {\n\timage, err := graph.Get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tarchive, err := image.TarLayer(compression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, sf.FormatProgress(\"\", \"Buffering to disk\", \"%v\/%v (%v)\"), sf, true), tmp.Root)\n}\n\n\/\/ Mktemp creates a temporary sub-directory inside the graph's filesystem.\nfunc (graph *Graph) Mktemp(id string) (string, error) {\n\tif id == \"\" {\n\t\tid = GenerateID()\n\t}\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Couldn't create temp: %s\", err)\n\t}\n\tif tmp.Exists(id) {\n\t\treturn \"\", fmt.Errorf(\"Image %s already exists\", id)\n\t}\n\treturn tmp.imageRoot(id), nil\n}\n\n\/\/ getDockerInitLayer returns the path of a layer containing a mountpoint suitable\n\/\/ for bind-mounting dockerinit into the container. The mountpoint is simply an\n\/\/ empty file at \/.dockerinit\n\/\/\n\/\/ This extra layer is used by all containers as the top-most ro layer. It protects\n\/\/ the container from unwanted side-effects on the rw layer.\nfunc (graph *Graph) getDockerInitLayer() (string, error) {\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tinitLayer := tmp.imageRoot(\"_dockerinit\")\n\tif err := os.Mkdir(initLayer, 0755); err != nil && !os.IsExist(err) {\n\t\t\/\/ If directory already existed, keep going.\n\t\t\/\/ For all other errors, abort.\n\t\treturn \"\", err\n\t}\n\n\tfor pth, typ := range map[string]string{\n\t\t\"\/dev\/pts\":         \"dir\",\n\t\t\"\/dev\/shm\":         \"dir\",\n\t\t\"\/proc\":            \"dir\",\n\t\t\"\/sys\":             \"dir\",\n\t\t\"\/.dockerinit\":     \"file\",\n\t\t\"\/etc\/resolv.conf\": \"file\",\n\t\t\/\/ \"var\/run\": \"dir\",\n\t\t\/\/ \"var\/lock\": \"dir\",\n\t} {\n\t\tif _, err := os.Stat(path.Join(initLayer, pth)); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tswitch typ {\n\t\t\t\tcase \"dir\":\n\t\t\t\t\tif err := os.MkdirAll(path.Join(initLayer, pth), 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\t\tif err := os.MkdirAll(path.Join(initLayer, path.Dir(pth)), 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\n\t\t\t\t\tif f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t}\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\n\t\/\/ Layer is ready to use, if it wasn't before.\n\treturn initLayer, nil\n}\n\nfunc (graph *Graph) tmp() (*Graph, error) {\n\t\/\/ Changed to _tmp from :tmp:, because it messed with \":\" separators in aufs branch syntax...\n\treturn NewGraph(path.Join(graph.Root, \"_tmp\"))\n}\n\n\/\/ Check if given error is \"not empty\".\n\/\/ Note: this is the way golang does it internally with os.IsNotExists.\nfunc isNotEmpty(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 strings.Contains(err.Error(), \" not empty\")\n}\n\n\/\/ Delete atomically removes an image from the graph.\nfunc (graph *Graph) Delete(name string) error {\n\tid, err := graph.idIndex.Get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttmp, err := graph.Mktemp(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tgraph.idIndex.Delete(id)\n\terr = os.Rename(graph.imageRoot(id), tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.RemoveAll(tmp)\n}\n\n\/\/ Map returns a list of all images in the graph, addressable by ID.\nfunc (graph *Graph) Map() (map[string]*Image, error) {\n\t\/\/ FIXME: this should replace All()\n\tall, err := graph.All()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timages := make(map[string]*Image, len(all))\n\tfor _, image := range all {\n\t\timages[image.ID] = image\n\t}\n\treturn images, nil\n}\n\n\/\/ All returns a list of all images in the graph.\nfunc (graph *Graph) All() ([]*Image, error) {\n\tvar images []*Image\n\terr := graph.WalkAll(func(image *Image) {\n\t\timages = append(images, image)\n\t})\n\treturn images, err\n}\n\n\/\/ WalkAll iterates over each image in the graph, and passes it to a handler.\n\/\/ The walking order is undetermined.\nfunc (graph *Graph) WalkAll(handler func(*Image)) error {\n\tfiles, err := ioutil.ReadDir(graph.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, st := range files {\n\t\tif img, err := graph.Get(st.Name()); err != nil {\n\t\t\t\/\/ Skip image\n\t\t\tcontinue\n\t\t} else if handler != nil {\n\t\t\thandler(img)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ByParent returns a lookup table of images by their parent.\n\/\/ If an image of id ID has 3 children images, then the value for key ID\n\/\/ will be a list of 3 images.\n\/\/ If an image has no children, it will not have an entry in the table.\nfunc (graph *Graph) ByParent() (map[string][]*Image, error) {\n\tbyParent := make(map[string][]*Image)\n\terr := graph.WalkAll(func(image *Image) {\n\t\tparent, err := graph.Get(image.Parent)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif children, exists := byParent[parent.ID]; exists {\n\t\t\tbyParent[parent.ID] = []*Image{image}\n\t\t} else {\n\t\t\tbyParent[parent.ID] = append(children, image)\n\t\t}\n\t})\n\treturn byParent, err\n}\n\n\/\/ Heads returns all heads in the graph, keyed by id.\n\/\/ A head is an image which is not the parent of another image in the graph.\nfunc (graph *Graph) Heads() (map[string]*Image, error) {\n\theads := make(map[string]*Image)\n\tbyParent, err := graph.ByParent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = graph.WalkAll(func(image *Image) {\n\t\t\/\/ If it's not in the byParent lookup table, then\n\t\t\/\/ it's not a parent -> so it's a head!\n\t\tif _, exists := byParent[image.ID]; !exists {\n\t\t\theads[image.ID] = image\n\t\t}\n\t})\n\treturn heads, err\n}\n\nfunc (graph *Graph) imageRoot(id string) string {\n\treturn path.Join(graph.Root, id)\n}\n<commit_msg>Fix Graph ByParent() to generate list of child images per parent image.<commit_after>package docker\n\nimport (\n\t\"fmt\"\n\t\"github.com\/dotcloud\/docker\/utils\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Graph is a store for versioned filesystem images and the relationship between them.\ntype Graph struct {\n\tRoot    string\n\tidIndex *utils.TruncIndex\n}\n\n\/\/ NewGraph instantiates a new graph at the given root path in the filesystem.\n\/\/ `root` will be created if it doesn't exist.\nfunc NewGraph(root string) (*Graph, error) {\n\tabspath, err := filepath.Abs(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Create the root directory if it doesn't exists\n\tif err := os.MkdirAll(root, 0700); err != nil && !os.IsExist(err) {\n\t\treturn nil, err\n\t}\n\tgraph := &Graph{\n\t\tRoot:    abspath,\n\t\tidIndex: utils.NewTruncIndex(),\n\t}\n\tif err := graph.restore(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn graph, nil\n}\n\nfunc (graph *Graph) restore() error {\n\tdir, err := ioutil.ReadDir(graph.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, v := range dir {\n\t\tid := v.Name()\n\t\tgraph.idIndex.Add(id)\n\t}\n\treturn nil\n}\n\n\/\/ FIXME: Implement error subclass instead of looking at the error text\n\/\/ Note: This is the way golang implements os.IsNotExists on Plan9\nfunc (graph *Graph) IsNotExist(err error) bool {\n\treturn err != nil && (strings.Contains(err.Error(), \"does not exist\") || strings.Contains(err.Error(), \"No such\"))\n}\n\n\/\/ Exists returns true if an image is registered at the given id.\n\/\/ If the image doesn't exist or if an error is encountered, false is returned.\nfunc (graph *Graph) Exists(id string) bool {\n\tif _, err := graph.Get(id); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Get returns the image with the given id, or an error if the image doesn't exist.\nfunc (graph *Graph) Get(name string) (*Image, error) {\n\tid, err := graph.idIndex.Get(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ FIXME: return nil when the image doesn't exist, instead of an error\n\timg, err := LoadImage(graph.imageRoot(id))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif img.ID != id {\n\t\treturn nil, fmt.Errorf(\"Image stored at '%s' has wrong id '%s'\", id, img.ID)\n\t}\n\timg.graph = graph\n\tif img.Size == 0 {\n\t\troot, err := img.root()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := StoreSize(img, root); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn img, nil\n}\n\n\/\/ Create creates a new image and registers it in the graph.\nfunc (graph *Graph) Create(layerData Archive, container *Container, comment, author string, config *Config) (*Image, error) {\n\timg := &Image{\n\t\tID:            GenerateID(),\n\t\tComment:       comment,\n\t\tCreated:       time.Now(),\n\t\tDockerVersion: VERSION,\n\t\tAuthor:        author,\n\t\tConfig:        config,\n\t\tArchitecture:  \"x86_64\",\n\t}\n\tif container != nil {\n\t\timg.Parent = container.Image\n\t\timg.Container = container.ID\n\t\timg.ContainerConfig = *container.Config\n\t}\n\tif err := graph.Register(nil, layerData, img); err != nil {\n\t\treturn nil, err\n\t}\n\treturn img, nil\n}\n\n\/\/ Register imports a pre-existing image into the graph.\n\/\/ FIXME: pass img as first argument\nfunc (graph *Graph) Register(jsonData []byte, layerData Archive, img *Image) error {\n\tif err := ValidateID(img.ID); err != nil {\n\t\treturn err\n\t}\n\t\/\/ (This is a convenience to save time. Race conditions are taken care of by os.Rename)\n\tif graph.Exists(img.ID) {\n\t\treturn fmt.Errorf(\"Image %s already exists\", img.ID)\n\t}\n\ttmp, err := graph.Mktemp(\"\")\n\tdefer os.RemoveAll(tmp)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Mktemp failed: %s\", err)\n\t}\n\tif err := StoreImage(img, jsonData, layerData, tmp); err != nil {\n\t\treturn err\n\t}\n\t\/\/ Commit\n\tif err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil {\n\t\treturn err\n\t}\n\timg.graph = graph\n\tgraph.idIndex.Add(img.ID)\n\treturn nil\n}\n\n\/\/ TempLayerArchive creates a temporary archive of the given image's filesystem layer.\n\/\/   The archive is stored on disk and will be automatically deleted as soon as has been read.\n\/\/   If output is not nil, a human-readable progress bar will be written to it.\n\/\/   FIXME: does this belong in Graph? How about MktempFile, let the caller use it for archives?\nfunc (graph *Graph) TempLayerArchive(id string, compression Compression, sf *utils.StreamFormatter, output io.Writer) (*TempArchive, error) {\n\timage, err := graph.Get(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tarchive, err := image.TarLayer(compression)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, sf.FormatProgress(\"\", \"Buffering to disk\", \"%v\/%v (%v)\"), sf, true), tmp.Root)\n}\n\n\/\/ Mktemp creates a temporary sub-directory inside the graph's filesystem.\nfunc (graph *Graph) Mktemp(id string) (string, error) {\n\tif id == \"\" {\n\t\tid = GenerateID()\n\t}\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Couldn't create temp: %s\", err)\n\t}\n\tif tmp.Exists(id) {\n\t\treturn \"\", fmt.Errorf(\"Image %s already exists\", id)\n\t}\n\treturn tmp.imageRoot(id), nil\n}\n\n\/\/ getDockerInitLayer returns the path of a layer containing a mountpoint suitable\n\/\/ for bind-mounting dockerinit into the container. The mountpoint is simply an\n\/\/ empty file at \/.dockerinit\n\/\/\n\/\/ This extra layer is used by all containers as the top-most ro layer. It protects\n\/\/ the container from unwanted side-effects on the rw layer.\nfunc (graph *Graph) getDockerInitLayer() (string, error) {\n\ttmp, err := graph.tmp()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tinitLayer := tmp.imageRoot(\"_dockerinit\")\n\tif err := os.Mkdir(initLayer, 0755); err != nil && !os.IsExist(err) {\n\t\t\/\/ If directory already existed, keep going.\n\t\t\/\/ For all other errors, abort.\n\t\treturn \"\", err\n\t}\n\n\tfor pth, typ := range map[string]string{\n\t\t\"\/dev\/pts\":         \"dir\",\n\t\t\"\/dev\/shm\":         \"dir\",\n\t\t\"\/proc\":            \"dir\",\n\t\t\"\/sys\":             \"dir\",\n\t\t\"\/.dockerinit\":     \"file\",\n\t\t\"\/etc\/resolv.conf\": \"file\",\n\t\t\/\/ \"var\/run\": \"dir\",\n\t\t\/\/ \"var\/lock\": \"dir\",\n\t} {\n\t\tif _, err := os.Stat(path.Join(initLayer, pth)); err != nil {\n\t\t\tif os.IsNotExist(err) {\n\t\t\t\tswitch typ {\n\t\t\t\tcase \"dir\":\n\t\t\t\t\tif err := os.MkdirAll(path.Join(initLayer, pth), 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\t\tif err := os.MkdirAll(path.Join(initLayer, path.Dir(pth)), 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t}\n\n\t\t\t\t\tif f, err := os.OpenFile(path.Join(initLayer, pth), os.O_CREATE, 0755); err != nil {\n\t\t\t\t\t\treturn \"\", err\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t}\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\n\t\/\/ Layer is ready to use, if it wasn't before.\n\treturn initLayer, nil\n}\n\nfunc (graph *Graph) tmp() (*Graph, error) {\n\t\/\/ Changed to _tmp from :tmp:, because it messed with \":\" separators in aufs branch syntax...\n\treturn NewGraph(path.Join(graph.Root, \"_tmp\"))\n}\n\n\/\/ Check if given error is \"not empty\".\n\/\/ Note: this is the way golang does it internally with os.IsNotExists.\nfunc isNotEmpty(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 strings.Contains(err.Error(), \" not empty\")\n}\n\n\/\/ Delete atomically removes an image from the graph.\nfunc (graph *Graph) Delete(name string) error {\n\tid, err := graph.idIndex.Get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttmp, err := graph.Mktemp(\"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tgraph.idIndex.Delete(id)\n\terr = os.Rename(graph.imageRoot(id), tmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.RemoveAll(tmp)\n}\n\n\/\/ Map returns a list of all images in the graph, addressable by ID.\nfunc (graph *Graph) Map() (map[string]*Image, error) {\n\t\/\/ FIXME: this should replace All()\n\tall, err := graph.All()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timages := make(map[string]*Image, len(all))\n\tfor _, image := range all {\n\t\timages[image.ID] = image\n\t}\n\treturn images, nil\n}\n\n\/\/ All returns a list of all images in the graph.\nfunc (graph *Graph) All() ([]*Image, error) {\n\tvar images []*Image\n\terr := graph.WalkAll(func(image *Image) {\n\t\timages = append(images, image)\n\t})\n\treturn images, err\n}\n\n\/\/ WalkAll iterates over each image in the graph, and passes it to a handler.\n\/\/ The walking order is undetermined.\nfunc (graph *Graph) WalkAll(handler func(*Image)) error {\n\tfiles, err := ioutil.ReadDir(graph.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, st := range files {\n\t\tif img, err := graph.Get(st.Name()); err != nil {\n\t\t\t\/\/ Skip image\n\t\t\tcontinue\n\t\t} else if handler != nil {\n\t\t\thandler(img)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ByParent returns a lookup table of images by their parent.\n\/\/ If an image of id ID has 3 children images, then the value for key ID\n\/\/ will be a list of 3 images.\n\/\/ If an image has no children, it will not have an entry in the table.\nfunc (graph *Graph) ByParent() (map[string][]*Image, error) {\n\tbyParent := make(map[string][]*Image)\n\terr := graph.WalkAll(func(image *Image) {\n\t\tparent, err := graph.Get(image.Parent)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif children, exists := byParent[parent.ID]; exists {\n\t\t\tbyParent[parent.ID] = append(children, image)\n\t\t} else {\n\t\t\tbyParent[parent.ID] = []*Image{image}\n\t\t}\n\t})\n\treturn byParent, err\n}\n\n\/\/ Heads returns all heads in the graph, keyed by id.\n\/\/ A head is an image which is not the parent of another image in the graph.\nfunc (graph *Graph) Heads() (map[string]*Image, error) {\n\theads := make(map[string]*Image)\n\tbyParent, err := graph.ByParent()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = graph.WalkAll(func(image *Image) {\n\t\t\/\/ If it's not in the byParent lookup table, then\n\t\t\/\/ it's not a parent -> so it's a head!\n\t\tif _, exists := byParent[image.ID]; !exists {\n\t\t\theads[image.ID] = image\n\t\t}\n\t})\n\treturn heads, err\n}\n\nfunc (graph *Graph) imageRoot(id string) string {\n\treturn path.Join(graph.Root, id)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ gogl provides a framework for representing and working with graphs.\npackage gogl\n\n\/\/ Constants defining graph capabilities and behaviors.\nconst (\n\tE_DIRECTED, EM_DIRECTED = 1 << iota, 1<<iota - 1\n\tE_UNDIRECTED, EM_UNDIRECTED\n\tE_WEIGHTED, EM_WEIGHTED\n\tE_TYPED, EM_TYPED\n\tE_SIGNED, EM_SIGNED\n\tE_LOOPS, EM_LOOPS\n\tE_MULTIGRAPH, EM_MULTIGRAPH\n)\n\ntype Vertex interface{}\n\ntype Edge struct {\n\tTail, Head Vertex\n}\n\ntype Graph interface {\n\tEachVertex(f func(vertex Vertex))\n\tEachEdge(f func(edge Edge))\n\tEachAdjacent(vertex Vertex, f func(adjacent Vertex))\n\tHasVertex(vertex Vertex) bool\n\tOrder() uint\n\tSize() uint\n\tGetSubgraph([]Vertex) Graph\n}\n\ntype MutableGraph interface {\n\tGraph\n\tAddVertex(v interface{}) bool\n\tRemoveVertex(v interface{}) bool\n}\n\ntype DirectedGraph interface {\n\tGraph\n\tTranspose() DirectedGraph\n\tIsAcyclic() bool\n\tGetCycles() [][]interface{}\n}\n\ntype MutableDirectedGraph interface {\n\tMutableGraph\n\tDirectedGraph\n\taddDirectedEdge(source interface{}, target interface{}) bool\n\tremoveDirectedEdge(source interface{}, target interface{}) bool\n}\n<commit_msg>Fix interfaces so they actually work.<commit_after>\/\/ gogl provides a framework for representing and working with graphs.\npackage gogl\n\n\/\/ Constants defining graph capabilities and behaviors.\nconst (\n\tE_DIRECTED, EM_DIRECTED = 1 << iota, 1<<iota - 1\n\tE_UNDIRECTED, EM_UNDIRECTED\n\tE_WEIGHTED, EM_WEIGHTED\n\tE_TYPED, EM_TYPED\n\tE_SIGNED, EM_SIGNED\n\tE_LOOPS, EM_LOOPS\n\tE_MULTIGRAPH, EM_MULTIGRAPH\n)\n\ntype Vertex interface{}\n\ntype Edge struct {\n\tTail, Head Vertex\n}\n\ntype Graph interface {\n\tEachVertex(f func(vertex Vertex))\n\tEachEdge(f func(edge Edge))\n\tEachAdjacent(vertex Vertex, f func(adjacent Vertex))\n\tHasVertex(vertex Vertex) bool\n\tOrder() uint\n\tSize() uint\n\tAddVertex(v interface{}) bool\n\tRemoveVertex(v interface{}) bool\n}\n\ntype DirectedGraph interface {\n\tGraph\n\tTranspose() DirectedGraph\n\tIsAcyclic() bool\n\tGetCycles() [][]interface{}\n\taddDirectedEdge(source interface{}, target interface{}) bool\n\tremoveDirectedEdge(source interface{}, target interface{}) bool\n}\n<|endoftext|>"}
{"text":"<commit_before>package gogl\n\nimport (\n\t\"fmt\"\n)\n\n\/* Vertex structures *\/\n\n\/\/ As a rule, gogl tries to place as low a requirement on its vertices as\n\/\/ possible. This is because, from a purely graph theoretic perspective,\n\/\/ vertices are inert. Boring, even. Graphs are more about the topology, the\n\/\/ characteristics of the edges connecting the points than the points\n\/\/ themselves. Your use case cares about the content of your vertices, but gogl\n\/\/ does not.  Consequently, anything can act as a vertex.\ntype Vertex interface{}\n\n\/* Atomic graph interfaces *\/\n\n\/\/ A VertexEnumerator iteratively enumerates vertices.\ntype VertexEnumerator interface {\n\tEachVertex(f func(Vertex))\n}\n\n\/\/ An EdgeEnumerator iteratively enumerates edges.\ntype EdgeEnumerator interface {\n\tEachEdge(f func(Edge))\n}\n\n\/\/ An AdjacencyEnumerator iteratively enumerates a given vertex's adjacent vertices.\ntype AdjacencyEnumerator interface {\n\tEachAdjacent(start Vertex, f func(adjacent Vertex))\n}\n\n\/\/ A VertexMembershipChecker can indicate the presence of a vertex.\ntype VertexMembershipChecker interface {\n\tHasVertex(Vertex) bool \/\/ Whether or not the vertex is present in the set\n}\n\n\/\/ An InOutDegreeChecker reports the number of edges incident to a given vertex.\n\/\/ TODO use this\ntype DegreeChecker interface {\n\tDegree(Vertex) (degree int, exists bool) \/\/ Number of incident edges; if vertex is present\n}\n\n\/\/ An InOutDegreeChecker reports the number of in or out-edges a given vertex has.\ntype InOutDegreeChecker interface {\n\tInDegree(Vertex) (degree int, exists bool)  \/\/ Number of in-edges; if vertex is present\n\tOutDegree(Vertex) (degree int, exists bool) \/\/ Number of out-edges; if vertex is present\n}\n\n\/\/ An EdgeMembershipChecker can indicate the presence of an edge.\ntype EdgeMembershipChecker interface {\n\tHasEdge(Edge) bool\n}\n\n\/\/ A VertexSetMutator allows the addition and removal of vertices from a set.\ntype VertexSetMutator interface {\n\tEnsureVertex(...Vertex)\n\tRemoveVertex(...Vertex)\n}\n\n\/\/ An EdgeSetMutator allows the addition and removal of edges from a set.\ntype EdgeSetMutator interface {\n\tAddEdges(edges ...Edge)\n\tRemoveEdges(edges ...Edge)\n}\n\n\/\/ A WeightedEdgeSetMutator allows the addition and removal of weighted edges from a set.\ntype WeightedEdgeSetMutator interface {\n\tAddEdges(edges ...WeightedEdge)\n\tRemoveEdges(edges ...WeightedEdge)\n}\n\n\/\/ A LabeledEdgeSetMutator allows the addition and removal of labeled edges from a set.\ntype LabeledEdgeSetMutator interface {\n\tAddEdges(edges ...LabeledEdge)\n\tRemoveEdges(edges ...LabeledEdge)\n}\n\n\/\/ A PropertyEdgeSetMutator allows the addition and removal of data edges from a set.\ntype PropertyEdgeSetMutator interface {\n\tAddEdges(edges ...PropertyEdge)\n\tRemoveEdges(edges ...PropertyEdge)\n}\n\n\/\/ A Transposer produces a transposed version of a DirectedGraph.\ntype Transposer interface {\n\tTranspose() DirectedGraph\n}\n\n\/* Aggregate graph interfaces *\/\n\n\/\/ Graph is gogl's most basic interface: it contains only the methods that\n\/\/ *every* type of graph implements.\n\/\/\n\/\/ Graph is intentionally underspecified: both directed and undirected graphs\n\/\/ implement it; simple graphs, multigraphs, weighted, labeled, or any\n\/\/ combination thereof.\n\/\/\n\/\/ The semantics of some of these methods vary slightly from one graph type\n\/\/ to another, but in general, the basic Graph methods are supplemented, not\n\/\/ superceded, by the methods in more specific interfaces.\n\/\/\n\/\/ Graph is a purely read oriented interface; the various Mutable*Graph\n\/\/ interfaces contain the methods for writing.\ntype Graph interface {\n\tVertexEnumerator        \/\/ Allows enumerated traversal of vertices\n\tEdgeEnumerator          \/\/ Allows enumerated traversal of edges\n\tAdjacencyEnumerator     \/\/ Allows enumerated traversal of a vertex's adjacent vertices\n\tVertexMembershipChecker \/\/ Allows inspection of contained vertices\n\tEdgeMembershipChecker   \/\/ Allows inspection of contained edges\n\tInOutDegreeChecker      \/\/ Reports in- and out-degree of vertices\n\tOrder() int             \/\/ Total number of vertices in the graph\n\tSize() int              \/\/ Total number of edges in the graph\n}\n\n\/\/ DirectedGraph describes a Graph all of whose edges are directed.\n\/\/\n\/\/ Implementing DirectedGraph is the only unambiguous signal gogl provides\n\/\/ that a graph's edges are directed.\ntype DirectedGraph interface {\n\tGraph\n\tTransposer \/\/ DirectedGraphs can produce a transpose of themselves\n}\n\n\/\/ MutableGraph describes a graph with basic edges (no weighting, labeling, etc.)\n\/\/ that can be modified freely by adding or removing vertices or edges.\ntype MutableGraph interface {\n\tGraph\n\tVertexSetMutator\n\tEdgeSetMutator\n}\n\n\/\/ A simple graph is in opposition to a multigraph: it disallows loops and\n\/\/ parallel edges.\ntype SimpleGraph interface {\n\tGraph\n\tDensity() float64\n}\n\n\/\/ A weighted graph is a graph subtype where the edges have a numeric weight;\n\/\/ as described by the WeightedEdge interface, this weight is a signed int.\n\/\/\n\/\/ WeightedGraphs have both the HasEdge() and HasWeightedEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its weight.\n\/\/\n\/\/ HasWeightedEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge weights are the same.\ntype WeightedGraph interface {\n\tGraph\n\tHasWeightedEdge(e WeightedEdge) bool\n\tEachWeightedEdge(f func(edge WeightedEdge))\n}\n\n\/\/ MutableWeightedGraph is the mutable version of a weighted graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only weighted edges can be present in the graph.\ntype MutableWeightedGraph interface {\n\tWeightedGraph\n\tVertexSetMutator\n\tWeightedEdgeSetMutator\n}\n\n\/\/ A labeled graph is a graph subtype where the edges have an identifier;\n\/\/ as described by the LabeledEdge interface, this identifier is a string.\n\/\/\n\/\/ LabeledGraphs have both the HasEdge() and HasLabeledEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its label.\n\/\/\n\/\/ HasLabeledEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge labels are the same.\ntype LabeledGraph interface {\n\tGraph\n\tHasLabeledEdge(e LabeledEdge) bool\n\tEachLabeledEdge(f func(edge LabeledEdge))\n}\n\n\/\/ LabeledWeightedGraph is the mutable version of a labeled graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only labeled edges can be present in the graph.\ntype MutableLabeledGraph interface {\n\tLabeledGraph\n\tVertexSetMutator\n\tLabeledEdgeSetMutator\n}\n\n\/\/ A data graph is a graph subtype where the edges carry arbitrary Go data;\n\/\/ as described by the PropertyEdge interface, this identifier is an interface{}.\n\/\/\n\/\/ PropertyGraphs have both the HasEdge() and HasPropertyEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its label.\n\/\/\n\/\/ HasPropertyEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge data is the same. Simple comparison will typically be used\n\/\/ to establish data equality, which means that using noncomparables (a slice,\n\/\/ map, or non-pointer struct containing a slice or a map) for the data will\n\/\/ cause a panic.\ntype PropertyGraph interface {\n\tGraph\n\tHasPropertyEdge(e PropertyEdge) bool\n\tEachPropertyEdge(f func(edge PropertyEdge))\n}\n\n\/\/ MutablePropertyGraph is the mutable version of a propety graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only property edges can be present in the graph.\ntype MutablePropertyGraph interface {\n\tPropertyGraph\n\tVertexSetMutator\n\tPropertyEdgeSetMutator\n}\n\n\/* Graph creation *\/\n\ntype GraphFactory func() interface{}\n\nvar Graphs = make(map[string]GraphFactory, 0)\n\n\/\/ Creates a new graph instance.\n\/\/\n\/\/ You will need to type assert the returned graph to the interface appropriate\n\/\/ for your use case: Graph, DirectedGraph, MutableGraph, WeightedGraph, etc.\nfunc New(name string) (graph interface{}, err error) {\n\tif _, exists := Graphs[name]; !exists {\n\t\treturn nil, fmt.Errorf(\"No graph is registered with the name %q\", name)\n\t}\n\n\treturn Graphs[name](), nil\n}\n\nfunc RegisterGraph(name string, factory GraphFactory) error {\n\tif _, exists := Graphs[name]; exists {\n\t\treturn fmt.Errorf(\"A graph is already registered with the name %q\", name)\n\t}\n\n\tg := factory()\n\n\tif _, ok := g.(Graph); ok {\n\t\treturn nil\n\t} else if _, ok := g.(WeightedGraph); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Value returned from factory does not implement a known Graph interface\")\n}\n\nfunc init() {\n\tRegisterGraph(\"basic.directed\", func() interface{} {\n\t\treturn NewDirected()\n\t})\n\tRegisterGraph(\"basic.undirected\", func() interface{} {\n\t\treturn NewUndirected()\n\t})\n\tRegisterGraph(\"weighted.directed\", func() interface{} {\n\t\treturn NewWeightedDirected()\n\t})\n\tRegisterGraph(\"weighted.undirected\", func() interface{} {\n\t\treturn NewWeightedUndirected()\n\t})\n}\n<commit_msg>Add incidence edge\/arc enumerator interfaces.<commit_after>package gogl\n\nimport (\n\t\"fmt\"\n)\n\n\/* Vertex structures *\/\n\n\/\/ As a rule, gogl tries to place as low a requirement on its vertices as\n\/\/ possible. This is because, from a purely graph theoretic perspective,\n\/\/ vertices are inert. Boring, even. Graphs are more about the topology, the\n\/\/ characteristics of the edges connecting the points than the points\n\/\/ themselves. Your use case cares about the content of your vertices, but gogl\n\/\/ does not.  Consequently, anything can act as a vertex.\ntype Vertex interface{}\n\n\/* Atomic graph interfaces *\/\n\n\/\/ A VertexEnumerator iteratively enumerates vertices.\ntype VertexEnumerator interface {\n\tEachVertex(f func(Vertex))\n}\n\n\/\/ An EdgeEnumerator iteratively enumerates edges.\ntype EdgeEnumerator interface {\n\tEachEdge(f func(Edge))\n}\n\n\/\/ An IncidentEdgeEnumerator iteratively enumerates a given vertex's incident edges.\ntype IncidentEdgeEnumerator interface {\n\tEachEdgeIncidentTo(Vertex, f func(Edge)) bool\n}\n\n\/\/ An IncidentArcEnumerator iteratively enumerates a given vertex's incident arcs (directed edges).\n\/\/ One enumerator provides inbound edges, the other outbound edges.\ntype IncidentArcEnumerator interface {\n\tEachArcFrom(Vertex, f func(Edge)) bool\n\tEachArcTo(Vertex, f func(Edge)) bool\n}\n\n\/\/ An AdjacencyEnumerator iteratively enumerates a given vertex's adjacent vertices.\ntype AdjacencyEnumerator interface {\n\tEachAdjacent(start Vertex, f func(adjacent Vertex))\n}\n\n\/\/ A VertexMembershipChecker can indicate the presence of a vertex.\ntype VertexMembershipChecker interface {\n\tHasVertex(Vertex) bool \/\/ Whether or not the vertex is present in the set\n}\n\n\/\/ An InOutDegreeChecker reports the number of edges incident to a given vertex.\n\/\/ TODO use this\ntype DegreeChecker interface {\n\tDegreeOf(Vertex) (degree int, exists bool) \/\/ Number of incident edges; if vertex is present\n}\n\n\/\/ An InOutDegreeChecker reports the number of in or out-edges a given vertex has.\ntype InOutDegreeChecker interface {\n\tInDegree(Vertex) (degree int, exists bool)  \/\/ Number of in-edges; if vertex is present\n\tOutDegree(Vertex) (degree int, exists bool) \/\/ Number of out-edges; if vertex is present\n}\n\n\/\/ An EdgeMembershipChecker can indicate the presence of an edge.\ntype EdgeMembershipChecker interface {\n\tHasEdge(Edge) bool\n}\n\n\/\/ A VertexSetMutator allows the addition and removal of vertices from a set.\ntype VertexSetMutator interface {\n\tEnsureVertex(...Vertex)\n\tRemoveVertex(...Vertex)\n}\n\n\/\/ An EdgeSetMutator allows the addition and removal of edges from a set.\ntype EdgeSetMutator interface {\n\tAddEdges(edges ...Edge)\n\tRemoveEdges(edges ...Edge)\n}\n\n\/\/ A WeightedEdgeSetMutator allows the addition and removal of weighted edges from a set.\ntype WeightedEdgeSetMutator interface {\n\tAddEdges(edges ...WeightedEdge)\n\tRemoveEdges(edges ...WeightedEdge)\n}\n\n\/\/ A LabeledEdgeSetMutator allows the addition and removal of labeled edges from a set.\ntype LabeledEdgeSetMutator interface {\n\tAddEdges(edges ...LabeledEdge)\n\tRemoveEdges(edges ...LabeledEdge)\n}\n\n\/\/ A PropertyEdgeSetMutator allows the addition and removal of data edges from a set.\ntype PropertyEdgeSetMutator interface {\n\tAddEdges(edges ...PropertyEdge)\n\tRemoveEdges(edges ...PropertyEdge)\n}\n\n\/\/ A Transposer produces a transposed version of a DirectedGraph.\ntype Transposer interface {\n\tTranspose() DirectedGraph\n}\n\n\/* Aggregate graph interfaces *\/\n\n\/\/ Graph is gogl's most basic interface: it contains only the methods that\n\/\/ *every* type of graph implements.\n\/\/\n\/\/ Graph is intentionally underspecified: both directed and undirected graphs\n\/\/ implement it; simple graphs, multigraphs, weighted, labeled, or any\n\/\/ combination thereof.\n\/\/\n\/\/ The semantics of some of these methods vary slightly from one graph type\n\/\/ to another, but in general, the basic Graph methods are supplemented, not\n\/\/ superceded, by the methods in more specific interfaces.\n\/\/\n\/\/ Graph is a purely read oriented interface; the various Mutable*Graph\n\/\/ interfaces contain the methods for writing.\ntype Graph interface {\n\tVertexEnumerator        \/\/ Allows enumerated traversal of vertices\n\tEdgeEnumerator          \/\/ Allows enumerated traversal of edges\n\tAdjacencyEnumerator     \/\/ Allows enumerated traversal of a vertex's adjacent vertices\n\tVertexMembershipChecker \/\/ Allows inspection of contained vertices\n\tEdgeMembershipChecker   \/\/ Allows inspection of contained edges\n\tInOutDegreeChecker      \/\/ Reports in- and out-degree of vertices\n\tOrder() int             \/\/ Total number of vertices in the graph\n\tSize() int              \/\/ Total number of edges in the graph\n}\n\n\/\/ DirectedGraph describes a Graph all of whose edges are directed.\n\/\/\n\/\/ Implementing DirectedGraph is the only unambiguous signal gogl provides\n\/\/ that a graph's edges are directed.\ntype DirectedGraph interface {\n\tGraph\n\tTransposer \/\/ DirectedGraphs can produce a transpose of themselves\n}\n\n\/\/ MutableGraph describes a graph with basic edges (no weighting, labeling, etc.)\n\/\/ that can be modified freely by adding or removing vertices or edges.\ntype MutableGraph interface {\n\tGraph\n\tVertexSetMutator\n\tEdgeSetMutator\n}\n\n\/\/ A simple graph is in opposition to a multigraph: it disallows loops and\n\/\/ parallel edges.\ntype SimpleGraph interface {\n\tGraph\n\tDensity() float64\n}\n\n\/\/ A weighted graph is a graph subtype where the edges have a numeric weight;\n\/\/ as described by the WeightedEdge interface, this weight is a signed int.\n\/\/\n\/\/ WeightedGraphs have both the HasEdge() and HasWeightedEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its weight.\n\/\/\n\/\/ HasWeightedEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge weights are the same.\ntype WeightedGraph interface {\n\tGraph\n\tHasWeightedEdge(e WeightedEdge) bool\n\tEachWeightedEdge(f func(edge WeightedEdge))\n}\n\n\/\/ MutableWeightedGraph is the mutable version of a weighted graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only weighted edges can be present in the graph.\ntype MutableWeightedGraph interface {\n\tWeightedGraph\n\tVertexSetMutator\n\tWeightedEdgeSetMutator\n}\n\n\/\/ A labeled graph is a graph subtype where the edges have an identifier;\n\/\/ as described by the LabeledEdge interface, this identifier is a string.\n\/\/\n\/\/ LabeledGraphs have both the HasEdge() and HasLabeledEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its label.\n\/\/\n\/\/ HasLabeledEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge labels are the same.\ntype LabeledGraph interface {\n\tGraph\n\tHasLabeledEdge(e LabeledEdge) bool\n\tEachLabeledEdge(f func(edge LabeledEdge))\n}\n\n\/\/ LabeledWeightedGraph is the mutable version of a labeled graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only labeled edges can be present in the graph.\ntype MutableLabeledGraph interface {\n\tLabeledGraph\n\tVertexSetMutator\n\tLabeledEdgeSetMutator\n}\n\n\/\/ A data graph is a graph subtype where the edges carry arbitrary Go data;\n\/\/ as described by the PropertyEdge interface, this identifier is an interface{}.\n\/\/\n\/\/ PropertyGraphs have both the HasEdge() and HasPropertyEdge() methods.\n\/\/ Correct implementations should treat the difference as a matter of strictness:\n\/\/\n\/\/ HasEdge() should return true as long as an edge exists\n\/\/ connecting the two given vertices (respecting directed or undirected as\n\/\/ appropriate), regardless of its label.\n\/\/\n\/\/ HasPropertyEdge() should return true iff an edge exists connecting the\n\/\/ two given vertices (respecting directed or undirected as appropriate),\n\/\/ AND if the edge data is the same. Simple comparison will typically be used\n\/\/ to establish data equality, which means that using noncomparables (a slice,\n\/\/ map, or non-pointer struct containing a slice or a map) for the data will\n\/\/ cause a panic.\ntype PropertyGraph interface {\n\tGraph\n\tHasPropertyEdge(e PropertyEdge) bool\n\tEachPropertyEdge(f func(edge PropertyEdge))\n}\n\n\/\/ MutablePropertyGraph is the mutable version of a propety graph. Its\n\/\/ AddEdges() method is incompatible with MutableGraph, guaranteeing\n\/\/ only property edges can be present in the graph.\ntype MutablePropertyGraph interface {\n\tPropertyGraph\n\tVertexSetMutator\n\tPropertyEdgeSetMutator\n}\n\n\/* Graph creation *\/\n\ntype GraphFactory func() interface{}\n\nvar Graphs = make(map[string]GraphFactory, 0)\n\n\/\/ Creates a new graph instance.\n\/\/\n\/\/ You will need to type assert the returned graph to the interface appropriate\n\/\/ for your use case: Graph, DirectedGraph, MutableGraph, WeightedGraph, etc.\nfunc New(name string) (graph interface{}, err error) {\n\tif _, exists := Graphs[name]; !exists {\n\t\treturn nil, fmt.Errorf(\"No graph is registered with the name %q\", name)\n\t}\n\n\treturn Graphs[name](), nil\n}\n\nfunc RegisterGraph(name string, factory GraphFactory) error {\n\tif _, exists := Graphs[name]; exists {\n\t\treturn fmt.Errorf(\"A graph is already registered with the name %q\", name)\n\t}\n\n\tg := factory()\n\n\tif _, ok := g.(Graph); ok {\n\t\treturn nil\n\t} else if _, ok := g.(WeightedGraph); ok {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Value returned from factory does not implement a known Graph interface\")\n}\n\nfunc init() {\n\tRegisterGraph(\"basic.directed\", func() interface{} {\n\t\treturn NewDirected()\n\t})\n\tRegisterGraph(\"basic.undirected\", func() interface{} {\n\t\treturn NewUndirected()\n\t})\n\tRegisterGraph(\"weighted.directed\", func() interface{} {\n\t\treturn NewWeightedDirected()\n\t})\n\tRegisterGraph(\"weighted.undirected\", func() interface{} {\n\t\treturn NewWeightedUndirected()\n\t})\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 gcscaching_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\/gcscaching\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\/gcsfake\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestIntegration(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype IntegrationTest struct {\n\tcache   gcscaching.StatCache\n\tclock   timeutil.SimulatedClock\n\twrapped gcs.Bucket\n\n\tbucket gcs.Bucket\n}\n\nfunc init() { RegisterTestSuite(&IntegrationTest{}) }\n\nfunc (t *IntegrationTest) SetUp(ti *TestInfo) {\n\t\/\/ Set up a fixed, non-zero time.\n\tt.clock.SetTime(time.Date(2015, 4, 5, 2, 15, 0, 0, time.Local))\n\n\t\/\/ Set up dependencies.\n\tconst cacheCapacity = 100\n\tt.cache = gcscaching.NewStatCache(cacheCapacity)\n\tt.wrapped = gcsfake.NewFakeBucket(&t.clock, \"some_bucket\")\n\n\tt.bucket = gcscaching.NewFastStatBucket(\n\t\tttl,\n\t\tt.cache,\n\t\t&t.clock,\n\t\tt.wrapped)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Test functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *IntegrationTest) StatUnknownTwice() {\n\tvar err error\n\treq := &gcs.StatObjectRequest{\n\t\tName: \"taco\",\n\t}\n\n\t\/\/ First\n\t_, err = t.bucket.StatObject(context.Background(), req)\n\tExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{}))\n\n\t\/\/ Second\n\t_, err = t.bucket.StatObject(context.Background(), req)\n\tExpectThat(err, HasSameTypeAs(&gcs.NotFoundError{}))\n}\n\nfunc (t *IntegrationTest) CreateThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) ListThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) CreateThenUpdateThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) DeleteThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n<commit_msg>IntegrationTest.StatDoesntCacheNotFoundErrors<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 gcscaching_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\/gcscaching\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\/gcsfake\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\/gcsutil\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestIntegration(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype IntegrationTest struct {\n\tcache   gcscaching.StatCache\n\tclock   timeutil.SimulatedClock\n\twrapped gcs.Bucket\n\n\tbucket gcs.Bucket\n}\n\nfunc init() { RegisterTestSuite(&IntegrationTest{}) }\n\nfunc (t *IntegrationTest) SetUp(ti *TestInfo) {\n\t\/\/ Set up a fixed, non-zero time.\n\tt.clock.SetTime(time.Date(2015, 4, 5, 2, 15, 0, 0, time.Local))\n\n\t\/\/ Set up dependencies.\n\tconst cacheCapacity = 100\n\tt.cache = gcscaching.NewStatCache(cacheCapacity)\n\tt.wrapped = gcsfake.NewFakeBucket(&t.clock, \"some_bucket\")\n\n\tt.bucket = gcscaching.NewFastStatBucket(\n\t\tttl,\n\t\tt.cache,\n\t\t&t.clock,\n\t\tt.wrapped)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Test functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *IntegrationTest) StatDoesntCacheNotFoundErrors() {\n\tconst name = \"taco\"\n\tvar err error\n\n\t\/\/ Stat an unknown object.\n\treq := &gcs.StatObjectRequest{\n\t\tName: name,\n\t}\n\n\t_, err = t.bucket.StatObject(context.Background(), req)\n\tAssertThat(err, HasSameTypeAs(&gcs.NotFoundError{}))\n\n\t\/\/ Create the object through the back door.\n\t_, err = gcsutil.CreateObject(context.Background(), t.wrapped, name, \"\")\n\tAssertEq(nil, err)\n\n\t\/\/ Stat again. We should now see the object.\n\to, err := t.bucket.StatObject(context.Background(), req)\n\tAssertEq(nil, err)\n\tExpectNe(nil, o)\n}\n\nfunc (t *IntegrationTest) CreateThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) ListThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) CreateThenUpdateThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n\nfunc (t *IntegrationTest) DeleteThenStat() {\n\tAssertFalse(true, \"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package errors\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ New returns an error that formats as the given text.\nfunc New(text string) error {\n\treturn errors.New(text)\n}\n\n\/\/ wrapperError satisfies the error interface.\ntype wrapperError struct {\n\tmsg    string\n\tdetail []string\n\tdata   map[string]interface{}\n\tstack  []StackFrame\n\troot   error\n}\n\n\/\/ It satisfies the error interface.\nfunc (e wrapperError) Error() string {\n\treturn e.msg\n}\n\n\/\/ Root returns the original error that was wrapped by one or more\n\/\/ calls to Wrap. If e does not wrap other errors, it will be returned\n\/\/ as-is.\nfunc Root(e error) error {\n\tif wErr, ok := e.(wrapperError); ok {\n\t\treturn wErr.root\n\t}\n\treturn e\n}\n\n\/\/ wrap adds a context message and stack trace to err and returns a new error\n\/\/ containing the new context. This function is meant to be composed within\n\/\/ other exported functions, such as Wrap and WithDetail.\n\/\/ The argument stackSkip is the number of stack frames to ascend when\n\/\/ generating stack straces, where 0 is the caller of wrap.\nfunc wrap(err error, msg string, stackSkip int) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\twerr, ok := err.(wrapperError)\n\tif !ok {\n\t\twerr.root = err\n\t\twerr.msg = err.Error()\n\t\twerr.stack = getStack(stackSkip+2, stackTraceSize)\n\t}\n\tif msg != \"\" {\n\t\twerr.msg = msg + \": \" + werr.msg\n\t}\n\n\treturn werr\n}\n\n\/\/ Wrap adds a context message and stack trace to err and returns a new error\n\/\/ with the new context. Arguments are handled as in fmt.Print.\n\/\/ Use Root to recover the original error wrapped by one or more calls to Wrap.\n\/\/ Use Stack to recover the stack trace.\n\/\/ Wrap returns nil if err is nil.\nfunc Wrap(err error, a ...interface{}) error {\n\treturn wrap(err, fmt.Sprint(a...), 1)\n}\n\n\/\/ Wrapf is like Wrap, but arguments are handled as in fmt.Printf.\nfunc Wrapf(err error, format string, a ...interface{}) error {\n\treturn wrap(err, fmt.Sprintf(format, a...), 1)\n}\n\n\/\/ WithDetail returns a new error that wraps\n\/\/ err as a chain error messsage containing text\n\/\/ as its additional context.\n\/\/ Function Detail will return the given text\n\/\/ when called on the new error value.\nfunc WithDetail(err error, text string) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif text == \"\" {\n\t\treturn err\n\t}\n\te1 := wrap(err, text, 1).(wrapperError)\n\te1.detail = append(e1.detail, text)\n\treturn e1\n}\n\n\/\/ WithDetailf is like WithDetail, except it formats\n\/\/ the detail message as in fmt.Printf.\n\/\/ Function Detail will return the formatted text\n\/\/ when called on the new error value.\nfunc WithDetailf(err error, format string, v ...interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\ttext := fmt.Sprintf(format, v...)\n\te1 := wrap(err, text, 1).(wrapperError)\n\te1.detail = append(e1.detail, text)\n\treturn e1\n}\n\n\/\/ Detail returns the detail message contained in err, if any.\n\/\/ An error has a detail message if it was made by WithDetail\n\/\/ or WithDetailf.\nfunc Detail(err error) string {\n\twrapper, _ := err.(wrapperError)\n\treturn strings.Join(wrapper.detail, \"; \")\n}\n\n\/\/ withData returns a new error that wraps err\n\/\/ as a chain error message containing v as\n\/\/ an extra data item.\n\/\/ Calling Data on the returned error yields v.\n\/\/ Note that if err already has a data item,\n\/\/ it will not be accessible via the returned error value.\nfunc withData(err error, v map[string]interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\te1 := wrap(err, \"\", 1).(wrapperError)\n\te1.data = v\n\treturn e1\n}\n\n\/\/ WithData returns a new error that wraps err\n\/\/ as a chain error message containing a value of type\n\/\/ map[string]interface{} as an extra data item.\n\/\/ The map contains the values in the map in err,\n\/\/ if any, plus the items in keyval.\n\/\/ Keyval takes the form\n\/\/   k1, v1, k2, v2, ...\n\/\/ Values kN must be strings.\n\/\/ Calling Data on the returned error yields the map.\n\/\/ Note that if err already has a data item of any other type,\n\/\/ it will not be accessible via the returned error value.\nfunc WithData(err error, keyval ...interface{}) error {\n\t\/\/ TODO(kr): add vet check for odd-length keyval and non-string keys\n\tnewkv := make(map[string]interface{})\n\tfor k, v := range Data(err) {\n\t\tnewkv[k] = v\n\t}\n\tfor i := 0; i < len(keyval); i += 2 {\n\t\tnewkv[keyval[i].(string)] = keyval[i+1]\n\t}\n\treturn withData(err, newkv)\n}\n\n\/\/ Data returns the data item in err, if any.\nfunc Data(err error) map[string]interface{} {\n\twrapper, _ := err.(wrapperError)\n\treturn wrapper.data\n}\n\n\/\/ Sub returns an error with all the associated data from old,\n\/\/ including stack trace, detail, message, and data, but using\n\/\/ new as the root error. It also wraps the newly-created error\n\/\/ with the formatted error string from old.\n\/\/\n\/\/ Sub returns nil when either new or old is nil.\n\/\/\n\/\/ Use this when you need to substitute a new root error in place\n\/\/ of an existing error that may already hold a stack trace\n\/\/ or other metadata.\nfunc Sub(new, old error) error {\n\tif wrapper, ok := old.(wrapperError); ok && new != nil {\n\t\twrapper.root = Root(new)\n\t\twrapper.msg = new.Error()\n\t\tnew = wrapper\n\t}\n\tif old == nil {\n\t\treturn nil\n\t}\n\treturn Wrap(new, old.Error())\n}\n<commit_msg>errors: clarify documentation<commit_after>package errors\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ New returns an error that formats as the given text.\nfunc New(text string) error {\n\treturn errors.New(text)\n}\n\n\/\/ wrapperError satisfies the error interface.\ntype wrapperError struct {\n\tmsg    string\n\tdetail []string\n\tdata   map[string]interface{}\n\tstack  []StackFrame\n\troot   error\n}\n\n\/\/ It satisfies the error interface.\nfunc (e wrapperError) Error() string {\n\treturn e.msg\n}\n\n\/\/ Root returns the original error that was wrapped by one or more\n\/\/ calls to Wrap. If e does not wrap other errors, it will be returned\n\/\/ as-is.\nfunc Root(e error) error {\n\tif wErr, ok := e.(wrapperError); ok {\n\t\treturn wErr.root\n\t}\n\treturn e\n}\n\n\/\/ wrap adds a context message and stack trace to err and returns a new error\n\/\/ containing the new context. This function is meant to be composed within\n\/\/ other exported functions, such as Wrap and WithDetail.\n\/\/ The argument stackSkip is the number of stack frames to ascend when\n\/\/ generating stack straces, where 0 is the caller of wrap.\nfunc wrap(err error, msg string, stackSkip int) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\twerr, ok := err.(wrapperError)\n\tif !ok {\n\t\twerr.root = err\n\t\twerr.msg = err.Error()\n\t\twerr.stack = getStack(stackSkip+2, stackTraceSize)\n\t}\n\tif msg != \"\" {\n\t\twerr.msg = msg + \": \" + werr.msg\n\t}\n\n\treturn werr\n}\n\n\/\/ Wrap adds a context message and stack trace to err and returns a new error\n\/\/ with the new context. Arguments are handled as in fmt.Print.\n\/\/ Use Root to recover the original error wrapped by one or more calls to Wrap.\n\/\/ Use Stack to recover the stack trace.\n\/\/ Wrap returns nil if err is nil.\nfunc Wrap(err error, a ...interface{}) error {\n\treturn wrap(err, fmt.Sprint(a...), 1)\n}\n\n\/\/ Wrapf is like Wrap, but arguments are handled as in fmt.Printf.\nfunc Wrapf(err error, format string, a ...interface{}) error {\n\treturn wrap(err, fmt.Sprintf(format, a...), 1)\n}\n\n\/\/ WithDetail returns a new error that wraps\n\/\/ err as a chain error messsage containing text\n\/\/ as its additional context.\n\/\/ Function Detail will return the given text\n\/\/ when called on the new error value.\nfunc WithDetail(err error, text string) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif text == \"\" {\n\t\treturn err\n\t}\n\te1 := wrap(err, text, 1).(wrapperError)\n\te1.detail = append(e1.detail, text)\n\treturn e1\n}\n\n\/\/ WithDetailf is like WithDetail, except it formats\n\/\/ the detail message as in fmt.Printf.\n\/\/ Function Detail will return the formatted text\n\/\/ when called on the new error value.\nfunc WithDetailf(err error, format string, v ...interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\ttext := fmt.Sprintf(format, v...)\n\te1 := wrap(err, text, 1).(wrapperError)\n\te1.detail = append(e1.detail, text)\n\treturn e1\n}\n\n\/\/ Detail returns the detail message contained in err, if any.\n\/\/ An error has a detail message if it was made by WithDetail\n\/\/ or WithDetailf.\nfunc Detail(err error) string {\n\twrapper, _ := err.(wrapperError)\n\treturn strings.Join(wrapper.detail, \"; \")\n}\n\n\/\/ withData returns a new error that wraps err\n\/\/ as a chain error message containing v as\n\/\/ an extra data item.\n\/\/ Calling Data on the returned error yields v.\n\/\/ Note that if err already has a data item,\n\/\/ it will not be accessible via the returned error value.\nfunc withData(err error, v map[string]interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\te1 := wrap(err, \"\", 1).(wrapperError)\n\te1.data = v\n\treturn e1\n}\n\n\/\/ WithData returns a new error that wraps err\n\/\/ as a chain error message containing a value of type\n\/\/ map[string]interface{} as an extra data item.\n\/\/ The map contains the values in the map in err,\n\/\/ if any, plus the items in keyval.\n\/\/ Keyval takes the form\n\/\/   k1, v1, k2, v2, ...\n\/\/ Values kN must be strings.\n\/\/ Calling Data on the returned error yields the map.\n\/\/ Note that if err already has a data item of any other type,\n\/\/ it will not be accessible via the returned error value.\nfunc WithData(err error, keyval ...interface{}) error {\n\t\/\/ TODO(kr): add vet check for odd-length keyval and non-string keys\n\tnewkv := make(map[string]interface{})\n\tfor k, v := range Data(err) {\n\t\tnewkv[k] = v\n\t}\n\tfor i := 0; i < len(keyval); i += 2 {\n\t\tnewkv[keyval[i].(string)] = keyval[i+1]\n\t}\n\treturn withData(err, newkv)\n}\n\n\/\/ Data returns the data item in err, if any.\nfunc Data(err error) map[string]interface{} {\n\twrapper, _ := err.(wrapperError)\n\treturn wrapper.data\n}\n\n\/\/ Sub returns an error containing root as its root and\n\/\/ taking all other metadata (stack trace, detail, message,\n\/\/ and data items) from err.\n\/\/\n\/\/ Sub returns nil when either root or err is nil.\n\/\/\n\/\/ Use this when you need to substitute a new root error in place\n\/\/ of an existing error that may already hold a stack trace\n\/\/ or other metadata.\nfunc Sub(root, err error) error {\n\tif wrapper, ok := err.(wrapperError); ok && root != nil {\n\t\twrapper.root = Root(root)\n\t\twrapper.msg = root.Error()\n\t\troot = wrapper\n\t}\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn Wrap(root, err.Error())\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 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\tmuxPacketSynAck\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\tdefer stream.mu.Unlock()\n\tif stream.state != streamStateSynRecv && stream.state != streamStateClosed {\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\tif stream.state == streamStateClosed {\n\t\t\/\/ Go into the listening state and wait for a syn\n\t\tstream.setState(streamStateListen)\n\t\tif err := stream.waitState(streamStateSynRecv); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif stream.state == streamStateSynRecv {\n\t\t\/\/ Send a syn-ack\n\t\tif _, err := m.write(stream.id, muxPacketSynAck, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := stream.waitState(streamStateEstablished); 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\tdefer stream.mu.Unlock()\n\tif stream.state != streamStateClosed {\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\tif err := stream.waitState(streamStateEstablished); err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.write(id, muxPacketAck, nil)\n\treturn stream, nil\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\/\/ Make sure we attempt to use the next biggest stream ID\n\tif id >= m.curId {\n\t\tm.curId = id + 1\n\t}\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\tlog.Printf(\"[INFO] Mux connection loop exiting\")\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\tlog.Printf(\"[TRACE] Stream %d received packet %d\", id, packetType)\n\t\tswitch packetType {\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\tfallthrough\n\t\t\tcase streamStateListen:\n\t\t\t\tstream.setState(streamStateSynRecv)\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 muxPacketAck:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateSynRecv:\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 muxPacketSynAck:\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\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] SynAck 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\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\tswitch stream.state {\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tfallthrough\n\t\t\tcase streamStateFinWait2:\n\t\t\t\tfallthrough\n\t\t\tcase 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\tdefault:\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 && state != streamStateCloseWait {\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) setState(state streamState) {\n\tlog.Printf(\"[TRACE] Stream %d went to state %d\", s.id, state)\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\nfunc (s *Stream) waitState(target streamState) error {\n\t\/\/ Register a state change listener to wait for changes\n\tstateCh := make(chan streamState, 10)\n\ts.stateChange[stateCh] = struct{}{}\n\ts.mu.Unlock()\n\n\tdefer func() {\n\t\ts.mu.Lock()\n\t\tdelete(s.stateChange, stateCh)\n\t}()\n\n\tstate := <-stateCh\n\tif state == target {\n\t\treturn nil\n\t} else {\n\t\treturn fmt.Errorf(\"Stream %d went to bad state: %d\", s.id, state)\n\t}\n}\n<commit_msg>packer\/rpc: Clean up old streams [GH-708]<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\tdoneCh  chan struct{}\n}\n\ntype muxPacketType byte\n\nconst (\n\tmuxPacketSyn muxPacketType = iota\n\tmuxPacketSynAck\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\tdoneCh:  make(chan struct{}),\n\t}\n\n\tgo m.cleaner()\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\tdefer stream.mu.Unlock()\n\tif stream.state != streamStateSynRecv && stream.state != streamStateClosed {\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\tif stream.state == streamStateClosed {\n\t\t\/\/ Go into the listening state and wait for a syn\n\t\tstream.setState(streamStateListen)\n\t\tif err := stream.waitState(streamStateSynRecv); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif stream.state == streamStateSynRecv {\n\t\t\/\/ Send a syn-ack\n\t\tif _, err := m.write(stream.id, muxPacketSynAck, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif err := stream.waitState(streamStateEstablished); 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\tdefer stream.mu.Unlock()\n\tif stream.state != streamStateClosed {\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\tif err := stream.waitState(streamStateEstablished); err != nil {\n\t\treturn nil, err\n\t}\n\n\tm.write(id, muxPacketAck, nil)\n\treturn stream, nil\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\/\/ Make sure we attempt to use the next biggest stream ID\n\tif id >= m.curId {\n\t\tm.curId = id + 1\n\t}\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) cleaner() {\n\tfor {\n\t\tdone := false\n\t\tselect {\n\t\tcase <-time.After(500 * time.Millisecond):\n\t\tcase <-m.doneCh:\n\t\t\tdone = true\n\t\t}\n\n\t\tm.mu.Lock()\n\t\tfor id, s := range m.streams {\n\t\t\ts.mu.Lock()\n\t\t\tif s.state == streamStateClosed {\n\t\t\t\tdelete(m.streams, id)\n\t\t\t}\n\t\t\ts.mu.Unlock()\n\t\t}\n\n\t\tif done {\n\t\t\tfor _, s := range m.streams {\n\t\t\t\ts.mu.Lock()\n\t\t\t\ts.closeWriter()\n\t\t\t\ts.mu.Unlock()\n\t\t\t}\n\t\t}\n\t\tm.mu.Unlock()\n\n\t\tif done {\n\t\t\treturn\n\t\t}\n\t}\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\tlog.Printf(\"[INFO] Mux connection loop exiting\")\n\t\tclose(m.doneCh)\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\tlog.Printf(\"[TRACE] Stream %d received packet %d\", id, packetType)\n\t\tswitch packetType {\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\tfallthrough\n\t\t\tcase streamStateListen:\n\t\t\t\tstream.setState(streamStateSynRecv)\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 muxPacketAck:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateSynRecv:\n\t\t\t\tstream.setState(streamStateEstablished)\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tstream.setState(streamStateFinWait2)\n\t\t\tcase streamStateLastAck:\n\t\t\t\tstream.closeWriter()\n\t\t\t\tfallthrough\n\t\t\tcase streamStateClosing:\n\t\t\t\tstream.setState(streamStateClosed)\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 muxPacketSynAck:\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\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] SynAck 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.closeWriter()\n\t\t\t\tstream.setState(streamStateCloseWait)\n\t\t\t\tm.write(id, muxPacketAck, nil)\n\t\t\tcase streamStateFinWait2:\n\t\t\t\tstream.closeWriter()\n\t\t\t\tstream.setState(streamStateClosed)\n\t\t\t\tm.write(id, muxPacketAck, nil)\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tstream.closeWriter()\n\t\t\t\tstream.setState(streamStateClosing)\n\t\t\t\tm.write(id, muxPacketAck, nil)\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\tswitch stream.state {\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tfallthrough\n\t\t\tcase streamStateFinWait2:\n\t\t\t\tfallthrough\n\t\t\tcase 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\tdefault:\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\tstreamStateClosing\n\tstreamStateLastAck\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.setState(streamStateLastAck)\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 && state != streamStateCloseWait {\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) closeWriter() {\n\ts.writeCh <- nil\n}\n\nfunc (s *Stream) setState(state streamState) {\n\tlog.Printf(\"[TRACE] Stream %d went to state %d\", s.id, state)\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\nfunc (s *Stream) waitState(target streamState) error {\n\t\/\/ Register a state change listener to wait for changes\n\tstateCh := make(chan streamState, 10)\n\ts.stateChange[stateCh] = struct{}{}\n\ts.mu.Unlock()\n\n\tdefer func() {\n\t\ts.mu.Lock()\n\t\tdelete(s.stateChange, stateCh)\n\t}()\n\n\tstate := <-stateCh\n\tif state == target {\n\t\treturn nil\n\t} else {\n\t\treturn fmt.Errorf(\"Stream %d went to bad state: %d\", s.id, state)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gleam\n\nimport (\n\t\"crypto\/tls\"\n\t\"log\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n\n\tmqtt \"github.com\/eclipse\/paho.mqtt.golang\"\n\t\"github.com\/mikespook\/golib\/signal\"\n\t\"github.com\/mikespook\/schego\"\n)\n\ntype Gleam struct {\n\tlua        *luaEnv\n\tconfig     Config\n\tmqttClient mqtt.Client\n\tscheduler  *schego.Scheduler\n}\n\nfunc NewGleam(workdir string) *Gleam {\n\treturn &Gleam{\n\t\tlua: newLuaEnv(workdir),\n\t}\n}\n\nfunc (g *Gleam) Init() error {\n\tif err := g.lua.Init(&g.config); err != nil {\n\t\treturn err\n\t}\n\n\tg.initMQTT()\n\tg.initSchedule(&g.config)\n\n\treturn g.lua.onEvent(AfterInitFunc, g.mqttClient)\n}\n\nfunc (g *Gleam) initSchedule(config *Config) {\n\tg.scheduler = schego.New(config.Schedule.Tick * time.Millisecond)\n\tg.scheduler.ErrorFunc = g.lua.onError\n\tfor name, interval := range config.Schedule.Tasks {\n\t\tf := g.lua.newOnSchedule(name, &g.mqttClient)\n\t\tg.scheduler.Add(name, time.Now(), interval*time.Millisecond, schego.ForEver, f)\n\t\tfn := \"Skip\"\n\t\tif f != nil {\n\t\t\tfn = \"Serve\"\n\t\t}\n\t\tlog.Printf(\"Schedule: %s (%d) => %s\", name, interval, fn)\n\t}\n}\n\nfunc (g *Gleam) initMQTT() {\n\topts := mqtt.NewClientOptions()\n\tfor _, broker := range g.config.MQTT {\n\t\topts.AddBroker(broker.Addr)\n\t\tlog.Printf(\"Add Broker: %s@%s\", broker.Username, broker.Addr)\n\t\tif broker.Username != \"\" {\n\t\t\topts.SetUsername(broker.Username).SetPassword(broker.Password)\n\t\t}\n\t}\n\topts.SetClientID(g.config.ClientId)\n\tlog.Printf(\"ClientId: %s\", g.config.ClientId)\n\topts.SetDefaultPublishHandler(g.lua.newOnMessage(MessageFunc))\n\topts.SetAutoReconnect(true)\n\tif g.config.NotVerifyTLS {\n\t\topts.SetTLSConfig(&tls.Config{InsecureSkipVerify: true})\n\t}\n\topts.SetOnConnectHandler(g.newOnConnect())\n\topts.SetConnectionLostHandler(g.newOnLostConnect())\n\tg.mqttClient = mqtt.NewClient(opts)\n\tfor {\n\t\ttoken := g.mqttClient.Connect()\n\t\tif !token.Wait() || token.Error() == nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"Conn Error: %s\", token.Error())\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\nfunc (g *Gleam) newOnConnect() mqtt.OnConnectHandler {\n\treturn func(client mqtt.Client) {\n\t\tfor name, task := range g.config.Tasks {\n\t\t\tfor topic, qos := range task {\n\t\t\t\tf := g.lua.newOnMessage(name)\n\t\t\t\tif f == nil {\n\t\t\t\t\tname = \"{default}\"\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Subscribe: %s (%d) => %s\", topic, qos, name)\n\t\t\t\tif token := client.Subscribe(topic, qos, f); token.Wait() && token.Error() != nil {\n\t\t\t\t\tlog.Printf(\"Subscribe Error: %s %s\", topic, token.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (g *Gleam) newOnLostConnect() mqtt.ConnectionLostHandler {\n\treturn func(client mqtt.Client, err error) {\n\t\tlog.Printf(\"Conn Error: %s\", err)\n\t}\n}\n\nfunc (g *Gleam) Serve() {\n\tgo g.scheduler.Serve()\n\n\tsh := signal.New(nil)\n\tsh.Bind(os.Interrupt, func() uint {\n\t\treturn signal.BreakExit\n\t})\n\tsh.Bind(syscall.SIGTERM, func() uint {\n\t\treturn signal.BreakExit\n\t})\n\tsh.Wait()\n}\n\nfunc (g *Gleam) Final() error {\n\tif err := g.scheduler.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tfor topic, _ := range g.config.Tasks {\n\t\tif token := g.mqttClient.Unsubscribe(topic); token.Wait() && token.Error() != nil {\n\t\t\tlog.Printf(\"Unsubscribe error: %s => [%s]\", topic, token.Error())\n\t\t}\n\t\tlog.Printf(\"Unsubscribe: %s\", topic)\n\t}\n\n\tif err := g.lua.onEvent(BeforeFinalizeFunc, g.mqttClient); err != nil {\n\t\tlog.Printf(\"BeforeFinalize: %s\", err)\n\t}\n\tif g.config.FinalTick != 0 {\n\t\ttime.Sleep(g.config.FinalTick * time.Millisecond)\n\t}\n\tg.mqttClient.Disconnect(500)\n\tg.lua.Final()\n\treturn nil\n}\n<commit_msg>fixed nil object method call<commit_after>package gleam\n\nimport (\n\t\"crypto\/tls\"\n\t\"log\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n\n\tmqtt \"github.com\/eclipse\/paho.mqtt.golang\"\n\t\"github.com\/mikespook\/golib\/signal\"\n\t\"github.com\/mikespook\/schego\"\n)\n\ntype Gleam struct {\n\tlua        *luaEnv\n\tconfig     Config\n\tmqttClient mqtt.Client\n\tscheduler  *schego.Scheduler\n}\n\nfunc NewGleam(workdir string) *Gleam {\n\treturn &Gleam{\n\t\tlua: newLuaEnv(workdir),\n\t}\n}\n\nfunc (g *Gleam) Init() error {\n\tif err := g.lua.Init(&g.config); err != nil {\n\t\treturn err\n\t}\n\n\tg.initMQTT()\n\tg.initSchedule()\n\n\treturn g.lua.onEvent(AfterInitFunc, g.mqttClient)\n}\n\nfunc (g *Gleam) initSchedule() {\n\tif g.config.Schedule.Tick == 0 {\n\t\tlog.Printf(\"Scheduler not init\")\n\t\treturn\n\t}\n\tg.scheduler = schego.New(g.config.Schedule.Tick * time.Millisecond)\n\tg.scheduler.ErrorFunc = g.lua.onError\n\tfor name, interval := range g.config.Schedule.Tasks {\n\t\tf := g.lua.newOnSchedule(name, &g.mqttClient)\n\t\tg.scheduler.Add(name, time.Now(), interval*time.Millisecond, schego.ForEver, f)\n\t\tfn := \"Skip\"\n\t\tif f != nil {\n\t\t\tfn = \"Serve\"\n\t\t}\n\t\tlog.Printf(\"Schedule: %s (%d) => %s\", name, interval, fn)\n\t}\n}\n\nfunc (g *Gleam) initMQTT() {\n\tif g.config.ClientId == \"\" {\n\t\tlog.Printf(\"MQTT not init\")\n\t\treturn\n\t}\n\n\topts := mqtt.NewClientOptions()\n\tfor _, broker := range g.config.MQTT {\n\t\topts.AddBroker(broker.Addr)\n\t\tlog.Printf(\"Add Broker: %s@%s\", broker.Username, broker.Addr)\n\t\tif broker.Username != \"\" {\n\t\t\topts.SetUsername(broker.Username).SetPassword(broker.Password)\n\t\t}\n\t}\n\topts.SetClientID(g.config.ClientId)\n\tlog.Printf(\"ClientId: %s\", g.config.ClientId)\n\topts.SetDefaultPublishHandler(g.lua.newOnMessage(MessageFunc))\n\topts.SetAutoReconnect(true)\n\tif g.config.NotVerifyTLS {\n\t\topts.SetTLSConfig(&tls.Config{InsecureSkipVerify: true})\n\t}\n\topts.SetOnConnectHandler(g.newOnConnect())\n\topts.SetConnectionLostHandler(g.newOnLostConnect())\n\tg.mqttClient = mqtt.NewClient(opts)\n\tfor {\n\t\ttoken := g.mqttClient.Connect()\n\t\tif !token.Wait() || token.Error() == nil {\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"Conn Error: %s\", token.Error())\n\t\ttime.Sleep(5 * time.Second)\n\t}\n}\n\nfunc (g *Gleam) newOnConnect() mqtt.OnConnectHandler {\n\treturn func(client mqtt.Client) {\n\t\tfor name, task := range g.config.Tasks {\n\t\t\tfor topic, qos := range task {\n\t\t\t\tf := g.lua.newOnMessage(name)\n\t\t\t\tif f == nil {\n\t\t\t\t\tname = \"{default}\"\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Subscribe: %s (%d) => %s\", topic, qos, name)\n\t\t\t\tif token := client.Subscribe(topic, qos, f); token.Wait() && token.Error() != nil {\n\t\t\t\t\tlog.Printf(\"Subscribe Error: %s %s\", topic, token.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (g *Gleam) newOnLostConnect() mqtt.ConnectionLostHandler {\n\treturn func(client mqtt.Client, err error) {\n\t\tlog.Printf(\"Conn Error: %s\", err)\n\t}\n}\n\nfunc (g *Gleam) Serve() {\n\tif g.scheduler != nil {\n\t\tgo g.scheduler.Serve()\n\t}\n\n\tsh := signal.New(nil)\n\tsh.Bind(os.Interrupt, func() uint {\n\t\treturn signal.BreakExit\n\t})\n\tsh.Bind(syscall.SIGTERM, func() uint {\n\t\treturn signal.BreakExit\n\t})\n\tsh.Wait()\n}\n\nfunc (g *Gleam) Final() error {\n\tif g.scheduler != nil {\n\t\tif err := g.scheduler.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor topic, _ := range g.config.Tasks {\n\t\tif token := g.mqttClient.Unsubscribe(topic); token.Wait() && token.Error() != nil {\n\t\t\tlog.Printf(\"Unsubscribe error: %s => [%s]\", topic, token.Error())\n\t\t}\n\t\tlog.Printf(\"Unsubscribe: %s\", topic)\n\t}\n\n\tif err := g.lua.onEvent(BeforeFinalizeFunc, g.mqttClient); err != nil {\n\t\tlog.Printf(\"BeforeFinalize: %s\", err)\n\t}\n\tif g.config.FinalTick != 0 {\n\t\ttime.Sleep(g.config.FinalTick * time.Millisecond)\n\t}\n\tif g.mqttClient != nil {\n\t\tg.mqttClient.Disconnect(500)\n\t}\n\tg.lua.Final()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package mongo\n\nimport (\n\tl \"logger\"\n\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nfunc PostLoginPageData(loginInfo *PostLogin) (*LoginStatus, error) {\n\n\tl.PutInfo(l.I_M_PostPage, loginInfo, nil)\n\n\t_, ok := users[loginInfo.UserId]\n\tif ok {\n\t\tvar teamName string\n\t\tfor _, team := range teams {\n\t\t\tfor _, userid := range team.UserIds {\n\t\t\t\tif userid == loginInfo.UserId {\n\t\t\t\t\tteamName = team.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User ID\":   loginInfo.UserId,\n\t\t\t\t\"User Name\": users[loginInfo.UserId].Name,\n\t\t\t},\n\t\t\t\"login success\",\n\t\t\tl.Debug,\n\t\t)\n\t\tloginStatus := &LoginStatus{\n\t\t\tStatus:   \"success\",\n\t\t\tUserId:   loginInfo.UserId,\n\t\t\tUserName: users[loginInfo.UserId].Name,\n\t\t\tTeam:     teamName,\n\t\t\tAdmin:    players[loginInfo.UserId].Admin,\n\t\t}\n\t\treturn loginStatus, nil\n\t} else {\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User ID\": loginInfo.UserId,\n\t\t\t},\n\t\t\t\"login faild\",\n\t\t\tl.Debug,\n\t\t)\n\t\treturn &LoginStatus{Status: \"failed\"}, nil\n\t}\n}\n\nfunc PostApplyScoreData(teamName string, ApplyScore *PostApplyScore) (*Status, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, ApplyScore)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetPlayerCol(ApplyScore.UserIds)\n\n\tAUserIdInTheTeam := teams[teamName].UserIds[0]\n\tif players[AUserIdInTheTeam].Apply != 0 {\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User Apply\": players[AUserIdInTheTeam].Apply,\n\t\t\t},\n\t\t\t\"Apply score is already registered\",\n\t\t\tl.Debug,\n\t\t)\n\t\treturn &Status{\"already registered\"}, nil\n\t}\n\tfor playerIndex, userId := range ApplyScore.UserIds {\n\n\t\tfindQuery := bson.M{\"userid\": userId}\n\t\tsetQuery := bson.M{\"$set\": bson.M{\"apply\": ApplyScore.Apply[playerIndex]}}\n\t\tif err = UpdateMongoData(\"player\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, ApplyScore.Apply[playerIndex])\n\t\t\treturn &Status{\"failed\"}, err\n\t\t}\n\t}\n\n\treturn &Status{\"success\"}, nil\n}\n\nfunc PostScoreViewSheetPageData(teamName string, definedTeam *PostDefinedTeam) (*Status, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, definedTeam)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetTeamCol(teamName)\n\n\tfindQuery := bson.M{\"name\": teamName}\n\tsetQuery := bson.M{\"$set\": bson.M{\"defined\": true}}\n\tif err = UpdateMongoData(\"team\", findQuery, setQuery); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Update, teamName)\n\t\treturn &Status{\"failed\"}, err\n\t}\n\n\treturn &Status{\"success\"}, nil\n}\n\nfunc PostScoreEntrySheetPageData(teamName string, holeString string, teamScore *PostTeamScore) (*RequestTakePictureStatus, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, teamScore)\n\n\tuserIds := teams[teamName].UserIds\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetPlayerCol(userIds)\n\n\tif len(holeString) == 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_Nil, teamName)\n\t\treturn &RequestTakePictureStatus{Status: \"failed\"}, errors.New(\"hole is not string\")\n\t}\n\n\tholeNum, _ := strconv.Atoi(holeString)\n\tholeIndex := holeNum - 1\n\tholeIndexString := strconv.Itoa(holeIndex)\n\n\tif teamScore.Excnt != excnt[teamName][holeNum] {\n\t\treturn &RequestTakePictureStatus{Status: \"other updated\"}, nil\n\t} else {\n\t\texcnt[teamName][holeNum]++\n\t}\n\n\tfor playerIndex, userId := range teamScore.UserIds {\n\t\ttotal, putt := teamScore.Total[playerIndex], teamScore.Putt[playerIndex]\n\n\t\tfindQuery := bson.M{\"userid\": userId}\n\t\tsetQuery := bson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\t\"score.\" + holeIndexString + \".total\": total,\n\t\t\t\t\"score.\" + holeIndexString + \".putt\":  putt,\n\t\t\t},\n\t\t}\n\t\tif err = UpdateMongoData(\"player\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, userId)\n\t\t\treturn &RequestTakePictureStatus{Status: \"failed update score\"}, err\n\t\t}\n\t}\n\t\/\/\tThread登録\n\tif err := RegisterThreadOfScore(holeString, teamScore); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_RegisterThread, teamScore)\n\t\treturn nil, err\n\t}\n\n\t\/\/\tチーム内に写真リクエストがあるか確認する\n\trequestTakePictureStatus, err := RequestTakePicture(userIds)\n\tif err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_SearchPhotoTask, userIds)\n\t\treturn nil, err\n\t}\n\n\treturn requestTakePictureStatus, nil\n}\n\nfunc UpsertNewTimeLine(thread *Thread) error {\n\tl.PutInfo(l.I_M_PostPage, thread, nil)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetAllThreadCol()\n\n\tdefaultColor := \"#c0c0c0\"\n\n\tif len(thread.ThreadId) != 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_WrongData, thread)\n\t\treturn errors.New(\"thread id exists\")\n\t}\n\n\tdb, session := mongoInit()\n\tthreadCol := db.C(\"thread\")\n\tdefer session.Close()\n\n\tthread.ThreadId = make20lengthHashString()\n\tthread.CreatedAt = time.Now().Format(datetimeFormat)\n\tthread.ColorCode = defaultColor\n\tif err = threadCol.Insert(thread); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Insert, thread)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc UpdateExistingTimeLine(thread *Thread) (*Thread, error) {\n\tl.PutInfo(l.I_M_PostPage, thread, nil)\n\n\ttargetThreadId := thread.ThreadId\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetAllThreadCol()\n\n\tcolorFeeling := make(map[string]string)\n\tcolorFeeling[\"default\"] = \"#c0c0c0\"\n\tcolorFeeling[\"angry\"] = \"#ff7f7f\"\n\tcolorFeeling[\"great\"] = \"#ffff7f\"\n\tcolorFeeling[\"sad\"] = \"#7fbfff\"\n\tcolorFeeling[\"vexing\"] = \"#7fff7f\"\n\n\tif len(targetThreadId) == 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_Nil, thread)\n\t\treturn nil, errors.New(\"thread id do not exist\")\n\t}\n\n\tif len(thread.ColorCode) == 0 {\n\t\tl.PutErr(err, l.Trace(), l.E_Nil, thread.ColorCode)\n\t\treturn nil, errors.New(\"current colorCode do not contain in posted thread\")\n\t}\n\tif len(thread.Reactions) > 1 {\n\t\tl.PutErr(err, l.Trace(), l.E_TooManyData, thread.Reactions)\n\t\treturn nil, errors.New(\"reactions is not 1\")\n\t}\n\n\tcurrentFeeling := \"\"\n\tcurrentColor := threads[targetThreadId].ColorCode\n\tpostedFeeling := getFeelingFromAWSUrl(thread.Reactions[0].Content)\n\tpostedColor := colorFeeling[postedFeeling]\n\n\tfor feeling, code := range colorFeeling {\n\t\tif currentColor == code {\n\t\t\tcurrentFeeling = feeling\n\t\t}\n\t}\n\n\tthread.Reactions[0].DateTime = time.Now().Format(datetimeFormat)\n\tfindQuery := bson.M{\"threadid\": targetThreadId}\n\tpushQuery := bson.M{\"$push\": bson.M{\"reactions\": thread.Reactions[0]}}\n\tif err = UpdateMongoData(\"thread\", findQuery, pushQuery); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Update, thread.Reactions[0])\n\t\treturn nil, err\n\t}\n\n\t\/\/投稿された感情と、現在の感情に相違がある場合\n\tif currentFeeling != postedFeeling {\n\t\tvar setColor string\n\t\tvar currentFeelingCount, postedFeelingCount int\n\n\t\tif currentColor == colorFeeling[\"default\"] {\n\t\t\tsetColor = postedColor\n\t\t} else {\n\n\t\t\t\/\/直前の更新を反映させる\n\t\t\tSetAllThreadCol()\n\n\t\t\tfor _, r := range threads[targetThreadId].Reactions {\n\t\t\t\tswitch getFeelingFromAWSUrl(r[\"content\"].(string)) {\n\t\t\t\tcase currentFeeling:\n\t\t\t\t\tcurrentFeelingCount++\n\t\t\t\tcase postedFeeling:\n\t\t\t\t\tpostedFeelingCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif currentFeelingCount >= postedFeelingCount {\n\t\t\t\tsetColor = currentColor\n\t\t\t} else {\n\t\t\t\tsetColor = postedColor\n\t\t\t}\n\t\t}\n\n\t\tsetQuery := bson.M{\"$set\": bson.M{\"colorcode\": setColor}}\n\n\t\tif err = UpdateMongoData(\"thread\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, setColor)\n\t\t\treturn nil, err\n\t\t}\n\t\tthread.ColorCode = setColor\n\t}\n\treturn thread, nil\n}\n<commit_msg>new thread push<commit_after>package mongo\n\nimport (\n\tl \"logger\"\n\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nfunc PostLoginPageData(loginInfo *PostLogin) (*LoginStatus, error) {\n\n\tl.PutInfo(l.I_M_PostPage, loginInfo, nil)\n\n\t_, ok := users[loginInfo.UserId]\n\tif ok {\n\t\tvar teamName string\n\t\tfor _, team := range teams {\n\t\t\tfor _, userid := range team.UserIds {\n\t\t\t\tif userid == loginInfo.UserId {\n\t\t\t\t\tteamName = team.Name\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User ID\":   loginInfo.UserId,\n\t\t\t\t\"User Name\": users[loginInfo.UserId].Name,\n\t\t\t},\n\t\t\t\"login success\",\n\t\t\tl.Debug,\n\t\t)\n\t\tloginStatus := &LoginStatus{\n\t\t\tStatus:   \"success\",\n\t\t\tUserId:   loginInfo.UserId,\n\t\t\tUserName: users[loginInfo.UserId].Name,\n\t\t\tTeam:     teamName,\n\t\t\tAdmin:    players[loginInfo.UserId].Admin,\n\t\t}\n\t\treturn loginStatus, nil\n\t} else {\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User ID\": loginInfo.UserId,\n\t\t\t},\n\t\t\t\"login faild\",\n\t\t\tl.Debug,\n\t\t)\n\t\treturn &LoginStatus{Status: \"failed\"}, nil\n\t}\n}\n\nfunc PostApplyScoreData(teamName string, ApplyScore *PostApplyScore) (*Status, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, ApplyScore)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetPlayerCol(ApplyScore.UserIds)\n\n\tAUserIdInTheTeam := teams[teamName].UserIds[0]\n\tif players[AUserIdInTheTeam].Apply != 0 {\n\t\tl.Output(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"User Apply\": players[AUserIdInTheTeam].Apply,\n\t\t\t},\n\t\t\t\"Apply score is already registered\",\n\t\t\tl.Debug,\n\t\t)\n\t\treturn &Status{\"already registered\"}, nil\n\t}\n\tfor playerIndex, userId := range ApplyScore.UserIds {\n\n\t\tfindQuery := bson.M{\"userid\": userId}\n\t\tsetQuery := bson.M{\"$set\": bson.M{\"apply\": ApplyScore.Apply[playerIndex]}}\n\t\tif err = UpdateMongoData(\"player\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, ApplyScore.Apply[playerIndex])\n\t\t\treturn &Status{\"failed\"}, err\n\t\t}\n\t}\n\n\treturn &Status{\"success\"}, nil\n}\n\nfunc PostScoreViewSheetPageData(teamName string, definedTeam *PostDefinedTeam) (*Status, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, definedTeam)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetTeamCol(teamName)\n\n\tfindQuery := bson.M{\"name\": teamName}\n\tsetQuery := bson.M{\"$set\": bson.M{\"defined\": true}}\n\tif err = UpdateMongoData(\"team\", findQuery, setQuery); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Update, teamName)\n\t\treturn &Status{\"failed\"}, err\n\t}\n\n\treturn &Status{\"success\"}, nil\n}\n\nfunc PostScoreEntrySheetPageData(teamName string, holeString string, teamScore *PostTeamScore) (*RequestTakePictureStatus, error) {\n\tl.PutInfo(l.I_M_PostPage, teamName, teamScore)\n\n\tuserIds := teams[teamName].UserIds\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetPlayerCol(userIds)\n\n\tif len(holeString) == 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_Nil, teamName)\n\t\treturn &RequestTakePictureStatus{Status: \"failed\"}, errors.New(\"hole is not string\")\n\t}\n\n\tholeNum, _ := strconv.Atoi(holeString)\n\tholeIndex := holeNum - 1\n\tholeIndexString := strconv.Itoa(holeIndex)\n\n\tif teamScore.Excnt != excnt[teamName][holeNum] {\n\t\treturn &RequestTakePictureStatus{Status: \"other updated\"}, nil\n\t} else {\n\t\texcnt[teamName][holeNum]++\n\t}\n\n\tfor playerIndex, userId := range teamScore.UserIds {\n\t\ttotal, putt := teamScore.Total[playerIndex], teamScore.Putt[playerIndex]\n\n\t\tfindQuery := bson.M{\"userid\": userId}\n\t\tsetQuery := bson.M{\n\t\t\t\"$set\": bson.M{\n\t\t\t\t\"score.\" + holeIndexString + \".total\": total,\n\t\t\t\t\"score.\" + holeIndexString + \".putt\":  putt,\n\t\t\t},\n\t\t}\n\t\tif err = UpdateMongoData(\"player\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, userId)\n\t\t\treturn &RequestTakePictureStatus{Status: \"failed update score\"}, err\n\t\t}\n\t}\n\t\/\/\tThread登録\n\tif err := RegisterThreadOfScore(holeString, teamScore); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_RegisterThread, teamScore)\n\t\treturn nil, err\n\t}\n\n\t\/\/\tチーム内に写真リクエストがあるか確認する\n\trequestTakePictureStatus, err := RequestTakePicture(userIds)\n\tif err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_SearchPhotoTask, userIds)\n\t\treturn nil, err\n\t}\n\n\treturn requestTakePictureStatus, nil\n}\n\nfunc UpsertNewTimeLine(thread *Thread) error {\n\tl.PutInfo(l.I_M_PostPage, thread, nil)\n\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetAllThreadCol()\n\n\tdefaultColor := \"#c0c0c0\"\n\n\tif len(thread.ThreadId) != 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_WrongData, thread)\n\t\treturn errors.New(\"thread id exists\")\n\t}\n\n\tdb, session := mongoInit()\n\tthreadCol := db.C(\"thread\")\n\tdefer session.Close()\n\n\tthread.ThreadId = make20lengthHashString()\n\tthread.CreatedAt = time.Now().Format(datetimeFormat)\n\tthread.ColorCode = defaultColor\n\tif err = threadCol.Insert(thread); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Insert, thread)\n\t\treturn err\n\t}\n\n\tThreadChan <- thread\n\n\treturn nil\n}\n\nfunc UpdateExistingTimeLine(thread *Thread) (*Thread, error) {\n\tl.PutInfo(l.I_M_PostPage, thread, nil)\n\n\ttargetThreadId := thread.ThreadId\n\t\/\/更新情報をGlobal変数に格納する\n\tdefer SetAllThreadCol()\n\n\tcolorFeeling := make(map[string]string)\n\tcolorFeeling[\"default\"] = \"#c0c0c0\"\n\tcolorFeeling[\"angry\"] = \"#ff7f7f\"\n\tcolorFeeling[\"great\"] = \"#ffff7f\"\n\tcolorFeeling[\"sad\"] = \"#7fbfff\"\n\tcolorFeeling[\"vexing\"] = \"#7fff7f\"\n\n\tif len(targetThreadId) == 0 {\n\t\tl.PutErr(nil, l.Trace(), l.E_Nil, thread)\n\t\treturn nil, errors.New(\"thread id do not exist\")\n\t}\n\n\tif len(thread.ColorCode) == 0 {\n\t\tl.PutErr(err, l.Trace(), l.E_Nil, thread.ColorCode)\n\t\treturn nil, errors.New(\"current colorCode do not contain in posted thread\")\n\t}\n\tif len(thread.Reactions) > 1 {\n\t\tl.PutErr(err, l.Trace(), l.E_TooManyData, thread.Reactions)\n\t\treturn nil, errors.New(\"reactions is not 1\")\n\t}\n\n\tcurrentFeeling := \"\"\n\tcurrentColor := threads[targetThreadId].ColorCode\n\tpostedFeeling := getFeelingFromAWSUrl(thread.Reactions[0].Content)\n\tpostedColor := colorFeeling[postedFeeling]\n\n\tfor feeling, code := range colorFeeling {\n\t\tif currentColor == code {\n\t\t\tcurrentFeeling = feeling\n\t\t}\n\t}\n\n\tthread.Reactions[0].DateTime = time.Now().Format(datetimeFormat)\n\tfindQuery := bson.M{\"threadid\": targetThreadId}\n\tpushQuery := bson.M{\"$push\": bson.M{\"reactions\": thread.Reactions[0]}}\n\tif err = UpdateMongoData(\"thread\", findQuery, pushQuery); err != nil {\n\t\tl.PutErr(err, l.Trace(), l.E_M_Update, thread.Reactions[0])\n\t\treturn nil, err\n\t}\n\n\t\/\/投稿された感情と、現在の感情に相違がある場合\n\tif currentFeeling != postedFeeling {\n\t\tvar setColor string\n\t\tvar currentFeelingCount, postedFeelingCount int\n\n\t\tif currentColor == colorFeeling[\"default\"] {\n\t\t\tsetColor = postedColor\n\t\t} else {\n\n\t\t\t\/\/直前の更新を反映させる\n\t\t\tSetAllThreadCol()\n\n\t\t\tfor _, r := range threads[targetThreadId].Reactions {\n\t\t\t\tswitch getFeelingFromAWSUrl(r[\"content\"].(string)) {\n\t\t\t\tcase currentFeeling:\n\t\t\t\t\tcurrentFeelingCount++\n\t\t\t\tcase postedFeeling:\n\t\t\t\t\tpostedFeelingCount++\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif currentFeelingCount >= postedFeelingCount {\n\t\t\t\tsetColor = currentColor\n\t\t\t} else {\n\t\t\t\tsetColor = postedColor\n\t\t\t}\n\t\t}\n\n\t\tsetQuery := bson.M{\"$set\": bson.M{\"colorcode\": setColor}}\n\n\t\tif err = UpdateMongoData(\"thread\", findQuery, setQuery); err != nil {\n\t\t\tl.PutErr(err, l.Trace(), l.E_M_Update, setColor)\n\t\t\treturn nil, err\n\t\t}\n\t\tthread.ColorCode = setColor\n\t}\n\treturn thread, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package metrics\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ InmemSink provides a MetricSink that does in-memory aggregation\n\/\/ without sending metrics over a network. It can be embedded within\n\/\/ an application to provide profiling information.\ntype InmemSink struct {\n\t\/\/ How long is each aggregation interval\n\tinterval time.Duration\n\n\t\/\/ Retain controls how many metrics interval we keep\n\tretain time.Duration\n\n\t\/\/ maxIntervals is the maximum length of intervals.\n\t\/\/ It is retain \/ interval.\n\tmaxIntervals int\n\n\t\/\/ intervals is a slice of the retained intervals\n\tintervals    []*IntervalMetrics\n\tintervalLock sync.RWMutex\n\t\n\trateDenom float64\n}\n\n\/\/ IntervalMetrics stores the aggregated metrics\n\/\/ for a specific interval\ntype IntervalMetrics struct {\n\tsync.RWMutex\n\n\t\/\/ The start time of the interval\n\tInterval time.Time\nr\n\t\/\/ Gauges maps the key to the last set value\n\tGauges map[string]float32\n\n\t\/\/ Points maps the string to the list of emitted values\n\t\/\/ from EmitKey\n\tPoints map[string][]float32\n\n\t\/\/ Counters maps the string key to a sum of the counter\n\t\/\/ values\n\tCounters map[string]*AggregateSample\n\n\t\/\/ Samples maps the key to an AggregateSample,\n\t\/\/ which has the rolled up view of a sample\n\tSamples map[string]*AggregateSample\n}\n\n\/\/ NewIntervalMetrics creates a new IntervalMetrics for a given interval\nfunc NewIntervalMetrics(intv time.Time) *IntervalMetrics {\n\treturn &IntervalMetrics{\n\t\tInterval: intv,\n\t\tGauges:   make(map[string]float32),\n\t\tPoints:   make(map[string][]float32),\n\t\tCounters: make(map[string]*AggregateSample),\n\t\tSamples:  make(map[string]*AggregateSample),\n\t}\n}\n\n\/\/ AggregateSample is used to hold aggregate metrics\n\/\/ about a sample\ntype AggregateSample struct {\n\tCount       int       \/\/ The count of emitted pairs\n\tRate\t        float64   \/\/ The count of emitted pairs per time unit (usually 1 second)\n\tSum         float64   \/\/ The sum of values\n\tSumSq       float64   \/\/ The sum of squared values\n\tMin         float64   \/\/ Minimum value\n\tMax         float64   \/\/ Maximum value\n\tLastUpdated time.Time \/\/ When value was last updated\n}\n\n\/\/ Computes a Stddev of the values\nfunc (a *AggregateSample) Stddev() float64 {\n\tnum := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)\n\tdiv := float64(a.Count * (a.Count - 1))\n\tif div == 0 {\n\t\treturn 0\n\t}\n\treturn math.Sqrt(num \/ div)\n}\n\n\/\/ Computes a mean of the values\nfunc (a *AggregateSample) Mean() float64 {\n\tif a.Count == 0 {\n\t\treturn 0\n\t}\n\treturn a.Sum \/ float64(a.Count)\n}\n\n\/\/ Ingest is used to update a sample\nfunc (a *AggregateSample) Ingest(v float64, rateDenom float64) {\n\ta.Count++\n\ta.Sum += v\n\ta.SumSq += (v * v)\n\tif v < a.Min || a.Count == 1 {\n\t\ta.Min = v\n\t}\n\tif v > a.Max || a.Count == 1 {\n\t\ta.Max = v\n\t}\n\ta.Rate = float64(a.Count)\/rateDenom\n\ta.LastUpdated = time.Now()\n}\n\nfunc (a *AggregateSample) String() string {\n\tif a.Count == 0 {\n\t\treturn \"Count: 0\"\n\t} else if a.Stddev() == 0 {\n\t\treturn fmt.Sprintf(\"Count: %d Sum: %0.3f LastUpdated: %s\", a.Count, a.Sum, a.LastUpdated)\n\t} else {\n\t\treturn fmt.Sprintf(\"Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s\",\n\t\t\ta.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated)\n\t}\n}\n\n\/\/ NewInmemSink is used to construct a new in-memory sink.\n\/\/ Uses an aggregation interval and maximum retention period.\nfunc NewInmemSink(interval, retain time.Duration) *InmemSink {\n\trateTimeUnit := time.Second\n\ti := &InmemSink{\n\t\tinterval:     interval,\n\t\tretain:       retain,\n\t\tmaxIntervals: int(retain \/ interval),\n\t\trateDenom: float64(interval.Nanoseconds()) \/ float64(rateTimeUnit.Nanoseconds()),\n\t}\n\ti.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)\n\treturn i\n}\n\nfunc (i *InmemSink) SetGauge(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\tintv.Gauges[k] = val\n}\n\nfunc (i *InmemSink) EmitKey(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\tvals := intv.Points[k]\n\tintv.Points[k] = append(vals, val)\n}\n\nfunc (i *InmemSink) IncrCounter(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\n\tagg := intv.Counters[k]\n\tif agg == nil {\n\t\tagg = &AggregateSample{}\n\t\tintv.Counters[k] = agg\n\t}\n\tagg.Ingest(float64(val), i.rateDenom)\n}\n\nfunc (i *InmemSink) AddSample(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\n\tagg := intv.Samples[k]\n\tif agg == nil {\n\t\tagg = &AggregateSample{}\n\t\tintv.Samples[k] = agg\n\t}\n\tagg.Ingest(float64(val), i.rateDenom)\n}\n\n\/\/ Data is used to retrieve all the aggregated metrics\n\/\/ Intervals may be in use, and a read lock should be acquired\nfunc (i *InmemSink) Data() []*IntervalMetrics {\n\t\/\/ Get the current interval, forces creation\n\ti.getInterval()\n\n\ti.intervalLock.RLock()\n\tdefer i.intervalLock.RUnlock()\n\n\tintervals := make([]*IntervalMetrics, len(i.intervals))\n\tcopy(intervals, i.intervals)\n\treturn intervals\n}\n\nfunc (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics {\n\ti.intervalLock.RLock()\n\tdefer i.intervalLock.RUnlock()\n\n\tn := len(i.intervals)\n\tif n > 0 && i.intervals[n-1].Interval == intv {\n\t\treturn i.intervals[n-1]\n\t}\n\treturn nil\n}\n\nfunc (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics {\n\ti.intervalLock.Lock()\n\tdefer i.intervalLock.Unlock()\n\n\t\/\/ Check for an existing interval\n\tn := len(i.intervals)\n\tif n > 0 && i.intervals[n-1].Interval == intv {\n\t\treturn i.intervals[n-1]\n\t}\n\n\t\/\/ Add the current interval\n\tcurrent := NewIntervalMetrics(intv)\n\ti.intervals = append(i.intervals, current)\n\tn++\n\n\t\/\/ Truncate the intervals if they are too long\n\tif n >= i.maxIntervals {\n\t\tcopy(i.intervals[0:], i.intervals[n-i.maxIntervals:])\n\t\ti.intervals = i.intervals[:i.maxIntervals]\n\t}\n\treturn current\n}\n\n\/\/ getInterval returns the current interval to write to\nfunc (i *InmemSink) getInterval() *IntervalMetrics {\n\tintv := time.Now().Truncate(i.interval)\n\tif m := i.getExistingInterval(intv); m != nil {\n\t\treturn m\n\t}\n\treturn i.createInterval(intv)\n}\n\n\/\/ Flattens the key for formatting, removes spaces\nfunc (i *InmemSink) flattenKey(parts []string) string {\n\tjoined := strings.Join(parts, \".\")\n\treturn strings.Replace(joined, \" \", \"_\", -1)\n}\n<commit_msg>Fix stupid typo<commit_after>package metrics\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ InmemSink provides a MetricSink that does in-memory aggregation\n\/\/ without sending metrics over a network. It can be embedded within\n\/\/ an application to provide profiling information.\ntype InmemSink struct {\n\t\/\/ How long is each aggregation interval\n\tinterval time.Duration\n\n\t\/\/ Retain controls how many metrics interval we keep\n\tretain time.Duration\n\n\t\/\/ maxIntervals is the maximum length of intervals.\n\t\/\/ It is retain \/ interval.\n\tmaxIntervals int\n\n\t\/\/ intervals is a slice of the retained intervals\n\tintervals    []*IntervalMetrics\n\tintervalLock sync.RWMutex\n\t\n\trateDenom float64\n}\n\n\/\/ IntervalMetrics stores the aggregated metrics\n\/\/ for a specific interval\ntype IntervalMetrics struct {\n\tsync.RWMutex\n\n\t\/\/ The start time of the interval\n\tInterval time.Time\n\n\t\/\/ Gauges maps the key to the last set value\n\tGauges map[string]float32\n\n\t\/\/ Points maps the string to the list of emitted values\n\t\/\/ from EmitKey\n\tPoints map[string][]float32\n\n\t\/\/ Counters maps the string key to a sum of the counter\n\t\/\/ values\n\tCounters map[string]*AggregateSample\n\n\t\/\/ Samples maps the key to an AggregateSample,\n\t\/\/ which has the rolled up view of a sample\n\tSamples map[string]*AggregateSample\n}\n\n\/\/ NewIntervalMetrics creates a new IntervalMetrics for a given interval\nfunc NewIntervalMetrics(intv time.Time) *IntervalMetrics {\n\treturn &IntervalMetrics{\n\t\tInterval: intv,\n\t\tGauges:   make(map[string]float32),\n\t\tPoints:   make(map[string][]float32),\n\t\tCounters: make(map[string]*AggregateSample),\n\t\tSamples:  make(map[string]*AggregateSample),\n\t}\n}\n\n\/\/ AggregateSample is used to hold aggregate metrics\n\/\/ about a sample\ntype AggregateSample struct {\n\tCount       int       \/\/ The count of emitted pairs\n\tRate\t        float64   \/\/ The count of emitted pairs per time unit (usually 1 second)\n\tSum         float64   \/\/ The sum of values\n\tSumSq       float64   \/\/ The sum of squared values\n\tMin         float64   \/\/ Minimum value\n\tMax         float64   \/\/ Maximum value\n\tLastUpdated time.Time \/\/ When value was last updated\n}\n\n\/\/ Computes a Stddev of the values\nfunc (a *AggregateSample) Stddev() float64 {\n\tnum := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2)\n\tdiv := float64(a.Count * (a.Count - 1))\n\tif div == 0 {\n\t\treturn 0\n\t}\n\treturn math.Sqrt(num \/ div)\n}\n\n\/\/ Computes a mean of the values\nfunc (a *AggregateSample) Mean() float64 {\n\tif a.Count == 0 {\n\t\treturn 0\n\t}\n\treturn a.Sum \/ float64(a.Count)\n}\n\n\/\/ Ingest is used to update a sample\nfunc (a *AggregateSample) Ingest(v float64, rateDenom float64) {\n\ta.Count++\n\ta.Sum += v\n\ta.SumSq += (v * v)\n\tif v < a.Min || a.Count == 1 {\n\t\ta.Min = v\n\t}\n\tif v > a.Max || a.Count == 1 {\n\t\ta.Max = v\n\t}\n\ta.Rate = float64(a.Count)\/rateDenom\n\ta.LastUpdated = time.Now()\n}\n\nfunc (a *AggregateSample) String() string {\n\tif a.Count == 0 {\n\t\treturn \"Count: 0\"\n\t} else if a.Stddev() == 0 {\n\t\treturn fmt.Sprintf(\"Count: %d Sum: %0.3f LastUpdated: %s\", a.Count, a.Sum, a.LastUpdated)\n\t} else {\n\t\treturn fmt.Sprintf(\"Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s\",\n\t\t\ta.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated)\n\t}\n}\n\n\/\/ NewInmemSink is used to construct a new in-memory sink.\n\/\/ Uses an aggregation interval and maximum retention period.\nfunc NewInmemSink(interval, retain time.Duration) *InmemSink {\n\trateTimeUnit := time.Second\n\ti := &InmemSink{\n\t\tinterval:     interval,\n\t\tretain:       retain,\n\t\tmaxIntervals: int(retain \/ interval),\n\t\trateDenom: float64(interval.Nanoseconds()) \/ float64(rateTimeUnit.Nanoseconds()),\n\t}\n\ti.intervals = make([]*IntervalMetrics, 0, i.maxIntervals)\n\treturn i\n}\n\nfunc (i *InmemSink) SetGauge(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\tintv.Gauges[k] = val\n}\n\nfunc (i *InmemSink) EmitKey(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\tvals := intv.Points[k]\n\tintv.Points[k] = append(vals, val)\n}\n\nfunc (i *InmemSink) IncrCounter(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\n\tagg := intv.Counters[k]\n\tif agg == nil {\n\t\tagg = &AggregateSample{}\n\t\tintv.Counters[k] = agg\n\t}\n\tagg.Ingest(float64(val), i.rateDenom)\n}\n\nfunc (i *InmemSink) AddSample(key []string, val float32) {\n\tk := i.flattenKey(key)\n\tintv := i.getInterval()\n\n\tintv.Lock()\n\tdefer intv.Unlock()\n\n\tagg := intv.Samples[k]\n\tif agg == nil {\n\t\tagg = &AggregateSample{}\n\t\tintv.Samples[k] = agg\n\t}\n\tagg.Ingest(float64(val), i.rateDenom)\n}\n\n\/\/ Data is used to retrieve all the aggregated metrics\n\/\/ Intervals may be in use, and a read lock should be acquired\nfunc (i *InmemSink) Data() []*IntervalMetrics {\n\t\/\/ Get the current interval, forces creation\n\ti.getInterval()\n\n\ti.intervalLock.RLock()\n\tdefer i.intervalLock.RUnlock()\n\n\tintervals := make([]*IntervalMetrics, len(i.intervals))\n\tcopy(intervals, i.intervals)\n\treturn intervals\n}\n\nfunc (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics {\n\ti.intervalLock.RLock()\n\tdefer i.intervalLock.RUnlock()\n\n\tn := len(i.intervals)\n\tif n > 0 && i.intervals[n-1].Interval == intv {\n\t\treturn i.intervals[n-1]\n\t}\n\treturn nil\n}\n\nfunc (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics {\n\ti.intervalLock.Lock()\n\tdefer i.intervalLock.Unlock()\n\n\t\/\/ Check for an existing interval\n\tn := len(i.intervals)\n\tif n > 0 && i.intervals[n-1].Interval == intv {\n\t\treturn i.intervals[n-1]\n\t}\n\n\t\/\/ Add the current interval\n\tcurrent := NewIntervalMetrics(intv)\n\ti.intervals = append(i.intervals, current)\n\tn++\n\n\t\/\/ Truncate the intervals if they are too long\n\tif n >= i.maxIntervals {\n\t\tcopy(i.intervals[0:], i.intervals[n-i.maxIntervals:])\n\t\ti.intervals = i.intervals[:i.maxIntervals]\n\t}\n\treturn current\n}\n\n\/\/ getInterval returns the current interval to write to\nfunc (i *InmemSink) getInterval() *IntervalMetrics {\n\tintv := time.Now().Truncate(i.interval)\n\tif m := i.getExistingInterval(intv); m != nil {\n\t\treturn m\n\t}\n\treturn i.createInterval(intv)\n}\n\n\/\/ Flattens the key for formatting, removes spaces\nfunc (i *InmemSink) flattenKey(parts []string) string {\n\tjoined := strings.Join(parts, \".\")\n\treturn strings.Replace(joined, \" \", \"_\", -1)\n}\n<|endoftext|>"}
{"text":"<commit_before>\npackage main\n\nimport (\n  \"fmt\"\n  \"strconv\"\n  \"unicode\"\n  \"utf8\"\n)\n\nconst (\n  kSplit = iota         \/\/ proceed down out & out1\n  kAltBegin             \/\/ begin of alt section, i.e. '('\n  kAltEnd               \/\/ end of alt section, i.e. ')'\n  kRune                 \/\/ if match rune, proceed down out\n  kCall                 \/\/ if matcher passes, proceed down out\n  kMatch                \/\/ success state!\n)\n\n\/**\n * Single instruction in regexp.\n *\/\ntype instr struct {\n  idx int               \/\/ index of this instr\n  mode byte             \/\/ mode (as above)\n  out *instr            \/\/ next instr to process\n  out1 *instr           \/\/ alt next instr (for kSplit)\n  rune int              \/\/ rune to match (kRune)\n  matcher func(rune int) bool   \/\/ matcher method (for kCall)\n  alt int               \/\/ identifier of alt branch (for kAlt{Begin,End})\n}\n\n\/**\n * String-representation of an individual instruction.\n *\/\nfunc (i *instr) str() string {\n  str := fmt.Sprintf(\"{%d\", i.idx)\n  out := \"\"\n  if i.out != nil {\n    out += fmt.Sprintf(\" out=%d\", i.out.idx)\n  }\n  switch i.mode {\n  case kSplit:\n    str += \" kSplit\"\n    if i.out1 != nil {\n      out += fmt.Sprintf(\" out1=%d\", i.out1.idx)\n    }\n  case kAltBegin:\n    str += fmt.Sprintf(\" kAltBegin alt=%d\", i.alt)\n  case kAltEnd:\n    str += fmt.Sprintf(\" kAltEnd alt=%d\", i.alt)\n  case kRune:\n    str += fmt.Sprintf(\" kRune rune=%c\", i.rune)\n  case kCall:\n    str += \" kCall meth=?\"\n  case kMatch:\n    str += \" kMatch\"\n  }\n  return str + out + \"}\"\n}\n\ntype parser struct {\n  src string\n  ch int\n  pos int\n  prog []*instr\n  inst int\n  altpos int\n}\n\n\/*\n * Generic matcher for consuming instr instances (i.e. kRune\/kCall). Does not\n * match anything else.\n *\/\nfunc (s *instr) match(rune int) bool {\n  if s.mode == kRune {\n    return s.rune == rune || s.rune == -1\n  } else if s.mode == kCall {\n    return s.matcher(rune)\n  }\n  return false\n}\n\n\/**\n * Generate a new pre-indexed instr.\n *\/\nfunc (p *parser) instr() *instr {\n  if p.inst == len(p.prog) {\n    panic(\"overflow instr buffer\")\n  }\n  i := &instr{p.inst, kSplit, nil, nil, -1, nil, -1}\n  p.prog[p.inst] = i\n  p.inst += 1\n  return i\n}\n\n\/**\n * Store\/return the next character in parser. -1 indicates EOF.\n *\/\nfunc (p *parser) nextc() int {\n  if p.pos >= len(p.src) {\n    p.ch = -1\n  } else {\n\t\tc, w := utf8.DecodeRuneInString(p.src[p.pos:])\n\t\tp.ch = c\n\t\tp.pos += w\n  }\n  return p.ch\n}\n\n\/**\n * Connect from -> to.\n *\/\nfunc (p *parser) out(from *instr, to *instr) {\n  if from.out == nil {\n    from.out = to\n  } else if from.mode == kSplit && from.out1 == nil {\n    from.out1 = to\n  } else {\n    panic(\"can't out\")\n  }\n}\n\nfunc (p *parser) alt() (start *instr, end *instr) {\n  altpos := p.altpos\n  p.altpos += 1\n\n  if p.ch != '(' {\n    panic(\"alt must start with '('\")\n  }\n\n  end = p.instr() \/\/ shared end state for alt\n  end.mode = kAltEnd\n  end.alt = altpos\n\n  p.nextc()\n  b_start, b_end := p.regexp()\n  start = b_start\n  p.out(b_end, end)\n\n  for p.ch == '|' {\n    split := p.instr()\n    p.out(split, b_start)\n\n    p.nextc()\n    b_start, b_end = p.regexp()\n    p.out(split, b_start)\n    p.out(b_end, end)\n\n    start = split\n  }\n\n  if p.ch != ')' {\n    panic(\"alt must end with ')'\")\n  }\n\n  alt_begin := p.instr()\n  alt_begin.mode = kAltBegin\n  alt_begin.alt = altpos\n  p.out(alt_begin, start)\n  return alt_begin, end\n}\n\nfunc (p *parser) term() (start *instr, end *instr) {\n  start = p.instr()\n  end = start\n\n  switch p.ch {\n  case -1:\n    panic(\"EOF in term\")\n  case '*', '+', '{', '?':\n    panic(\"unexpected expansion char\")\n  case ')', '}', ']':\n    panic(\"unexpected close element\")\n  case '(':\n    start, end = p.alt()\n  case '[':\n    panic(\"not yet supported: [\")\n  case '$':\n    panic(\"not yet supported: end of string\")\n  case '^':\n    panic(\"not yet supported: start of string\")\n  case '.':\n    start.mode = kRune\n  case '\\\\':\n    next := p.nextc()\n    start.mode = kRune\n    switch next {\n    case 'n':\n      start.rune = '\\n'\n    case 't':\n      start.rune = '\\t'\n    default:\n      \/\/ TODO: limit this to punctuation\n      start.rune = next\n    }\n  default:\n    start.mode = kRune\n    start.rune = p.ch\n  }\n  p.nextc()\n  return start, end\n}\n\nfunc (p *parser) closure() (start *instr, end *instr) {\n  start, end = p.term()\n\n  switch p.ch {\n  case '?', '*':\n    p_start := start\n    p_end := end\n    start = p.instr()\n    end = p.instr()\n    p.out(start, p_start)\n    p.out(start, end)\n    p.out(p_end, end)\n    if p.ch == '*' {\n      p.out(end, start)\n    }\n    p.nextc()\n  case '+':\n    p_end := end\n    end = p.instr()\n    p.out(p_end, end)\n    p.out(end, start)\n    p.nextc()\n  case '{':\n    count_str := \"\"\n    p.nextc()\n    for unicode.IsDigit(p.ch) {\n      count_str += fmt.Sprintf(\"%c\", p.ch)\n      p.nextc()\n    }\n    if len(count_str) == 0 {\n      panic(\"{ must be followed by digit\")\n    }\n    if p.ch == '}' {\n      \/\/ fixed expansion\n      count, _ := strconv.Atoi(count_str)\n      panic(fmt.Sprintf(\"can't yet expand to: %d\", count))\n    } else if p.ch == ',' {\n      panic(\"can't handle anything but {n}\")\n    } else {\n      panic(\"unexpected char in {}\")\n    }\n  }\n  return start, end\n}\n\n\/**\n * Match a regexp (defined as [closure]*) from parser, until either: EOF, |, or\n * ) is encountered.\n *\/\nfunc (p *parser) regexp() (start *instr, end *instr) {\n  start = p.instr()\n  curr := start\n\n  for {\n    if p.ch == -1 || p.ch == '|' || p.ch == ')' {\n      break\n    }\n    s, e := p.closure()\n    p.out(curr, s)\n    curr = e\n  }\n\n  end = p.instr()\n  p.out(curr, end)\n  return start, end\n}\n\n\/**\n * Cleanup the given program. Assumes the given input is a flat slice containing\n * no nil instructions. Will not clean up the first instruction, as it is always\n * the canonical entry point for the regexp.\n *\n * Returns a similarly flat slice containing no nil instructions, however the\n * slice may potentially be smaller.\n *\/\nfunc cleanup(prog []*instr) []*instr {\n  \/\/ TODO: Clear kSplit recursion. In some cases, kSplit paths may recurse back\n  \/\/ on themselves. We can remove this and convert it to a single-instr kSplit.\n\n  \/\/ Iterate through the program, and remove single-instr kSplits.\n  \/\/ NB: Don't parse the first instr, it will always be single.\n  for i := 1; i < len(prog); i++ {\n    pi := prog[i]\n    if pi.mode == kSplit && (pi.out1 == nil || pi.out == pi.out1) {\n      for j := 0; j < len(prog); j++ {\n        if prog[j] == nil {\n          continue\n        }\n        pj := prog[j]\n        if pj.out == pi {\n          pj.out = pi.out\n        }\n        if pj.out1 == pi {\n          pj.out1 = pi.out\n        }\n      }\n      prog[i] = nil\n    }\n  }\n\n  \/\/ We may now have nil gaps: shift everything up.\n  last := 0\n  for i := 0; i < len(prog); i++ {\n    if prog[i] != nil {\n      last = i\n    } else {\n      \/\/ find next non-nil, move here\n      var found int\n      for found = i; found < len(prog); found++ {\n        if prog[found] != nil {\n          break\n        }\n      }\n      if found == len(prog) {\n        break \/\/ no more entries\n      }\n\n      \/\/ move found to i\n      prog[i] = prog[found]\n      prog[i].idx = i\n      prog[found] = nil\n      last = i\n    }\n  }\n\n  return prog[0:last+1]\n}\n\n\/**\n * Generates a simple straight-forward NFA.\n *\/\nfunc Parse(src string) (r *sregexp) {\n  p := parser{src, -1, 0, make([]*instr, 128), 0, 0}\n  begin := p.instr()\n  match := p.instr()\n  match.mode = kMatch\n\n  p.nextc()\n  start, end := p.regexp()\n\n  if p.nextc() != -1 {\n    panic(\"could not consume all of regexp!\")\n  }\n\n  p.out(begin, start)\n  p.out(end, match)\n\n  result := p.prog[0:end.idx+1]\n  result = cleanup(result)\n\n  return &sregexp{result, p.altpos}\n}\n<commit_msg>fixes to parser<commit_after>\npackage main\n\nimport (\n  \"fmt\"\n  \"strconv\"\n  \"unicode\"\n  \"utf8\"\n)\n\nconst (\n  kSplit = iota         \/\/ proceed down out & out1\n  kAltBegin             \/\/ begin of alt section, i.e. '('\n  kAltEnd               \/\/ end of alt section, i.e. ')'\n  kRune                 \/\/ if match rune, proceed down out\n  kCall                 \/\/ if matcher passes, proceed down out\n  kMatch                \/\/ success state!\n)\n\n\/**\n * Single instruction in regexp.\n *\/\ntype instr struct {\n  idx int               \/\/ index of this instr\n  mode byte             \/\/ mode (as above)\n  out *instr            \/\/ next instr to process\n  out1 *instr           \/\/ alt next instr (for kSplit)\n  rune int              \/\/ rune to match (kRune)\n  matcher func(rune int) bool   \/\/ matcher method (for kCall)\n  alt int               \/\/ identifier of alt branch (for kAlt{Begin,End})\n}\n\n\/**\n * String-representation of an individual instruction.\n *\/\nfunc (i *instr) str() string {\n  str := fmt.Sprintf(\"{%d\", i.idx)\n  out := \"\"\n  if i.out != nil {\n    out += fmt.Sprintf(\" out=%d\", i.out.idx)\n  }\n  switch i.mode {\n  case kSplit:\n    str += \" kSplit\"\n    if i.out1 != nil {\n      out += fmt.Sprintf(\" out1=%d\", i.out1.idx)\n    }\n  case kAltBegin:\n    str += fmt.Sprintf(\" kAltBegin alt=%d\", i.alt)\n  case kAltEnd:\n    str += fmt.Sprintf(\" kAltEnd alt=%d\", i.alt)\n  case kRune:\n    str += fmt.Sprintf(\" kRune rune=%c\", i.rune)\n  case kCall:\n    str += \" kCall meth=?\"\n  case kMatch:\n    str += \" kMatch\"\n  }\n  return str + out + \"}\"\n}\n\ntype parser struct {\n  src string\n  ch int\n  pos int\n  prog []*instr\n  inst int\n  altpos int\n}\n\n\/*\n * Generic matcher for consuming instr instances (i.e. kRune\/kCall). Does not\n * match anything else.\n *\/\nfunc (s *instr) match(rune int) bool {\n  if s.mode == kRune {\n    return s.rune == rune || s.rune == -1\n  } else if s.mode == kCall {\n    return s.matcher(rune)\n  }\n  return false\n}\n\n\/**\n * Generate a new pre-indexed instr.\n *\/\nfunc (p *parser) instr() *instr {\n  if p.inst == len(p.prog) {\n    panic(\"overflow instr buffer\")\n  }\n  i := &instr{p.inst, kSplit, nil, nil, -1, nil, -1}\n  p.prog[p.inst] = i\n  p.inst += 1\n  return i\n}\n\n\/**\n * Store\/return the next character in parser. -1 indicates EOF.\n *\/\nfunc (p *parser) nextc() int {\n  if p.pos >= len(p.src) {\n    p.ch = -1\n  } else {\n\t\tc, w := utf8.DecodeRuneInString(p.src[p.pos:])\n\t\tp.ch = c\n\t\tp.pos += w\n  }\n  return p.ch\n}\n\n\/**\n * Connect from -> to.\n *\/\nfunc (p *parser) out(from *instr, to *instr) {\n  if from.out == nil {\n    from.out = to\n  } else if from.mode == kSplit && from.out1 == nil {\n    from.out1 = to\n  } else {\n    panic(\"can't out\")\n  }\n}\n\nfunc (p *parser) alt() (start *instr, end *instr) {\n  altpos := p.altpos\n  p.altpos += 1\n\n  if p.ch != '(' {\n    panic(\"alt must start with '('\")\n  }\n\n  end = p.instr() \/\/ shared end state for alt\n  end.mode = kAltEnd\n  end.alt = altpos\n\n  p.nextc()\n  b_start, b_end := p.regexp()\n  start = b_start\n  p.out(b_end, end)\n\n  for p.ch == '|' {\n    start = p.instr()\n    p.out(start, b_start)\n\n    p.nextc()\n    b_start, b_end = p.regexp()\n    p.out(start, b_start)\n    p.out(b_end, end)\n    b_start = start\n  }\n\n  if p.ch != ')' {\n    panic(\"alt must end with ')'\")\n  }\n\n  alt_begin := p.instr()\n  alt_begin.mode = kAltBegin\n  alt_begin.alt = altpos\n  p.out(alt_begin, start)\n  return alt_begin, end\n}\n\nfunc (p *parser) term() (start *instr, end *instr) {\n  start = p.instr()\n  end = start\n\n  switch p.ch {\n  case -1:\n    panic(\"EOF in term\")\n  case '*', '+', '{', '?':\n    panic(\"unexpected expansion char\")\n  case ')', '}', ']':\n    panic(\"unexpected close element\")\n  case '(':\n    start, end = p.alt()\n  case '[':\n    panic(\"not yet supported: [\")\n  case '$':\n    panic(\"not yet supported: end of string\")\n  case '^':\n    panic(\"not yet supported: start of string\")\n  case '.':\n    start.mode = kRune\n  case '\\\\':\n    next := p.nextc()\n    start.mode = kRune\n    switch next {\n    case 'n':\n      start.rune = '\\n'\n    case 't':\n      start.rune = '\\t'\n    default:\n      \/\/ TODO: limit this to punctuation\n      start.rune = next\n    }\n  default:\n    start.mode = kRune\n    start.rune = p.ch\n  }\n  p.nextc()\n  return start, end\n}\n\nfunc (p *parser) closure() (start *instr, end *instr) {\n  start, end = p.term()\n\n  switch p.ch {\n  case '?', '*':\n    p_start := start\n    p_end := end\n    start = p.instr()\n    end = p.instr()\n    p.out(start, p_start)\n    p.out(start, end)\n    if p.ch == '?' {\n      p.out(p_end, end)\n    } else {\n      p.out(p_end, start)\n    }\n    p.nextc()\n  case '+':\n    p_end := end\n    end = p.instr()\n    p.out(p_end, end)\n    p.out(end, start)\n    p.nextc()\n  case '{':\n    count_str := \"\"\n    p.nextc()\n    for unicode.IsDigit(p.ch) {\n      count_str += fmt.Sprintf(\"%c\", p.ch)\n      p.nextc()\n    }\n    if len(count_str) == 0 {\n      panic(\"{ must be followed by digit\")\n    }\n    if p.ch == '}' {\n      \/\/ fixed expansion\n      count, _ := strconv.Atoi(count_str)\n      panic(fmt.Sprintf(\"can't yet expand to: %d\", count))\n    } else if p.ch == ',' {\n      panic(\"can't handle anything but {n}\")\n    } else {\n      panic(\"unexpected char in {}\")\n    }\n  }\n  return start, end\n}\n\n\/**\n * Match a regexp (defined as [closure]*) from parser, until either: EOF, |, or\n * ) is encountered.\n *\/\nfunc (p *parser) regexp() (start *instr, end *instr) {\n  start = p.instr()\n  curr := start\n\n  for {\n    if p.ch == -1 || p.ch == '|' || p.ch == ')' {\n      break\n    }\n    s, e := p.closure()\n    p.out(curr, s)\n    curr = e\n  }\n\n  end = p.instr()\n  p.out(curr, end)\n  return start, end\n}\n\n\/**\n * Cleanup the given program. Assumes the given input is a flat slice containing\n * no nil instructions. Will not clean up the first instruction, as it is always\n * the canonical entry point for the regexp.\n *\n * Returns a similarly flat slice containing no nil instructions, however the\n * slice may potentially be smaller.\n *\/\nfunc cleanup(prog []*instr) []*instr {\n  \/\/ Detect kSplit recursion. We can remove this and convert it to a single path.\n  states := NewStateSet(len(prog), len(prog))\n  for i := 1; i < len(prog); i++ {\n    states.Clear()\n    pi := prog[i]\n    var fn func(ci *instr) bool\n    fn = func(ci *instr) bool {\n      if ci != nil && ci.mode == kSplit {\n        if states.Put(ci.idx) {\n          \/\/ NOTE: I'm not sure if this will ever happen. Panic for now. If we're\n          \/\/ confident this won't happen, we could move the panic to runtime.\n          panic(\"regexp should never loop\")\n          return true\n        }\n        if fn(ci.out) {\n          ci.out = nil\n        }\n        if fn(ci.out1) {\n          ci.out1 = nil\n        }\n        return true\n      }\n      return false\n    }\n    fn(pi)\n  }\n\n  \/\/ Iterate through the program, and remove single-instr kSplits.\n  \/\/ NB: Don't parse the first instr, it will always be single.\n  for i := 1; i < len(prog); i++ {\n    pi := prog[i]\n    if pi.mode == kSplit && (pi.out1 == nil || pi.out == pi.out1) {\n      for j := 0; j < len(prog); j++ {\n        if prog[j] == nil {\n          continue\n        }\n        pj := prog[j]\n        if pj.out == pi {\n          pj.out = pi.out\n        }\n        if pj.out1 == pi {\n          pj.out1 = pi.out\n        }\n      }\n      prog[i] = nil\n    }\n  }\n\n  \/\/ We may now have nil gaps: shift everything up.\n  last := 0\n  for i := 0; i < len(prog); i++ {\n    if prog[i] != nil {\n      last = i\n    } else {\n      \/\/ find next non-nil, move here\n      var found int\n      for found = i; found < len(prog); found++ {\n        if prog[found] != nil {\n          break\n        }\n      }\n      if found == len(prog) {\n        break \/\/ no more entries\n      }\n\n      \/\/ move found to i\n      prog[i] = prog[found]\n      prog[i].idx = i\n      prog[found] = nil\n      last = i\n    }\n  }\n\n  return prog[0:last+1]\n}\n\n\/**\n * Generates a simple straight-forward NFA.\n *\/\nfunc Parse(src string) (r *sregexp) {\n  p := parser{src, -1, 0, make([]*instr, 128), 0, 0}\n  begin := p.instr()\n  match := p.instr()\n  match.mode = kMatch\n\n  p.nextc()\n  start, end := p.regexp()\n\n  if p.nextc() != -1 {\n    panic(\"could not consume all of regexp!\")\n  }\n\n  p.out(begin, start)\n  p.out(end, match)\n\n  result := p.prog[0:end.idx+1]\n  result = cleanup(result)\n\n  return &sregexp{result, p.altpos}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"os\"\n)\n\ntype Options struct {\n\t\/* verbosity level *\/\n\tVerbose []bool `short:\"v\" long:\"verbose\" description:\"verbose output\"`\n}\n\nvar options Options\nvar parser = flags.NewParser(&options, flags.Default)\n\nfunc main() {\n\tif _, err := parser.Parse(); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>all flag and command descriptions must be in caps<commit_after>package main\n\nimport (\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"os\"\n)\n\ntype Options struct {\n\t\/* verbosity level *\/\n\tVerbose []bool `short:\"v\" long:\"verbose\" description:\"Verbose output\"`\n}\n\nvar options Options\nvar parser = flags.NewParser(&options, flags.Default)\n\nfunc main() {\n\tif _, err := parser.Parse(); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package goreq\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"compress\/gzip\"\n\t\"compress\/zlib\"\n\t\"crypto\/tls\"\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\/url\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Request struct {\n\theaders           []headerTuple\n\tMethod            string\n\tUri               string\n\tBody              interface{}\n\tQueryString       interface{}\n\tTimeout           time.Duration\n\tContentType       string\n\tAccept            string\n\tHost              string\n\tUserAgent         string\n\tInsecure          bool\n\tMaxRedirects      int\n\tRedirectHeaders   bool\n\tProxy             string\n\tCompression       *compression\n\tBasicAuthUsername string\n\tBasicAuthPassword string\n}\n\ntype compression struct {\n\twriter          func(buffer io.Writer) (io.WriteCloser, error)\n\treader          func(buffer io.Reader) (io.ReadCloser, error)\n\tContentEncoding string\n}\n\ntype Response struct {\n\tStatusCode    int\n\tContentLength int64\n\tBody          *Body\n\tHeader        http.Header\n}\n\ntype headerTuple struct {\n\tname  string\n\tvalue string\n}\n\ntype Body struct {\n\treader           io.ReadCloser\n\tcompressedReader io.ReadCloser\n}\n\ntype Error struct {\n\ttimeout bool\n\tErr     error\n}\n\nfunc (e *Error) Timeout() bool {\n\treturn e.timeout\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Err.Error()\n}\n\nfunc (b *Body) Read(p []byte) (int, error) {\n\tif b.compressedReader != nil {\n\t\treturn b.compressedReader.Read(p)\n\t}\n\treturn b.reader.Read(p)\n}\n\nfunc (b *Body) Close() error {\n\terr := b.reader.Close()\n\tif b.compressedReader != nil {\n\t\treturn b.compressedReader.Close()\n\t}\n\treturn err\n}\n\nfunc (b *Body) FromJsonTo(o interface{}) error {\n\tif body, err := ioutil.ReadAll(b); err != nil {\n\t\treturn err\n\t} else if err := json.Unmarshal(body, o); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Body) ToString() (string, error) {\n\tbody, err := ioutil.ReadAll(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\nfunc Gzip() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn gzip.NewReader(buffer)\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn gzip.NewWriter(buffer), nil\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"gzip\"}\n}\n\nfunc Deflate() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn flate.NewReader(buffer), nil\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn flate.NewWriter(buffer, -1)\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"deflate\"}\n}\n\nfunc Zlib() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn zlib.NewReader(buffer)\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn zlib.NewWriter(buffer), nil\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"deflate\"}\n}\n\nfunc paramParse(query interface{}) (string, error) {\n\tswitch query.(type) {\n\tcase url.Values:\n\t\treturn query.(url.Values).Encode(), nil\n\tcase *url.Values:\n\t\treturn query.(*url.Values).Encode(), nil\n\tdefault:\n\t\tvar (\n\t\t\tv = &url.Values{}\n\t\t\ts = reflect.ValueOf(query)\n\t\t\tt = reflect.TypeOf(query)\n\t\t)\n\t\tfor t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\t\ts = s.Elem()\n\t\t\tt = s.Type()\n\t\t}\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tif len(t.Field(i).PkgPath) > 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tv.Add(strings.ToLower(t.Field(i).Name), fmt.Sprintf(\"%v\", s.Field(i).Interface()))\n\t\t}\n\t\treturn v.Encode(), nil\n\t}\n}\n\nfunc prepareRequestBody(b interface{}) (io.Reader, error) {\n\tswitch b.(type) {\n\tcase string:\n\t\t\/\/ treat is as text\n\t\treturn strings.NewReader(b.(string)), nil\n\tcase io.Reader:\n\t\t\/\/ treat is as text\n\t\treturn b.(io.Reader), nil\n\tcase []byte:\n\t\t\/\/treat as byte array\n\t\treturn bytes.NewReader(b.([]byte)), nil\n\tcase nil:\n\t\treturn nil, nil\n\tdefault:\n\t\t\/\/ try to jsonify it\n\t\tj, err := json.Marshal(b)\n\t\tif err == nil {\n\t\t\treturn bytes.NewReader(j), nil\n\t\t}\n\t\treturn nil, err\n\t}\n}\n\nvar defaultDialer = &net.Dialer{Timeout: 1000 * time.Millisecond}\nvar defaultTransport = &http.Transport{Dial: defaultDialer.Dial, Proxy: http.ProxyFromEnvironment}\nvar defaultClient = &http.Client{Transport: defaultTransport}\n\nvar proxyTransport *http.Transport\nvar proxyClient *http.Client\n\nfunc SetConnectTimeout(duration time.Duration) {\n\tdefaultDialer.Timeout = duration\n}\n\nfunc (r *Request) AddHeader(name string, value string) {\n\tif r.headers == nil {\n\t\tr.headers = []headerTuple{}\n\t}\n\tr.headers = append(r.headers, headerTuple{name: name, value: value})\n}\n\nfunc (r Request) Do() (*Response, error) {\n\tvar req *http.Request\n\tvar er error\n\tvar transport = defaultTransport\n\tvar client = defaultClient\n\tvar redirectFailed bool\n\n\tr.Method = valueOrDefault(r.Method, \"GET\")\n\n\tif r.Proxy != \"\" {\n\t\tproxyUrl, err := url.Parse(r.Proxy)\n\t\tif err != nil {\n\t\t\t\/\/ proxy address is in a wrong format\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\tif proxyTransport == nil {\n\t\t\tproxyTransport = &http.Transport{Dial: defaultDialer.Dial, Proxy: http.ProxyURL(proxyUrl)}\n\t\t\tproxyClient = &http.Client{Transport: proxyTransport}\n\t\t} else {\n\t\t\tproxyTransport.Proxy = http.ProxyURL(proxyUrl)\n\t\t}\n\t\ttransport = proxyTransport\n\t\tclient = proxyClient\n\t}\n\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\tif len(via) > r.MaxRedirects {\n\t\t\tredirectFailed = true\n\t\t\treturn errors.New(\"Error redirecting. MaxRedirects reached\")\n\t\t}\n\n\t\t\/\/By default Golang will not redirect request headers\n\t\t\/\/ https:\/\/code.google.com\/p\/go\/issues\/detail?id=4800&q=request%20header\n\t\tif r.RedirectHeaders {\n\t\t\tfor key, val := range via[0].Header {\n\t\t\t\treq.Header[key] = val\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif r.Insecure {\n\t\ttransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t} else if transport.TLSClientConfig != nil {\n\t\t\/\/ the default TLS client (when transport.TLSClientConfig==nil) is\n\t\t\/\/ already set to verify, so do nothing in that case\n\t\ttransport.TLSClientConfig.InsecureSkipVerify = false\n\t}\n\n\tb, e := prepareRequestBody(r.Body)\n\tif e != nil {\n\t\t\/\/ there was a problem marshaling the body\n\t\treturn nil, &Error{Err: e}\n\t}\n\n\tif r.QueryString != nil {\n\t\tparam, e := paramParse(r.QueryString)\n\t\tif e != nil {\n\t\t\treturn nil, &Error{Err: e}\n\t\t}\n\t\tr.Uri = r.Uri + \"?\" + param\n\t}\n\n\tvar bodyReader io.Reader\n\tif b != nil && r.Compression != nil {\n\t\tbuffer := bytes.NewBuffer([]byte{})\n\t\treadBuffer := bufio.NewReader(b)\n\t\twriter, err := r.Compression.writer(buffer)\n\t\tif err != nil {\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\t_, e = readBuffer.WriteTo(writer)\n\t\twriter.Close()\n\t\tif e != nil {\n\t\t\treturn nil, &Error{Err: e}\n\t\t}\n\t\tbodyReader = buffer\n\t} else {\n\t\tbodyReader = b\n\t}\n\treq, er = http.NewRequest(r.Method, r.Uri, bodyReader)\n\n\tif er != nil {\n\t\t\/\/ we couldn't parse the URL.\n\t\treturn nil, &Error{Err: er}\n\t}\n\n\t\/\/ add headers to the request\n\treq.Host = r.Host\n\treq.Header.Add(\"User-Agent\", r.UserAgent)\n\treq.Header.Add(\"Content-Type\", r.ContentType)\n\treq.Header.Add(\"Accept\", r.Accept)\n\tif r.Compression != nil {\n\t\treq.Header.Add(\"Content-Encoding\", r.Compression.ContentEncoding)\n\t\treq.Header.Add(\"Accept-Encoding\", r.Compression.ContentEncoding)\n\t}\n\tif r.headers != nil {\n\t\tfor _, header := range r.headers {\n\t\t\treq.Header.Add(header.name, header.value)\n\t\t}\n\t}\n\n\t\/\/use basic auth if required\n\tif r.BasicAuthUsername != \"\" {\n\t\treq.SetBasicAuth(r.BasicAuthUsername, r.BasicAuthPassword)\n\t}\n\n\ttimeout := false\n\tvar timer *time.Timer\n\tif r.Timeout > 0 {\n\t\ttimer = time.AfterFunc(r.Timeout, func() {\n\t\t\ttransport.CancelRequest(req)\n\t\t\ttimeout = true\n\t\t})\n\t}\n\n\tres, err := client.Do(req)\n\tif timer != nil {\n\t\ttimer.Stop()\n\t}\n\n\tif err != nil {\n\t\tif !timeout {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *net.OpError:\n\t\t\t\ttimeout = err.Timeout()\n\t\t\tcase *url.Error:\n\t\t\t\tif op, ok := err.Err.(*net.OpError); ok {\n\t\t\t\t\ttimeout = op.Timeout()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar response *Response\n\t\t\/\/If redirect fails we still want to return response data\n\t\tif redirectFailed {\n\t\t\tresponse = &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body}}\n\t\t}\n\n\t\treturn response, &Error{timeout: timeout, Err: err}\n\t}\n\n\tif r.Compression != nil && strings.Contains(res.Header.Get(\"Content-Encoding\"), r.Compression.ContentEncoding) {\n\t\tcompressedReader, err := r.Compression.reader(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\treturn &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body, compressedReader: compressedReader}}, nil\n\t} else {\n\t\treturn &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body}}, nil\n\t}\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<commit_msg>Add Error when QueryString not supported<commit_after>package goreq\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"compress\/gzip\"\n\t\"compress\/zlib\"\n\t\"crypto\/tls\"\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\/url\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Request struct {\n\theaders           []headerTuple\n\tMethod            string\n\tUri               string\n\tBody              interface{}\n\tQueryString       interface{}\n\tTimeout           time.Duration\n\tContentType       string\n\tAccept            string\n\tHost              string\n\tUserAgent         string\n\tInsecure          bool\n\tMaxRedirects      int\n\tRedirectHeaders   bool\n\tProxy             string\n\tCompression       *compression\n\tBasicAuthUsername string\n\tBasicAuthPassword string\n}\n\ntype compression struct {\n\twriter          func(buffer io.Writer) (io.WriteCloser, error)\n\treader          func(buffer io.Reader) (io.ReadCloser, error)\n\tContentEncoding string\n}\n\ntype Response struct {\n\tStatusCode    int\n\tContentLength int64\n\tBody          *Body\n\tHeader        http.Header\n}\n\ntype headerTuple struct {\n\tname  string\n\tvalue string\n}\n\ntype Body struct {\n\treader           io.ReadCloser\n\tcompressedReader io.ReadCloser\n}\n\ntype Error struct {\n\ttimeout bool\n\tErr     error\n}\n\nfunc (e *Error) Timeout() bool {\n\treturn e.timeout\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Err.Error()\n}\n\nfunc (b *Body) Read(p []byte) (int, error) {\n\tif b.compressedReader != nil {\n\t\treturn b.compressedReader.Read(p)\n\t}\n\treturn b.reader.Read(p)\n}\n\nfunc (b *Body) Close() error {\n\terr := b.reader.Close()\n\tif b.compressedReader != nil {\n\t\treturn b.compressedReader.Close()\n\t}\n\treturn err\n}\n\nfunc (b *Body) FromJsonTo(o interface{}) error {\n\tif body, err := ioutil.ReadAll(b); err != nil {\n\t\treturn err\n\t} else if err := json.Unmarshal(body, o); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Body) ToString() (string, error) {\n\tbody, err := ioutil.ReadAll(b)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\nfunc Gzip() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn gzip.NewReader(buffer)\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn gzip.NewWriter(buffer), nil\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"gzip\"}\n}\n\nfunc Deflate() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn flate.NewReader(buffer), nil\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn flate.NewWriter(buffer, -1)\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"deflate\"}\n}\n\nfunc Zlib() *compression {\n\treader := func(buffer io.Reader) (io.ReadCloser, error) {\n\t\treturn zlib.NewReader(buffer)\n\t}\n\twriter := func(buffer io.Writer) (io.WriteCloser, error) {\n\t\treturn zlib.NewWriter(buffer), nil\n\t}\n\treturn &compression{writer: writer, reader: reader, ContentEncoding: \"deflate\"}\n}\n\nfunc paramParse(query interface{}) (string, error) {\n\tswitch query.(type) {\n\tcase url.Values:\n\t\treturn query.(url.Values).Encode(), nil\n\tcase *url.Values:\n\t\treturn query.(*url.Values).Encode(), nil\n\tdefault:\n\t\tvar (\n\t\t\tv = &url.Values{}\n\t\t\ts = reflect.ValueOf(query)\n\t\t\tt = reflect.TypeOf(query)\n\t\t)\n\t\tfor t.Kind() == reflect.Ptr || t.Kind() == reflect.Interface {\n\t\t\ts = s.Elem()\n\t\t\tt = s.Type()\n\t\t}\n\t\tif t.Kind() == reflect.Struct {\n\t\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\t\tif len(t.Field(i).PkgPath) > 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tv.Add(strings.ToLower(t.Field(i).Name), fmt.Sprintf(\"%v\", s.Field(i).Interface()))\n\t\t\t}\n\t\t\treturn v.Encode(), nil\n\t\t} else {\n\t\t\treturn \"\", errors.New(\"Can not parse QueryString.\")\n\t\t}\n\t}\n}\n\nfunc prepareRequestBody(b interface{}) (io.Reader, error) {\n\tswitch b.(type) {\n\tcase string:\n\t\t\/\/ treat is as text\n\t\treturn strings.NewReader(b.(string)), nil\n\tcase io.Reader:\n\t\t\/\/ treat is as text\n\t\treturn b.(io.Reader), nil\n\tcase []byte:\n\t\t\/\/treat as byte array\n\t\treturn bytes.NewReader(b.([]byte)), nil\n\tcase nil:\n\t\treturn nil, nil\n\tdefault:\n\t\t\/\/ try to jsonify it\n\t\tj, err := json.Marshal(b)\n\t\tif err == nil {\n\t\t\treturn bytes.NewReader(j), nil\n\t\t}\n\t\treturn nil, err\n\t}\n}\n\nvar defaultDialer = &net.Dialer{Timeout: 1000 * time.Millisecond}\nvar defaultTransport = &http.Transport{Dial: defaultDialer.Dial, Proxy: http.ProxyFromEnvironment}\nvar defaultClient = &http.Client{Transport: defaultTransport}\n\nvar proxyTransport *http.Transport\nvar proxyClient *http.Client\n\nfunc SetConnectTimeout(duration time.Duration) {\n\tdefaultDialer.Timeout = duration\n}\n\nfunc (r *Request) AddHeader(name string, value string) {\n\tif r.headers == nil {\n\t\tr.headers = []headerTuple{}\n\t}\n\tr.headers = append(r.headers, headerTuple{name: name, value: value})\n}\n\nfunc (r Request) Do() (*Response, error) {\n\tvar req *http.Request\n\tvar er error\n\tvar transport = defaultTransport\n\tvar client = defaultClient\n\tvar redirectFailed bool\n\n\tr.Method = valueOrDefault(r.Method, \"GET\")\n\n\tif r.Proxy != \"\" {\n\t\tproxyUrl, err := url.Parse(r.Proxy)\n\t\tif err != nil {\n\t\t\t\/\/ proxy address is in a wrong format\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\tif proxyTransport == nil {\n\t\t\tproxyTransport = &http.Transport{Dial: defaultDialer.Dial, Proxy: http.ProxyURL(proxyUrl)}\n\t\t\tproxyClient = &http.Client{Transport: proxyTransport}\n\t\t} else {\n\t\t\tproxyTransport.Proxy = http.ProxyURL(proxyUrl)\n\t\t}\n\t\ttransport = proxyTransport\n\t\tclient = proxyClient\n\t}\n\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\tif len(via) > r.MaxRedirects {\n\t\t\tredirectFailed = true\n\t\t\treturn errors.New(\"Error redirecting. MaxRedirects reached\")\n\t\t}\n\n\t\t\/\/By default Golang will not redirect request headers\n\t\t\/\/ https:\/\/code.google.com\/p\/go\/issues\/detail?id=4800&q=request%20header\n\t\tif r.RedirectHeaders {\n\t\t\tfor key, val := range via[0].Header {\n\t\t\t\treq.Header[key] = val\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif r.Insecure {\n\t\ttransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t} else if transport.TLSClientConfig != nil {\n\t\t\/\/ the default TLS client (when transport.TLSClientConfig==nil) is\n\t\t\/\/ already set to verify, so do nothing in that case\n\t\ttransport.TLSClientConfig.InsecureSkipVerify = false\n\t}\n\n\tb, e := prepareRequestBody(r.Body)\n\tif e != nil {\n\t\t\/\/ there was a problem marshaling the body\n\t\treturn nil, &Error{Err: e}\n\t}\n\n\tif r.QueryString != nil {\n\t\tparam, e := paramParse(r.QueryString)\n\t\tif e != nil {\n\t\t\treturn nil, &Error{Err: e}\n\t\t}\n\t\tr.Uri = r.Uri + \"?\" + param\n\t}\n\n\tvar bodyReader io.Reader\n\tif b != nil && r.Compression != nil {\n\t\tbuffer := bytes.NewBuffer([]byte{})\n\t\treadBuffer := bufio.NewReader(b)\n\t\twriter, err := r.Compression.writer(buffer)\n\t\tif err != nil {\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\t_, e = readBuffer.WriteTo(writer)\n\t\twriter.Close()\n\t\tif e != nil {\n\t\t\treturn nil, &Error{Err: e}\n\t\t}\n\t\tbodyReader = buffer\n\t} else {\n\t\tbodyReader = b\n\t}\n\treq, er = http.NewRequest(r.Method, r.Uri, bodyReader)\n\n\tif er != nil {\n\t\t\/\/ we couldn't parse the URL.\n\t\treturn nil, &Error{Err: er}\n\t}\n\n\t\/\/ add headers to the request\n\treq.Host = r.Host\n\treq.Header.Add(\"User-Agent\", r.UserAgent)\n\treq.Header.Add(\"Content-Type\", r.ContentType)\n\treq.Header.Add(\"Accept\", r.Accept)\n\tif r.Compression != nil {\n\t\treq.Header.Add(\"Content-Encoding\", r.Compression.ContentEncoding)\n\t\treq.Header.Add(\"Accept-Encoding\", r.Compression.ContentEncoding)\n\t}\n\tif r.headers != nil {\n\t\tfor _, header := range r.headers {\n\t\t\treq.Header.Add(header.name, header.value)\n\t\t}\n\t}\n\n\t\/\/use basic auth if required\n\tif r.BasicAuthUsername != \"\" {\n\t\treq.SetBasicAuth(r.BasicAuthUsername, r.BasicAuthPassword)\n\t}\n\n\ttimeout := false\n\tvar timer *time.Timer\n\tif r.Timeout > 0 {\n\t\ttimer = time.AfterFunc(r.Timeout, func() {\n\t\t\ttransport.CancelRequest(req)\n\t\t\ttimeout = true\n\t\t})\n\t}\n\n\tres, err := client.Do(req)\n\tif timer != nil {\n\t\ttimer.Stop()\n\t}\n\n\tif err != nil {\n\t\tif !timeout {\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *net.OpError:\n\t\t\t\ttimeout = err.Timeout()\n\t\t\tcase *url.Error:\n\t\t\t\tif op, ok := err.Err.(*net.OpError); ok {\n\t\t\t\t\ttimeout = op.Timeout()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar response *Response\n\t\t\/\/If redirect fails we still want to return response data\n\t\tif redirectFailed {\n\t\t\tresponse = &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body}}\n\t\t}\n\n\t\treturn response, &Error{timeout: timeout, Err: err}\n\t}\n\n\tif r.Compression != nil && strings.Contains(res.Header.Get(\"Content-Encoding\"), r.Compression.ContentEncoding) {\n\t\tcompressedReader, err := r.Compression.reader(res.Body)\n\t\tif err != nil {\n\t\t\treturn nil, &Error{Err: err}\n\t\t}\n\t\treturn &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body, compressedReader: compressedReader}}, nil\n\t} else {\n\t\treturn &Response{StatusCode: res.StatusCode, ContentLength: res.ContentLength, Header: res.Header, Body: &Body{reader: res.Body}}, nil\n\t}\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<|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\"regexp\"\n\t\"strings\"\n)\n\ntype Toc struct {\n\t\/\/ DocToc\n\tdepth  []int\n\tspaces []string\n\ttitle  []string\n\tlink   []string\n}\n\nfunc headerTitle() string {\n\theader := \"\\n**Table of Contents**\"\n\treturn header\n}\n\nfunc headerCredits() string {\n\treturn \"\\n<!-- Table of Contents generated by [gotoc](https:\/\/github.com\/Belekkk\/gotoc) -->\"\n}\n\nfunc createHeader(title string) string {\n\tcontentHeader := fmt.Sprintf(\"%s %s \\n\", headerCredits(), title)\n\treturn contentHeader\n}\n\nfunc removeSpecialCharacters(str string) string {\n\tr, _ := regexp.Compile(\"([a-zA-Z]+)\")\n\tcleanedStr := r.FindAllString(str, -1)\n\treturn strings.Join(cleanedStr, \" \")\n}\n\nfunc formatLink(str string) string {\n\tlink := strings.Replace(str, \" \", \"-\", -1)\n\tlink = strings.ToLower(link)\n\tlink = strings.Join([]string{\"#\", link}, \"\")\n\treturn link\n}\n\nfunc computeSpaces(depth int) string {\n\tspaces := strings.Repeat(\" \", depth)\n\treturn spaces\n}\n\nfunc main() {\n\tvar startsWith bool\n\tvar line string\n\tvar doctoc = new(Toc)\n\tvar fileContent []string\n\n\tfilename := flag.String(\"file\", \"\", \"a string\")\n\tmaxDepth := flag.Int(\"depth\", 3, \"an int\")\n\ttitle := flag.String(\"title\", headerTitle(), \"a string\")\n\tnoTitle := flag.Bool(\"notitle\", false, \"a bool\")\n\tflag.Parse()\n\n\tfile, err := os.OpenFile(*filename, os.O_RDWR|os.O_APPEND, 0600)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline = scanner.Text()\n\t\tstartsWith = strings.HasPrefix(line, \"#\")\n\t\tif startsWith == true {\n\t\t\theaderCount := strings.Count(line, \"#\")\n\n\t\t\tif headerCount <= *maxDepth {\n\t\t\t\tcontent := line[headerCount+1:]\n\t\t\t\tdoctoc.depth = append(doctoc.depth, headerCount)\n\t\t\t\tindentation := (headerCount - 1) * 2\n\t\t\t\tnSpaces := computeSpaces(indentation)\n\t\t\t\tcleanedContent := removeSpecialCharacters(content)\n\t\t\t\tdoctoc.spaces = append(doctoc.spaces, nSpaces)\n\t\t\t\tdoctoc.title = append(doctoc.title, content)\n\t\t\t\tdoctoc.link = append(doctoc.link, formatLink(cleanedContent))\n\t\t\t}\n\t\t}\n\t\tfileContent = append(fileContent, line)\n\t}\n\n\terr = os.Remove(*filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif *noTitle == true {\n\t\t*title = \"\"\n\t}\n\n\tnewFile, err := os.OpenFile(*filename, os.O_CREATE|os.O_RDWR, 0600)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer newFile.Close()\n\n\tif _, err = newFile.WriteString(createHeader(*title)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor i := range doctoc.depth {\n\t\tdoctocContent := fmt.Sprintf(\"%s- [%s](%s) \\n\", doctoc.spaces[i], doctoc.title[i], doctoc.link[i])\n\t\tif _, err = newFile.WriteString(doctocContent); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfor i := range fileContent {\n\t\toriginalContent := fmt.Sprintf(\"%s\\n\", fileContent[i])\n\t\tif _, err = newFile.WriteString(originalContent); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<commit_msg>Improve output<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Toc struct {\n\t\/\/ DocToc\n\tdepth  []int\n\tspaces []string\n\ttitle  []string\n\tlink   []string\n}\n\nfunc headerTitle() string {\n\theader := \"\\n**Table of Contents**\"\n\treturn header\n}\n\nfunc headerCredits() string {\n\treturn \"\\n<!-- Table of Contents generated by [gotoc](https:\/\/github.com\/Belekkk\/gotoc) -->\"\n}\n\nfunc createHeader(title string) string {\n\tcontentHeader := fmt.Sprintf(\"%s %s \\n\", headerCredits(), title)\n\treturn contentHeader\n}\n\nfunc removeSpecialCharacters(str string) string {\n\tr, _ := regexp.Compile(\"([a-zA-Z]+)\")\n\tcleanedStr := r.FindAllString(str, -1)\n\treturn strings.Join(cleanedStr, \" \")\n}\n\nfunc formatLink(str string) string {\n\tlink := strings.Replace(str, \" \", \"-\", -1)\n\tlink = strings.ToLower(link)\n\tlink = strings.Join([]string{\"#\", link}, \"\")\n\treturn link\n}\n\nfunc computeSpaces(depth int) string {\n\tspaces := strings.Repeat(\" \", depth)\n\treturn spaces\n}\n\nfunc outputLine(n int) string {\n\tline := strings.Repeat(\"-\", n)\n\treturn line\n}\n\nfunc main() {\n\tvar startsWith bool\n\tvar line string\n\tvar doctoc = new(Toc)\n\tvar fileContent []string\n\n\tfilename := flag.String(\"file\", \"\", \"a string\")\n\tmaxDepth := flag.Int(\"depth\", 3, \"an int\")\n\ttitle := flag.String(\"title\", headerTitle(), \"a string\")\n\tnoTitle := flag.Bool(\"notitle\", false, \"a bool\")\n\tflag.Parse()\n\n\tfile, err := os.OpenFile(*filename, os.O_RDWR|os.O_APPEND, 0600)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline = scanner.Text()\n\t\tstartsWith = strings.HasPrefix(line, \"#\")\n\t\tif startsWith == true {\n\t\t\theaderCount := strings.Count(line, \"#\")\n\n\t\t\tif headerCount <= *maxDepth {\n\t\t\t\tcontent := line[headerCount+1:]\n\t\t\t\tdoctoc.depth = append(doctoc.depth, headerCount)\n\t\t\t\tindentation := (headerCount - 1) * 2\n\t\t\t\tnSpaces := computeSpaces(indentation)\n\t\t\t\tcleanedContent := removeSpecialCharacters(content)\n\t\t\t\tdoctoc.spaces = append(doctoc.spaces, nSpaces)\n\t\t\t\tdoctoc.title = append(doctoc.title, content)\n\t\t\t\tdoctoc.link = append(doctoc.link, formatLink(cleanedContent))\n\t\t\t}\n\t\t}\n\t\tfileContent = append(fileContent, line)\n\t}\n\n\terr = os.Remove(*filename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif *noTitle == true {\n\t\t*title = \"\"\n\t}\n\n\tnewFile, err := os.OpenFile(*filename, os.O_CREATE|os.O_RDWR, 0600)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer newFile.Close()\n\n\tif _, err = newFile.WriteString(createHeader(*title)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tos.Stderr.WriteString(\"Generating Table of Contents\\n\")\n\tos.Stderr.WriteString(fmt.Sprintf(\"%s\\n\", outputLine(28)))\n\tfor i := range doctoc.depth {\n\t\tdoctocContent := fmt.Sprintf(\"%s- [%s](%s) \\n\", doctoc.spaces[i], doctoc.title[i], doctoc.link[i])\n\t\tif _, err = newFile.WriteString(doctocContent); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tos.Stderr.WriteString(fmt.Sprintf(\"'%s' will be updated\\n\", *filename))\n\tfor i := range fileContent {\n\t\toriginalContent := fmt.Sprintf(\"%s\\n\", fileContent[i])\n\t\tif _, err = newFile.WriteString(originalContent); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tos.Stderr.WriteString(\"Done\\n\")\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The kube-etcd-controller 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 e2e\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/kube-etcd-controller\/pkg\/spec\"\n\t\"github.com\/coreos\/kube-etcd-controller\/pkg\/util\/k8sutil\"\n\t\"github.com\/coreos\/kube-etcd-controller\/test\/e2e\/framework\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\tk8sclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestResizeCluster3to5(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\n\ttestEtcd.Spec.Size = 5\n\tif err := updateEtcdCluster(f, testEtcd); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 5, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 5 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestResizeCluster5to3(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 5))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 5, 90); err != nil {\n\t\tt.Fatalf(\"failed to create 5 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 5 members cluster\")\n\n\ttestEtcd.Spec.Size = 3\n\tif err := updateEtcdCluster(f, testEtcd); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestOneMemberRecovery(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tnames, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\n\tif err := killMembers(f, names[0]); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestDisasterRecovery(t *testing.T) {\n\tf := framework.Global\n\tbackupPolicy := &spec.BackupPolicy{\n\t\tSnapshotIntervalInSecond: 120,\n\t\tMaxSnapshot:              5,\n\t\tVolumeSizeInMB:           512,\n\t\tStorageType:              spec.BackupStorageTypePersistentVolume,\n\t\tCleanupBackupIfDeleted:   true,\n\t}\n\torigEtcd := makeEtcdCluster(\"test-etcd-\", 3)\n\torigEtcd = etcdClusterWithBackup(origEtcd, backupPolicy)\n\ttestEtcd, err := createEtcdCluster(f, origEtcd)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ TODO: add checking of removal of backup pod\n\t}()\n\n\tnames, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\tif err := killMembers(f, names[0], names[1]); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 120); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n\t\/\/ TODO: add checking of data in etcd\n}\n\nfunc waitUntilSizeReached(f *framework.Framework, clusterName string, size, timeout int) ([]string, error) {\n\treturn waitSizeReachedWithFilter(f, clusterName, size, timeout, func(*api.Pod) bool { return true })\n}\n\nfunc waitSizeReachedWithFilter(f *framework.Framework, clusterName string, size, timeout int, filterPod func(*api.Pod) bool) ([]string, error) {\n\tvar names []string\n\terr := wait.Poll(5*time.Second, time.Duration(timeout)*time.Second, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.Pods(f.Namespace.Name).List(k8sutil.EtcdPodListOpt(clusterName))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tnames = nil\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tif pod.Status.Phase == api.PodRunning {\n\t\t\t\tnames = append(names, pod.Name)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"waiting size (%d), etcd pods: %v\\n\", size, names)\n\t\tif len(names) != size {\n\t\t\treturn false, nil\n\t\t}\n\t\t\/\/ TODO: check etcd member membership\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn names, nil\n}\n\nfunc killMembers(f *framework.Framework, names ...string) error {\n\tfor _, name := range names {\n\t\terr := f.KubeClient.Pods(f.Namespace.Name).Delete(name, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc makeEtcdCluster(genName string, size int) *spec.EtcdCluster {\n\treturn &spec.EtcdCluster{\n\t\tTypeMeta: unversioned.TypeMeta{\n\t\t\tKind:       \"EtcdCluster\",\n\t\t\tAPIVersion: \"coreos.com\/v1\",\n\t\t},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tGenerateName: genName,\n\t\t},\n\t\tSpec: spec.ClusterSpec{\n\t\t\tSize: size,\n\t\t},\n\t}\n}\n\nfunc etcdClusterWithBackup(ec *spec.EtcdCluster, backupPolicy *spec.BackupPolicy) *spec.EtcdCluster {\n\tec.Spec.Backup = backupPolicy\n\treturn ec\n}\nfunc etcdClusterWithVersion(ec *spec.EtcdCluster, version string) *spec.EtcdCluster {\n\tec.Spec.Version = version\n\treturn ec\n}\n\nfunc createEtcdCluster(f *framework.Framework, e *spec.EtcdCluster) (*spec.EtcdCluster, error) {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := f.KubeClient.Client.Post(\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\", f.MasterHost, f.Namespace.Name),\n\t\t\"application\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusCreated {\n\t\treturn nil, fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\tdecoder := json.NewDecoder(resp.Body)\n\tres := &spec.EtcdCluster{}\n\tif err := decoder.Decode(res); err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Printf(\"created etcd cluster: %v\\n\", res.Name)\n\treturn res, nil\n}\n\nfunc updateEtcdCluster(f *framework.Framework, e *spec.EtcdCluster) error {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\",\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\/%s\", f.MasterHost, f.Namespace.Name, e.Name),\n\t\tbytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tresp, err := f.KubeClient.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\treturn nil\n}\n\nfunc deleteEtcdCluster(f *framework.Framework, name string) error {\n\t\/\/ TODO: save etcd logs.\n\tfmt.Printf(\"deleting etcd cluster: %v\\n\", name)\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := getLogs(f.KubeClient, f.Namespace.Name, \"kube-etcd-controller\", \"kube-etcd-controller\", buf); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"kube-etcd-controller logs ===\")\n\tfmt.Println(buf.String())\n\tfmt.Println(\"kube-etcd-controller logs END ===\")\n\n\treq, err := http.NewRequest(\"DELETE\",\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\/%s\", f.MasterHost, f.Namespace.Name, name), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := f.KubeClient.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\treturn nil\n}\n\nfunc getLogs(kubecli *k8sclient.Client, ns, p, c string, out io.Writer) error {\n\treq := kubecli.RESTClient.Get().\n\t\tNamespace(ns).\n\t\tResource(\"pods\").\n\t\tName(p).\n\t\tSubResource(\"log\").\n\t\tParam(\"container\", c).\n\t\tParam(\"tailLines\", \"20\")\n\n\treadCloser, err := req.Stream()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer readCloser.Close()\n\n\t_, err = io.Copy(out, readCloser)\n\treturn err\n}\n<commit_msg>e2e: add etcd pods info and failed pod logs<commit_after>\/\/ Copyright 2016 The kube-etcd-controller 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 e2e\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/kube-etcd-controller\/pkg\/spec\"\n\t\"github.com\/coreos\/kube-etcd-controller\/pkg\/util\/k8sutil\"\n\t\"github.com\/coreos\/kube-etcd-controller\/test\/e2e\/framework\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/unversioned\"\n\tk8sclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n)\n\nfunc TestCreateCluster(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestResizeCluster3to5(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\n\ttestEtcd.Spec.Size = 5\n\tif err := updateEtcdCluster(f, testEtcd); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 5, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 5 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestResizeCluster5to3(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 5))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 5, 90); err != nil {\n\t\tt.Fatalf(\"failed to create 5 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 5 members cluster\")\n\n\ttestEtcd.Spec.Size = 3\n\tif err := updateEtcdCluster(f, testEtcd); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestOneMemberRecovery(t *testing.T) {\n\tf := framework.Global\n\ttestEtcd, err := createEtcdCluster(f, makeEtcdCluster(\"test-etcd-\", 3))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tnames, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\n\tif err := killMembers(f, names[0]); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n}\n\nfunc TestDisasterRecovery(t *testing.T) {\n\tf := framework.Global\n\tbackupPolicy := &spec.BackupPolicy{\n\t\tSnapshotIntervalInSecond: 120,\n\t\tMaxSnapshot:              5,\n\t\tVolumeSizeInMB:           512,\n\t\tStorageType:              spec.BackupStorageTypePersistentVolume,\n\t\tCleanupBackupIfDeleted:   true,\n\t}\n\torigEtcd := makeEtcdCluster(\"test-etcd-\", 3)\n\torigEtcd = etcdClusterWithBackup(origEtcd, backupPolicy)\n\ttestEtcd, err := createEtcdCluster(f, origEtcd)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := deleteEtcdCluster(f, testEtcd.Name); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ TODO: add checking of removal of backup pod\n\t}()\n\n\tnames, err := waitUntilSizeReached(f, testEtcd.Name, 3, 60)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create 3 members etcd cluster: %v\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"reached to 3 members cluster\")\n\tif err := killMembers(f, names[0], names[1]); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := waitUntilSizeReached(f, testEtcd.Name, 3, 120); err != nil {\n\t\tt.Fatalf(\"failed to resize to 3 members etcd cluster: %v\", err)\n\t}\n\t\/\/ TODO: add checking of data in etcd\n}\n\nfunc waitUntilSizeReached(f *framework.Framework, clusterName string, size, timeout int) ([]string, error) {\n\treturn waitSizeReachedWithFilter(f, clusterName, size, timeout, func(*api.Pod) bool { return true })\n}\n\nfunc waitSizeReachedWithFilter(f *framework.Framework, clusterName string, size, timeout int, filterPod func(*api.Pod) bool) ([]string, error) {\n\tvar names []string\n\terr := wait.Poll(5*time.Second, time.Duration(timeout)*time.Second, func() (done bool, err error) {\n\t\tpodList, err := f.KubeClient.Pods(f.Namespace.Name).List(k8sutil.EtcdPodListOpt(clusterName))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tnames = nil\n\t\tfor i := range podList.Items {\n\t\t\tpod := &podList.Items[i]\n\t\t\tif pod.Status.Phase == api.PodRunning {\n\t\t\t\tnames = append(names, pod.Name)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"waiting size (%d), etcd pods: %v\\n\", size, names)\n\t\tif len(names) != size {\n\t\t\treturn false, nil\n\t\t}\n\t\t\/\/ TODO: check etcd member membership\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn names, nil\n}\n\nfunc killMembers(f *framework.Framework, names ...string) error {\n\tfor _, name := range names {\n\t\terr := f.KubeClient.Pods(f.Namespace.Name).Delete(name, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc makeEtcdCluster(genName string, size int) *spec.EtcdCluster {\n\treturn &spec.EtcdCluster{\n\t\tTypeMeta: unversioned.TypeMeta{\n\t\t\tKind:       \"EtcdCluster\",\n\t\t\tAPIVersion: \"coreos.com\/v1\",\n\t\t},\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tGenerateName: genName,\n\t\t},\n\t\tSpec: spec.ClusterSpec{\n\t\t\tSize: size,\n\t\t},\n\t}\n}\n\nfunc etcdClusterWithBackup(ec *spec.EtcdCluster, backupPolicy *spec.BackupPolicy) *spec.EtcdCluster {\n\tec.Spec.Backup = backupPolicy\n\treturn ec\n}\nfunc etcdClusterWithVersion(ec *spec.EtcdCluster, version string) *spec.EtcdCluster {\n\tec.Spec.Version = version\n\treturn ec\n}\n\nfunc createEtcdCluster(f *framework.Framework, e *spec.EtcdCluster) (*spec.EtcdCluster, error) {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := f.KubeClient.Client.Post(\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\", f.MasterHost, f.Namespace.Name),\n\t\t\"application\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusCreated {\n\t\treturn nil, fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\tdecoder := json.NewDecoder(resp.Body)\n\tres := &spec.EtcdCluster{}\n\tif err := decoder.Decode(res); err != nil {\n\t\treturn nil, err\n\t}\n\tfmt.Printf(\"created etcd cluster: %v\\n\", res.Name)\n\treturn res, nil\n}\n\nfunc updateEtcdCluster(f *framework.Framework, e *spec.EtcdCluster) error {\n\tb, err := json.Marshal(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\",\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\/%s\", f.MasterHost, f.Namespace.Name, e.Name),\n\t\tbytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tresp, err := f.KubeClient.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\treturn nil\n}\n\nfunc deleteEtcdCluster(f *framework.Framework, name string) error {\n\tfmt.Printf(\"deleting etcd cluster: %v\\n\", name)\n\tpodList, err := f.KubeClient.Pods(f.Namespace.Name).List(k8sutil.EtcdPodListOpt(name))\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"etcd pods ======\")\n\tfor i := range podList.Items {\n\t\tpod := &podList.Items[i]\n\t\tfmt.Printf(\"pod (%v): status (%v)\\n\", pod.Name, pod.Status.Phase)\n\t\tbuf := bytes.NewBuffer(nil)\n\n\t\tif pod.Status.Phase == api.PodFailed {\n\t\t\tif err := getLogs(f.KubeClient, f.Namespace.Name, pod.Name, \"etcd\", buf); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Println(pod.Name, \"logs ===\")\n\t\t\tfmt.Println(buf.String())\n\t\t\tfmt.Println(pod.Name, \"logs END ===\")\n\t\t}\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := getLogs(f.KubeClient, f.Namespace.Name, \"kube-etcd-controller\", \"kube-etcd-controller\", buf); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"kube-etcd-controller logs ===\")\n\tfmt.Println(buf.String())\n\tfmt.Println(\"kube-etcd-controller logs END ===\")\n\n\treq, err := http.NewRequest(\"DELETE\",\n\t\tfmt.Sprintf(\"%s\/apis\/coreos.com\/v1\/namespaces\/%s\/etcdclusters\/%s\", f.MasterHost, f.Namespace.Name, name), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := f.KubeClient.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status: %v\", resp.Status)\n\t}\n\treturn nil\n}\n\nfunc getLogs(kubecli *k8sclient.Client, ns, p, c string, out io.Writer) error {\n\treq := kubecli.RESTClient.Get().\n\t\tNamespace(ns).\n\t\tResource(\"pods\").\n\t\tName(p).\n\t\tSubResource(\"log\").\n\t\tParam(\"container\", c).\n\t\tParam(\"tailLines\", \"20\")\n\n\treadCloser, err := req.Stream()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer readCloser.Close()\n\n\t_, err = io.Copy(out, readCloser)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n)\n\ntype IPAddress struct {\n\tIP string `json:\"ip\"`\n}\n\nfunc ipify(w http.ResponseWriter, r *http.Request) {\n\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\tfmt.Println(r.Header[\"X-Forwarded-For\"])\n\t\/\/host, _, err := net.SplitHostPort(r.Header[\"X-Forwarded-For\"])\n\tif err != nil {\n\t\tlog.Fatal(\"SplitHostPort:\", err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tjsonStr, _ := json.MarshalIndent(IPAddress{host}, \"\", \"  \")\n\tfmt.Fprintf(w, string(jsonStr))\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", ipify)\n\n\terr := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>Trying to grab the last element.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n)\n\ntype IPAddress struct {\n\tIP string `json:\"ip\"`\n}\n\nfunc ipify(w http.ResponseWriter, r *http.Request) {\n\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\tfmt.Println(r.Header[\"X-Forwarded-For\"][len(r.Header[\"X-Forwarded-For\"])])\n\t\/\/host, _, err := net.SplitHostPort(r.Header[\"X-Forwarded-For\"])\n\tif err != nil {\n\t\tlog.Fatal(\"SplitHostPort:\", err)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tjsonStr, _ := json.MarshalIndent(IPAddress{host}, \"\", \"  \")\n\tfmt.Fprintf(w, string(jsonStr))\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", ipify)\n\n\terr := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"github.com\/tears-of-noobs\/bytefmt\"\n\t\"fmt\"\n\t\"github.com\/sandreas\/graft\/pattern\"\n\t\"github.com\/sandreas\/graft\/file\"\n\t\"strconv\"\n\t\"regexp\"\n\t\"path\"\n\t\"strings\"\n\t\"math\"\n\t\"time\"\n)\n\nvar (\n\tapp = kingpin.New(\"graft\", \"A command-line tool to locate and transfer files\")\n\tsourcePatternParameter = app.Arg(\"source-pattern\", \"source pattern - used to locate files (e.g. src\/*)\").Required().String()\n\tdestinationPatternParameter = app.Arg(\"destination-pattern\", \"destination pattern for transfer (e.g. dst\/$1)\").Default(\"\").String()\n\n\texportTo = app.Flag(\"export-to\", \"export source listing to file, one line per found item\").Default(\"\").String()\n\tfilesFrom = app.Flag(\"files-from\", \"import source listing from file, one line per item\").Default(\"\").String()\n\n\tminAge = app.Flag(\"min-age\", \" minimum age (e.g. -2 days, -8 weeks, 2015-10-10, etc.)\").Default(\"\").String()\n\tmaxAge = app.Flag(\"max-age\", \"maximum age (e.g. 2 days, 8 weeks, 2015-10-10, etc.)\").Default(\"\").String()\n\n\n\tcaseSensitive = app.Flag(\"case-sensitive\", \"be case sensitive when matching files and folders\").Bool()\n\tdryRun = app.Flag(\"dry-run\", \"dry-run \/ simulation mode\").Bool()\n\thideMatches = app.Flag(\"hide-matches\", \"hide matches in search mode ($1: ...)\").Bool()\n\tmove = app.Flag(\"move\", \"move \/ rename files - do not make a copy\").Bool()\n\tquiet = app.Flag(\"quiet\", \"quiet mode - do not show any output\").Bool()\n\tregex = app.Flag(\"regex\", \"use a real regex instead of glob patterns (e.g. src\/.*\\\\.jpg)\").Bool()\n\ttimes = app.Flag(\"times\", \"transfer source modify times to destination\").Bool()\n)\n\nvar dirsToRemove = make([]string, 0)\nfunc main() {\n\tkingpin.MustParse(app.Parse(os.Args[1:]))\n\n\t\/\/firstBytes := int64(1003838300);\n\t\/\/size := firstBytes * 5;\n\t\/\/chunkSize:= int64(32*1024);\n\t\/\/\n\t\/\/handleProgress(firstBytes, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*2, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*3, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*4, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*5, size, chunkSize)\n\t\/\/os.Exit(0)\n\n\tsourcePattern := *sourcePatternParameter\n\tdestinationPattern := *destinationPatternParameter\n\n\tpatternPath, pat := pattern.ParsePathPattern(sourcePattern)\n\n\tsourcePathStat, err := os.Stat(patternPath)\n\n\tif sourcePathStat.Mode().IsRegular() {\n\t\tif strings.HasSuffix(destinationPattern, \"\/\") || strings.HasSuffix(destinationPattern, \"\\\\\") {\n\t\t\tdestinationPattern += sourcePathStat.Name()\n\t\t}\n\t\ttransferElementHandler(sourcePattern, destinationPattern)\n\t\treturn\n\t}\n\n\n\tif destinationPattern == \"\" {\n\t\tsearchIn := patternPath\n\t\tif patternPath == \"\" {\n\t\t\tsearchIn = \".\/\"\n\t\t}\n\n\t\tsearchFor := \"\"\n\t\tif pat != \"\" {\n\t\t\tsearchFor = pat\n\t\t}\n\t\tprntln(\"search in '\" + searchIn + \"': \" + searchFor)\n\n\t} else if (*move) {\n\t\tprntln(\"move: \" + sourcePattern + \" => \" + destinationPattern)\n\t} else {\n\t\tprntln(\"copy: \" + sourcePattern + \" => \" + destinationPattern)\n\t}\n\tprntln(\"\")\n\n\tif ! *regex {\n\t\tpat = pattern.GlobToRegex(pat)\n\t}\n\n\tcaseInsensitiveQualifier := \"(?i)\"\n\tif *caseSensitive {\n\t\tcaseInsensitiveQualifier = \"\"\n\t}\n\n\tcompiledPattern, err := pattern.CompileNormalizedPathPattern(patternPath, caseInsensitiveQualifier + pat)\n\tif err == nil && compiledPattern.NumSubexp() == 0 && pat != \"\" {\n\t\tcompiledPattern, err = pattern.CompileNormalizedPathPattern(patternPath, caseInsensitiveQualifier + \"(\" + pat + \")\")\n\t}\n\n\tif err != nil {\n\t\tprntln(\"could not compile source pattern, please use slashes to qualify paths (recognized path: \" + patternPath + \", pattern\" + pat + \")\")\n\t\treturn\n\t}\n\n\tvar matchingPaths []string\n\n\tif *filesFrom != \"\" {\n\t\tif ! file.Exists(*filesFrom) {\n\t\t\tprntln(\"Could not load files from \" + *filesFrom)\n\t\t\treturn\n\t\t}\n\t\tmatchingPaths, err = file.ReadAllLinesFunc(*filesFrom, file.SkipEmptyLines)\n\t} else {\n\t\t \/\/matchingPaths, err = file.WalkPathByPattern(patternPath, compiledPattern, progressHandlerWalkPathByPattern)\n\t\tmatchingFiles, _ := file.WalkPathFiltered(patternPath, func(f file.File, err error)(bool) {\n\t\t\tnormalizedPath := pattern.NormalizeDirSep(f.Path)\n\t\t\tif ! compiledPattern.MatchString(normalizedPath) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn minAgeFilter(f) && maxAgeFilter(f)\n\t\t}, progressHandlerWalkPathByPattern)\n\n\t\tfor _, element := range matchingFiles {\n\t\t\tmatchingPaths = append(matchingPaths, element.Path)\n\t\t}\n\n\t\tif *exportTo != \"\" {\n\t\t\texportFile(*exportTo, matchingPaths)\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tprntln(\"Could not load sources path \" + patternPath + \":\", err.Error())\n\t\treturn\n\t}\n\n\n\n\tif destinationPattern == \"\" {\n\t\tfor _, element := range matchingPaths {\n\t\t\tfindElementHandler(element, compiledPattern)\n\t\t}\n\t\treturn\n\t}\n\n\tdstPath, dstPatt := pattern.ParsePathPattern(destinationPattern)\n\tvar dst string\n\tfor _, element := range matchingPaths {\n\t\tif dstPatt == \"\" {\n\t\t\tdst = pattern.NormalizeDirSep(dstPath + element[len(patternPath)+1:])\n\t\t} else {\n\t\t\tdst = compiledPattern.ReplaceAllString(pattern.NormalizeDirSep(element), pattern.NormalizeDirSep(destinationPattern))\n\t\t}\n\t\ttransferElementHandler(element, dst)\n\t}\n\n\tif *move {\n\t\tfor _, dirToRemove := range dirsToRemove {\n\t\t\tos.Remove(dirToRemove)\n\t\t}\n\t}\n\treturn\n}\n\nfunc minAgeFilter(f file.File)(bool) {\n\tif *minAge == \"\" {\n\t\treturn true\n\t}\n\n\tminAgeTime, err := pattern.StrToAge(*minAge, time.Now())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn minAgeTime.UnixNano() > f.ModTime().UnixNano()\n}\n\nfunc maxAgeFilter(f file.File)(bool) {\n\tif *maxAge == \"\" {\n\t\treturn true\n\t}\n\n\tmaxAgeTime, err := pattern.StrToAge(*maxAge, time.Now())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn maxAgeTime.UnixNano() < f.ModTime().UnixNano()\n}\n\n\nfunc progressHandlerWalkPathByPattern(entriesWalked, entriesMatched int64, finished bool) (int64) {\n\tvar progress string;\n\tif entriesMatched == 0 {\n\t\tprogress = fmt.Sprintf(\"scanning - total: %d\", entriesWalked)\n\t} else {\n\t\tprogress = fmt.Sprintf(\"scanning - total: %d,  matches: %d\", entriesWalked, entriesMatched)\n\t}\n\t\/\/ prnt(\"\\x0c\" + progressBar)\n\tprnt(\"\\r\" + progress)\n\tif finished {\n\t\tprntln(\"\")\n\t\tprntln(\"\")\n\t}\n\tif(entriesWalked > 1000) {\n\t\treturn 500\n\t}\n\treturn 100\n}\n\n\nfunc exportFile(file string, lines []string) {\n\tf, err := os.Create(*exportTo)\n\tif err != nil {\n\t\tprntln(\"could not create export file \" + file + \": \" + err.Error())\n\t\treturn;\n\t}\n\t_, err = f.WriteString(strings.Join(lines, \"\\n\"))\n\tdefer f.Close()\n\tif err != nil {\n\t\tprntln(\"could not write export file \" + file + \": \" + err.Error())\n\t}\n\n}\n\nfunc appendRemoveDir(dir string) {\n\tif (*move) {\n\t\tdirsToRemove = append(dirsToRemove, dir)\n\t}\n}\n\n\nvar timerLastUpdate time.Time\nvar reportInterval int64\nvar bytesLastUpdate int64\n\nfunc startTimer(bytesTransferred, interval int64) {\n\tif bytesTransferred == 0 {\n\t\ttimerLastUpdate = time.Now()\n\t\treportInterval = interval\n\t\tbytesLastUpdate = 0\n\t}\n}\n\nfunc getReportStatus(bytesTransferred, size int64) (bool, float64, float64) {\n\ttimeDiffNano := time.Now().UnixNano() - timerLastUpdate.UnixNano()\n\t timeDiffSeconds := float64(timeDiffNano) \/ float64(time.Second)\n\t\/\/ if timeDiffSeconds >= float64(reportInterval) {\n\tif timeDiffNano >= reportInterval {\n\t\tbytesDiff := bytesTransferred - bytesLastUpdate\n\t\tbytesPerSecond := float64(float64(bytesDiff) \/ float64(timeDiffSeconds))\n\t\tpercent := float64(bytesTransferred) \/ float64(size)\n\n\t\tbytesLastUpdate = bytesTransferred\n\t\ttimerLastUpdate = time.Now()\n\n\t\treturn true, bytesPerSecond, percent\n\t}\n\n\treturn false, 0, 0\n}\n\n\n\nfunc handleProgress(bytesTransferred, size, chunkSize int64) (int64) {\n\n\tif size <= 0 {\n\t\treturn chunkSize\n\t}\n\n\tstartTimer(bytesTransferred, 1 * int64(time.Second))\n\tshouldReport, bytesPerSecond, percent := getReportStatus(bytesTransferred, size)\n\tif shouldReport {\n\t\tbandwidthOutput := \" \" + bytefmt.FormatBytes(bytesPerSecond, 2, true) + \"\/s\"\n\t\tcharCountWhenFullyTransmitted := 20\n\t\tprogressChars := int(math.Floor(percent * float64(charCountWhenFullyTransmitted)))\n\t\tnormalizedInt := percent * 100\n\t\tpercentOutput := strconv.FormatFloat(normalizedInt, 'f', 2, 64)\n\t\tif bytesPerSecond == 0 {\n\t\t\tbandwidthOutput = \"\"\n\t\t}\n\t\tprogressBar := fmt.Sprintf(\"[%-\" + strconv.Itoa(charCountWhenFullyTransmitted + 1)+ \"s] \" +percentOutput +  \"%%\" + bandwidthOutput, strings.Repeat(\"=\", progressChars) + \">\")\n\n\t\tprnt(\"\\r\" + progressBar)\n\t}\n\n\tif bytesTransferred == size {\n\t\tprntln(\"\")\n\t}\n\n\treturn chunkSize\n}\n\nfunc prntln(a ...interface{}) (n int, err error) {\n\tif ! *quiet {\n\t\treturn fmt.Println(a...)\n\t}\n\treturn n, err\n}\n\nfunc prnt(a...interface{}) (n int, err error) {\n\tif ! *quiet {\n\t\treturn fmt.Print(a...)\n\t}\n\treturn n, err\n}\n\nfunc findElementHandler(element string, compiledPattern *regexp.Regexp) {\n\tprntln(element)\n\tif *hideMatches {\n\t\treturn\n\t}\n\telementMatches := pattern.BuildMatchList(compiledPattern, element)\n\tfor i := 0; i < len(elementMatches); i++ {\n\t\tprntln(\"    $\" + strconv.Itoa(i + 1) + \": \" + elementMatches[i])\n\t}\n\n}\n\nfunc transferElementHandler(src, dst string) {\n\n\tprntln(src + \" => \" + dst)\n\n\tif *dryRun {\n\t\treturn\n\t}\n\n\tsrcStat, srcErr := os.Stat(src)\n\n\tif srcErr != nil {\n\t\tprntln(\"could not read source: \", srcErr)\n\t\treturn\n\t}\n\n\tdstStat, _ := os.Stat(dst)\n\tdstExists := file.Exists(dst)\n\tif srcStat.IsDir() {\n\t\tif ! dstExists {\n\t\t\tif os.MkdirAll(dst, srcStat.Mode()) != nil {\n\t\t\t\tprntln(\"Could not create destination directory\")\n\t\t\t}\n\t\t\tappendRemoveDir(dst)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\n\t\tif dstStat.IsDir() {\n\t\t\tappendRemoveDir(dst)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\n\t\tprntln(\"destination already exists as file, source is a directory\")\n\t\treturn\n\t}\n\n\tif dstExists && dstStat.IsDir() {\n\t\tprntln(\"destination already exists as directory, source is a file\")\n\t\treturn\n\t}\n\n\tsrcDir := path.Dir(src)\n\tsrcDirStat, _ := os.Stat(srcDir)\n\n\tdstDir := path.Dir(dst)\n\tif ! file.Exists(dstDir) {\n\t\tos.MkdirAll(dstDir, srcDirStat.Mode())\n\t}\n\n\tif *move {\n\t\trenameErr := os.Rename(src, dst)\n\t\tif renameErr == nil {\n\t\t\tappendRemoveDir(srcDir)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\t\tprntln(\"Could not rename source\")\n\t\treturn\n\t}\n\n\tsrcPointer, srcPointerErr := os.Open(src)\n\tif srcPointerErr != nil {\n\t\tprntln(\"Could not open source file\")\n\t\treturn\n\t}\n\tdstPointer, dstPointerErr := os.OpenFile(dst, os.O_WRONLY | os.O_CREATE, srcStat.Mode())\n\n\tif dstPointerErr != nil {\n\t\tprntln(\"Could not create destination file\", dstPointerErr.Error())\n\t\treturn\n\t}\n\n\tfile.CopyResumed(srcPointer, dstPointer, handleProgress)\n\tfixTimes(dst, srcStat)\n}\n\nfunc fixTimes(dst string, inStats os.FileInfo) {\n\tif *times {\n\t\tos.Chtimes(dst, inStats.ModTime(), inStats.ModTime())\n\t}\n}<commit_msg>Small fix for bandwidth output<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"github.com\/tears-of-noobs\/bytefmt\"\n\t\"fmt\"\n\t\"github.com\/sandreas\/graft\/pattern\"\n\t\"github.com\/sandreas\/graft\/file\"\n\t\"strconv\"\n\t\"regexp\"\n\t\"path\"\n\t\"strings\"\n\t\"math\"\n\t\"time\"\n)\n\nvar (\n\tapp = kingpin.New(\"graft\", \"A command-line tool to locate and transfer files\")\n\tsourcePatternParameter = app.Arg(\"source-pattern\", \"source pattern - used to locate files (e.g. src\/*)\").Required().String()\n\tdestinationPatternParameter = app.Arg(\"destination-pattern\", \"destination pattern for transfer (e.g. dst\/$1)\").Default(\"\").String()\n\n\texportTo = app.Flag(\"export-to\", \"export source listing to file, one line per found item\").Default(\"\").String()\n\tfilesFrom = app.Flag(\"files-from\", \"import source listing from file, one line per item\").Default(\"\").String()\n\n\tminAge = app.Flag(\"min-age\", \" minimum age (e.g. -2 days, -8 weeks, 2015-10-10, etc.)\").Default(\"\").String()\n\tmaxAge = app.Flag(\"max-age\", \"maximum age (e.g. 2 days, 8 weeks, 2015-10-10, etc.)\").Default(\"\").String()\n\n\n\tcaseSensitive = app.Flag(\"case-sensitive\", \"be case sensitive when matching files and folders\").Bool()\n\tdryRun = app.Flag(\"dry-run\", \"dry-run \/ simulation mode\").Bool()\n\thideMatches = app.Flag(\"hide-matches\", \"hide matches in search mode ($1: ...)\").Bool()\n\tmove = app.Flag(\"move\", \"move \/ rename files - do not make a copy\").Bool()\n\tquiet = app.Flag(\"quiet\", \"quiet mode - do not show any output\").Bool()\n\tregex = app.Flag(\"regex\", \"use a real regex instead of glob patterns (e.g. src\/.*\\\\.jpg)\").Bool()\n\ttimes = app.Flag(\"times\", \"transfer source modify times to destination\").Bool()\n)\n\nvar dirsToRemove = make([]string, 0)\nfunc main() {\n\tkingpin.MustParse(app.Parse(os.Args[1:]))\n\n\t\/\/firstBytes := int64(1003838300);\n\t\/\/size := firstBytes * 5;\n\t\/\/chunkSize:= int64(32*1024);\n\t\/\/\n\t\/\/handleProgress(firstBytes, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*2, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*3, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*4, size, chunkSize)\n\t\/\/time.Sleep(3 * time.Second)\n\t\/\/handleProgress(firstBytes*5, size, chunkSize)\n\t\/\/os.Exit(0)\n\n\tsourcePattern := *sourcePatternParameter\n\tdestinationPattern := *destinationPatternParameter\n\n\tpatternPath, pat := pattern.ParsePathPattern(sourcePattern)\n\n\tsourcePathStat, err := os.Stat(patternPath)\n\n\tif sourcePathStat.Mode().IsRegular() {\n\t\tif strings.HasSuffix(destinationPattern, \"\/\") || strings.HasSuffix(destinationPattern, \"\\\\\") {\n\t\t\tdestinationPattern += sourcePathStat.Name()\n\t\t}\n\t\ttransferElementHandler(sourcePattern, destinationPattern)\n\t\treturn\n\t}\n\n\n\tif destinationPattern == \"\" {\n\t\tsearchIn := patternPath\n\t\tif patternPath == \"\" {\n\t\t\tsearchIn = \".\/\"\n\t\t}\n\n\t\tsearchFor := \"\"\n\t\tif pat != \"\" {\n\t\t\tsearchFor = pat\n\t\t}\n\t\tprntln(\"search in '\" + searchIn + \"': \" + searchFor)\n\n\t} else if (*move) {\n\t\tprntln(\"move: \" + sourcePattern + \" => \" + destinationPattern)\n\t} else {\n\t\tprntln(\"copy: \" + sourcePattern + \" => \" + destinationPattern)\n\t}\n\tprntln(\"\")\n\n\tif ! *regex {\n\t\tpat = pattern.GlobToRegex(pat)\n\t}\n\n\tcaseInsensitiveQualifier := \"(?i)\"\n\tif *caseSensitive {\n\t\tcaseInsensitiveQualifier = \"\"\n\t}\n\n\tcompiledPattern, err := pattern.CompileNormalizedPathPattern(patternPath, caseInsensitiveQualifier + pat)\n\tif err == nil && compiledPattern.NumSubexp() == 0 && pat != \"\" {\n\t\tcompiledPattern, err = pattern.CompileNormalizedPathPattern(patternPath, caseInsensitiveQualifier + \"(\" + pat + \")\")\n\t}\n\n\tif err != nil {\n\t\tprntln(\"could not compile source pattern, please use slashes to qualify paths (recognized path: \" + patternPath + \", pattern\" + pat + \")\")\n\t\treturn\n\t}\n\n\tvar matchingPaths []string\n\n\tif *filesFrom != \"\" {\n\t\tif ! file.Exists(*filesFrom) {\n\t\t\tprntln(\"Could not load files from \" + *filesFrom)\n\t\t\treturn\n\t\t}\n\t\tmatchingPaths, err = file.ReadAllLinesFunc(*filesFrom, file.SkipEmptyLines)\n\t} else {\n\t\t \/\/matchingPaths, err = file.WalkPathByPattern(patternPath, compiledPattern, progressHandlerWalkPathByPattern)\n\t\tmatchingFiles, _ := file.WalkPathFiltered(patternPath, func(f file.File, err error)(bool) {\n\t\t\tnormalizedPath := pattern.NormalizeDirSep(f.Path)\n\t\t\tif ! compiledPattern.MatchString(normalizedPath) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\treturn minAgeFilter(f) && maxAgeFilter(f)\n\t\t}, progressHandlerWalkPathByPattern)\n\n\t\tfor _, element := range matchingFiles {\n\t\t\tmatchingPaths = append(matchingPaths, element.Path)\n\t\t}\n\n\t\tif *exportTo != \"\" {\n\t\t\texportFile(*exportTo, matchingPaths)\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tprntln(\"Could not load sources path \" + patternPath + \":\", err.Error())\n\t\treturn\n\t}\n\n\n\n\tif destinationPattern == \"\" {\n\t\tfor _, element := range matchingPaths {\n\t\t\tfindElementHandler(element, compiledPattern)\n\t\t}\n\t\treturn\n\t}\n\n\tdstPath, dstPatt := pattern.ParsePathPattern(destinationPattern)\n\tvar dst string\n\tfor _, element := range matchingPaths {\n\t\tif dstPatt == \"\" {\n\t\t\tdst = pattern.NormalizeDirSep(dstPath + element[len(patternPath)+1:])\n\t\t} else {\n\t\t\tdst = compiledPattern.ReplaceAllString(pattern.NormalizeDirSep(element), pattern.NormalizeDirSep(destinationPattern))\n\t\t}\n\t\ttransferElementHandler(element, dst)\n\t}\n\n\tif *move {\n\t\tfor _, dirToRemove := range dirsToRemove {\n\t\t\tos.Remove(dirToRemove)\n\t\t}\n\t}\n\treturn\n}\n\nfunc minAgeFilter(f file.File)(bool) {\n\tif *minAge == \"\" {\n\t\treturn true\n\t}\n\n\tminAgeTime, err := pattern.StrToAge(*minAge, time.Now())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn minAgeTime.UnixNano() > f.ModTime().UnixNano()\n}\n\nfunc maxAgeFilter(f file.File)(bool) {\n\tif *maxAge == \"\" {\n\t\treturn true\n\t}\n\n\tmaxAgeTime, err := pattern.StrToAge(*maxAge, time.Now())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn maxAgeTime.UnixNano() < f.ModTime().UnixNano()\n}\n\n\nfunc progressHandlerWalkPathByPattern(entriesWalked, entriesMatched int64, finished bool) (int64) {\n\tvar progress string;\n\tif entriesMatched == 0 {\n\t\tprogress = fmt.Sprintf(\"scanning - total: %d\", entriesWalked)\n\t} else {\n\t\tprogress = fmt.Sprintf(\"scanning - total: %d,  matches: %d\", entriesWalked, entriesMatched)\n\t}\n\t\/\/ prnt(\"\\x0c\" + progressBar)\n\tprnt(\"\\r\" + progress)\n\tif finished {\n\t\tprntln(\"\")\n\t\tprntln(\"\")\n\t}\n\tif(entriesWalked > 1000) {\n\t\treturn 500\n\t}\n\treturn 100\n}\n\n\nfunc exportFile(file string, lines []string) {\n\tf, err := os.Create(*exportTo)\n\tif err != nil {\n\t\tprntln(\"could not create export file \" + file + \": \" + err.Error())\n\t\treturn;\n\t}\n\t_, err = f.WriteString(strings.Join(lines, \"\\n\"))\n\tdefer f.Close()\n\tif err != nil {\n\t\tprntln(\"could not write export file \" + file + \": \" + err.Error())\n\t}\n\n}\n\nfunc appendRemoveDir(dir string) {\n\tif (*move) {\n\t\tdirsToRemove = append(dirsToRemove, dir)\n\t}\n}\n\n\nvar timerLastUpdate time.Time\nvar reportInterval int64\nvar bytesLastUpdate int64\n\nfunc startTimer(bytesTransferred, interval int64) {\n\tif bytesTransferred == 0 {\n\t\ttimerLastUpdate = time.Now()\n\t\treportInterval = interval\n\t\tbytesLastUpdate = 0\n\t}\n}\n\nfunc getReportStatus(bytesTransferred, size int64) (bool, float64, float64) {\n\ttimeDiffNano := time.Now().UnixNano() - timerLastUpdate.UnixNano()\n\t timeDiffSeconds := float64(timeDiffNano) \/ float64(time.Second)\n\t\/\/ if timeDiffSeconds >= float64(reportInterval) {\n\tif timeDiffNano >= reportInterval {\n\t\tbytesDiff := bytesTransferred - bytesLastUpdate\n\t\tbytesPerSecond := float64(float64(bytesDiff) \/ float64(timeDiffSeconds))\n\t\tpercent := float64(bytesTransferred) \/ float64(size)\n\n\t\tbytesLastUpdate = bytesTransferred\n\t\ttimerLastUpdate = time.Now()\n\n\t\treturn true, bytesPerSecond, percent\n\t}\n\n\treturn false, 0, 0\n}\n\n\n\nfunc handleProgress(bytesTransferred, size, chunkSize int64) (int64) {\n\n\tif size <= 0 {\n\t\treturn chunkSize\n\t}\n\n\tstartTimer(bytesTransferred, 1 * int64(time.Second))\n\tshouldReport, bytesPerSecond, percent := getReportStatus(bytesTransferred, size)\n\tif shouldReport {\n\t\tbandwidthOutput := \"   \" + bytefmt.FormatBytes(bytesPerSecond, 2, true) + \"\/s\"\n\t\tcharCountWhenFullyTransmitted := 20\n\t\tprogressChars := int(math.Floor(percent * float64(charCountWhenFullyTransmitted)))\n\t\tnormalizedInt := percent * 100\n\t\tpercentOutput := strconv.FormatFloat(normalizedInt, 'f', 2, 64)\n\t\tif bytesPerSecond == 0 {\n\t\t\tbandwidthOutput = \"\"\n\t\t}\n\t\tprogressBar := fmt.Sprintf(\"[%-\" + strconv.Itoa(charCountWhenFullyTransmitted + 1)+ \"s] \" +percentOutput +  \"%%\" + bandwidthOutput, strings.Repeat(\"=\", progressChars) + \">\")\n\n\t\tprnt(\"\\r\" + progressBar)\n\t}\n\n\tif bytesTransferred == size {\n\t\tprntln(\"\")\n\t}\n\n\treturn chunkSize\n}\n\nfunc prntln(a ...interface{}) (n int, err error) {\n\tif ! *quiet {\n\t\treturn fmt.Println(a...)\n\t}\n\treturn n, err\n}\n\nfunc prnt(a...interface{}) (n int, err error) {\n\tif ! *quiet {\n\t\treturn fmt.Print(a...)\n\t}\n\treturn n, err\n}\n\nfunc findElementHandler(element string, compiledPattern *regexp.Regexp) {\n\tprntln(element)\n\tif *hideMatches {\n\t\treturn\n\t}\n\telementMatches := pattern.BuildMatchList(compiledPattern, element)\n\tfor i := 0; i < len(elementMatches); i++ {\n\t\tprntln(\"    $\" + strconv.Itoa(i + 1) + \": \" + elementMatches[i])\n\t}\n\n}\n\nfunc transferElementHandler(src, dst string) {\n\n\tprntln(src + \" => \" + dst)\n\n\tif *dryRun {\n\t\treturn\n\t}\n\n\tsrcStat, srcErr := os.Stat(src)\n\n\tif srcErr != nil {\n\t\tprntln(\"could not read source: \", srcErr)\n\t\treturn\n\t}\n\n\tdstStat, _ := os.Stat(dst)\n\tdstExists := file.Exists(dst)\n\tif srcStat.IsDir() {\n\t\tif ! dstExists {\n\t\t\tif os.MkdirAll(dst, srcStat.Mode()) != nil {\n\t\t\t\tprntln(\"Could not create destination directory\")\n\t\t\t}\n\t\t\tappendRemoveDir(dst)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\n\t\tif dstStat.IsDir() {\n\t\t\tappendRemoveDir(dst)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\n\t\tprntln(\"destination already exists as file, source is a directory\")\n\t\treturn\n\t}\n\n\tif dstExists && dstStat.IsDir() {\n\t\tprntln(\"destination already exists as directory, source is a file\")\n\t\treturn\n\t}\n\n\tsrcDir := path.Dir(src)\n\tsrcDirStat, _ := os.Stat(srcDir)\n\n\tdstDir := path.Dir(dst)\n\tif ! file.Exists(dstDir) {\n\t\tos.MkdirAll(dstDir, srcDirStat.Mode())\n\t}\n\n\tif *move {\n\t\trenameErr := os.Rename(src, dst)\n\t\tif renameErr == nil {\n\t\t\tappendRemoveDir(srcDir)\n\t\t\tfixTimes(dst, srcStat)\n\t\t\treturn\n\t\t}\n\t\tprntln(\"Could not rename source\")\n\t\treturn\n\t}\n\n\tsrcPointer, srcPointerErr := os.Open(src)\n\tif srcPointerErr != nil {\n\t\tprntln(\"Could not open source file\")\n\t\treturn\n\t}\n\tdstPointer, dstPointerErr := os.OpenFile(dst, os.O_WRONLY | os.O_CREATE, srcStat.Mode())\n\n\tif dstPointerErr != nil {\n\t\tprntln(\"Could not create destination file\", dstPointerErr.Error())\n\t\treturn\n\t}\n\n\tfile.CopyResumed(srcPointer, dstPointer, handleProgress)\n\tfixTimes(dst, srcStat)\n}\n\nfunc fixTimes(dst string, inStats os.FileInfo) {\n\tif *times {\n\t\tos.Chtimes(dst, inStats.ModTime(), inStats.ModTime())\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar lastSeenLimit = 30 * 24 * time.Hour\nvar lastSeenWriteThresh = time.Minute\nvar greeting *template.Template\n\n\/\/ maps channel -> (nick -> last seen)\nvar lastSeen = struct {\n\tmtx sync.Mutex\n\tm   map[string]map[string]time.Time\n}{}\n\nfunc init() {\n\treadLastSeen()\n\treadGreeting()\n}\n\nfunc touchLastSeen(channel string, nick string) (absent time.Duration) {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\tc := lastSeen.m[channel]\n\tif c == nil {\n\t\tc = make(map[string]time.Time)\n\t\tlastSeen.m[channel] = c\n\t}\n\tt := c[nick]\n\tc[nick] = time.Now()\n\treturn time.Now().Sub(t)\n}\n\nfunc runnerGreet(parsed Message) {\n\tbotnick := *nick\n\tif botnick == Nick(parsed) {\n\t\t\/\/ we ignore ourselves\n\t\treturn\n\t}\n\tnick := Nick(parsed)\n\n\tvar channel string\n\tswitch parsed.Command {\n\tcase \"JOIN\":\n\t\tchannel = parsed.Trailing\n\tcase \"PART\":\n\t\tchannel = Target(parsed)\n\tcase \"PRIVMSG\":\n\t\tchannel = Target(parsed)\n\tdefault:\n\t\treturn\n\t}\n\n\t\/\/ TODO: Make channels configurable\n\tif channel != \"#chaos-hd\" {\n\t\treturn\n\t}\n\n\tif channel == \"\" || channel[0] != '#' {\n\t\tlog.Printf(\"Not greeting in non-channel %q\", channel)\n\t\treturn\n\t}\n\n\t\/\/ To handle renames of users correctly, we also save the hostmask. Only if\n\t\/\/ we've seen neither it's a genuinely new user.\n\tabsentNick := touchLastSeen(channel, nick)\n\tabsentHostmask := touchLastSeen(channel, Hostmask(parsed))\n\tseen := (absentNick <= lastSeenLimit) || (absentHostmask <= lastSeenLimit)\n\tif parsed.Command == \"JOIN\" && !seen {\n\t\tlog.Printf(\"I have not seen %q in %q recently, so I'm greeting them\", nick, channel)\n\n\t\tparams := struct {\n\t\t\tNick string\n\t\t\tBot  string\n\t\t}{nick, botnick}\n\n\t\tvar msg string\n\n\t\tmsgBuf := new(bytes.Buffer)\n\t\tif greeting == nil {\n\t\t\tmsg = fmt.Sprintf(\"Hey %s! o\/\", nick)\n\t\t} else if err := greeting.Execute(msgBuf, params); err != nil {\n\t\t\tlog.Println(\"Could not render greeting:\", err)\n\t\t\tmsg = fmt.Sprintf(\"Hey %s! o\/\", nick)\n\t\t} else {\n\t\t\tmsg = msgBuf.String()\n\t\t}\n\t\tPrivmsg(channel, msg)\n\t}\n\n\tif absentNick > lastSeenWriteThresh || absentHostmask > lastSeenWriteThresh {\n\t\twriteLastSeen()\n\t}\n}\n\nfunc writeLastSeen() {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\tlog.Println(\"Writing last-seen\")\n\n\t\/\/ Take out the garbage\n\tfor _, c := range lastSeen.m {\n\t\tfor nick, last := range c {\n\t\t\tif time.Now().Sub(last) > lastSeenLimit {\n\t\t\t\tdelete(c, nick)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ We write the file atomically to prevent corruption\n\ttmp, err := ioutil.TempFile(\".\", \".last-seen\")\n\tif err != nil {\n\t\tlog.Println(\"Could not create temporary file for last-seen:\", err)\n\t\treturn\n\t}\n\tdefer os.Remove(tmp.Name())\n\n\tif err := gob.NewEncoder(tmp).Encode(lastSeen.m); err != nil {\n\t\tlog.Println(\"Could not write last-seen:\", err)\n\t\treturn\n\t}\n\n\tif err := os.Rename(tmp.Name(), \"last-seen\"); err != nil {\n\t\tlog.Println(\"Could not write last-seen:\", err)\n\t\treturn\n\t}\n}\n\nfunc readLastSeen() {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\t\/\/ Make sure, lastSeen is initialized to a sane, if empty, value.\n\tdefer func() {\n\t\tif lastSeen.m == nil {\n\t\t\tlastSeen.m = make(map[string]map[string]time.Time)\n\t\t}\n\t}()\n\n\tf, err := os.Open(\"last-seen\")\n\tif err != nil {\n\t\tlog.Println(\"Could not read last-seen:\", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tvar m map[string]map[string]time.Time\n\tif err := gob.NewDecoder(f).Decode(&m); err != nil {\n\t\tlog.Println(\"Could not read last-seen:\", err)\n\t\treturn\n\t}\n\tlastSeen.m = m\n}\n\nfunc readGreeting() {\n\tt, err := template.ParseFiles(\"greeting.txt\")\n\tif err != nil {\n\t\tlog.Println(\"Could not parse greeting:\", err)\n\t\treturn\n\t}\n\tgreeting = t\n}\n<commit_msg>greet: Strip trailing _ when remembering people<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar lastSeenLimit = 30 * 24 * time.Hour\nvar lastSeenWriteThresh = time.Minute\nvar greeting *template.Template\n\n\/\/ maps channel -> (nick -> last seen)\nvar lastSeen = struct {\n\tmtx sync.Mutex\n\tm   map[string]map[string]time.Time\n}{}\n\nfunc init() {\n\treadLastSeen()\n\treadGreeting()\n}\n\nfunc touchLastSeen(channel string, nick string) (absent time.Duration) {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\tc := lastSeen.m[channel]\n\tif c == nil {\n\t\tc = make(map[string]time.Time)\n\t\tlastSeen.m[channel] = c\n\t}\n\tt := c[nick]\n\tc[nick] = time.Now()\n\treturn time.Now().Sub(t)\n}\n\nfunc runnerGreet(parsed Message) {\n\tbotnick := *nick\n\tif botnick == Nick(parsed) {\n\t\t\/\/ we ignore ourselves\n\t\treturn\n\t}\n\tnick := Nick(parsed)\n\n\tvar channel string\n\tswitch parsed.Command {\n\tcase \"JOIN\":\n\t\tchannel = parsed.Trailing\n\tcase \"PART\":\n\t\tchannel = Target(parsed)\n\tcase \"PRIVMSG\":\n\t\tchannel = Target(parsed)\n\tdefault:\n\t\treturn\n\t}\n\n\t\/\/ TODO: Make channels configurable\n\tif channel != \"#chaos-hd\" {\n\t\treturn\n\t}\n\n\tif channel == \"\" || channel[0] != '#' {\n\t\tlog.Printf(\"Not greeting in non-channel %q\", channel)\n\t\treturn\n\t}\n\n\t\/\/ To handle renames of users correctly, we also save the hostmask. Only if\n\t\/\/ we've seen neither it's a genuinely new user. We strip trailing _, they\n\t\/\/ usually appear for duplicate links when the original nick is taken by a\n\t\/\/ ghost.\n\tabsentNick := touchLastSeen(channel, strings.TrimRight(nick, \"_\"))\n\tabsentHostmask := touchLastSeen(channel, Hostmask(parsed))\n\tseen := (absentNick <= lastSeenLimit) || (absentHostmask <= lastSeenLimit)\n\tif parsed.Command == \"JOIN\" && !seen {\n\t\tlog.Printf(\"I have not seen %q in %q recently, so I'm greeting them\", nick, channel)\n\n\t\tparams := struct {\n\t\t\tNick string\n\t\t\tBot  string\n\t\t}{nick, botnick}\n\n\t\tvar msg string\n\n\t\tmsgBuf := new(bytes.Buffer)\n\t\tif greeting == nil {\n\t\t\tmsg = fmt.Sprintf(\"Hey %s! o\/\", nick)\n\t\t} else if err := greeting.Execute(msgBuf, params); err != nil {\n\t\t\tlog.Println(\"Could not render greeting:\", err)\n\t\t\tmsg = fmt.Sprintf(\"Hey %s! o\/\", nick)\n\t\t} else {\n\t\t\tmsg = msgBuf.String()\n\t\t}\n\t\tPrivmsg(channel, msg)\n\t}\n\n\tif absentNick > lastSeenWriteThresh || absentHostmask > lastSeenWriteThresh {\n\t\twriteLastSeen()\n\t}\n}\n\nfunc writeLastSeen() {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\tlog.Println(\"Writing last-seen\")\n\n\t\/\/ Take out the garbage\n\tfor _, c := range lastSeen.m {\n\t\tfor nick, last := range c {\n\t\t\tif time.Now().Sub(last) > lastSeenLimit {\n\t\t\t\tdelete(c, nick)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ We write the file atomically to prevent corruption\n\ttmp, err := ioutil.TempFile(\".\", \".last-seen\")\n\tif err != nil {\n\t\tlog.Println(\"Could not create temporary file for last-seen:\", err)\n\t\treturn\n\t}\n\tdefer os.Remove(tmp.Name())\n\n\tif err := gob.NewEncoder(tmp).Encode(lastSeen.m); err != nil {\n\t\tlog.Println(\"Could not write last-seen:\", err)\n\t\treturn\n\t}\n\n\tif err := os.Rename(tmp.Name(), \"last-seen\"); err != nil {\n\t\tlog.Println(\"Could not write last-seen:\", err)\n\t\treturn\n\t}\n}\n\nfunc readLastSeen() {\n\tlastSeen.mtx.Lock()\n\tdefer lastSeen.mtx.Unlock()\n\n\t\/\/ Make sure, lastSeen is initialized to a sane, if empty, value.\n\tdefer func() {\n\t\tif lastSeen.m == nil {\n\t\t\tlastSeen.m = make(map[string]map[string]time.Time)\n\t\t}\n\t}()\n\n\tf, err := os.Open(\"last-seen\")\n\tif err != nil {\n\t\tlog.Println(\"Could not read last-seen:\", err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tvar m map[string]map[string]time.Time\n\tif err := gob.NewDecoder(f).Decode(&m); err != nil {\n\t\tlog.Println(\"Could not read last-seen:\", err)\n\t\treturn\n\t}\n\tlastSeen.m = m\n}\n\nfunc readGreeting() {\n\tt, err := template.ParseFiles(\"greeting.txt\")\n\tif err != nil {\n\t\tlog.Println(\"Could not parse greeting:\", err)\n\t\treturn\n\t}\n\tgreeting = t\n}\n<|endoftext|>"}
{"text":"<commit_before>package pdb\n\nimport (\n\t\"unicode\"\n\n\t\"github.com\/TuftsBCB\/seq\"\n)\n\nfunc (m Model) seqAtomsGuess() []*Residue {\n\tseqres := m.Chain.Sequence\n\tmapping := make([]*Residue, len(seqres))\n\tif len(seqres) != len(m.Residues) {\n\t\t\/\/ This is a last ditch effort. Use the ATOM sequence number as an\n\t\t\/\/ index into the SEQRES residues.\n\t\tfor _, r := range m.Residues {\n\t\t\tsi := r.SequenceNum - 1\n\t\t\tif si >= 0 && si < len(seqres) && seqres[si] == r.Name {\n\t\t\t\tmapping[si] = r\n\t\t\t}\n\t\t}\n\t\treturn mapping\n\t}\n\n\tfor i, r := range m.Residues {\n\t\tif i < len(seqres) && seqres[i] == r.Name {\n\t\t\tmapping[i] = r\n\t\t}\n\t}\n\treturn mapping\n}\n\nfunc (m Model) seqAtomsAlign() []*Residue {\n\tseqres := m.Chain.Sequence\n\tatomResidues := make([]seq.Residue, len(m.Residues))\n\tfor i, r := range m.Residues {\n\t\tatomResidues[i] = r.Name\n\t}\n\taligned := seq.NeedlemanWunsch(seqres, atomResidues, seq.MatBlosum62)\n\n\tmapped := make([]*Residue, len(seqres))\n\tatomi := 0\n\tfor i, r := range aligned.B {\n\t\tif r == '-' {\n\t\t\tmapped[i] = nil\n\t\t} else {\n\t\t\tmapped[i] = m.Residues[atomi]\n\t\t\tatomi++\n\t\t}\n\t}\n\treturn mapped\n}\n\n\/\/ Attempts to accomplish the same thing as seqAtomsWithMissing, but instead\n\/\/ of mapping one residue at a time, we map *chunks* at a time. That is,\n\/\/ a chunk is any group of contiguous residues.\nfunc (m Model) seqAtomsChunksMerge() []*Residue {\n\tseqres := m.Chain.Sequence\n\n\t\/\/ Check to make sure that the total number of missing residues, plus the\n\t\/\/ total number of ATOM record residues equal the total number of residues\n\t\/\/ in the SEQRES records. Otherwise, the merge will fail.\n\tif len(seqres) != len(m.Chain.Missing)+len(m.Residues) {\n\t\treturn m.seqAtomsAlign()\n\t}\n\n\tresult := make([]*Residue, len(seqres))\n\tmchunks := chunk(m.Chain.Missing, m.Residues)\n\tfchunks := chunk(m.Residues, m.Chain.Missing)\n\n\t\/\/ If the PDB file is corrupted, a merge will fail.\n\t\/\/ So we fall back to alignment.\n\tif ok := merge(result, 0, seqres, nil, mchunks, fchunks); !ok {\n\t\treturn m.seqAtomsAlign()\n\t}\n\n\t\/\/ X out any residues that don't have ATOM records.\n\tfor i := range result {\n\t\tif result[i].Atoms == nil {\n\t\t\tresult[i] = nil\n\t\t}\n\t}\n\treturn result\n}\n\nfunc merge(result []*Residue, end int, seqres []seq.Residue,\n\tchunkToMerge []*Residue, mchunks, fchunks [][]*Residue) bool {\n\n\tif chunkToMerge != nil {\n\t\ti := 0\n\t\tfor ; i < len(chunkToMerge); i++ {\n\t\t\tif chunkToMerge[i].Name != seqres[end+i] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tresult[end+i] = chunkToMerge[i]\n\t\t}\n\t\tend += i\n\t}\n\tswitch {\n\tcase len(mchunks) == 0 && len(fchunks) == 0:\n\t\treturn true\n\tcase len(mchunks) == 0:\n\t\treturn merge(result, end, seqres, fchunks[0], nil, fchunks[1:])\n\tcase len(fchunks) == 0:\n\t\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], nil)\n\t}\n\n\t\/\/ This is a little weird. We really want to alternate chunks, since\n\t\/\/ a chunk is split presumably where there are holes.\n\t\/\/ But, we don't force it.\n\t\/\/ So we express a preference for it by trying the alternate first, and\n\t\/\/ fallback to similar chunk second.\n\tswitch {\n\tcase len(chunkToMerge) > 0 && chunkToMerge[0].Atoms == nil:\n\t\t\/\/ The current chunk is from missing, so prefer filled.\n\t\treturn merge(result, end, seqres, fchunks[0], mchunks, fchunks[1:]) ||\n\t\t\tmerge(result, end, seqres, mchunks[0], mchunks[1:], fchunks)\n\tcase len(chunkToMerge) > 0 && chunkToMerge[0].Atoms != nil:\n\t\t\/\/ The current chunk is from filled, so prefer missing.\n\t\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], fchunks) ||\n\t\t\tmerge(result, end, seqres, fchunks[0], mchunks, fchunks[1:])\n\t}\n\n\t\/\/ doesn't matter what we do here.\n\t\/\/ (this is the beginning)\n\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], fchunks) ||\n\t\tmerge(result, end, seqres, fchunks[0], mchunks, fchunks[1:])\n}\n\n\/\/ chunk splits up residues in a list of contiguous segments.\nfunc chunk(residues []*Residue, other []*Residue) [][]*Residue {\n\tif len(residues) == 0 {\n\t\treturn nil\n\t}\n\n\tchunks := make([][]*Residue, 0)\n\n\tcur := make([]*Residue, 1)\n\tlast := residues[0]\n\tcur[0] = last\n\tfor i := 1; i < len(residues); i++ {\n\t\tr := residues[i]\n\n\t\tif last.isContiguous(r, other) {\n\t\t\tcur = append(cur, r)\n\t\t\tlast = r\n\t\t\tcontinue\n\t\t}\n\n\t\tchunks = append(chunks, cur)\n\t\tcur = make([]*Residue, 1)\n\t\tcur[0] = r\n\t\tlast = r\n\t}\n\tchunks = append(chunks, cur)\n\n\treturn chunks\n}\n\nfunc (a Residue) less(b Residue) bool {\n\treturn a.SequenceNum < b.SequenceNum ||\n\t\t(a.SequenceNum == b.SequenceNum && a.InsertionCode < b.InsertionCode)\n}\n\nfunc (a Residue) equals(b Residue) bool {\n\treturn a.SequenceNum == b.SequenceNum && a.InsertionCode == b.InsertionCode\n}\n\nfunc (a *Residue) isContiguous(b *Residue, other []*Residue) bool {\n\t\/\/ If any residue in \"other\" is next to a or b, then we cannot claim\n\t\/\/ contiguity.\n\tfor i := range other {\n\t\tif a.SequenceNum == other[i].SequenceNum {\n\t\t\treturn false\n\t\t}\n\t\tif b.SequenceNum == other[i].SequenceNum {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn a.isNext(b)\n}\n\nfunc (a *Residue) isNext(b *Residue) bool {\n\tasn, bsn := a.SequenceNum, b.SequenceNum\n\n\t\/\/ We make the assumption that any two residues with the same sequence\n\t\/\/ number are always contiguous.\n\t\/\/ Note that this has problems. Consider the case with two ATOM records\n\t\/\/ with sequence numbers 36 and 37, but a missing residue with sequence\n\t\/\/ number 36 and insertion code A. So it should go 36 -> 36A -> 37.\n\t\/\/ To remedy this, the caller must make sure that all missing (or filled)\n\t\/\/ residues don't have the same sequence number.\n\tif asn == bsn {\n\t\treturn true\n\t}\n\tif asn+1 == bsn || asn-1 == bsn {\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype residues []*Residue\n\nfunc (rs residues) String() string {\n\tbs := make([]byte, len(rs))\n\tfor i, r := range rs {\n\t\tswitch {\n\t\tcase r == nil:\n\t\t\tbs[i] = '-'\n\t\tcase r.Atoms == nil:\n\t\t\tbs[i] = byte(unicode.ToLower(rune(r.Name)))\n\t\tdefault:\n\t\t\tbs[i] = byte(r.Name)\n\t\t}\n\t}\n\treturn string(bs)\n}\n\ntype gappedResidues []*Residue\n\nfunc (rs gappedResidues) String() string {\n\tbs := make([]byte, len(rs))\n\tfor i, r := range rs {\n\t\tif r == nil || r.Atoms == nil {\n\t\t\tbs[i] = '-'\n\t\t} else {\n\t\t\tbs[i] = byte(r.Name)\n\t\t}\n\t}\n\treturn string(bs)\n}\n<commit_msg>Update to new NeedlemanWunsch interface.<commit_after>package pdb\n\nimport (\n\t\"unicode\"\n\n\t\"github.com\/TuftsBCB\/seq\"\n)\n\nfunc (m Model) seqAtomsGuess() []*Residue {\n\tseqres := m.Chain.Sequence\n\tmapping := make([]*Residue, len(seqres))\n\tif len(seqres) != len(m.Residues) {\n\t\t\/\/ This is a last ditch effort. Use the ATOM sequence number as an\n\t\t\/\/ index into the SEQRES residues.\n\t\tfor _, r := range m.Residues {\n\t\t\tsi := r.SequenceNum - 1\n\t\t\tif si >= 0 && si < len(seqres) && seqres[si] == r.Name {\n\t\t\t\tmapping[si] = r\n\t\t\t}\n\t\t}\n\t\treturn mapping\n\t}\n\n\tfor i, r := range m.Residues {\n\t\tif i < len(seqres) && seqres[i] == r.Name {\n\t\t\tmapping[i] = r\n\t\t}\n\t}\n\treturn mapping\n}\n\nfunc (m Model) seqAtomsAlign() []*Residue {\n\tseqres := m.Chain.Sequence\n\tatomResidues := make([]seq.Residue, len(m.Residues))\n\tfor i, r := range m.Residues {\n\t\tatomResidues[i] = r.Name\n\t}\n\taligned := seq.NeedlemanWunsch(seqres, atomResidues, seq.SubstBlosum62)\n\n\tmapped := make([]*Residue, len(seqres))\n\tatomi := 0\n\tfor i, r := range aligned.B {\n\t\tif r == '-' {\n\t\t\tmapped[i] = nil\n\t\t} else {\n\t\t\tmapped[i] = m.Residues[atomi]\n\t\t\tatomi++\n\t\t}\n\t}\n\treturn mapped\n}\n\n\/\/ Attempts to accomplish the same thing as seqAtomsWithMissing, but instead\n\/\/ of mapping one residue at a time, we map *chunks* at a time. That is,\n\/\/ a chunk is any group of contiguous residues.\nfunc (m Model) seqAtomsChunksMerge() []*Residue {\n\tseqres := m.Chain.Sequence\n\n\t\/\/ Check to make sure that the total number of missing residues, plus the\n\t\/\/ total number of ATOM record residues equal the total number of residues\n\t\/\/ in the SEQRES records. Otherwise, the merge will fail.\n\tif len(seqres) != len(m.Chain.Missing)+len(m.Residues) {\n\t\treturn m.seqAtomsAlign()\n\t}\n\n\tresult := make([]*Residue, len(seqres))\n\tmchunks := chunk(m.Chain.Missing, m.Residues)\n\tfchunks := chunk(m.Residues, m.Chain.Missing)\n\n\t\/\/ If the PDB file is corrupted, a merge will fail.\n\t\/\/ So we fall back to alignment.\n\tif ok := merge(result, 0, seqres, nil, mchunks, fchunks); !ok {\n\t\treturn m.seqAtomsAlign()\n\t}\n\n\t\/\/ X out any residues that don't have ATOM records.\n\tfor i := range result {\n\t\tif result[i].Atoms == nil {\n\t\t\tresult[i] = nil\n\t\t}\n\t}\n\treturn result\n}\n\nfunc merge(result []*Residue, end int, seqres []seq.Residue,\n\tchunkToMerge []*Residue, mchunks, fchunks [][]*Residue) bool {\n\n\tif chunkToMerge != nil {\n\t\ti := 0\n\t\tfor ; i < len(chunkToMerge); i++ {\n\t\t\tif chunkToMerge[i].Name != seqres[end+i] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tresult[end+i] = chunkToMerge[i]\n\t\t}\n\t\tend += i\n\t}\n\tswitch {\n\tcase len(mchunks) == 0 && len(fchunks) == 0:\n\t\treturn true\n\tcase len(mchunks) == 0:\n\t\treturn merge(result, end, seqres, fchunks[0], nil, fchunks[1:])\n\tcase len(fchunks) == 0:\n\t\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], nil)\n\t}\n\n\t\/\/ This is a little weird. We really want to alternate chunks, since\n\t\/\/ a chunk is split presumably where there are holes.\n\t\/\/ But, we don't force it.\n\t\/\/ So we express a preference for it by trying the alternate first, and\n\t\/\/ fallback to similar chunk second.\n\tswitch {\n\tcase len(chunkToMerge) > 0 && chunkToMerge[0].Atoms == nil:\n\t\t\/\/ The current chunk is from missing, so prefer filled.\n\t\treturn merge(result, end, seqres, fchunks[0], mchunks, fchunks[1:]) ||\n\t\t\tmerge(result, end, seqres, mchunks[0], mchunks[1:], fchunks)\n\tcase len(chunkToMerge) > 0 && chunkToMerge[0].Atoms != nil:\n\t\t\/\/ The current chunk is from filled, so prefer missing.\n\t\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], fchunks) ||\n\t\t\tmerge(result, end, seqres, fchunks[0], mchunks, fchunks[1:])\n\t}\n\n\t\/\/ doesn't matter what we do here.\n\t\/\/ (this is the beginning)\n\treturn merge(result, end, seqres, mchunks[0], mchunks[1:], fchunks) ||\n\t\tmerge(result, end, seqres, fchunks[0], mchunks, fchunks[1:])\n}\n\n\/\/ chunk splits up residues in a list of contiguous segments.\nfunc chunk(residues []*Residue, other []*Residue) [][]*Residue {\n\tif len(residues) == 0 {\n\t\treturn nil\n\t}\n\n\tchunks := make([][]*Residue, 0)\n\n\tcur := make([]*Residue, 1)\n\tlast := residues[0]\n\tcur[0] = last\n\tfor i := 1; i < len(residues); i++ {\n\t\tr := residues[i]\n\n\t\tif last.isContiguous(r, other) {\n\t\t\tcur = append(cur, r)\n\t\t\tlast = r\n\t\t\tcontinue\n\t\t}\n\n\t\tchunks = append(chunks, cur)\n\t\tcur = make([]*Residue, 1)\n\t\tcur[0] = r\n\t\tlast = r\n\t}\n\tchunks = append(chunks, cur)\n\n\treturn chunks\n}\n\nfunc (a Residue) less(b Residue) bool {\n\treturn a.SequenceNum < b.SequenceNum ||\n\t\t(a.SequenceNum == b.SequenceNum && a.InsertionCode < b.InsertionCode)\n}\n\nfunc (a Residue) equals(b Residue) bool {\n\treturn a.SequenceNum == b.SequenceNum && a.InsertionCode == b.InsertionCode\n}\n\nfunc (a *Residue) isContiguous(b *Residue, other []*Residue) bool {\n\t\/\/ If any residue in \"other\" is next to a or b, then we cannot claim\n\t\/\/ contiguity.\n\tfor i := range other {\n\t\tif a.SequenceNum == other[i].SequenceNum {\n\t\t\treturn false\n\t\t}\n\t\tif b.SequenceNum == other[i].SequenceNum {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn a.isNext(b)\n}\n\nfunc (a *Residue) isNext(b *Residue) bool {\n\tasn, bsn := a.SequenceNum, b.SequenceNum\n\n\t\/\/ We make the assumption that any two residues with the same sequence\n\t\/\/ number are always contiguous.\n\t\/\/ Note that this has problems. Consider the case with two ATOM records\n\t\/\/ with sequence numbers 36 and 37, but a missing residue with sequence\n\t\/\/ number 36 and insertion code A. So it should go 36 -> 36A -> 37.\n\t\/\/ To remedy this, the caller must make sure that all missing (or filled)\n\t\/\/ residues don't have the same sequence number.\n\tif asn == bsn {\n\t\treturn true\n\t}\n\tif asn+1 == bsn || asn-1 == bsn {\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype residues []*Residue\n\nfunc (rs residues) String() string {\n\tbs := make([]byte, len(rs))\n\tfor i, r := range rs {\n\t\tswitch {\n\t\tcase r == nil:\n\t\t\tbs[i] = '-'\n\t\tcase r.Atoms == nil:\n\t\t\tbs[i] = byte(unicode.ToLower(rune(r.Name)))\n\t\tdefault:\n\t\t\tbs[i] = byte(r.Name)\n\t\t}\n\t}\n\treturn string(bs)\n}\n\ntype gappedResidues []*Residue\n\nfunc (rs gappedResidues) String() string {\n\tbs := make([]byte, len(rs))\n\tfor i, r := range rs {\n\t\tif r == nil || r.Atoms == nil {\n\t\t\tbs[i] = '-'\n\t\t} else {\n\t\t\tbs[i] = byte(r.Name)\n\t\t}\n\t}\n\treturn string(bs)\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 mako\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"cloud.google.com\/go\/compute\/metadata\"\n\t\"knative.dev\/pkg\/injection\/clients\/kubeclient\"\n\n\t\"github.com\/google\/mako\/go\/quickstore\"\n\tqpb \"github.com\/google\/mako\/proto\/quickstore\/quickstore_go_proto\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"knative.dev\/pkg\/changeset\"\n\t\"knative.dev\/pkg\/controller\"\n\t\"knative.dev\/pkg\/injection\"\n)\n\nconst (\n\t\/\/ sidecarAddress is the address of the Mako sidecar to which we locally\n\t\/\/ write results, and it authenticates and publishes them to Mako after\n\t\/\/ assorted preprocessing.\n\tsidecarAddress = \"localhost:9813\"\n)\n\n\/\/ EscapeTag replaces characters that Mako doesn't accept with ones it does.\nfunc EscapeTag(tag string) string {\n\treturn strings.ReplaceAll(tag, \".\", \"_\")\n}\n\n\/\/ Setup sets up the mako client for the provided benchmarkKey.\n\/\/ It will add a few common tags and allow each benchmark to add custm tags as well.\n\/\/ It returns the mako client handle to store metrics, a method to close the connection\n\/\/ to mako server once done and error in case of failures.\nfunc Setup(ctx context.Context, extraTags ...string) (context.Context, *quickstore.Quickstore, func(context.Context), error) {\n\ttags := append(MustGetTags(), extraTags...)\n\t\/\/ Get the commit of the benchmarks\n\tcommitID, err := changeset.Get()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Setup a deployment informer, so that we can use the lister to track\n\t\/\/ desired and available pod counts.\n\tcfg, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tctx, informers := injection.Default.SetupInformers(ctx, cfg)\n\tif err := controller.StartInformers(ctx.Done(), informers...); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Get the Kubernetes version from the API server.\n\tversion, err := kubeclient.Get(ctx).Discovery().ServerVersion()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Decorate GCP metadata as tags (when we're running on GCP).\n\tif projectID, err := metadata.ProjectID(); err != nil {\n\t\tlog.Printf(\"GCP project ID is not available: %v\", err)\n\t} else {\n\t\ttags = append(tags, \"project-id=\"+EscapeTag(projectID))\n\t}\n\tif zone, err := metadata.Zone(); err != nil {\n\t\tlog.Printf(\"GCP zone is not available: %v\", err)\n\t} else {\n\t\ttags = append(tags, \"zone=\"+EscapeTag(zone))\n\t}\n\tif machineType, err := metadata.Get(\"instance\/machine-type\"); err != nil {\n\t\tlog.Printf(\"GCP machine type is not available: %v\", err)\n\t} else if parts := strings.Split(machineType, \"\/\"); len(parts) != 4 {\n\t\ttags = append(tags, \"instanceType=\"+EscapeTag(parts[3]))\n\t}\n\n\tqs, qclose, err := quickstore.NewAtAddress(ctx, &qpb.QuickstoreInput{\n\t\tBenchmarkKey: MustGetBenchmark(),\n\t\tTags: append(tags,\n\t\t\t\"commit=\"+commitID,\n\t\t\t\"kubernetes=\"+EscapeTag(version.String()),\n\t\t\tEscapeTag(runtime.Version()),\n\t\t),\n\t}, sidecarAddress)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn ctx, qs, qclose, nil\n}\n<commit_msg>Add the number of nodes as a Mako tag. (#611)<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 mako\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"cloud.google.com\/go\/compute\/metadata\"\n\t\"knative.dev\/pkg\/injection\/clients\/kubeclient\"\n\n\t\"github.com\/google\/mako\/go\/quickstore\"\n\tqpb \"github.com\/google\/mako\/proto\/quickstore\/quickstore_go_proto\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"knative.dev\/pkg\/changeset\"\n\t\"knative.dev\/pkg\/controller\"\n\t\"knative.dev\/pkg\/injection\"\n)\n\nconst (\n\t\/\/ sidecarAddress is the address of the Mako sidecar to which we locally\n\t\/\/ write results, and it authenticates and publishes them to Mako after\n\t\/\/ assorted preprocessing.\n\tsidecarAddress = \"localhost:9813\"\n)\n\n\/\/ EscapeTag replaces characters that Mako doesn't accept with ones it does.\nfunc EscapeTag(tag string) string {\n\treturn strings.ReplaceAll(tag, \".\", \"_\")\n}\n\n\/\/ Setup sets up the mako client for the provided benchmarkKey.\n\/\/ It will add a few common tags and allow each benchmark to add custm tags as well.\n\/\/ It returns the mako client handle to store metrics, a method to close the connection\n\/\/ to mako server once done and error in case of failures.\nfunc Setup(ctx context.Context, extraTags ...string) (context.Context, *quickstore.Quickstore, func(context.Context), error) {\n\ttags := append(MustGetTags(), extraTags...)\n\t\/\/ Get the commit of the benchmarks\n\tcommitID, err := changeset.Get()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Setup a deployment informer, so that we can use the lister to track\n\t\/\/ desired and available pod counts.\n\tcfg, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tctx, informers := injection.Default.SetupInformers(ctx, cfg)\n\tif err := controller.StartInformers(ctx.Done(), informers...); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Get the Kubernetes version from the API server.\n\tkc := kubeclient.Get(ctx)\n\tversion, err := kc.Discovery().ServerVersion()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Determine the number of Kubernetes nodes through the kubernetes client.\n\tnodes, err := kc.CoreV1().Nodes().List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\ttags = append(tags, \"nodes=\"+fmt.Sprintf(\"%d\", len(nodes.Items)))\n\n\t\/\/ Decorate GCP metadata as tags (when we're running on GCP).\n\tif projectID, err := metadata.ProjectID(); err != nil {\n\t\tlog.Printf(\"GCP project ID is not available: %v\", err)\n\t} else {\n\t\ttags = append(tags, \"project-id=\"+EscapeTag(projectID))\n\t}\n\tif zone, err := metadata.Zone(); err != nil {\n\t\tlog.Printf(\"GCP zone is not available: %v\", err)\n\t} else {\n\t\ttags = append(tags, \"zone=\"+EscapeTag(zone))\n\t}\n\tif machineType, err := metadata.Get(\"instance\/machine-type\"); err != nil {\n\t\tlog.Printf(\"GCP machine type is not available: %v\", err)\n\t} else if parts := strings.Split(machineType, \"\/\"); len(parts) != 4 {\n\t\ttags = append(tags, \"instanceType=\"+EscapeTag(parts[3]))\n\t}\n\n\tqs, qclose, err := quickstore.NewAtAddress(ctx, &qpb.QuickstoreInput{\n\t\tBenchmarkKey: MustGetBenchmark(),\n\t\tTags: append(tags,\n\t\t\t\"commit=\"+commitID,\n\t\t\t\"kubernetes=\"+EscapeTag(version.String()),\n\t\t\tEscapeTag(runtime.Version()),\n\t\t),\n\t}, sidecarAddress)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\treturn ctx, qs, qclose, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gyazo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/google\/go-querystring\/query\"\n)\n\nconst (\n\tversion         = \"0.1\"\n\tdefaultEndpoint = \"https:\/\/api.gyazo.com\"\n\tuploadEndpoint  = \"https:\/\/upload.gyazo.com\"\n)\n\n\/\/ Client manages communication with the Gyazo API\ntype Client struct {\n\t\/\/ Gyazo API access token.\n\ttoken string\n\n\t\/\/ client provides request to API endpoints.\n\tclient *http.Client\n\n\t\/\/ DefaultEndpint is Gyazo API endpoint.\n\tDefaultEndpoint string\n\n\t\/\/ UploadEndpint is Gyazo upload API endpoint.\n\tUploadEndpoint string\n}\n\n\/\/ Image represents a uploaded image.\n\/\/\n\/\/ Gyazo API docs: https:\/\/gyazo.com\/api\/docs\/image\ntype Image struct {\n\tID           string `json:\"image_id\"`\n\tPermalinkURL string `json:\"permalink_url\"`\n\tThumbURL     string `json:\"thumb_url\"`\n\tURL          string `json:\"url\"`\n\tType         string `json:\"type\"`\n\tStar         string `json:\"star\"`\n\tCreatedAt    string `json:\"created_at\"`\n}\n\n\/\/ ListOptions specifies the optional parameters to the List.\ntype ListOptions struct {\n\tPage    int `url:\"page,omitempty\"`\n\tPerPage int `url:\"per_page,omitempty\"`\n}\n\n\/\/ NewClient returns a new Gyazo API client.\nfunc NewClient(token string) (*Client, error) {\n\tif token == \"\" {\n\t\treturn nil, errors.New(\"access token is empty\")\n\t}\n\n\tc := &Client{token, http.DefaultClient, defaultEndpoint, uploadEndpoint}\n\treturn c, nil\n}\n\n\/\/ List returns user images\nfunc (c *Client) List(opts *ListOptions) (*[]Image, error) {\n\turl := c.DefaultEndpoint + \"\/api\/images\"\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", c.token))\n\n\t\/\/ Build and set query parameters\n\tif opts != nil {\n\t\tparams, err := query.Values(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.URL.RawQuery = params.Encode()\n\t}\n\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(res.Status)\n\t}\n\n\tlist := new([]Image)\n\tif err = json.NewDecoder(res.Body).Decode(&list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}\n<commit_msg>Use oauth2 package to OAuth2 authentication<commit_after>package gyazo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/google\/go-querystring\/query\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nconst (\n\tversion         = \"0.1\"\n\tdefaultEndpoint = \"https:\/\/api.gyazo.com\"\n\tuploadEndpoint  = \"https:\/\/upload.gyazo.com\"\n)\n\n\/\/ Client manages communication with the Gyazo API\ntype Client struct {\n\t\/\/ Gyazo API access token.\n\ttoken string\n\n\t\/\/ client provides request to API endpoints.\n\tclient *http.Client\n\n\t\/\/ DefaultEndpint is Gyazo API endpoint.\n\tDefaultEndpoint string\n\n\t\/\/ UploadEndpint is Gyazo upload API endpoint.\n\tUploadEndpoint string\n}\n\n\/\/ Image represents a uploaded image.\n\/\/\n\/\/ Gyazo API docs: https:\/\/gyazo.com\/api\/docs\/image\ntype Image struct {\n\tID           string `json:\"image_id\"`\n\tPermalinkURL string `json:\"permalink_url\"`\n\tThumbURL     string `json:\"thumb_url\"`\n\tURL          string `json:\"url\"`\n\tType         string `json:\"type\"`\n\tStar         string `json:\"star\"`\n\tCreatedAt    string `json:\"created_at\"`\n}\n\n\/\/ ListOptions specifies the optional parameters to the List.\ntype ListOptions struct {\n\tPage    int `url:\"page,omitempty\"`\n\tPerPage int `url:\"per_page,omitempty\"`\n}\n\n\/\/ NewClient returns a new Gyazo API client.\nfunc NewClient(token string) (*Client, error) {\n\tif token == \"\" {\n\t\treturn nil, errors.New(\"access token is empty\")\n\t}\n\n\t\/\/ Create an OAuth2 client to authentication\n\toauthClient := oauth2.NewClient(\n\t\toauth2.NoContext,\n\t\toauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}),\n\t)\n\n\tc := &Client{token, oauthClient, defaultEndpoint, uploadEndpoint}\n\treturn c, nil\n}\n\n\/\/ List returns user images\nfunc (c *Client) List(opts *ListOptions) (*[]Image, error) {\n\turl := c.DefaultEndpoint + \"\/api\/images\"\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Build and set query parameters\n\tif opts != nil {\n\t\tparams, err := query.Values(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treq.URL.RawQuery = params.Encode()\n\t}\n\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(res.Status)\n\t}\n\n\tlist := new([]Image)\n\tif err = json.NewDecoder(res.Body).Decode(&list); err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\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 cbft\n\nimport (\n\t\"container\/heap\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype ConsistencyParams struct {\n\t\/\/ A Level value of \"\" means stale is ok; \"at_plus\" means we need\n\t\/\/ consistency at least at or beyond the consistency vector but\n\t\/\/ not before.\n\tLevel string `json:\"level\"`\n\n\t\/\/ Keyed by indexName.\n\tVectors map[string]ConsistencyVector `json:\"vectors\"`\n\n\t\/\/ TODO: Can user specify certain partition UUID (like vbucket UUID)?\n}\n\n\/\/ Key is partition, value is seq.\ntype ConsistencyVector map[string]uint64\n\ntype ConsistencyWaiter interface {\n\tConsistencyWait(partition string,\n\t\tconsistencyLevel string,\n\t\tconsistencySeq uint64,\n\t\tcancelCh chan string) error\n}\n\ntype ConsistencyWaitReq struct {\n\tConsistencyLevel string\n\tConsistencySeq   uint64\n\tCancelCh         chan string\n\tDoneCh           chan error\n}\n\ntype ErrorConsistencyWait struct {\n\tErr    error  \/\/ The underlying, wrapped error.\n\tStatus string \/\/ Short status reason, like \"timeout\", \"cancelled\", etc.\n\n\t\/\/ Keyed by partitionId, value is pair of start\/end seq's.\n\tStartEndSeqs map[string][]uint64\n}\n\nfunc (e *ErrorConsistencyWait) Error() string {\n\treturn fmt.Sprintf(\"ErrorConsistencyWait, startEndSeqs: %#v,\"+\n\t\t\" err: %v\", e.StartEndSeqs, e.Err)\n}\n\n\/\/ ---------------------------------------------------------\n\nfunc ConsistencyWaitDone(partition string, cancelCh chan string,\n\tdoneCh chan error, currSeq func() uint64) error {\n\tseqStart := currSeq()\n\n\tselect {\n\tcase status := <-cancelCh:\n\t\tif status == \"\" { \/\/ For example, status might be \"timeout\".\n\t\t\tstatus = \"cancelled\"\n\t\t}\n\n\t\trv := map[string][]uint64{}\n\t\trv[partition] = []uint64{seqStart, currSeq()}\n\n\t\terr := fmt.Errorf(\"ConsistencyWaitDone cancelled, status: %s\", status)\n\n\t\treturn &ErrorConsistencyWait{ \/\/ TODO: track stats.\n\t\t\tErr:          err,\n\t\t\tStatus:       status,\n\t\t\tStartEndSeqs: rv,\n\t\t}\n\n\tcase err := <-doneCh:\n\t\treturn err \/\/ TODO: track stats.\n\t}\n}\n\nfunc ConsistencyWaitPartitions(\n\tt ConsistencyWaiter,\n\tpartitions []string,\n\tconsistencyLevel string,\n\tconsistencyVector map[string]uint64,\n\tcancelCh chan string) error {\n\tfor _, partition := range partitions {\n\t\tconsistencySeq := consistencyVector[partition]\n\t\tif consistencySeq > 0 {\n\t\t\terr := t.ConsistencyWait(partition,\n\t\t\t\tconsistencyLevel, consistencySeq, cancelCh)\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 ConsistencyWaitPIndex(pindex *PIndex, t ConsistencyWaiter,\n\tconsistencyParams *ConsistencyParams, cancelCh chan string) error {\n\tif consistencyParams != nil &&\n\t\tconsistencyParams.Level != \"\" &&\n\t\tconsistencyParams.Vectors != nil {\n\t\tconsistencyVector := consistencyParams.Vectors[pindex.IndexName]\n\t\tif consistencyVector != nil {\n\t\t\terr := ConsistencyWaitPartitions(t, pindex.sourcePartitionsArr,\n\t\t\t\tconsistencyParams.Level, consistencyVector, cancelCh)\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 ConsistencyWaitGroup(indexName string,\n\tconsistencyParams *ConsistencyParams, cancelCh chan string,\n\tlocalPIndexes []*PIndex,\n\taddLocalPIndex func(*PIndex) error) error {\n\tvar errConsistencyM sync.Mutex\n\tvar errConsistency error\n\n\tvar wg sync.WaitGroup\n\n\tfor _, localPIndex := range localPIndexes {\n\t\terr := addLocalPIndex(localPIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif consistencyParams != nil &&\n\t\t\tconsistencyParams.Level != \"\" &&\n\t\t\tconsistencyParams.Vectors != nil {\n\t\t\tconsistencyVector := consistencyParams.Vectors[indexName]\n\t\t\tif consistencyVector != nil {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(localPIndex *PIndex,\n\t\t\t\t\tconsistencyVector map[string]uint64) {\n\t\t\t\t\tdefer wg.Done()\n\n\t\t\t\t\terr := ConsistencyWaitPartitions(localPIndex.Dest,\n\t\t\t\t\t\tlocalPIndex.sourcePartitionsArr,\n\t\t\t\t\t\tconsistencyParams.Level,\n\t\t\t\t\t\tconsistencyVector,\n\t\t\t\t\t\tcancelCh)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrConsistencyM.Lock()\n\t\t\t\t\t\terrConsistency = err\n\t\t\t\t\t\terrConsistencyM.Unlock()\n\t\t\t\t\t}\n\t\t\t\t}(localPIndex, consistencyVector)\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Wait()\n\n\tif errConsistency != nil {\n\t\treturn errConsistency\n\t}\n\n\tif cancelCh != nil {\n\t\tselect {\n\t\tcase status := <-cancelCh:\n\t\t\treturn fmt.Errorf(\"cancelled, status: %s\", status)\n\t\tdefault:\n\t\t}\n\t}\n\n\t\/\/ TODO: There's likely a race here where at this point we've now\n\t\/\/ waited for all the (local) pindexes to reach the requested\n\t\/\/ consistency levels, but before we actually can use the\n\t\/\/ constructed alias and kick off a query, an adversary does a\n\t\/\/ rollback.  Using the alias to query after that might now be\n\t\/\/ incorrectly running against data some time back in the past.\n\n\treturn nil\n}\n\n\/\/ ---------------------------------------------------------\n\n\/\/ A cwrQueue is a consistency wait request queue, implementing the\n\/\/ heap.Interface for consistencyWaitReq's.\ntype cwrQueue []*ConsistencyWaitReq\n\nfunc (pq cwrQueue) Len() int { return len(pq) }\n\nfunc (pq cwrQueue) Less(i, j int) bool {\n\treturn pq[i].ConsistencySeq < pq[j].ConsistencySeq\n}\n\nfunc (pq cwrQueue) Swap(i, j int) {\n\tpq[i], pq[j] = pq[j], pq[i]\n}\n\nfunc (pq *cwrQueue) Push(x interface{}) {\n\t*pq = append(*pq, x.(*ConsistencyWaitReq))\n}\n\nfunc (pq *cwrQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}\n\n\/\/ ---------------------------------------------------------\n\nfunc RunConsistencyWaitQueue(\n\tcwrCh chan *ConsistencyWaitReq,\n\tm *sync.Mutex,\n\tcwrQueue *cwrQueue,\n\tcurrSeq func() uint64) {\n\tfor cwr := range cwrCh {\n\t\tm.Lock()\n\n\t\tif cwr.ConsistencyLevel == \"\" {\n\t\t\tclose(cwr.DoneCh) \/\/ We treat \"\" like stale=ok, so we're done.\n\t\t} else if cwr.ConsistencyLevel == \"at_plus\" {\n\t\t\tif cwr.ConsistencySeq > currSeq() {\n\t\t\t\theap.Push(cwrQueue, cwr)\n\t\t\t} else {\n\t\t\t\tclose(cwr.DoneCh)\n\t\t\t}\n\t\t} else {\n\t\t\tcwr.DoneCh <- fmt.Errorf(\"consistency wait unsupported level: %s,\"+\n\t\t\t\t\" cwr: %#v\", cwr.ConsistencyLevel, cwr)\n\t\t\tclose(cwr.DoneCh)\n\t\t}\n\n\t\tm.Unlock()\n\t}\n\n\t\/\/ If we reach here, then we're closing down so cancel\/error any\n\t\/\/ callers waiting for consistency.\n\tm.Lock()\n\tdefer m.Unlock()\n\n\terr := fmt.Errorf(\"consistency wait closed\")\n\n\tfor _, cwr := range *cwrQueue {\n\t\tcwr.DoneCh <- err\n\t\tclose(cwr.DoneCh)\n\t}\n}\n<commit_msg>use goroutines to keep cwrQueue lock window short<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 cbft\n\nimport (\n\t\"container\/heap\"\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype ConsistencyParams struct {\n\t\/\/ A Level value of \"\" means stale is ok; \"at_plus\" means we need\n\t\/\/ consistency at least at or beyond the consistency vector but\n\t\/\/ not before.\n\tLevel string `json:\"level\"`\n\n\t\/\/ Keyed by indexName.\n\tVectors map[string]ConsistencyVector `json:\"vectors\"`\n\n\t\/\/ TODO: Can user specify certain partition UUID (like vbucket UUID)?\n}\n\n\/\/ Key is partition, value is seq.\ntype ConsistencyVector map[string]uint64\n\ntype ConsistencyWaiter interface {\n\tConsistencyWait(partition string,\n\t\tconsistencyLevel string,\n\t\tconsistencySeq uint64,\n\t\tcancelCh chan string) error\n}\n\ntype ConsistencyWaitReq struct {\n\tConsistencyLevel string\n\tConsistencySeq   uint64\n\tCancelCh         chan string\n\tDoneCh           chan error\n}\n\ntype ErrorConsistencyWait struct {\n\tErr    error  \/\/ The underlying, wrapped error.\n\tStatus string \/\/ Short status reason, like \"timeout\", \"cancelled\", etc.\n\n\t\/\/ Keyed by partitionId, value is pair of start\/end seq's.\n\tStartEndSeqs map[string][]uint64\n}\n\nfunc (e *ErrorConsistencyWait) Error() string {\n\treturn fmt.Sprintf(\"ErrorConsistencyWait, startEndSeqs: %#v,\"+\n\t\t\" err: %v\", e.StartEndSeqs, e.Err)\n}\n\n\/\/ ---------------------------------------------------------\n\nfunc ConsistencyWaitDone(partition string, cancelCh chan string,\n\tdoneCh chan error, currSeq func() uint64) error {\n\tseqStart := currSeq()\n\n\tselect {\n\tcase status := <-cancelCh:\n\t\tif status == \"\" { \/\/ For example, status might be \"timeout\".\n\t\t\tstatus = \"cancelled\"\n\t\t}\n\n\t\trv := map[string][]uint64{}\n\t\trv[partition] = []uint64{seqStart, currSeq()}\n\n\t\terr := fmt.Errorf(\"ConsistencyWaitDone cancelled, status: %s\", status)\n\n\t\treturn &ErrorConsistencyWait{ \/\/ TODO: track stats.\n\t\t\tErr:          err,\n\t\t\tStatus:       status,\n\t\t\tStartEndSeqs: rv,\n\t\t}\n\n\tcase err := <-doneCh:\n\t\treturn err \/\/ TODO: track stats.\n\t}\n}\n\nfunc ConsistencyWaitPartitions(\n\tt ConsistencyWaiter,\n\tpartitions []string,\n\tconsistencyLevel string,\n\tconsistencyVector map[string]uint64,\n\tcancelCh chan string) error {\n\tfor _, partition := range partitions {\n\t\tconsistencySeq := consistencyVector[partition]\n\t\tif consistencySeq > 0 {\n\t\t\terr := t.ConsistencyWait(partition,\n\t\t\t\tconsistencyLevel, consistencySeq, cancelCh)\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 ConsistencyWaitPIndex(pindex *PIndex, t ConsistencyWaiter,\n\tconsistencyParams *ConsistencyParams, cancelCh chan string) error {\n\tif consistencyParams != nil &&\n\t\tconsistencyParams.Level != \"\" &&\n\t\tconsistencyParams.Vectors != nil {\n\t\tconsistencyVector := consistencyParams.Vectors[pindex.IndexName]\n\t\tif consistencyVector != nil {\n\t\t\terr := ConsistencyWaitPartitions(t, pindex.sourcePartitionsArr,\n\t\t\t\tconsistencyParams.Level, consistencyVector, cancelCh)\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 ConsistencyWaitGroup(indexName string,\n\tconsistencyParams *ConsistencyParams, cancelCh chan string,\n\tlocalPIndexes []*PIndex,\n\taddLocalPIndex func(*PIndex) error) error {\n\tvar errConsistencyM sync.Mutex\n\tvar errConsistency error\n\n\tvar wg sync.WaitGroup\n\n\tfor _, localPIndex := range localPIndexes {\n\t\terr := addLocalPIndex(localPIndex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif consistencyParams != nil &&\n\t\t\tconsistencyParams.Level != \"\" &&\n\t\t\tconsistencyParams.Vectors != nil {\n\t\t\tconsistencyVector := consistencyParams.Vectors[indexName]\n\t\t\tif consistencyVector != nil {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(localPIndex *PIndex,\n\t\t\t\t\tconsistencyVector map[string]uint64) {\n\t\t\t\t\tdefer wg.Done()\n\n\t\t\t\t\terr := ConsistencyWaitPartitions(localPIndex.Dest,\n\t\t\t\t\t\tlocalPIndex.sourcePartitionsArr,\n\t\t\t\t\t\tconsistencyParams.Level,\n\t\t\t\t\t\tconsistencyVector,\n\t\t\t\t\t\tcancelCh)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrConsistencyM.Lock()\n\t\t\t\t\t\terrConsistency = err\n\t\t\t\t\t\terrConsistencyM.Unlock()\n\t\t\t\t\t}\n\t\t\t\t}(localPIndex, consistencyVector)\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Wait()\n\n\tif errConsistency != nil {\n\t\treturn errConsistency\n\t}\n\n\tif cancelCh != nil {\n\t\tselect {\n\t\tcase status := <-cancelCh:\n\t\t\treturn fmt.Errorf(\"cancelled, status: %s\", status)\n\t\tdefault:\n\t\t}\n\t}\n\n\t\/\/ TODO: There's likely a race here where at this point we've now\n\t\/\/ waited for all the (local) pindexes to reach the requested\n\t\/\/ consistency levels, but before we actually can use the\n\t\/\/ constructed alias and kick off a query, an adversary does a\n\t\/\/ rollback.  Using the alias to query after that might now be\n\t\/\/ incorrectly running against data some time back in the past.\n\n\treturn nil\n}\n\n\/\/ ---------------------------------------------------------\n\n\/\/ A cwrQueue is a consistency wait request queue, implementing the\n\/\/ heap.Interface for consistencyWaitReq's.\ntype cwrQueue []*ConsistencyWaitReq\n\nfunc (pq cwrQueue) Len() int { return len(pq) }\n\nfunc (pq cwrQueue) Less(i, j int) bool {\n\treturn pq[i].ConsistencySeq < pq[j].ConsistencySeq\n}\n\nfunc (pq cwrQueue) Swap(i, j int) {\n\tpq[i], pq[j] = pq[j], pq[i]\n}\n\nfunc (pq *cwrQueue) Push(x interface{}) {\n\t*pq = append(*pq, x.(*ConsistencyWaitReq))\n}\n\nfunc (pq *cwrQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}\n\n\/\/ ---------------------------------------------------------\n\nfunc RunConsistencyWaitQueue(\n\tcwrCh chan *ConsistencyWaitReq,\n\tm *sync.Mutex,\n\tcwrQueue *cwrQueue,\n\tcurrSeq func() uint64) {\n\tfor cwr := range cwrCh {\n\t\tm.Lock()\n\n\t\tif cwr.ConsistencyLevel == \"\" {\n\t\t\tclose(cwr.DoneCh) \/\/ We treat \"\" like stale=ok, so we're done.\n\t\t} else if cwr.ConsistencyLevel == \"at_plus\" {\n\t\t\tif cwr.ConsistencySeq > currSeq() {\n\t\t\t\theap.Push(cwrQueue, cwr)\n\t\t\t} else {\n\t\t\t\tclose(cwr.DoneCh)\n\t\t\t}\n\t\t} else {\n\t\t\tcwr.DoneCh <- fmt.Errorf(\"consistency wait unsupported level: %s,\"+\n\t\t\t\t\" cwr: %#v\", cwr.ConsistencyLevel, cwr)\n\t\t\tclose(cwr.DoneCh)\n\t\t}\n\n\t\tm.Unlock()\n\t}\n\n\t\/\/ If we reach here, then we're closing down so cancel\/error any\n\t\/\/ callers waiting for consistency.\n\tm.Lock()\n\tdefer m.Unlock()\n\n\terr := fmt.Errorf(\"consistency wait closed\")\n\n\tfor _, cwr := range *cwrQueue {\n\t\t\/\/ TODO: Perhaps extra goroutine here isn't necessary, but the\n\t\t\/\/ motivation is to keep cwrQueue's lock window short.\n\t\tgo func(cwr *ConsistencyWaitReq) {\n\t\t\tcwr.DoneCh <- err\n\t\t\tclose(cwr.DoneCh)\n\t\t}(cwr)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package haigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/yaml.v2\"\n)\n\ntype param struct {\n\tName string\n\tType string\n}\n\ntype HaigoQuery struct {\n\tName        string  `yaml:\"name\"`\n\tDescription string  `yaml:\"description,omitempty\"`\n\tQueryString string  `yaml:\"query\"`\n\tparams      []param \/\/ TODO\n}\n\ntype HaigoParams map[string]interface{}\n\n\/\/ Execute - Returns configured mgo Query.\nfunc (h *HaigoQuery) Execute(col *mgo.Collection, params HaigoParams) (*mgo.Query, error) {\n\n\tq, err := h.Query(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn col.Find(q), nil\n}\n\n\/\/ HaigoFile - YAML formatted file with MongoDB Queries.\n\/\/\n\/\/\t---\n\/\/    - name: basic-select\n\/\/      description: Basic MongoDB Select\n\/\/      query: '{\"type\": {{.type}} }'\n\/\/\n\/\/    - name: conditional\n\/\/      description: Conditional Query\n\/\/      query: '{\n\/\/         \"type\": \"food\",\n\/\/         \"$or\": [ { \"qty\": { \"$gt\": {{.qty}} } }, { \"name\": {{.name}} } ]\n\/\/      }'\ntype HaigoFile struct {\n\tQueries map[string]*HaigoQuery\n}\n\nfunc (m *HaigoFile) unmarshalYAML(data []byte) error {\n\n\tvar hqs []HaigoQuery\n\n\terr := yaml.Unmarshal(data, &hqs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqm := make(map[string]*HaigoQuery)\n\n\tfor i := range hqs {\n\t\tqm[hqs[i].Name] = &hqs[i]\n\t}\n\n\tm.Queries = qm\n\n\treturn nil\n}\n\n\/\/ sanitizeParams - Adds single quotes if param is a string (as needed by Mongo).\nfunc sanitizeParams(params HaigoParams) HaigoParams {\n\tfor k, v := range params {\n\t\tswitch v.(type) {\n\t\tcase string:\n\t\t\tparams[k] = fmt.Sprintf(\"\\\"%s\\\"\", v)\n\t\t}\n\n\t}\n\treturn params\n}\n\n\/\/ Query - Accepts a params map and returns a map for use with the mgo `find()`\n\/\/ function.\nfunc (h *HaigoQuery) Query(params HaigoParams) (map[string]interface{}, error) {\n\n\t\/\/ Create the template\n\tt, err := template.New(\"haigo\").Parse(h.QueryString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Buffer to capture string\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ Execute template\n\terr = t.Execute(buf, sanitizeParams(params))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Unmarshal JSON into Map\n\tvar m map[string]interface{}\n\terr = json.Unmarshal(buf.Bytes(), &m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}\n\n\/\/ LoadQueryFile - Reads in Mongo Query File for use with Haigo.\nfunc LoadQueryFile(file string) (*HaigoFile, error) {\n\treturn parseMongoFile(file)\n}\n<commit_msg>include YAML sample<commit_after>package haigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/yaml.v2\"\n)\n\ntype param struct {\n\tName string\n\tType string\n}\n\ntype HaigoQuery struct {\n\tName        string  `yaml:\"name\"`\n\tDescription string  `yaml:\"description,omitempty\"`\n\tQueryString string  `yaml:\"query\"`\n\tparams      []param \/\/ TODO\n}\n\ntype HaigoParams map[string]interface{}\n\n\/\/ Execute - Returns configured mgo Query.\nfunc (h *HaigoQuery) Execute(col *mgo.Collection, params HaigoParams) (*mgo.Query, error) {\n\n\tq, err := h.Query(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn col.Find(q), nil\n}\n\n\/\/ HaigoFile - YAML formatted file with MongoDB Queries.\n\/\/\n\/\/ ---\n\/\/    - name: basic-select\n\/\/      description: Basic MongoDB Select\n\/\/      query: '{\"type\": {{.type}} }'\n\/\/\n\/\/    - name: conditional\n\/\/      description: Conditional Query\n\/\/      query: '{\n\/\/         \"type\": \"food\",\n\/\/         \"$or\": [ { \"qty\": { \"$gt\": {{.qty}} } }, { \"name\": {{.name}} } ]\n\/\/      }'\ntype HaigoFile struct {\n\tQueries map[string]*HaigoQuery\n}\n\nfunc (m *HaigoFile) unmarshalYAML(data []byte) error {\n\n\tvar hqs []HaigoQuery\n\n\terr := yaml.Unmarshal(data, &hqs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tqm := make(map[string]*HaigoQuery)\n\n\tfor i := range hqs {\n\t\tqm[hqs[i].Name] = &hqs[i]\n\t}\n\n\tm.Queries = qm\n\n\treturn nil\n}\n\n\/\/ sanitizeParams - Adds single quotes if param is a string (as needed by Mongo).\nfunc sanitizeParams(params HaigoParams) HaigoParams {\n\tfor k, v := range params {\n\t\tswitch v.(type) {\n\t\tcase string:\n\t\t\tparams[k] = fmt.Sprintf(\"\\\"%s\\\"\", v)\n\t\t}\n\n\t}\n\treturn params\n}\n\n\/\/ Query - Accepts a params map and returns a map for use with the mgo `find()`\n\/\/ function.\nfunc (h *HaigoQuery) Query(params HaigoParams) (map[string]interface{}, error) {\n\n\t\/\/ Create the template\n\tt, err := template.New(\"haigo\").Parse(h.QueryString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Buffer to capture string\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ Execute template\n\terr = t.Execute(buf, sanitizeParams(params))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Unmarshal JSON into Map\n\tvar m map[string]interface{}\n\terr = json.Unmarshal(buf.Bytes(), &m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}\n\n\/\/ LoadQueryFile - Reads in Mongo Query File for use with Haigo.\nfunc LoadQueryFile(file string) (*HaigoFile, error) {\n\treturn parseMongoFile(file)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/hello<commit_msg>Add a hello world console output<commit_after>\/\/hello\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello world\")\n}<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"crypto\/rand\"\n\t\"math\/big\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/logs\"\n)\n\n\/\/ RetryBackoff is the ACME client RetryBackoff that filters rate limit errors to our retry loop\n\/\/ inspired by acme\/http.go\nfunc RetryBackoff(n int, r *http.Request, res *http.Response) time.Duration {\n\tvar jitter time.Duration\n\tif x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {\n\t\t\/\/ Set the minimum to 1ms to avoid a case where\n\t\t\/\/ an invalid Retry-After value is parsed into 0 below,\n\t\t\/\/ resulting in the 0 returned value which would unintentionally\n\t\t\/\/ stop the retries.\n\t\tjitter = (1 + time.Duration(x.Int64())) * time.Millisecond\n\t}\n\tif _, ok := res.Header[\"Retry-After\"]; ok {\n\t\t\/\/ if Retry-After is set we should\n\t\t\/\/ error and let the cert-manager logic retry instead\n\t\treturn -1\n\t}\n\n\t\/\/ don't retry more than 10 times\n\tif n > 10 {\n\t\treturn -1\n\t}\n\n\t\/\/ classic backoff here in case we got no reply\n\t\/\/ eg. flakes\n\tif n < 1 {\n\t\tn = 1\n\t}\n\n\tlogs.Log.V(logs.DebugLevel).WithValues(\"backoff\", d).Info(\"Hit an error in golang.org\/x\/crypto\/acme, retrying\")\n\n\td := time.Duration(1<<uint(n-1))*time.Second + jitter\n\tif d > 10*time.Second {\n\t\treturn 10 * time.Second\n\t}\n\treturn d\n}\n<commit_msg>Fix place of log<commit_after>package util\n\nimport (\n\t\"crypto\/rand\"\n\t\"math\/big\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/logs\"\n)\n\n\/\/ RetryBackoff is the ACME client RetryBackoff that filters rate limit errors to our retry loop\n\/\/ inspired by acme\/http.go\nfunc RetryBackoff(n int, r *http.Request, res *http.Response) time.Duration {\n\tvar jitter time.Duration\n\tif x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {\n\t\t\/\/ Set the minimum to 1ms to avoid a case where\n\t\t\/\/ an invalid Retry-After value is parsed into 0 below,\n\t\t\/\/ resulting in the 0 returned value which would unintentionally\n\t\t\/\/ stop the retries.\n\t\tjitter = (1 + time.Duration(x.Int64())) * time.Millisecond\n\t}\n\tif _, ok := res.Header[\"Retry-After\"]; ok {\n\t\t\/\/ if Retry-After is set we should\n\t\t\/\/ error and let the cert-manager logic retry instead\n\t\treturn -1\n\t}\n\n\t\/\/ don't retry more than 10 times\n\tif n > 10 {\n\t\treturn -1\n\t}\n\n\t\/\/ classic backoff here in case we got no reply\n\t\/\/ eg. flakes\n\tif n < 1 {\n\t\tn = 1\n\t}\n\n\td := time.Duration(1<<uint(n-1))*time.Second + jitter\n\tlogs.Log.V(logs.DebugLevel).WithValues(\"backoff\", d).Info(\"Hit an error in golang.org\/x\/crypto\/acme, retrying\")\n\tif d > 10*time.Second {\n\t\treturn 10 * time.Second\n\t}\n\treturn d\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 builder\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"mynewt.apache.org\/newt\/newt\/pkg\"\n\t\"mynewt.apache.org\/newt\/newt\/target\"\n\t\"mynewt.apache.org\/newt\/newt\/toolchain\"\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\ntype Builder struct {\n\tPackages map[*pkg.LocalPackage]*BuildPackage\n\tfeatures map[string]bool\n\tapis     map[string]*BuildPackage\n\n\tBsp          *pkg.BspPackage\n\tcompilerPkg  *pkg.LocalPackage\n\tcompilerInfo *toolchain.CompilerInfo\n\n\ttarget *target.Target\n}\n\nfunc NewBuilder(target *target.Target) (*Builder, error) {\n\tb := &Builder{}\n\n\tif err := b.Init(target); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\nfunc (b *Builder) Init(target *target.Target) error {\n\tb.target = target\n\n\tb.Packages = map[*pkg.LocalPackage]*BuildPackage{}\n\tb.features = map[string]bool{}\n\tb.apis = map[string]*BuildPackage{}\n\n\treturn nil\n}\n\nfunc (b *Builder) Features() map[string]bool {\n\treturn b.features\n}\n\nfunc (b *Builder) AddFeature(feature string) {\n\tb.features[feature] = true\n}\n\nfunc (b *Builder) AddPackage(npkg *pkg.LocalPackage) *BuildPackage {\n\t\/\/ Don't allow nil entries to the map\n\tif npkg == nil {\n\t\tpanic(\"Cannot add nil package builder map\")\n\t}\n\n\tbpkg := b.Packages[npkg]\n\tif bpkg == nil {\n\t\tbpkg = NewBuildPackage(npkg)\n\t\tb.Packages[npkg] = bpkg\n\t}\n\n\treturn bpkg\n}\n\n\/\/ @return bool                 true if this is a new API.\nfunc (b *Builder) AddApi(apiString string, bpkg *BuildPackage) bool {\n\tcurBpkg := b.apis[apiString]\n\tif curBpkg == nil {\n\t\tb.apis[apiString] = bpkg\n\t\treturn true\n\t} else {\n\t\tif curBpkg != bpkg {\n\t\t\tutil.StatusMessage(util.VERBOSITY_QUIET,\n\t\t\t\t\"Warning: API conflict: %s <-> %s\\n\", curBpkg.Name(),\n\t\t\t\tbpkg.Name())\n\t\t}\n\t\treturn false\n\t}\n}\n\nfunc (b *Builder) loadDeps() error {\n\t\/\/ Circularly resolve dependencies, identities, APIs, and required APIs\n\t\/\/ until no new ones exist.\n\tfor {\n\t\treprocess := false\n\t\tfor _, bpkg := range b.Packages {\n\t\t\tresolved, err := bpkg.Resolve(b)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !resolved {\n\t\t\t\treprocess = true\n\t\t\t}\n\t\t}\n\n\t\tif !reprocess {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"Building with the following \"+\n\t\t\"feature set: [\"+b.FeatureString()+\"]\\n\")\n\n\treturn nil\n}\n\n\/\/ Recursively compiles all the .c and .s files in the specified directory.\n\/\/ Architecture-specific files are also compiled.\nfunc buildDir(srcDir string, c *toolchain.Compiler, arch string,\n\tignDirs []string) error {\n\n\t\/\/ Quietly succeed if the source directory doesn't exist.\n\tif util.NodeNotExist(srcDir) {\n\t\treturn nil\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE,\n\t\t\"compiling src in base directory: %s\\n\", srcDir)\n\n\t\/\/ Start from the source directory.\n\tif err := os.Chdir(srcDir); err != nil {\n\t\treturn util.NewNewtError(err.Error())\n\t}\n\n\t\/\/ Don't recurse into destination directories.\n\tignDirs = append(ignDirs, \"obj\")\n\tignDirs = append(ignDirs, \"bin\")\n\n\t\/\/ Ignore architecture-specific source files for now.  Use a temporary\n\t\/\/ string slice here so that the \"arch\" directory is not ignored in the\n\t\/\/ subsequent architecture-specific compile phase.\n\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_C,\n\t\tappend(ignDirs, \"arch\")); err != nil {\n\n\t\treturn err\n\t}\n\n\tarchDir := srcDir + \"\/arch\/\" + arch + \"\/\"\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE,\n\t\t\"compiling architecture specific src pkgs in directory: %s\\n\",\n\t\tarchDir)\n\n\tif util.NodeExist(archDir) {\n\t\tif err := os.Chdir(archDir); err != nil {\n\t\t\treturn util.NewNewtError(err.Error())\n\t\t}\n\t\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_C,\n\t\t\tignDirs); err != nil {\n\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ compile assembly sources in recursive compile as well\n\t\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_ASM,\n\t\t\tignDirs); err != nil {\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Compiles and archives a package.\nfunc (b *Builder) buildPackage(bpkg *BuildPackage) error {\n\tsrcDir := bpkg.BasePath() + \"\/src\"\n\tif util.NodeNotExist(srcDir) {\n\t\t\/\/ Nothing to compile.\n\t\treturn nil\n\t}\n\n\tc, err := toolchain.NewCompiler(b.compilerPkg.BasePath(),\n\t\tb.PkgBinDir(bpkg.Name()), b.target.BuildProfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddInfo(b.compilerInfo)\n\n\tci, err := bpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddInfo(ci)\n\n\t\/\/ Build the package source in two phases:\n\t\/\/ 1. Non-test code.\n\t\/\/ 2. Test code (if the \"test\" feature is enabled).\n\t\/\/\n\t\/\/ This is done in two passes because the structure of\n\t\/\/ architecture-specific directories is different for normal code and test\n\t\/\/ code, and not easy to generalize into a single operation:\n\t\/\/     * src\/arch\/<target-arch>\n\t\/\/     * src\/test\/arch\/<target-arch>\n\tif err = buildDir(srcDir, c, b.target.Arch, []string{\"test\"}); err != nil {\n\t\treturn err\n\t}\n\tif b.features[\"test\"] {\n\t\ttestSrcDir := srcDir + \"\/test\"\n\t\tif err = buildDir(testSrcDir, c, b.target.Arch, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Create a static library (\"archive\").\n\tif err := os.Chdir(bpkg.BasePath() + \"\/\"); err != nil {\n\t\treturn util.NewNewtError(err.Error())\n\t}\n\tarchiveFile := b.ArchivePath(bpkg.Name())\n\tif err = c.CompileArchive(archiveFile); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Builder) link(elfName string) error {\n\tc, err := toolchain.NewCompiler(b.compilerPkg.BasePath(),\n\t\tb.PkgBinDir(elfName), b.target.BuildProfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpkgNames := []string{}\n\tfor _, bpkg := range b.Packages {\n\t\tarchivePath := b.ArchivePath(bpkg.Name())\n\t\tif util.NodeExist(archivePath) {\n\t\t\tpkgNames = append(pkgNames, archivePath)\n\t\t}\n\t}\n\n\tif b.Bsp.LinkerScript != \"\" {\n\t\tc.LinkerScript = b.Bsp.BasePath() + b.Bsp.LinkerScript\n\t}\n\terr = c.CompileElf(elfName, pkgNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Populates the builder with all the packages that need to be built, and\n\/\/ configures each package's build settings.  After this function executes,\n\/\/ packages are ready to be built.\nfunc (b *Builder) PrepBuild() error {\n\tif b.Bsp != nil {\n\t\t\/\/ Already prepped\n\t\treturn nil\n\t}\n\t\/\/ Collect the seed packages.\n\tbspPkg := b.target.Bsp()\n\tif bspPkg == nil {\n\t\tif b.target.BspName == \"\" {\n\t\t\treturn util.NewNewtError(\"BSP package not specified by target\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"BSP package not found: \" +\n\t\t\t\tb.target.BspName)\n\t\t}\n\t}\n\n\tb.Bsp = pkg.NewBspPackage(bspPkg)\n\tcompilerPkg := b.resolveCompiler()\n\tif compilerPkg == nil {\n\t\tif b.Bsp.CompilerName == \"\" {\n\t\t\treturn util.NewNewtError(\"Compiler package not specified by BSP\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"Compiler package not found: \" +\n\t\t\t\tb.Bsp.CompilerName)\n\t\t}\n\t}\n\n\t\/\/ An app package is not required (e.g., unit tests).\n\tappPkg := b.target.App()\n\n\t\/\/ Seed the builder with the app (if present), bsp, compiler, and target\n\t\/\/ packages.\n\n\tvar appBpkg *BuildPackage\n\tif appPkg != nil {\n\t\tappBpkg = b.Packages[appPkg]\n\t\tif appBpkg == nil {\n\t\t\tappBpkg = b.AddPackage(appPkg)\n\t\t}\n\t}\n\n\tbspBpkg := b.Packages[bspPkg]\n\tif bspBpkg == nil {\n\t\tbspBpkg = b.AddPackage(bspPkg)\n\t}\n\n\tcompilerBpkg := b.Packages[compilerPkg]\n\tif compilerBpkg == nil {\n\t\tcompilerBpkg = b.AddPackage(compilerPkg)\n\t}\n\n\ttargetBpkg := b.AddPackage(b.target.Package())\n\n\t\/\/ Populate the full set of packages to be built and resolve the feature\n\t\/\/ set.\n\tif err := b.loadDeps(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Terminate if any package has an unmet API requirement.\n\tif err := b.verifyApisSatisfied(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Populate the base set of compiler flags.  Flags from the following\n\t\/\/ packages get applied to every source file:\n\t\/\/     * app (if present)\n\t\/\/     * bsp\n\t\/\/     * compiler\n\t\/\/     * target\n\n\tbaseCi := toolchain.NewCompilerInfo()\n\n\t\/\/ App flags.\n\tif appBpkg != nil {\n\t\tappCi, err := appBpkg.CompilerInfo(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbaseCi.AddCompilerInfo(appCi)\n\t}\n\n\t\/\/ Bsp flags.\n\tbspCi, err := bspBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseCi.AddCompilerInfo(bspCi)\n\n\t\/\/ Target flags.\n\ttargetCi, err := targetBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseCi.AddCompilerInfo(targetCi)\n\n\t\/\/ Note: Compiler flags get added when compiler is created.\n\n\t\/\/ Read the BSP configuration.  These settings are necessary for the link\n\t\/\/ step.\n\tb.Bsp.Reload(b.Features())\n\n\tb.compilerPkg = compilerPkg\n\tb.compilerInfo = baseCi\n\n\treturn nil\n}\n\nfunc (b *Builder) Build() error {\n\tif b.target.App() == nil {\n\t\tif b.target.AppName == \"\" {\n\t\t\treturn util.NewNewtError(\"App package not specified by target\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"App package not found: \" +\n\t\t\t\tb.target.AppName)\n\t\t}\n\t}\n\n\t\/\/ Populate the package and feature sets and calculate the base compiler\n\t\/\/ flags.\n\terr := b.PrepBuild()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ XXX: If any yml files have changed, a full rebuild is required.  We\n\t\/\/ don't currently check this.\n\n\tfor _, bpkg := range b.Packages {\n\t\terr = b.buildPackage(bpkg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = b.link(b.AppElfPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Builder) Test(p *pkg.LocalPackage) error {\n\t\/\/ Seed the builder with the package under test.\n\ttestBpkg := b.AddPackage(p)\n\n\t\/\/ A few features are automatically supported when the test command is\n\t\/\/ used:\n\t\/\/     * test:      ensures that the test code gets compiled.\n\t\/\/     * selftest:  indicates that there is no app.\n\tb.AddFeature(\"test\")\n\tb.AddFeature(\"selftest\")\n\n\t\/\/ Populate the package and feature sets and calculate the base compiler\n\t\/\/ flags.\n\terr := b.PrepBuild()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Define the PKG_TEST symbol while the package under test is being\n\t\/\/ compiled.  This symbol enables the appropriate main function that\n\t\/\/ usually comes from an app.\n\ttestPkgCi, err := testBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttestPkgCi.Cflags = append(testPkgCi.Cflags, \"-DPKG_TEST\")\n\n\t\/\/ XXX: If any yml files have changed, a full rebuild is required.  We\n\t\/\/ don't currently check this.\n\n\tfor _, bpkg := range b.Packages {\n\t\terr = b.buildPackage(bpkg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttestFilename := b.TestExePath(p.Name())\n\terr = b.link(testFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the tests.\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Testing package %s\\n\", p.Name())\n\n\tif err := os.Chdir(filepath.Dir(testFilename)); err != nil {\n\t\treturn err\n\t}\n\n\to, err := util.ShellCommand(testFilename)\n\tif err != nil {\n\t\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"%s\", string(o))\n\n\t\treturn util.NewNewtError(\"Test crashed: \" + testFilename)\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s\", string(o))\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Test %s ok!\\n\", testFilename)\n\n\treturn nil\n}\n\nfunc (b *Builder) Clean() error {\n\tpath := b.BinDir()\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"Cleaning directory %s\\n\", path)\n\terr := os.RemoveAll(path)\n\treturn err\n}\n<commit_msg>Specify cpp symbol indicating target architecture.<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 builder\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"mynewt.apache.org\/newt\/newt\/pkg\"\n\t\"mynewt.apache.org\/newt\/newt\/target\"\n\t\"mynewt.apache.org\/newt\/newt\/toolchain\"\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\ntype Builder struct {\n\tPackages map[*pkg.LocalPackage]*BuildPackage\n\tfeatures map[string]bool\n\tapis     map[string]*BuildPackage\n\n\tBsp          *pkg.BspPackage\n\tcompilerPkg  *pkg.LocalPackage\n\tcompilerInfo *toolchain.CompilerInfo\n\n\ttarget *target.Target\n}\n\nfunc NewBuilder(target *target.Target) (*Builder, error) {\n\tb := &Builder{}\n\n\tif err := b.Init(target); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\nfunc (b *Builder) Init(target *target.Target) error {\n\tb.target = target\n\n\tb.Packages = map[*pkg.LocalPackage]*BuildPackage{}\n\tb.features = map[string]bool{}\n\tb.apis = map[string]*BuildPackage{}\n\n\treturn nil\n}\n\nfunc (b *Builder) Features() map[string]bool {\n\treturn b.features\n}\n\nfunc (b *Builder) AddFeature(feature string) {\n\tb.features[feature] = true\n}\n\nfunc (b *Builder) AddPackage(npkg *pkg.LocalPackage) *BuildPackage {\n\t\/\/ Don't allow nil entries to the map\n\tif npkg == nil {\n\t\tpanic(\"Cannot add nil package builder map\")\n\t}\n\n\tbpkg := b.Packages[npkg]\n\tif bpkg == nil {\n\t\tbpkg = NewBuildPackage(npkg)\n\t\tb.Packages[npkg] = bpkg\n\t}\n\n\treturn bpkg\n}\n\n\/\/ @return bool                 true if this is a new API.\nfunc (b *Builder) AddApi(apiString string, bpkg *BuildPackage) bool {\n\tcurBpkg := b.apis[apiString]\n\tif curBpkg == nil {\n\t\tb.apis[apiString] = bpkg\n\t\treturn true\n\t} else {\n\t\tif curBpkg != bpkg {\n\t\t\tutil.StatusMessage(util.VERBOSITY_QUIET,\n\t\t\t\t\"Warning: API conflict: %s <-> %s\\n\", curBpkg.Name(),\n\t\t\t\tbpkg.Name())\n\t\t}\n\t\treturn false\n\t}\n}\n\nfunc (b *Builder) loadDeps() error {\n\t\/\/ Circularly resolve dependencies, identities, APIs, and required APIs\n\t\/\/ until no new ones exist.\n\tfor {\n\t\treprocess := false\n\t\tfor _, bpkg := range b.Packages {\n\t\t\tresolved, err := bpkg.Resolve(b)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !resolved {\n\t\t\t\treprocess = true\n\t\t\t}\n\t\t}\n\n\t\tif !reprocess {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"Building with the following \"+\n\t\t\"feature set: [\"+b.FeatureString()+\"]\\n\")\n\n\treturn nil\n}\n\n\/\/ Recursively compiles all the .c and .s files in the specified directory.\n\/\/ Architecture-specific files are also compiled.\nfunc buildDir(srcDir string, c *toolchain.Compiler, arch string,\n\tignDirs []string) error {\n\n\t\/\/ Quietly succeed if the source directory doesn't exist.\n\tif util.NodeNotExist(srcDir) {\n\t\treturn nil\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE,\n\t\t\"compiling src in base directory: %s\\n\", srcDir)\n\n\t\/\/ Start from the source directory.\n\tif err := os.Chdir(srcDir); err != nil {\n\t\treturn util.NewNewtError(err.Error())\n\t}\n\n\t\/\/ Don't recurse into destination directories.\n\tignDirs = append(ignDirs, \"obj\")\n\tignDirs = append(ignDirs, \"bin\")\n\n\t\/\/ Ignore architecture-specific source files for now.  Use a temporary\n\t\/\/ string slice here so that the \"arch\" directory is not ignored in the\n\t\/\/ subsequent architecture-specific compile phase.\n\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_C,\n\t\tappend(ignDirs, \"arch\")); err != nil {\n\n\t\treturn err\n\t}\n\n\tarchDir := srcDir + \"\/arch\/\" + arch + \"\/\"\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE,\n\t\t\"compiling architecture specific src pkgs in directory: %s\\n\",\n\t\tarchDir)\n\n\tif util.NodeExist(archDir) {\n\t\tif err := os.Chdir(archDir); err != nil {\n\t\t\treturn util.NewNewtError(err.Error())\n\t\t}\n\t\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_C,\n\t\t\tignDirs); err != nil {\n\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ compile assembly sources in recursive compile as well\n\t\tif err := c.RecursiveCompile(toolchain.COMPILER_TYPE_ASM,\n\t\t\tignDirs); err != nil {\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Compiles and archives a package.\nfunc (b *Builder) buildPackage(bpkg *BuildPackage) error {\n\tsrcDir := bpkg.BasePath() + \"\/src\"\n\tif util.NodeNotExist(srcDir) {\n\t\t\/\/ Nothing to compile.\n\t\treturn nil\n\t}\n\n\tc, err := toolchain.NewCompiler(b.compilerPkg.BasePath(),\n\t\tb.PkgBinDir(bpkg.Name()), b.target.BuildProfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddInfo(b.compilerInfo)\n\n\tci, err := bpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.AddInfo(ci)\n\n\t\/\/ Build the package source in two phases:\n\t\/\/ 1. Non-test code.\n\t\/\/ 2. Test code (if the \"test\" feature is enabled).\n\t\/\/\n\t\/\/ This is done in two passes because the structure of\n\t\/\/ architecture-specific directories is different for normal code and test\n\t\/\/ code, and not easy to generalize into a single operation:\n\t\/\/     * src\/arch\/<target-arch>\n\t\/\/     * src\/test\/arch\/<target-arch>\n\tif err = buildDir(srcDir, c, b.target.Arch, []string{\"test\"}); err != nil {\n\t\treturn err\n\t}\n\tif b.features[\"test\"] {\n\t\ttestSrcDir := srcDir + \"\/test\"\n\t\tif err = buildDir(testSrcDir, c, b.target.Arch, nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Create a static library (\"archive\").\n\tif err := os.Chdir(bpkg.BasePath() + \"\/\"); err != nil {\n\t\treturn util.NewNewtError(err.Error())\n\t}\n\tarchiveFile := b.ArchivePath(bpkg.Name())\n\tif err = c.CompileArchive(archiveFile); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Builder) link(elfName string) error {\n\tc, err := toolchain.NewCompiler(b.compilerPkg.BasePath(),\n\t\tb.PkgBinDir(elfName), b.target.BuildProfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpkgNames := []string{}\n\tfor _, bpkg := range b.Packages {\n\t\tarchivePath := b.ArchivePath(bpkg.Name())\n\t\tif util.NodeExist(archivePath) {\n\t\t\tpkgNames = append(pkgNames, archivePath)\n\t\t}\n\t}\n\n\tif b.Bsp.LinkerScript != \"\" {\n\t\tc.LinkerScript = b.Bsp.BasePath() + b.Bsp.LinkerScript\n\t}\n\terr = c.CompileElf(elfName, pkgNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Populates the builder with all the packages that need to be built, and\n\/\/ configures each package's build settings.  After this function executes,\n\/\/ packages are ready to be built.\nfunc (b *Builder) PrepBuild() error {\n\tif b.Bsp != nil {\n\t\t\/\/ Already prepped\n\t\treturn nil\n\t}\n\t\/\/ Collect the seed packages.\n\tbspPkg := b.target.Bsp()\n\tif bspPkg == nil {\n\t\tif b.target.BspName == \"\" {\n\t\t\treturn util.NewNewtError(\"BSP package not specified by target\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"BSP package not found: \" +\n\t\t\t\tb.target.BspName)\n\t\t}\n\t}\n\n\tb.Bsp = pkg.NewBspPackage(bspPkg)\n\tcompilerPkg := b.resolveCompiler()\n\tif compilerPkg == nil {\n\t\tif b.Bsp.CompilerName == \"\" {\n\t\t\treturn util.NewNewtError(\"Compiler package not specified by BSP\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"Compiler package not found: \" +\n\t\t\t\tb.Bsp.CompilerName)\n\t\t}\n\t}\n\n\t\/\/ An app package is not required (e.g., unit tests).\n\tappPkg := b.target.App()\n\n\t\/\/ Seed the builder with the app (if present), bsp, compiler, and target\n\t\/\/ packages.\n\n\tvar appBpkg *BuildPackage\n\tif appPkg != nil {\n\t\tappBpkg = b.Packages[appPkg]\n\t\tif appBpkg == nil {\n\t\t\tappBpkg = b.AddPackage(appPkg)\n\t\t}\n\t}\n\n\tbspBpkg := b.Packages[bspPkg]\n\tif bspBpkg == nil {\n\t\tbspBpkg = b.AddPackage(bspPkg)\n\t}\n\n\tcompilerBpkg := b.Packages[compilerPkg]\n\tif compilerBpkg == nil {\n\t\tcompilerBpkg = b.AddPackage(compilerPkg)\n\t}\n\n\ttargetBpkg := b.AddPackage(b.target.Package())\n\n\t\/\/ Populate the full set of packages to be built and resolve the feature\n\t\/\/ set.\n\tif err := b.loadDeps(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Terminate if any package has an unmet API requirement.\n\tif err := b.verifyApisSatisfied(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Populate the base set of compiler flags.  Flags from the following\n\t\/\/ packages get applied to every source file:\n\t\/\/     * app (if present)\n\t\/\/     * bsp\n\t\/\/     * compiler (not added here)\n\t\/\/     * target\n\n\tbaseCi := toolchain.NewCompilerInfo()\n\n\t\/\/ App flags.\n\tif appBpkg != nil {\n\t\tappCi, err := appBpkg.CompilerInfo(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbaseCi.AddCompilerInfo(appCi)\n\t}\n\n\t\/\/ Bsp flags.\n\tbspCi, err := bspBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseCi.AddCompilerInfo(bspCi)\n\n\t\/\/ Target flags.\n\ttargetCi, err := targetBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Define a cpp symbol indicating the target architecture.\n\t\/\/ XXX: This should probably happen in the bsp after we move the arch field\n\t\/\/ from target to bsp.\n\ttargetCi.Cflags = append(targetCi.Cflags, \"-DARCH_\"+b.target.Arch)\n\n\tbaseCi.AddCompilerInfo(targetCi)\n\n\t\/\/ Note: Compiler flags get added when compiler is created.\n\n\t\/\/ Read the BSP configuration.  These settings are necessary for the link\n\t\/\/ step.\n\tb.Bsp.Reload(b.Features())\n\n\tb.compilerPkg = compilerPkg\n\tb.compilerInfo = baseCi\n\n\treturn nil\n}\n\nfunc (b *Builder) Build() error {\n\tif b.target.App() == nil {\n\t\tif b.target.AppName == \"\" {\n\t\t\treturn util.NewNewtError(\"App package not specified by target\")\n\t\t} else {\n\t\t\treturn util.NewNewtError(\"App package not found: \" +\n\t\t\t\tb.target.AppName)\n\t\t}\n\t}\n\n\t\/\/ Populate the package and feature sets and calculate the base compiler\n\t\/\/ flags.\n\terr := b.PrepBuild()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ XXX: If any yml files have changed, a full rebuild is required.  We\n\t\/\/ don't currently check this.\n\n\tfor _, bpkg := range b.Packages {\n\t\terr = b.buildPackage(bpkg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = b.link(b.AppElfPath())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Builder) Test(p *pkg.LocalPackage) error {\n\t\/\/ Seed the builder with the package under test.\n\ttestBpkg := b.AddPackage(p)\n\n\t\/\/ A few features are automatically supported when the test command is\n\t\/\/ used:\n\t\/\/     * test:      ensures that the test code gets compiled.\n\t\/\/     * selftest:  indicates that there is no app.\n\tb.AddFeature(\"test\")\n\tb.AddFeature(\"selftest\")\n\n\t\/\/ Populate the package and feature sets and calculate the base compiler\n\t\/\/ flags.\n\terr := b.PrepBuild()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Define the PKG_TEST symbol while the package under test is being\n\t\/\/ compiled.  This symbol enables the appropriate main function that\n\t\/\/ usually comes from an app.\n\ttestPkgCi, err := testBpkg.CompilerInfo(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttestPkgCi.Cflags = append(testPkgCi.Cflags, \"-DPKG_TEST\")\n\n\t\/\/ XXX: If any yml files have changed, a full rebuild is required.  We\n\t\/\/ don't currently check this.\n\n\tfor _, bpkg := range b.Packages {\n\t\terr = b.buildPackage(bpkg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttestFilename := b.TestExePath(p.Name())\n\terr = b.link(testFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the tests.\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Testing package %s\\n\", p.Name())\n\n\tif err := os.Chdir(filepath.Dir(testFilename)); err != nil {\n\t\treturn err\n\t}\n\n\to, err := util.ShellCommand(testFilename)\n\tif err != nil {\n\t\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"%s\", string(o))\n\n\t\treturn util.NewNewtError(\"Test crashed: \" + testFilename)\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s\", string(o))\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Test %s ok!\\n\", testFilename)\n\n\treturn nil\n}\n\nfunc (b *Builder) Clean() error {\n\tpath := b.BinDir()\n\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"Cleaning directory %s\\n\", path)\n\terr := os.RemoveAll(path)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hoisie\/redis\"\n)\n\ntype Hosts struct {\n\tfileHosts  *FileHosts\n\tredisHosts *RedisHosts\n}\n\nfunc NewHosts(hs HostsSettings, rs RedisSettings) Hosts {\n\tfileHosts := &FileHosts{hs.HostsFile, make(map[string]string)}\n\n\tvar redisHosts *RedisHosts\n\tif hs.RedisEnable {\n\t\trc := &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password}\n\t\tredisHosts = &RedisHosts{rc, hs.RedisKey, make(map[string]string)}\n\t}\n\n\thosts := Hosts{fileHosts, redisHosts}\n\thosts.refresh()\n\treturn hosts\n\n}\n\n\/*\n1. Match local \/etc\/hosts file first, remote redis records second\n2. Fetch hosts records from \/etc\/hosts file and redis per minute\n*\/\n\nfunc (h *Hosts) Get(domain string, family int) (ip net.IP, ok bool) {\n\n\tvar sip string\n\n\tif sip, ok = h.fileHosts.Get(domain); !ok {\n\t\tif h.redisHosts != nil {\n\t\t\tsip, ok = h.redisHosts.Get(domain)\n\t\t}\n\t}\n\n\tif sip == \"\" {\n\t\treturn nil, false\n\t}\n\n\tswitch family {\n\tcase _IP4Query:\n\t\tip = net.ParseIP(sip).To4()\n\tcase _IP6Query:\n\t\tip = net.ParseIP(sip).To16()\n\tdefault:\n\t\treturn nil, false\n\t}\n\treturn ip, (ip != nil)\n}\n\nfunc (h *Hosts) refresh() {\n\tticker := time.NewTicker(time.Minute)\n\tgo func() {\n\t\tfor {\n\t\t\th.fileHosts.Refresh()\n\t\t\tif h.redisHosts != nil {\n\t\t\t\th.redisHosts.Refresh()\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n}\n\ntype RedisHosts struct {\n\tredis *redis.Client\n\tkey   string\n\thosts map[string]string\n}\n\nfunc (r *RedisHosts) Get(domain string) (ip string, ok bool) {\n\tip, ok = r.hosts[domain]\n\treturn\n}\n\nfunc (r *RedisHosts) Set(domain, ip string) (bool, error) {\n\treturn r.redis.Hset(r.key, domain, []byte(ip))\n}\n\nfunc (r *RedisHosts) Refresh() {\n\tr.redis.Hgetall(r.key, r.hosts)\n\tDebug(\"update hosts records from redis\")\n}\n\ntype FileHosts struct {\n\tfile  string\n\thosts map[string]string\n}\n\nfunc (f *FileHosts) Get(domain string) (ip string, ok bool) {\n\tip, ok = f.hosts[domain]\n\treturn\n}\n\nfunc (f *FileHosts) Refresh() {\n\tbuf, err := os.Open(f.file)\n\tif err != nil {\n\t\tpanic(\"Can't open \" + f.file)\n\t}\n\tdefer buf.Close()\n\n\tscanner := bufio.NewScanner(buf)\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\t\tline = strings.TrimSpace(line)\n\n\t\tif strings.HasPrefix(line, \"#\") || line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tsli := strings.Split(line, \" \")\n\t\tif len(sli) == 1 {\n\t\t\tsli = strings.Split(line, \"\\t\")\n\t\t}\n\n\t\tif len(sli) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdomain := sli[len(sli)-1]\n\t\tip := sli[0]\n\t\tif !f.isDomain(domain) || !f.isIP(ip) {\n\t\t\tcontinue\n\t\t}\n\n\t\tf.hosts[domain] = ip\n\t}\n\tDebug(\"update hosts records from %s\", f.file)\n}\n\nfunc (f *FileHosts) isDomain(domain string) bool {\n\tif f.isIP(domain) {\n\t\treturn false\n\t}\n\tmatch, _ := regexp.MatchString(\"^[a-zA-Z0-9][a-zA-Z0-9-]\", domain)\n\treturn match\n}\n\nfunc (f *FileHosts) isIP(ip string) bool {\n\treturn (net.ParseIP(ip) != nil)\n}\n<commit_msg>Reinforced domain regex match<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hoisie\/redis\"\n)\n\ntype Hosts struct {\n\tfileHosts  *FileHosts\n\tredisHosts *RedisHosts\n}\n\nfunc NewHosts(hs HostsSettings, rs RedisSettings) Hosts {\n\tfileHosts := &FileHosts{hs.HostsFile, make(map[string]string)}\n\n\tvar redisHosts *RedisHosts\n\tif hs.RedisEnable {\n\t\trc := &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password}\n\t\tredisHosts = &RedisHosts{rc, hs.RedisKey, make(map[string]string)}\n\t}\n\n\thosts := Hosts{fileHosts, redisHosts}\n\thosts.refresh()\n\treturn hosts\n\n}\n\n\/*\n1. Match local \/etc\/hosts file first, remote redis records second\n2. Fetch hosts records from \/etc\/hosts file and redis per minute\n*\/\n\nfunc (h *Hosts) Get(domain string, family int) (ip net.IP, ok bool) {\n\n\tvar sip string\n\n\tif sip, ok = h.fileHosts.Get(domain); !ok {\n\t\tif h.redisHosts != nil {\n\t\t\tsip, ok = h.redisHosts.Get(domain)\n\t\t}\n\t}\n\n\tif sip == \"\" {\n\t\treturn nil, false\n\t}\n\n\tswitch family {\n\tcase _IP4Query:\n\t\tip = net.ParseIP(sip).To4()\n\tcase _IP6Query:\n\t\tip = net.ParseIP(sip).To16()\n\tdefault:\n\t\treturn nil, false\n\t}\n\treturn ip, (ip != nil)\n}\n\nfunc (h *Hosts) refresh() {\n\tticker := time.NewTicker(time.Minute)\n\tgo func() {\n\t\tfor {\n\t\t\th.fileHosts.Refresh()\n\t\t\tif h.redisHosts != nil {\n\t\t\t\th.redisHosts.Refresh()\n\t\t\t}\n\t\t\t<-ticker.C\n\t\t}\n\t}()\n}\n\ntype RedisHosts struct {\n\tredis *redis.Client\n\tkey   string\n\thosts map[string]string\n}\n\nfunc (r *RedisHosts) Get(domain string) (ip string, ok bool) {\n\tip, ok = r.hosts[domain]\n\treturn\n}\n\nfunc (r *RedisHosts) Set(domain, ip string) (bool, error) {\n\treturn r.redis.Hset(r.key, domain, []byte(ip))\n}\n\nfunc (r *RedisHosts) Refresh() {\n\tr.redis.Hgetall(r.key, r.hosts)\n\tDebug(\"update hosts records from redis\")\n}\n\ntype FileHosts struct {\n\tfile  string\n\thosts map[string]string\n}\n\nfunc (f *FileHosts) Get(domain string) (ip string, ok bool) {\n\tip, ok = f.hosts[domain]\n\treturn\n}\n\nfunc (f *FileHosts) Refresh() {\n\tbuf, err := os.Open(f.file)\n\tif err != nil {\n\t\tpanic(\"Can't open \" + f.file)\n\t}\n\tdefer buf.Close()\n\n\tscanner := bufio.NewScanner(buf)\n\tfor scanner.Scan() {\n\n\t\tline := scanner.Text()\n\t\tline = strings.TrimSpace(line)\n\n\t\tif strings.HasPrefix(line, \"#\") || line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tsli := strings.Split(line, \" \")\n\t\tif len(sli) == 1 {\n\t\t\tsli = strings.Split(line, \"\\t\")\n\t\t}\n\n\t\tif len(sli) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdomain := sli[len(sli)-1]\n\t\tip := sli[0]\n\t\tif !f.isDomain(domain) || !f.isIP(ip) {\n\t\t\tcontinue\n\t\t}\n\n\t\tf.hosts[domain] = ip\n\t}\n\tDebug(\"update hosts records from %s\", f.file)\n}\n\nfunc (f *FileHosts) isDomain(domain string) bool {\n\tif f.isIP(domain) {\n\t\treturn false\n\t}\n\tmatch, _ := regexp.MatchString(`^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}$`, domain)\n\treturn match\n}\n\nfunc (f *FileHosts) isIP(ip string) bool {\n\treturn (net.ParseIP(ip) != nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/robertkrimen\/otto\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar (\n\tcodeListPtr  = ArgsStrList(kingpin.Arg(\"code\", \"code\").Required())\n\tlineSeqPtr   = kingpin.Flag(\"line-seq\", \"code\").Short('l').Default(\"\\n\").String()\n\tcolumnSeqPtr = kingpin.Flag(\"column-seq\", \"code\").Short('c').Default(\" \").String()\n\tfuncListPtr  = ArgsStrList(kingpin.Flag(\"funcion\", \"function\").Short('f'))\n\tpathListPtr  = ArgsStrList(kingpin.Flag(\"path\", \"command search path\").Short('p'))\n\tjsListPtr    = ArgsStrList(kingpin.Flag(\"js\", \"Javascript file\").Short('j'))\n)\n\ntype argsStrList []string\n\nfunc (i *argsStrList) Set(value string) error {\n\t*i = append(*i, value)\n\treturn nil\n}\n\nfunc (i *argsStrList) String() string {\n\treturn \"\"\n}\n\nfunc (i *argsStrList) IsCumulative() bool {\n\treturn true\n}\n\nfunc ArgsStrList(s kingpin.Settings) (target *[]string) {\n\ttarget = new([]string)\n\ts.SetValue((*argsStrList)(target))\n\treturn\n}\n\nfunc readAll() string {\n\tbytes, err := ioutil.ReadAll(os.Stdin)\n\tif err == nil {\n\t\treturn string(bytes)\n\t} else {\n\t\tpanic(\"Failed to read stdin\")\n\t}\n}\n\nfunc readJSFile(vm *otto.Otto, path string) {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvm.Run(string(bytes))\n}\n\ntype Matrix [][]string\n\nfunc setPrintArrayFunc(vm *otto.Otto) {\n\tvm.Run(`\n\tprintArray = function(arr) {\n\t\tfor(i=0;i<arr.length;i+=1){\n\t\t\tconsole.log(i)\n\t\t}\n\t}`)\n\n}\n\nfunc callExternalFunc(cmd string, args []string) string {\n\tout, err := exec.Command(cmd, args...).Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(out)\n\n}\n\nfunc addPATHEnv(path string) {\n\toldEnv := os.Getenv(\"PATH\")\n\tnewEnv := path + \":\" + oldEnv\n\tos.Setenv(\"PATH\", newEnv)\n}\n\nfunc getWd() string {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cwd\n}\n\nfunc initExternelFunc(vm *otto.Otto, cmdPath string) {\n\tfuncName := cmdPath[:len(cmdPath)-len(filepath.Ext(cmdPath))]\n\tvm.Set(funcName, func(call otto.FunctionCall) otto.Value {\n\t\targs := make([]string, len(call.ArgumentList))\n\t\tfor i := 0; i < len(call.ArgumentList); i += 1 {\n\t\t\tret, err := call.Argument(i).ToString()\n\t\t\tif err == nil {\n\t\t\t\targs[i] = ret\n\t\t\t} else {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t}\n\t\toutput := callExternalFunc(cmdPath, args)\n\t\tresult, err := vm.ToValue(output)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn result\n\t})\n\n}\n\nfunc main() {\n\taddPATHEnv(getWd())\n\tfmt.Printf(\"\")\n\tkingpin.Parse()\n\n\tstdin := readAll()\n\tlines := strings.Split(stdin, *lineSeqPtr)\n\tmatrixPtr := new(Matrix)\n\n\tfor i := 0; i < len(lines); i += 1 {\n\t\t*matrixPtr = append(*matrixPtr, strings.Split(lines[i], *columnSeqPtr))\n\t}\n\n\tvm := otto.New()\n\n\tvm.Set(\"stdin\", stdin)\n\tvm.Set(\"stdout\", \"\")\n\tvm.Set(\"lines\", lines)\n\tvm.Set(\"matrix\", *matrixPtr)\n\tvm.Run(\"print = console.log\")\n\tsetPrintArrayFunc(vm)\n\n\tfor i := 0; i < len(*funcListPtr); i += 1 {\n\t\tinitExternelFunc(vm, (*funcListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*pathListPtr); i += 1 {\n\t\taddPATHEnv((*pathListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*jsListPtr); i += 1 {\n\t\tfmt.Printf(\"%v\", i)\n\t\treadJSFile(vm, (*jsListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*codeListPtr); i += 1 {\n\t\tvm.Run((*codeListPtr)[i])\n\t}\n\n}\n<commit_msg>fix help message<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/robertkrimen\/otto\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar (\n\tcodeListPtr  = ArgsStrList(kingpin.Arg(\"code\", \"the js code you want to run\").Required())\n\tlineSeqPtr   = kingpin.Flag(\"line-seq\", \"the char used for split line\").Short('l').Default(\"\\n\").String()\n\tcolumnSeqPtr = kingpin.Flag(\"column-seq\", \"the char used for split column\").Short('c').Default(\" \").String()\n\tfuncListPtr  = ArgsStrList(kingpin.Flag(\"funcion\", \"function\").Short('f'))\n\tpathListPtr  = ArgsStrList(kingpin.Flag(\"path\", \"command search path\").Short('p'))\n\tjsListPtr    = ArgsStrList(kingpin.Flag(\"js\", \"Javascript file\").Short('j'))\n)\n\ntype argsStrList []string\n\nfunc (i *argsStrList) Set(value string) error {\n\t*i = append(*i, value)\n\treturn nil\n}\n\nfunc (i *argsStrList) String() string {\n\treturn \"\"\n}\n\nfunc (i *argsStrList) IsCumulative() bool {\n\treturn true\n}\n\nfunc ArgsStrList(s kingpin.Settings) (target *[]string) {\n\ttarget = new([]string)\n\ts.SetValue((*argsStrList)(target))\n\treturn\n}\n\nfunc readAll() string {\n\tbytes, err := ioutil.ReadAll(os.Stdin)\n\tif err == nil {\n\t\treturn string(bytes)\n\t} else {\n\t\tpanic(\"Failed to read stdin\")\n\t}\n}\n\nfunc readJSFile(vm *otto.Otto, path string) {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvm.Run(string(bytes))\n}\n\ntype Matrix [][]string\n\nfunc setPrintArrayFunc(vm *otto.Otto) {\n\tvm.Run(`\n\tprintArray = function(arr) {\n\t\tfor(i=0;i<arr.length;i+=1){\n\t\t\tconsole.log(i)\n\t\t}\n\t}`)\n\n}\n\nfunc callExternalFunc(cmd string, args []string) string {\n\tout, err := exec.Command(cmd, args...).Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(out)\n\n}\n\nfunc addPATHEnv(path string) {\n\toldEnv := os.Getenv(\"PATH\")\n\tnewEnv := path + \":\" + oldEnv\n\tos.Setenv(\"PATH\", newEnv)\n}\n\nfunc getWd() string {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn cwd\n}\n\nfunc initExternelFunc(vm *otto.Otto, cmdPath string) {\n\tfuncName := cmdPath[:len(cmdPath)-len(filepath.Ext(cmdPath))]\n\tvm.Set(funcName, func(call otto.FunctionCall) otto.Value {\n\t\targs := make([]string, len(call.ArgumentList))\n\t\tfor i := 0; i < len(call.ArgumentList); i += 1 {\n\t\t\tret, err := call.Argument(i).ToString()\n\t\t\tif err == nil {\n\t\t\t\targs[i] = ret\n\t\t\t} else {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t}\n\t\toutput := callExternalFunc(cmdPath, args)\n\t\tresult, err := vm.ToValue(output)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn result\n\t})\n\n}\n\nfunc main() {\n\taddPATHEnv(getWd())\n\tfmt.Printf(\"\")\n\tkingpin.Parse()\n\n\tstdin := readAll()\n\tlines := strings.Split(stdin, *lineSeqPtr)\n\tmatrixPtr := new(Matrix)\n\n\tfor i := 0; i < len(lines); i += 1 {\n\t\t*matrixPtr = append(*matrixPtr, strings.Split(lines[i], *columnSeqPtr))\n\t}\n\n\tvm := otto.New()\n\n\tvm.Set(\"stdin\", stdin)\n\tvm.Set(\"stdout\", \"\")\n\tvm.Set(\"lines\", lines)\n\tvm.Set(\"matrix\", *matrixPtr)\n\tvm.Run(\"print = console.log\")\n\tsetPrintArrayFunc(vm)\n\n\tfor i := 0; i < len(*funcListPtr); i += 1 {\n\t\tinitExternelFunc(vm, (*funcListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*pathListPtr); i += 1 {\n\t\taddPATHEnv((*pathListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*jsListPtr); i += 1 {\n\t\tfmt.Printf(\"%v\", i)\n\t\treadJSFile(vm, (*jsListPtr)[i])\n\t}\n\n\tfor i := 0; i < len(*codeListPtr); i += 1 {\n\t\tvm.Run((*codeListPtr)[i])\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\nfunc main() {\n\n\tfmt.Println(\"Hello, This is GO here!\")\n}\n<commit_msg>a function<commit_after>package main\n\nimport \"fmt\"\n\nfunc dummy() (n int, err string) {\n   return 1, \"Error message\"\n}\n\nfunc main() {\n\tfmt.Println(\"Hello, This is GO here!\")\n        n, err := dummy()\n        fmt.Printf(\"n: %v, err: %v\", n, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package testdata provides test images.\npackage testdata\n\nimport (\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/pierrre\/imageserver\"\n)\n\nvar (\n\t\/\/ Dir is the path to the directory containing the test data.\n\tDir = initDir()\n\n\t\/\/ Images contains all images by filename.\n\tImages = make(map[string]*imageserver.Image)\n\n\t\/\/ SmallFileName is the file name of Small.\n\tSmallFileName = \"small.jpg\"\n\t\/\/ Small is a small Image.\n\tSmall = loadImage(SmallFileName, \"jpeg\")\n\t\/\/ MediumFileName is the file name of Medium.\n\tMediumFileName = \"medium.jpg\"\n\t\/\/ Medium is a medium Image.\n\tMedium = loadImage(MediumFileName, \"jpeg\")\n\t\/\/ LargeFileName is the file name of Large.\n\tLargeFileName = \"large.jpg\"\n\t\/\/ Large is a large image.\n\tLarge = loadImage(LargeFileName, \"jpeg\")\n\t\/\/ HugeFileName is the file name of Huge.\n\tHugeFileName = \"huge.jpg\"\n\t\/\/ Huge is a huge image.\n\tHuge = loadImage(HugeFileName, \"jpeg\")\n\t\/\/ AnimatedFileName is the file name of Animated.\n\tAnimatedFileName = \"animated.gif\"\n\t\/\/ Animated is an animated GIF Image.\n\tAnimated = loadImage(AnimatedFileName, \"gif\")\n\t\/\/ DalaiGammaFileName is the file name of DalaiGamma.\n\tDalaiGammaFileName = \"dalai_gamma.jpg\"\n\t\/\/ DalaiGamma is a gamma test Image (from http:\/\/www.4p8.com\/eric.brasseur\/gamma.html).\n\tDalaiGamma = loadImage(DalaiGammaFileName, \"jpeg\")\n\t\/\/ InvalidFileName is the file name of Invalid.\n\tInvalidFileName = \"invalid.jpg\"\n\t\/\/ Invalid is an invalid Image.\n\tInvalid = loadImage(InvalidFileName, \"jpeg\")\n\n\t\/\/ Server is an Image Server that uses filename as source.\n\tServer imageserver.Server = imageserver.ServerFunc(func(params imageserver.Params) (*imageserver.Image, error) {\n\t\tsource, err := params.Get(imageserver.SourceParam)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tname, ok := source.(string)\n\t\tif !ok {\n\t\t\treturn nil, &imageserver.ParamError{Param: imageserver.SourceParam, Message: \"not a string\"}\n\t\t}\n\t\tim, ok := Images[name]\n\t\tif !ok {\n\t\t\treturn nil, &imageserver.ParamError{Param: imageserver.SourceParam, Message: \"unknown image\"}\n\t\t}\n\t\treturn im, nil\n\t})\n)\n\nfunc initDir() string {\n\t_, currentFile, _, _ := runtime.Caller(0)\n\treturn filepath.Dir(currentFile)\n}\n\nfunc loadImage(filename string, format string) *imageserver.Image {\n\tfilePath := filepath.Join(Dir, filename)\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tim := &imageserver.Image{\n\t\tFormat: format,\n\t\tData:   data,\n\t}\n\tImages[filename] = im\n\treturn im\n}\n<commit_msg>testdata: expose a Get() function, and simplify code<commit_after>\/\/ Package testdata provides test images.\npackage testdata\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/pierrre\/imageserver\"\n)\n\nvar (\n\t\/\/ Dir is the path to the directory containing the test data.\n\tDir = initDir()\n\n\t\/\/ Images contains all images by filename.\n\tImages = make(map[string]*imageserver.Image)\n\n\t\/\/ SmallFileName is the file name of Small.\n\tSmallFileName = \"small.jpg\"\n\t\/\/ Small is a small Image.\n\tSmall = loadImage(SmallFileName, \"jpeg\")\n\t\/\/ MediumFileName is the file name of Medium.\n\tMediumFileName = \"medium.jpg\"\n\t\/\/ Medium is a medium Image.\n\tMedium = loadImage(MediumFileName, \"jpeg\")\n\t\/\/ LargeFileName is the file name of Large.\n\tLargeFileName = \"large.jpg\"\n\t\/\/ Large is a large image.\n\tLarge = loadImage(LargeFileName, \"jpeg\")\n\t\/\/ HugeFileName is the file name of Huge.\n\tHugeFileName = \"huge.jpg\"\n\t\/\/ Huge is a huge image.\n\tHuge = loadImage(HugeFileName, \"jpeg\")\n\t\/\/ AnimatedFileName is the file name of Animated.\n\tAnimatedFileName = \"animated.gif\"\n\t\/\/ Animated is an animated GIF Image.\n\tAnimated = loadImage(AnimatedFileName, \"gif\")\n\t\/\/ DalaiGammaFileName is the file name of DalaiGamma.\n\tDalaiGammaFileName = \"dalai_gamma.jpg\"\n\t\/\/ DalaiGamma is a gamma test Image (from http:\/\/www.4p8.com\/eric.brasseur\/gamma.html).\n\tDalaiGamma = loadImage(DalaiGammaFileName, \"jpeg\")\n\t\/\/ InvalidFileName is the file name of Invalid.\n\tInvalidFileName = \"invalid.jpg\"\n\t\/\/ Invalid is an invalid Image.\n\tInvalid = loadImage(InvalidFileName, \"jpeg\")\n\n\t\/\/ Server is an Image Server that uses filename as source.\n\tServer imageserver.Server = imageserver.ServerFunc(func(params imageserver.Params) (*imageserver.Image, error) {\n\t\tsource, err := params.GetString(imageserver.SourceParam)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tim, err := Get(source)\n\t\tif err != nil {\n\t\t\treturn nil, &imageserver.ParamError{Param: imageserver.SourceParam, Message: err.Error()}\n\t\t}\n\t\treturn im, nil\n\t})\n)\n\n\/\/ Get returns an Image for a name.\nfunc Get(name string) (*imageserver.Image, error) {\n\tim, ok := Images[name]\n\tif !ok {\n\t\treturn nil, errors.New(\"unknown image\")\n\t}\n\treturn im, nil\n}\n\nfunc initDir() string {\n\t_, currentFile, _, _ := runtime.Caller(0)\n\treturn filepath.Dir(currentFile)\n}\n\nfunc loadImage(filename string, format string) *imageserver.Image {\n\tfilePath := filepath.Join(Dir, filename)\n\tdata, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tim := &imageserver.Image{\n\t\tFormat: format,\n\t\tData:   data,\n\t}\n\tImages[filename] = im\n\treturn im\n}\n<|endoftext|>"}
{"text":"<commit_before>package jiffy\n\nconst (\n\tcancelTTL = iota\n\textendTTL\n)\n\nvar (\n\tregistry *Registry\n)\n\nfunc GetTopic(name string) *Topic {\n\treturn registry.GetTopic(name)\n}\n\nfunc init() {\n\tregistry = CreateRegistry()\n}\n<commit_msg>Comment for main exported fuctions<commit_after>package jiffy\n\nconst (\n\tcancelTTL = iota\n\textendTTL\n)\n\nvar (\n\tregistry *Registry\n)\n\n\/\/ Returns a topic from the global registry.\nfunc GetTopic(name string) *Topic {\n\treturn registry.GetTopic(name)\n}\n\nfunc init() {\n\tregistry = CreateRegistry()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Santiago Corredoira\n\/\/ Distributed under a BSD-like license.\npackage email\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/smtp\"\n\t\"path\/filepath\"\n)\n\ntype Message struct {\n\tFrom        string\n\tTo          []string\n\tSubject     string\n\tBody        string\n\tAttachments map[string][]byte\n}\n\nfunc (m *Message) Attach(file string) error {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, fileName := filepath.Split(file)\n\tm.Attachments[fileName] = b\n\treturn nil\n}\n\n\/\/ NewMessage returns a new Message that can compose an email with attachments\nfunc NewMessage(subject string, body string) *Message {\n\tm := &Message{Subject: subject, Body: body}\n\tm.Attachments = make(map[string][]byte)\n\treturn m\n}\n\nfunc (m *Message) Bytes() []byte {\n\tbuf := bytes.NewBuffer(nil)\n\n\tbuf.WriteString(\"Subject: \" + m.Subject + \"\\n\")\n\tbuf.WriteString(\"MIME-Version: 1.0\\n\")\n\n\tboundary := \"f46d043c813270fc6b04c2d223da\"\n\n\tif len(m.Attachments) > 0 {\n\t\tbuf.WriteString(\"Content-Type: multipart\/mixed; boundary=\" + boundary + \"\\n\")\n\t\tbuf.WriteString(\"--\" + boundary + \"\\n\")\n\t}\n\n\tbuf.WriteString(\"Content-Type: text\/plain; charset=utf-8\\n\")\n\tbuf.WriteString(m.Body)\n\n\tif len(m.Attachments) > 0 {\n\t\tfor k, v := range m.Attachments {\n\t\t\tbuf.WriteString(\"\\n\\n--\" + boundary + \"\\n\")\n\t\t\tbuf.WriteString(\"Content-Type: application\/octet-stream\\n\")\n\t\t\tbuf.WriteString(\"Content-Transfer-Encoding: base64\\n\")\n\t\t\tbuf.WriteString(\"Content-Disposition: attachment; filename=\\\"\" + k + \"\\\"\\n\\n\")\n\n\t\t\tb := make([]byte, base64.StdEncoding.EncodedLen(len(v)))\n\t\t\tbase64.StdEncoding.Encode(b, v)\n\t\t\tbuf.Write(b)\n\t\t\tbuf.WriteString(\"\\n--\" + boundary)\n\t\t}\n\n\t\tbuf.WriteString(\"--\")\n\t}\n\n\treturn buf.Bytes()\n}\n\nfunc Send(addr string, auth smtp.Auth, m *Message) error {\n\treturn smtp.SendMail(addr, auth, m.From, m.To, m.Bytes())\n}\n\nfunc SendUnencrypted(addr, user, password string, m *Message) error {\n\tauth := UnEncryptedAuth(user, password)\n\treturn smtp.SendMail(addr, auth, m.From, m.To, m.Bytes())\n}\n\ntype unEncryptedAuth struct {\n\tusername, password string\n}\n\n\/\/ InsecureAuth returns an Auth that implements the PLAIN authentication\n\/\/ mechanism as defined in RFC 4616.\n\/\/ The returned Auth uses the given username and password to authenticate\n\/\/ without checking a TLS connection or host like smtp.PlainAuth does.\nfunc UnEncryptedAuth(username, password string) smtp.Auth {\n\treturn &unEncryptedAuth{username, password}\n}\n\nfunc (a *unEncryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {\n\tresp := []byte(\"\\x00\" + a.username + \"\\x00\" + a.password)\n\treturn \"PLAIN\", resp, nil\n}\n\nfunc (a *unEncryptedAuth) Next(fromServer []byte, more bool) ([]byte, error) {\n\tif more {\n\t\t\/\/ We've already sent everything.\n\t\treturn nil, errors.New(\"unexpected server challenge\")\n\t}\n\treturn nil, nil\n}\n<commit_msg>Allow sending emails that have html content<commit_after>\/\/ Copyright 2012 Santiago Corredoira\n\/\/ Distributed under a BSD-like license.\npackage email\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/smtp\"\n\t\"path\/filepath\"\n)\n\ntype Message struct {\n\tFrom            string\n\tTo              []string\n\tSubject         string\n\tBody            string\n\tBodyContentType string\n\tAttachments     map[string][]byte\n}\n\nfunc (m *Message) Attach(file string) error {\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, fileName := filepath.Split(file)\n\tm.Attachments[fileName] = b\n\treturn nil\n}\n\n\/\/ NewMessage returns a new Message that can compose an email with attachments\nfunc NewMessage(subject string, body string) *Message {\n\tm := &Message{Subject: subject, Body: body, BodyContentType: \"text\/plain\"}\n\tm.Attachments = make(map[string][]byte)\n\treturn m\n}\n\nfunc NewHTMLMessage(subject string, body string) *Message {\n\tm := &Message{Subject: subject, Body: body, BodyContentType: \"text\/html\"}\n\tm.Attachments = make(map[string][]byte)\n\treturn m\n}\n\nfunc (m *Message) Bytes() []byte {\n\tbuf := bytes.NewBuffer(nil)\n\n\tbuf.WriteString(\"Subject: \" + m.Subject + \"\\n\")\n\tbuf.WriteString(\"MIME-Version: 1.0\\n\")\n\n\tboundary := \"f46d043c813270fc6b04c2d223da\"\n\n\tif len(m.Attachments) > 0 {\n\t\tbuf.WriteString(\"Content-Type: multipart\/mixed; boundary=\" + boundary + \"\\n\")\n\t\tbuf.WriteString(\"--\" + boundary + \"\\n\")\n\t}\n\n\tbuf.WriteString(fmt.Sprintf(\"Content-Type: %s; charset=utf-8\\n\", m.BodyContentType))\n\tbuf.WriteString(m.Body)\n\n\tif len(m.Attachments) > 0 {\n\t\tfor k, v := range m.Attachments {\n\t\t\tbuf.WriteString(\"\\n\\n--\" + boundary + \"\\n\")\n\t\t\tbuf.WriteString(\"Content-Type: application\/octet-stream\\n\")\n\t\t\tbuf.WriteString(\"Content-Transfer-Encoding: base64\\n\")\n\t\t\tbuf.WriteString(\"Content-Disposition: attachment; filename=\\\"\" + k + \"\\\"\\n\\n\")\n\n\t\t\tb := make([]byte, base64.StdEncoding.EncodedLen(len(v)))\n\t\t\tbase64.StdEncoding.Encode(b, v)\n\t\t\tbuf.Write(b)\n\t\t\tbuf.WriteString(\"\\n--\" + boundary)\n\t\t}\n\n\t\tbuf.WriteString(\"--\")\n\t}\n\n\treturn buf.Bytes()\n}\n\nfunc Send(addr string, auth smtp.Auth, m *Message) error {\n\treturn smtp.SendMail(addr, auth, m.From, m.To, m.Bytes())\n}\n\nfunc SendUnencrypted(addr, user, password string, m *Message) error {\n\tauth := UnEncryptedAuth(user, password)\n\treturn smtp.SendMail(addr, auth, m.From, m.To, m.Bytes())\n}\n\ntype unEncryptedAuth struct {\n\tusername, password string\n}\n\n\/\/ InsecureAuth returns an Auth that implements the PLAIN authentication\n\/\/ mechanism as defined in RFC 4616.\n\/\/ The returned Auth uses the given username and password to authenticate\n\/\/ without checking a TLS connection or host like smtp.PlainAuth does.\nfunc UnEncryptedAuth(username, password string) smtp.Auth {\n\treturn &unEncryptedAuth{username, password}\n}\n\nfunc (a *unEncryptedAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {\n\tresp := []byte(\"\\x00\" + a.username + \"\\x00\" + a.password)\n\treturn \"PLAIN\", resp, nil\n}\n\nfunc (a *unEncryptedAuth) Next(fromServer []byte, more bool) ([]byte, error) {\n\tif more {\n\t\t\/\/ We've already sent everything.\n\t\treturn nil, errors.New(\"unexpected server challenge\")\n\t}\n\treturn nil, nil\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\nconst (\n\t_NSIG        = 33\n\t_SI_USER     = 0\n\t_SS_DISABLE  = 4\n\t_RLIMIT_AS   = 10\n\t_SIG_BLOCK   = 1\n\t_SIG_UNBLOCK = 2\n\t_SIG_SETMASK = 3\n)\n\ntype mOS struct{}\n\n\/\/go:noescape\nfunc lwp_create(param *lwpparams) int32\n\n\/\/go:noescape\nfunc sigaltstack(new, old *sigaltstackt)\n\n\/\/go:noescape\nfunc sigaction(sig int32, new, old *sigactiont)\n\n\/\/go:noescape\nfunc sigprocmask(how int32, new, old *sigset)\n\n\/\/go:noescape\nfunc setitimer(mode int32, new, old *itimerval)\n\n\/\/go:noescape\nfunc sysctl(mib *uint32, miblen uint32, out *byte, size *uintptr, dst *byte, ndst uintptr) int32\n\n\/\/go:noescape\nfunc getrlimit(kind int32, limit unsafe.Pointer) int32\n\nfunc raise(sig int32)\nfunc raiseproc(sig int32)\n\n\/\/go:noescape\nfunc sys_umtx_sleep(addr *uint32, val, timeout int32) int32\n\n\/\/go:noescape\nfunc sys_umtx_wakeup(addr *uint32, val int32) int32\n\nfunc osyield()\n\nconst stackSystem = 0\n\n\/\/ From DragonFly's <sys\/sysctl.h>\nconst (\n\t_CTL_HW      = 6\n\t_HW_NCPU     = 3\n\t_HW_PAGESIZE = 7\n)\n\nvar sigset_all = sigset{[4]uint32{^uint32(0), ^uint32(0), ^uint32(0), ^uint32(0)}}\n\nfunc getncpu() int32 {\n\tmib := [2]uint32{_CTL_HW, _HW_NCPU}\n\tout := uint32(0)\n\tnout := unsafe.Sizeof(out)\n\tret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)\n\tif ret >= 0 {\n\t\treturn int32(out)\n\t}\n\treturn 1\n}\n\nfunc getPageSize() uintptr {\n\tmib := [2]uint32{_CTL_HW, _HW_PAGESIZE}\n\tout := uint32(0)\n\tnout := unsafe.Sizeof(out)\n\tret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)\n\tif ret >= 0 {\n\t\treturn uintptr(out)\n\t}\n\treturn 0\n}\n\n\/\/go:nosplit\nfunc futexsleep(addr *uint32, val uint32, ns int64) {\n\tsystemstack(func() {\n\t\tfutexsleep1(addr, val, ns)\n\t})\n}\n\nfunc futexsleep1(addr *uint32, val uint32, ns int64) {\n\tvar timeout int32\n\tif ns >= 0 {\n\t\t\/\/ The timeout is specified in microseconds - ensure that we\n\t\t\/\/ do not end up dividing to zero, which would put us to sleep\n\t\t\/\/ indefinitely...\n\t\ttimeout = timediv(ns, 1000, nil)\n\t\tif timeout == 0 {\n\t\t\ttimeout = 1\n\t\t}\n\t}\n\n\t\/\/ sys_umtx_sleep will return EWOULDBLOCK (EAGAIN) when the timeout\n\t\/\/ expires or EBUSY if the mutex value does not match.\n\tret := sys_umtx_sleep(addr, int32(val), timeout)\n\tif ret >= 0 || ret == -_EINTR || ret == -_EAGAIN || ret == -_EBUSY {\n\t\treturn\n\t}\n\n\tprint(\"umtx_sleep addr=\", addr, \" val=\", val, \" ret=\", ret, \"\\n\")\n\t*(*int32)(unsafe.Pointer(uintptr(0x1005))) = 0x1005\n}\n\n\/\/go:nosplit\nfunc futexwakeup(addr *uint32, cnt uint32) {\n\tret := sys_umtx_wakeup(addr, int32(cnt))\n\tif ret >= 0 {\n\t\treturn\n\t}\n\n\tsystemstack(func() {\n\t\tprint(\"umtx_wake_addr=\", addr, \" ret=\", ret, \"\\n\")\n\t\t*(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006\n\t})\n}\n\nfunc lwp_start(uintptr)\n\n\/\/ May run with m.p==nil, so write barriers are not allowed.\n\/\/go:nowritebarrier\nfunc newosproc(mp *m, stk unsafe.Pointer) {\n\tif false {\n\t\tprint(\"newosproc stk=\", stk, \" m=\", mp, \" g=\", mp.g0, \" lwp_start=\", funcPC(lwp_start), \" id=\", mp.id, \" ostk=\", &mp, \"\\n\")\n\t}\n\n\tvar oset sigset\n\tsigprocmask(_SIG_SETMASK, &sigset_all, &oset)\n\n\tparams := lwpparams{\n\t\tstart_func: funcPC(lwp_start),\n\t\targ:        unsafe.Pointer(mp),\n\t\tstack:      uintptr(stk),\n\t\ttid1:       unsafe.Pointer(&mp.procid),\n\t\ttid2:       nil,\n\t}\n\n\t\/\/ TODO: Check for error.\n\tlwp_create(&params)\n\tsigprocmask(_SIG_SETMASK, &oset, nil)\n}\n\nfunc osinit() {\n\tncpu = getncpu()\n\tphysPageSize = getPageSize()\n}\n\nvar urandom_dev = []byte(\"\/dev\/urandom\\x00\")\n\n\/\/go:nosplit\nfunc getRandomData(r []byte) {\n\tfd := open(&urandom_dev[0], 0 \/* O_RDONLY *\/, 0)\n\tn := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))\n\tclosefd(fd)\n\textendRandom(r, int(n))\n}\n\nfunc goenvs() {\n\tgoenvs_unix()\n}\n\n\/\/ Called to initialize a new m (including the bootstrap m).\n\/\/ Called on the parent thread (main thread in case of bootstrap), can allocate memory.\nfunc mpreinit(mp *m) {\n\tmp.gsignal = malg(32 * 1024)\n\tmp.gsignal.m = mp\n}\n\n\/\/go:nosplit\nfunc msigsave(mp *m) {\n\tsigprocmask(_SIG_SETMASK, nil, &mp.sigmask)\n}\n\n\/\/go:nosplit\nfunc msigrestore(sigmask sigset) {\n\tsigprocmask(_SIG_SETMASK, &sigmask, nil)\n}\n\n\/\/go:nosplit\nfunc sigblock() {\n\tsigprocmask(_SIG_SETMASK, &sigset_all, nil)\n}\n\n\/\/ Called to initialize a new m (including the bootstrap m).\n\/\/ Called on the new thread, cannot allocate memory.\nfunc minit() {\n\t_g_ := getg()\n\n\t\/\/ m.procid is a uint64, but lwp_start writes an int32. Fix it up.\n\t_g_.m.procid = uint64(*(*int32)(unsafe.Pointer(&_g_.m.procid)))\n\n\t\/\/ Initialize signal handling.\n\n\t\/\/ On DragonFly a thread created by pthread_create inherits\n\t\/\/ the signal stack of the creating thread. We always create\n\t\/\/ a new signal stack here, to avoid having two Go threads\n\t\/\/ using the same signal stack. This breaks the case of a\n\t\/\/ thread created in C that calls sigaltstack and then calls a\n\t\/\/ Go function, because we will lose track of the C code's\n\t\/\/ sigaltstack, but it's the best we can do.\n\tsignalstack(&_g_.m.gsignal.stack)\n\t_g_.m.newSigstack = true\n\n\t\/\/ restore signal mask from m.sigmask and unblock essential signals\n\tnmask := _g_.m.sigmask\n\tfor i := range sigtable {\n\t\tif sigtable[i].flags&_SigUnblock != 0 {\n\t\t\tnmask.__bits[(i-1)\/32] &^= 1 << ((uint32(i) - 1) & 31)\n\t\t}\n\t}\n\tsigprocmask(_SIG_SETMASK, &nmask, nil)\n}\n\n\/\/ Called from dropm to undo the effect of an minit.\n\/\/go:nosplit\nfunc unminit() {\n\tif getg().m.newSigstack {\n\t\tsignalstack(nil)\n\t}\n}\n\nfunc memlimit() uintptr {\n\t\/*\n\t\t                TODO: Convert to Go when something actually uses the result.\n\n\t\t\t\tRlimit rl;\n\t\t\t\textern byte runtime·text[], runtime·end[];\n\t\t\t\tuintptr used;\n\n\t\t\t\tif(runtime·getrlimit(RLIMIT_AS, &rl) != 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tif(rl.rlim_cur >= 0x7fffffff)\n\t\t\t\t\treturn 0;\n\n\t\t\t\t\/\/ Estimate our VM footprint excluding the heap.\n\t\t\t\t\/\/ Not an exact science: use size of binary plus\n\t\t\t\t\/\/ some room for thread stacks.\n\t\t\t\tused = runtime·end - runtime·text + (64<<20);\n\t\t\t\tif(used >= rl.rlim_cur)\n\t\t\t\t\treturn 0;\n\n\t\t\t\t\/\/ If there's not at least 16 MB left, we're probably\n\t\t\t\t\/\/ not going to be able to do much. Treat as no limit.\n\t\t\t\trl.rlim_cur -= used;\n\t\t\t\tif(rl.rlim_cur < (16<<20))\n\t\t\t\t\treturn 0;\n\n\t\t\t\treturn rl.rlim_cur - used;\n\t*\/\n\treturn 0\n}\n\nfunc sigtramp()\n\ntype sigactiont struct {\n\tsa_sigaction uintptr\n\tsa_flags     int32\n\tsa_mask      sigset\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc setsig(i int32, fn uintptr, restart bool) {\n\tvar sa sigactiont\n\tsa.sa_flags = _SA_SIGINFO | _SA_ONSTACK\n\tif restart {\n\t\tsa.sa_flags |= _SA_RESTART\n\t}\n\tsa.sa_mask = sigset_all\n\tif fn == funcPC(sighandler) {\n\t\tfn = funcPC(sigtramp)\n\t}\n\tsa.sa_sigaction = fn\n\tsigaction(i, &sa, nil)\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc setsigstack(i int32) {\n\tthrow(\"setsigstack\")\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc getsig(i int32) uintptr {\n\tvar sa sigactiont\n\tsigaction(i, nil, &sa)\n\tif sa.sa_sigaction == funcPC(sigtramp) {\n\t\treturn funcPC(sighandler)\n\t}\n\treturn sa.sa_sigaction\n}\n\n\/\/go:nosplit\nfunc signalstack(s *stack) {\n\tvar st sigaltstackt\n\tif s == nil {\n\t\tst.ss_flags = _SS_DISABLE\n\t} else {\n\t\tst.ss_sp = s.lo\n\t\tst.ss_size = s.hi - s.lo\n\t\tst.ss_flags = 0\n\t}\n\tsigaltstack(&st, nil)\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc updatesigmask(m sigmask) {\n\tvar mask sigset\n\tcopy(mask.__bits[:], m[:])\n\tsigprocmask(_SIG_SETMASK, &mask, nil)\n}\n\nfunc unblocksig(sig int32) {\n\tvar mask sigset\n\tmask.__bits[(sig-1)\/32] |= 1 << ((uint32(sig) - 1) & 31)\n\tsigprocmask(_SIG_UNBLOCK, &mask, nil)\n}\n<commit_msg>runtime: revert CL 18835; don't install new signal stack unconditionally on dragonfly<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\nconst (\n\t_NSIG        = 33\n\t_SI_USER     = 0\n\t_SS_DISABLE  = 4\n\t_RLIMIT_AS   = 10\n\t_SIG_BLOCK   = 1\n\t_SIG_UNBLOCK = 2\n\t_SIG_SETMASK = 3\n)\n\ntype mOS struct{}\n\n\/\/go:noescape\nfunc lwp_create(param *lwpparams) int32\n\n\/\/go:noescape\nfunc sigaltstack(new, old *sigaltstackt)\n\n\/\/go:noescape\nfunc sigaction(sig int32, new, old *sigactiont)\n\n\/\/go:noescape\nfunc sigprocmask(how int32, new, old *sigset)\n\n\/\/go:noescape\nfunc setitimer(mode int32, new, old *itimerval)\n\n\/\/go:noescape\nfunc sysctl(mib *uint32, miblen uint32, out *byte, size *uintptr, dst *byte, ndst uintptr) int32\n\n\/\/go:noescape\nfunc getrlimit(kind int32, limit unsafe.Pointer) int32\n\nfunc raise(sig int32)\nfunc raiseproc(sig int32)\n\n\/\/go:noescape\nfunc sys_umtx_sleep(addr *uint32, val, timeout int32) int32\n\n\/\/go:noescape\nfunc sys_umtx_wakeup(addr *uint32, val int32) int32\n\nfunc osyield()\n\nconst stackSystem = 0\n\n\/\/ From DragonFly's <sys\/sysctl.h>\nconst (\n\t_CTL_HW      = 6\n\t_HW_NCPU     = 3\n\t_HW_PAGESIZE = 7\n)\n\nvar sigset_all = sigset{[4]uint32{^uint32(0), ^uint32(0), ^uint32(0), ^uint32(0)}}\n\nfunc getncpu() int32 {\n\tmib := [2]uint32{_CTL_HW, _HW_NCPU}\n\tout := uint32(0)\n\tnout := unsafe.Sizeof(out)\n\tret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)\n\tif ret >= 0 {\n\t\treturn int32(out)\n\t}\n\treturn 1\n}\n\nfunc getPageSize() uintptr {\n\tmib := [2]uint32{_CTL_HW, _HW_PAGESIZE}\n\tout := uint32(0)\n\tnout := unsafe.Sizeof(out)\n\tret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0)\n\tif ret >= 0 {\n\t\treturn uintptr(out)\n\t}\n\treturn 0\n}\n\n\/\/go:nosplit\nfunc futexsleep(addr *uint32, val uint32, ns int64) {\n\tsystemstack(func() {\n\t\tfutexsleep1(addr, val, ns)\n\t})\n}\n\nfunc futexsleep1(addr *uint32, val uint32, ns int64) {\n\tvar timeout int32\n\tif ns >= 0 {\n\t\t\/\/ The timeout is specified in microseconds - ensure that we\n\t\t\/\/ do not end up dividing to zero, which would put us to sleep\n\t\t\/\/ indefinitely...\n\t\ttimeout = timediv(ns, 1000, nil)\n\t\tif timeout == 0 {\n\t\t\ttimeout = 1\n\t\t}\n\t}\n\n\t\/\/ sys_umtx_sleep will return EWOULDBLOCK (EAGAIN) when the timeout\n\t\/\/ expires or EBUSY if the mutex value does not match.\n\tret := sys_umtx_sleep(addr, int32(val), timeout)\n\tif ret >= 0 || ret == -_EINTR || ret == -_EAGAIN || ret == -_EBUSY {\n\t\treturn\n\t}\n\n\tprint(\"umtx_sleep addr=\", addr, \" val=\", val, \" ret=\", ret, \"\\n\")\n\t*(*int32)(unsafe.Pointer(uintptr(0x1005))) = 0x1005\n}\n\n\/\/go:nosplit\nfunc futexwakeup(addr *uint32, cnt uint32) {\n\tret := sys_umtx_wakeup(addr, int32(cnt))\n\tif ret >= 0 {\n\t\treturn\n\t}\n\n\tsystemstack(func() {\n\t\tprint(\"umtx_wake_addr=\", addr, \" ret=\", ret, \"\\n\")\n\t\t*(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006\n\t})\n}\n\nfunc lwp_start(uintptr)\n\n\/\/ May run with m.p==nil, so write barriers are not allowed.\n\/\/go:nowritebarrier\nfunc newosproc(mp *m, stk unsafe.Pointer) {\n\tif false {\n\t\tprint(\"newosproc stk=\", stk, \" m=\", mp, \" g=\", mp.g0, \" lwp_start=\", funcPC(lwp_start), \" id=\", mp.id, \" ostk=\", &mp, \"\\n\")\n\t}\n\n\tvar oset sigset\n\tsigprocmask(_SIG_SETMASK, &sigset_all, &oset)\n\n\tparams := lwpparams{\n\t\tstart_func: funcPC(lwp_start),\n\t\targ:        unsafe.Pointer(mp),\n\t\tstack:      uintptr(stk),\n\t\ttid1:       unsafe.Pointer(&mp.procid),\n\t\ttid2:       nil,\n\t}\n\n\t\/\/ TODO: Check for error.\n\tlwp_create(&params)\n\tsigprocmask(_SIG_SETMASK, &oset, nil)\n}\n\nfunc osinit() {\n\tncpu = getncpu()\n\tphysPageSize = getPageSize()\n}\n\nvar urandom_dev = []byte(\"\/dev\/urandom\\x00\")\n\n\/\/go:nosplit\nfunc getRandomData(r []byte) {\n\tfd := open(&urandom_dev[0], 0 \/* O_RDONLY *\/, 0)\n\tn := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))\n\tclosefd(fd)\n\textendRandom(r, int(n))\n}\n\nfunc goenvs() {\n\tgoenvs_unix()\n}\n\n\/\/ Called to initialize a new m (including the bootstrap m).\n\/\/ Called on the parent thread (main thread in case of bootstrap), can allocate memory.\nfunc mpreinit(mp *m) {\n\tmp.gsignal = malg(32 * 1024)\n\tmp.gsignal.m = mp\n}\n\n\/\/go:nosplit\nfunc msigsave(mp *m) {\n\tsigprocmask(_SIG_SETMASK, nil, &mp.sigmask)\n}\n\n\/\/go:nosplit\nfunc msigrestore(sigmask sigset) {\n\tsigprocmask(_SIG_SETMASK, &sigmask, nil)\n}\n\n\/\/go:nosplit\nfunc sigblock() {\n\tsigprocmask(_SIG_SETMASK, &sigset_all, nil)\n}\n\n\/\/ Called to initialize a new m (including the bootstrap m).\n\/\/ Called on the new thread, cannot allocate memory.\nfunc minit() {\n\t_g_ := getg()\n\n\t\/\/ m.procid is a uint64, but lwp_start writes an int32. Fix it up.\n\t_g_.m.procid = uint64(*(*int32)(unsafe.Pointer(&_g_.m.procid)))\n\n\t\/\/ Initialize signal handling.\n\tvar st sigaltstackt\n\tsigaltstack(nil, &st)\n\tif st.ss_flags&_SS_DISABLE != 0 {\n\t\tsignalstack(&_g_.m.gsignal.stack)\n\t\t_g_.m.newSigstack = true\n\t} else {\n\t\t\/\/ Use existing signal stack.\n\t\tstsp := uintptr(unsafe.Pointer(st.ss_sp))\n\t\t_g_.m.gsignal.stack.lo = stsp\n\t\t_g_.m.gsignal.stack.hi = stsp + st.ss_size\n\t\t_g_.m.gsignal.stackguard0 = stsp + _StackGuard\n\t\t_g_.m.gsignal.stackguard1 = stsp + _StackGuard\n\t\t_g_.m.gsignal.stackAlloc = st.ss_size\n\t\t_g_.m.newSigstack = false\n\t}\n\n\t\/\/ restore signal mask from m.sigmask and unblock essential signals\n\tnmask := _g_.m.sigmask\n\tfor i := range sigtable {\n\t\tif sigtable[i].flags&_SigUnblock != 0 {\n\t\t\tnmask.__bits[(i-1)\/32] &^= 1 << ((uint32(i) - 1) & 31)\n\t\t}\n\t}\n\tsigprocmask(_SIG_SETMASK, &nmask, nil)\n}\n\n\/\/ Called from dropm to undo the effect of an minit.\n\/\/go:nosplit\nfunc unminit() {\n\tif getg().m.newSigstack {\n\t\tsignalstack(nil)\n\t}\n}\n\nfunc memlimit() uintptr {\n\t\/*\n\t\t                TODO: Convert to Go when something actually uses the result.\n\n\t\t\t\tRlimit rl;\n\t\t\t\textern byte runtime·text[], runtime·end[];\n\t\t\t\tuintptr used;\n\n\t\t\t\tif(runtime·getrlimit(RLIMIT_AS, &rl) != 0)\n\t\t\t\t\treturn 0;\n\t\t\t\tif(rl.rlim_cur >= 0x7fffffff)\n\t\t\t\t\treturn 0;\n\n\t\t\t\t\/\/ Estimate our VM footprint excluding the heap.\n\t\t\t\t\/\/ Not an exact science: use size of binary plus\n\t\t\t\t\/\/ some room for thread stacks.\n\t\t\t\tused = runtime·end - runtime·text + (64<<20);\n\t\t\t\tif(used >= rl.rlim_cur)\n\t\t\t\t\treturn 0;\n\n\t\t\t\t\/\/ If there's not at least 16 MB left, we're probably\n\t\t\t\t\/\/ not going to be able to do much. Treat as no limit.\n\t\t\t\trl.rlim_cur -= used;\n\t\t\t\tif(rl.rlim_cur < (16<<20))\n\t\t\t\t\treturn 0;\n\n\t\t\t\treturn rl.rlim_cur - used;\n\t*\/\n\treturn 0\n}\n\nfunc sigtramp()\n\ntype sigactiont struct {\n\tsa_sigaction uintptr\n\tsa_flags     int32\n\tsa_mask      sigset\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc setsig(i int32, fn uintptr, restart bool) {\n\tvar sa sigactiont\n\tsa.sa_flags = _SA_SIGINFO | _SA_ONSTACK\n\tif restart {\n\t\tsa.sa_flags |= _SA_RESTART\n\t}\n\tsa.sa_mask = sigset_all\n\tif fn == funcPC(sighandler) {\n\t\tfn = funcPC(sigtramp)\n\t}\n\tsa.sa_sigaction = fn\n\tsigaction(i, &sa, nil)\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc setsigstack(i int32) {\n\tthrow(\"setsigstack\")\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc getsig(i int32) uintptr {\n\tvar sa sigactiont\n\tsigaction(i, nil, &sa)\n\tif sa.sa_sigaction == funcPC(sigtramp) {\n\t\treturn funcPC(sighandler)\n\t}\n\treturn sa.sa_sigaction\n}\n\n\/\/go:nosplit\nfunc signalstack(s *stack) {\n\tvar st sigaltstackt\n\tif s == nil {\n\t\tst.ss_flags = _SS_DISABLE\n\t} else {\n\t\tst.ss_sp = s.lo\n\t\tst.ss_size = s.hi - s.lo\n\t\tst.ss_flags = 0\n\t}\n\tsigaltstack(&st, nil)\n}\n\n\/\/go:nosplit\n\/\/go:nowritebarrierrec\nfunc updatesigmask(m sigmask) {\n\tvar mask sigset\n\tcopy(mask.__bits[:], m[:])\n\tsigprocmask(_SIG_SETMASK, &mask, nil)\n}\n\nfunc unblocksig(sig int32) {\n\tvar mask sigset\n\tmask.__bits[(sig-1)\/32] |= 1 << ((uint32(sig) - 1) & 31)\n\tsigprocmask(_SIG_UNBLOCK, &mask, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/ezekg\/git-hound\/Godeps\/_workspace\/src\/gopkg.in\/yaml.v2\"\n\t\"github.com\/ezekg\/git-hound\/Godeps\/_workspace\/src\/sourcegraph.com\/sourcegraph\/go-diff\/diff\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tregexes = make(map[string]*regexp.Regexp)\n)\n\n\/\/ A Hound contains the local configuration filename and all regexp patterns\n\/\/ used for sniffing git-diffs.\ntype Hound struct {\n\tFails  []string `yaml:\"fail\"`\n\tWarns  []string `yaml:\"warn\"`\n\tSkips  []string `yaml:\"skip\"`\n\tconfig string\n}\n\n\/\/ New initializes a new Hound instance by parsing regexp patterns from a\n\/\/ local configuration file and returns a status bool.\nfunc (h *Hound) New() bool {\n\tconfig, err := h.loadConfig()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\terr = h.parse(config)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ Sniff matches the passed git-diff hunk against all regexp patterns that\n\/\/ were parsed from the local configuration.\nfunc (h *Hound) Sniff(fileName string, hunk *diff.Hunk, smells chan<- smell, done chan<- bool) {\n\tdefer func() { done <- true }()\n\n\trxFileName, _ := h.regexp(`^\\w+\\\/`)\n\tfileName = rxFileName.ReplaceAllString(fileName, \"\")\n\tif _, ok := h.matchPatterns(h.Skips, []byte(fileName)); ok {\n\t\treturn\n\t}\n\n\trxModLines, _ := h.regexp(`(?m)^\\+\\s*(.+)$`)\n\tmatches := rxModLines.FindAllSubmatch(hunk.Body, -1)\n\n\tfor _, match := range matches {\n\t\tline := match[1]\n\n\t\tif pattern, warned := h.matchPatterns(h.Warns, line); warned {\n\t\t\tsmells <- smell{\n\t\t\t\tpattern:  pattern,\n\t\t\t\tfileName: fileName,\n\t\t\t\tline:     line,\n\t\t\t\tlineNum:  hunk.NewStartLine,\n\t\t\t\tseverity: 1,\n\t\t\t}\n\t\t}\n\n\t\tif pattern, failed := h.matchPatterns(h.Fails, line); failed {\n\t\t\tsmells <- smell{\n\t\t\t\tpattern:  pattern,\n\t\t\t\tfileName: fileName,\n\t\t\t\tline:     line,\n\t\t\t\tlineNum:  hunk.NewStartLine,\n\t\t\t\tseverity: 2,\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ loadConfig reads a local configuration file of regexp patterns and returns\n\/\/ the contents of the file.\nfunc (h *Hound) loadConfig() ([]byte, error) {\n\tfilename, _ := filepath.Abs(h.config)\n\treturn ioutil.ReadFile(filename)\n}\n\n\/\/ parse parses a configuration byte array and returns an error.\nfunc (h *Hound) parse(config []byte) error {\n\treturn yaml.Unmarshal(config, h)\n}\n\n\/\/ getRegexp looks for the specified pattern in Hound's regexes cache, and if\n\/\/ it is available, it will fetch from it. If it is not available, it\n\/\/ will compile the pattern and store it in the cache. Returns a Regexp\n\/\/ and an error.\nfunc (h *Hound) regexp(pattern string) (*regexp.Regexp, error) {\n\tif regexes[pattern] != nil {\n\t\treturn regexes[pattern], nil\n\t}\n\n\tr, err := regexp.Compile(pattern)\n\tif err == nil {\n\t\tregexes[pattern] = r\n\t}\n\n\treturn r, err\n}\n\n\/\/ match matches a byte array against a regexp pattern and returns a bool.\nfunc (h *Hound) match(pattern string, subject []byte) bool {\n\tr, err := h.regexp(pattern)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn r.Match(subject)\n}\n\n\/\/ matchPatterns matches a byte array against an array of regexp patterns and\n\/\/ returns the matched pattern and a bool.\nfunc (h *Hound) matchPatterns(patterns []string, subject []byte) (string, bool) {\n\tfor _, pattern := range patterns {\n\t\tif match := h.match(pattern, subject); match {\n\t\t\treturn pattern, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n<commit_msg>comment fix<commit_after>package main\n\nimport (\n\t\"github.com\/ezekg\/git-hound\/Godeps\/_workspace\/src\/gopkg.in\/yaml.v2\"\n\t\"github.com\/ezekg\/git-hound\/Godeps\/_workspace\/src\/sourcegraph.com\/sourcegraph\/go-diff\/diff\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tregexes = make(map[string]*regexp.Regexp)\n)\n\n\/\/ A Hound contains the local configuration filename and all regexp patterns\n\/\/ used for sniffing git-diffs.\ntype Hound struct {\n\tFails  []string `yaml:\"fail\"`\n\tWarns  []string `yaml:\"warn\"`\n\tSkips  []string `yaml:\"skip\"`\n\tconfig string\n}\n\n\/\/ New initializes a new Hound instance by parsing regexp patterns from a\n\/\/ local configuration file and returns a status bool.\nfunc (h *Hound) New() bool {\n\tconfig, err := h.loadConfig()\n\tif err != nil {\n\t\treturn false\n\t}\n\n\terr = h.parse(config)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ Sniff matches the passed git-diff hunk against all regexp patterns that\n\/\/ were parsed from the local configuration.\nfunc (h *Hound) Sniff(fileName string, hunk *diff.Hunk, smells chan<- smell, done chan<- bool) {\n\tdefer func() { done <- true }()\n\n\trxFileName, _ := h.regexp(`^\\w+\\\/`)\n\tfileName = rxFileName.ReplaceAllString(fileName, \"\")\n\tif _, ok := h.matchPatterns(h.Skips, []byte(fileName)); ok {\n\t\treturn\n\t}\n\n\trxModLines, _ := h.regexp(`(?m)^\\+\\s*(.+)$`)\n\tmatches := rxModLines.FindAllSubmatch(hunk.Body, -1)\n\n\tfor _, match := range matches {\n\t\tline := match[1]\n\n\t\tif pattern, warned := h.matchPatterns(h.Warns, line); warned {\n\t\t\tsmells <- smell{\n\t\t\t\tpattern:  pattern,\n\t\t\t\tfileName: fileName,\n\t\t\t\tline:     line,\n\t\t\t\tlineNum:  hunk.NewStartLine,\n\t\t\t\tseverity: 1,\n\t\t\t}\n\t\t}\n\n\t\tif pattern, failed := h.matchPatterns(h.Fails, line); failed {\n\t\t\tsmells <- smell{\n\t\t\t\tpattern:  pattern,\n\t\t\t\tfileName: fileName,\n\t\t\t\tline:     line,\n\t\t\t\tlineNum:  hunk.NewStartLine,\n\t\t\t\tseverity: 2,\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ loadConfig reads a local configuration file of regexp patterns and returns\n\/\/ the contents of the file.\nfunc (h *Hound) loadConfig() ([]byte, error) {\n\tfilename, _ := filepath.Abs(h.config)\n\treturn ioutil.ReadFile(filename)\n}\n\n\/\/ parse parses a configuration byte array and returns an error.\nfunc (h *Hound) parse(config []byte) error {\n\treturn yaml.Unmarshal(config, h)\n}\n\n\/\/ regexp looks for the specified pattern in Hound's regexes cache, and if\n\/\/ it is available, it will fetch from it. If it is not available, it\n\/\/ will compile the pattern and store it in the cache. Returns a Regexp\n\/\/ and an error.\nfunc (h *Hound) regexp(pattern string) (*regexp.Regexp, error) {\n\tif regexes[pattern] != nil {\n\t\treturn regexes[pattern], nil\n\t}\n\n\tr, err := regexp.Compile(pattern)\n\tif err == nil {\n\t\tregexes[pattern] = r\n\t}\n\n\treturn r, err\n}\n\n\/\/ match matches a byte array against a regexp pattern and returns a bool.\nfunc (h *Hound) match(pattern string, subject []byte) bool {\n\tr, err := h.regexp(pattern)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn r.Match(subject)\n}\n\n\/\/ matchPatterns matches a byte array against an array of regexp patterns and\n\/\/ returns the matched pattern and a bool.\nfunc (h *Hound) matchPatterns(patterns []string, subject []byte) (string, bool) {\n\tfor _, pattern := range patterns {\n\t\tif match := h.match(pattern, subject); match {\n\t\t\treturn pattern, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n<|endoftext|>"}
{"text":"<commit_before>package hq\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"github.com\/26000\/irchuu\/config\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n)\n\n\/\/ URI of the HQ endpoint.\nconst URI = \"https:\/\/26000.github.io\/irchuu\/version.json\"\n\n\/\/ Report checks for a new version sending data if enabled.\nfunc Report(irchuu *config.Irchuu, tg *config.Telegram, irc *config.Irc) {\n\tif irchuu.CheckUpdates || irchuu.SendStats {\n\t\tvar data url.Values\n\t\tresp, err := http.Get(URI)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to connect to HQ entrance (check for updates and\/or share stats): %v.\\n\",\n\t\t\t\terr)\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to connect to HQ entrance (check for updates and\/or share stats): %v.\\n\",\n\t\t\t\terr)\n\t\t\treturn\n\t\t}\n\n\t\tarr := make([]string, 4)\n\t\terr = json.Unmarshal(body, arr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"HQ entrance is crazy! Could not check for updates: %v.\\n\", err)\n\t\t}\n\n\t\tlayer, err := strconv.Atoi(arr[0])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to decode current layer: %v.\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tif layer > config.LAYER {\n\t\t\tlog.Println(\"New version available, please check https:\/\/github.com\/26000\/irchuu (or use `go get -u github.com\/26000\/irchuu`.\")\n\t\t} else {\n\t\t\tlog.Println(\"Using the latest version of IRChuu.\")\n\t\t}\n\n\t\tif irchuu.SendStats {\n\t\t\t\/\/data = captureData(tg, irc)\n\t\t}\n\t}\n}\n\n\/\/ captureData generates data to be sent on server.\nfunc captureData(tg *config.Telegram, irc *config.Irc) url.Values {\n\ttgHash := sha256.Sum256([]byte(strconv.FormatInt(tg.Group, 10)))\n\tircHash := sha256.Sum256([]byte(irc.Channel))\n\treturn url.Values{\"tg\": {base64.StdEncoding.EncodeToString(tgHash[:31])},\n\t\t\"irc\":   {base64.StdEncoding.EncodeToString(ircHash[:31])},\n\t\t\"layer\": {strconv.Itoa(config.LAYER)}}\n}\n<commit_msg>Fix typo<commit_after>package hq\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"github.com\/26000\/irchuu\/config\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n)\n\n\/\/ URI of the HQ endpoint.\nconst URI = \"https:\/\/26000.github.io\/irchuu\/version.json\"\n\n\/\/ Report checks for a new version sending data if enabled.\nfunc Report(irchuu *config.Irchuu, tg *config.Telegram, irc *config.Irc) {\n\tif irchuu.CheckUpdates || irchuu.SendStats {\n\t\tresp, err := http.Get(URI)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to connect to HQ entrance (check for updates and\/or share stats): %v.\\n\",\n\t\t\t\terr)\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to connect to HQ entrance (check for updates and\/or share stats): %v.\\n\",\n\t\t\t\terr)\n\t\t\treturn\n\t\t}\n\n\t\tarr := make([]string, 4)\n\t\terr = json.Unmarshal(body, arr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"HQ entrance is crazy! Could not check for updates: %v.\\n\", err)\n\t\t}\n\n\t\tlayer, err := strconv.Atoi(arr[0])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to decode current layer: %v.\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tif layer > config.LAYER {\n\t\t\tlog.Println(\"New version available, please check https:\/\/github.com\/26000\/irchuu (or use `go get -u github.com\/26000\/irchuu`.\")\n\t\t} else {\n\t\t\tlog.Println(\"Using the latest version of IRChuu.\")\n\t\t}\n\n\t\tif irchuu.SendStats {\n\t\t\t\/\/var data url.Values\n\t\t\t\/\/data = captureData(tg, irc)\n\t\t}\n\t}\n}\n\n\/\/ captureData generates data to be sent on server.\nfunc captureData(tg *config.Telegram, irc *config.Irc) url.Values {\n\ttgHash := sha256.Sum256([]byte(strconv.FormatInt(tg.Group, 10)))\n\tircHash := sha256.Sum256([]byte(irc.Channel))\n\treturn url.Values{\"tg\": {base64.StdEncoding.EncodeToString(tgHash[:31])},\n\t\t\"irc\":   {base64.StdEncoding.EncodeToString(ircHash[:31])},\n\t\t\"layer\": {strconv.Itoa(config.LAYER)}}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\t\"io\"\n\t\"fmt\"\n\t\"crypto\"\n)\n\ntype HashUnavailableError struct {\n\th crypto.Hash\n}\n\nfunc (e *HashUnavailableError) Error() string {\n\tvar hashName string\n\tswitch e.h {\n\tcase crypto.MD4: hashName = \"MD4\"\n\tcase crypto.MD5: hashName = \"MD5\"\n\tcase crypto.SHA1: hashName = \"SHA1\"\n\tcase crypto.SHA224: hashName = \"SHA224\"\n\tcase crypto.SHA256: hashName = \"SHA256\"\n\tcase crypto.SHA384: hashName = \"SHA384\"\n\tcase crypto.SHA512: hashName = \"SHA512\"\n\tcase crypto.MD5SHA1: hashName = \"MD5SHA1\"\n\tcase crypto.RIPEMD160: hashName = \"RIPEMD160\"\n\tdefault: hashName = \"unknown hash\"\n\t}\n\treturn fmt.Sprint(\"%s is not a known hash function or not linked into the binary\", hashName)\n}\n\ntype Entry struct {\n\tChecksum string\n\tFilename string\n}\n\nfunc (e *Entry) String() string {\n\treturn fmt.Sprintf(\"%s  %s\", e.Checksum, e.Filename)\n}\n\nfunc (e *Entry) Calculate(h crypto.Hash) (sum []byte, err error) {\n\tif !h.Available() {\n\t\treturn nil, &HashUnavailableError{h}\n\t}\n\thash := h.New()\n\n\tif file, err := os.Open(e.Filename); err != nil {\n\t\treturn nil, err\n\t} else if _, err = io.Copy(hash, file); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hash.Sum(nil), nil\n}\n\nfunc formatChecksum(h crypto.Hash, sum []byte) string {\n\treturn fmt.Sprintf(\"%x\", sum)\n}\n\nfunc (e *Entry) Fill(h crypto.Hash) (err error) {\n\tsum, err := e.Calculate(h)\n\tif err != nil {\n\t\treturn\n\t}\n\n\te.Checksum = formatChecksum(h, sum)\n\treturn\n}\n\nfunc (e *Entry) Verify(h crypto.Hash) (match bool, err error) {\n\tsum, err := e.Calculate(h)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmatch = formatChecksum(h, sum) == e.Checksum\n\treturn\n}\n\n<commit_msg>Force import of common hash functions<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"io\"\n\t\"fmt\"\n\t\"crypto\"\n\t\"crypto\/md5\"\n\t\"crypto\/sha1\"\n\t\"crypto\/sha512\"\n)\nvar _ = md5.New\nvar _ = sha1.New\nvar _ = sha512.New\n\ntype HashUnavailableError struct {\n\th crypto.Hash\n}\n\nfunc (e *HashUnavailableError) Error() string {\n\tvar hashName string\n\tswitch e.h {\n\tcase crypto.MD4: hashName = \"MD4\"\n\tcase crypto.MD5: hashName = \"MD5\"\n\tcase crypto.SHA1: hashName = \"SHA1\"\n\tcase crypto.SHA224: hashName = \"SHA224\"\n\tcase crypto.SHA256: hashName = \"SHA256\"\n\tcase crypto.SHA384: hashName = \"SHA384\"\n\tcase crypto.SHA512: hashName = \"SHA512\"\n\tcase crypto.MD5SHA1: hashName = \"MD5SHA1\"\n\tcase crypto.RIPEMD160: hashName = \"RIPEMD160\"\n\tdefault: hashName = \"unknown hash\"\n\t}\n\treturn fmt.Sprint(\"%s is not a known hash function or not linked into the binary\", hashName)\n}\n\ntype Entry struct {\n\tChecksum string\n\tFilename string\n}\n\nfunc (e *Entry) String() string {\n\treturn fmt.Sprintf(\"%s  %s\", e.Checksum, e.Filename)\n}\n\nfunc (e *Entry) Calculate(h crypto.Hash) (sum []byte, err error) {\n\tif !h.Available() {\n\t\treturn nil, &HashUnavailableError{h}\n\t}\n\thash := h.New()\n\n\tif file, err := os.Open(e.Filename); err != nil {\n\t\treturn nil, err\n\t} else if _, err = io.Copy(hash, file); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn hash.Sum(nil), nil\n}\n\nfunc formatChecksum(h crypto.Hash, sum []byte) string {\n\treturn fmt.Sprintf(\"%x\", sum)\n}\n\nfunc (e *Entry) Fill(h crypto.Hash) (err error) {\n\tsum, err := e.Calculate(h)\n\tif err != nil {\n\t\treturn\n\t}\n\n\te.Checksum = formatChecksum(h, sum)\n\treturn\n}\n\nfunc (e *Entry) Verify(h crypto.Hash) (match bool, err error) {\n\tsum, err := e.Calculate(h)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmatch = formatChecksum(h, sum) == e.Checksum\n\treturn\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 Eneo Tecnologia S.L.\n\/\/ Diego Fernández Barrera <bigomby@gmail.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\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 main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bsm\/sarama-cluster\"\n\t\"github.com\/redBorder\/rbforwarder\"\n)\n\n\/\/ KafkaConfig stores the configuration for the Kafka source\ntype KafkaConfig struct {\n\ttopics              []string \/\/ Topics where listen for messages\n\tbrokers             []string \/\/ Brokers to connect\n\tconsumergroup       string   \/\/ ID for the consumer\n\tconsumerGroupConfig *cluster.Config\n\tdeflate             bool\n}\n\n\/\/ KafkaConsumer get messages from multiple kafka topics\ntype KafkaConsumer struct {\n\tforwarder *rbforwarder.RBForwarder \/\/ The backend to send messages\n\tconsumer  *cluster.Consumer\n\tclosed    chan struct{}\n\tConfig    KafkaConfig \/\/ Cofiguration after the parsing\n\twg        sync.WaitGroup\n}\n\n\/\/ Start starts reading messages from kafka and pushing them to the pipeline\nfunc (k *KafkaConsumer) Start() {\n\tvar eventsReported uint64\n\tvar eventsSent uint64\n\tvar messages uint32\n\tvar err error\n\n\tk.closed = make(chan struct{})\n\n\tlogger = Logger.WithFields(logrus.Fields{\n\t\t\"prefix\": \"k2http\",\n\t})\n\n\tif *counter > 0 {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\t<-time.After(time.Duration(*counter) * time.Second)\n\t\t\t\tlogger.Infof(\"Messages per second: %d\", atomic.LoadUint32(&messages)\/5)\n\t\t\t\tatomic.StoreUint32(&messages, 0)\n\t\t\t}\n\t\t}()\n\t}\n\n\t\/\/ Start processing reports\n\tk.wg.Add(1)\n\tgo func() {\n\t\tfor r := range k.forwarder.GetOrderedReports() {\n\t\t\treport := r.(rbforwarder.Report)\n\t\t\tmessage := report.Opaque.(*sarama.ConsumerMessage)\n\n\t\t\tif report.Code != 0 {\n\t\t\t\tlogger.\n\t\t\t\t\tWithField(\"STATUS\", report.Status).\n\t\t\t\t\tWithField(\"OFFSET\", message.Offset).\n\t\t\t\t\tError(\"REPORT\")\n\t\t\t}\n\n\t\t\tk.consumer.MarkOffset(message, \"\")\n\t\t\teventsReported++\n\t\t}\n\n\t\tk.wg.Done()\n\t}()\n\n\t\/\/ Init consumer, consume errors & messages\nconsumerLoop:\n\tfor {\n\t\tk.consumer, err = cluster.NewConsumer(\n\t\t\tk.Config.brokers,\n\t\t\tk.Config.consumergroup,\n\t\t\tk.Config.topics,\n\t\t\tk.Config.consumerGroupConfig,\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Failed to start consumer: \", err)\n\t\t\tbreak\n\t\t}\n\n\t\tlogger.\n\t\t\tWithField(\"brokers\", k.Config.brokers).\n\t\t\tWithField(\"consumergroup\", k.Config.consumergroup).\n\t\t\tWithField(\"topics\", k.Config.topics).\n\t\t\tInfo(\"Started consumer\")\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-k.closed:\n\t\t\t\tbreak consumerLoop\n\t\t\tcase message := <-k.consumer.Messages():\n\t\t\t\tif message == nil {\n\t\t\t\t\tk.Config.consumerGroupConfig.Consumer.Offsets.Initial = sarama.OffsetOldest\n\t\t\t\t\tif err := k.consumer.Close(); err != nil {\n\t\t\t\t\t\tlogger.Error(\"Failed to close consumer: \", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\topts := map[string]interface{}{\n\t\t\t\t\t\"http_endpoint\": message.Topic,\n\t\t\t\t\t\"batch_group\":   message.Topic,\n\t\t\t\t}\n\n\t\t\t\tif k.Config.deflate {\n\t\t\t\t\topts[\"http_headers\"] = map[string]string{\n\t\t\t\t\t\t\"Content-Encoding\": \"deflate\",\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tk.forwarder.Produce(message.Value, opts, message)\n\n\t\t\t\teventsSent++\n\t\t\t\tatomic.AddUint32(&messages, 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tk.wg.Wait()\n\tlogger.Infof(\"TOTAL SENT MESSAGES: %d\", eventsSent)\n\tlogger.Infof(\"TOTAL REPORTS: %d\", eventsReported)\n\n\treturn\n}\n\n\/\/ Close closes the connection with Kafka\nfunc (k *KafkaConsumer) Close() {\n\tlogger.Info(\"Terminating... Press ctrl+c again to force exit\")\n\tctrlc := make(chan os.Signal, 1)\n\tsignal.Notify(ctrlc, os.Interrupt)\n\tgo func() {\n\t\t<-ctrlc\n\t\tlogger.Fatal(\"Forced exit\")\n\t}()\n\n\tk.closed <- struct{}{}\n\tif err := k.consumer.Close(); err != nil {\n\t\tlogger.Println(\"Failed to close consumer: \", err)\n\t} else {\n\t\tlogger.Info(\"Consumer terminated\")\n\t}\n\n\t<-time.After(5 * time.Second)\n\tk.forwarder.Close()\n}\n<commit_msg>:bug: Fix wrong message rate on counter<commit_after>\/\/ Copyright (C) 2016 Eneo Tecnologia S.L.\n\/\/ Diego Fernández Barrera <bigomby@gmail.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\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 main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bsm\/sarama-cluster\"\n\t\"github.com\/redBorder\/rbforwarder\"\n)\n\n\/\/ KafkaConfig stores the configuration for the Kafka source\ntype KafkaConfig struct {\n\ttopics              []string \/\/ Topics where listen for messages\n\tbrokers             []string \/\/ Brokers to connect\n\tconsumergroup       string   \/\/ ID for the consumer\n\tconsumerGroupConfig *cluster.Config\n\tdeflate             bool\n}\n\n\/\/ KafkaConsumer get messages from multiple kafka topics\ntype KafkaConsumer struct {\n\tforwarder *rbforwarder.RBForwarder \/\/ The backend to send messages\n\tconsumer  *cluster.Consumer\n\tclosed    chan struct{}\n\tConfig    KafkaConfig \/\/ Cofiguration after the parsing\n\twg        sync.WaitGroup\n}\n\n\/\/ Start starts reading messages from kafka and pushing them to the pipeline\nfunc (k *KafkaConsumer) Start() {\n\tvar eventsReported uint64\n\tvar eventsSent uint64\n\tvar messages uint32\n\tvar err error\n\n\tk.closed = make(chan struct{})\n\n\tlogger = Logger.WithFields(logrus.Fields{\n\t\t\"prefix\": \"k2http\",\n\t})\n\n\tif *counter > 0 {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\t<-time.After(time.Duration(*counter) * time.Second)\n\t\t\t\tlogger.Infof(\"Messages per second: %d\", atomic.LoadUint32(&messages)\/uint32(*counter))\n\t\t\t\tatomic.StoreUint32(&messages, 0)\n\t\t\t}\n\t\t}()\n\t}\n\n\t\/\/ Start processing reports\n\tk.wg.Add(1)\n\tgo func() {\n\t\tfor r := range k.forwarder.GetOrderedReports() {\n\t\t\treport := r.(rbforwarder.Report)\n\t\t\tmessage := report.Opaque.(*sarama.ConsumerMessage)\n\n\t\t\tif report.Code != 0 {\n\t\t\t\tlogger.\n\t\t\t\t\tWithField(\"STATUS\", report.Status).\n\t\t\t\t\tWithField(\"OFFSET\", message.Offset).\n\t\t\t\t\tError(\"REPORT\")\n\t\t\t}\n\n\t\t\tk.consumer.MarkOffset(message, \"\")\n\t\t\teventsReported++\n\t\t}\n\n\t\tk.wg.Done()\n\t}()\n\n\t\/\/ Init consumer, consume errors & messages\nconsumerLoop:\n\tfor {\n\t\tk.consumer, err = cluster.NewConsumer(\n\t\t\tk.Config.brokers,\n\t\t\tk.Config.consumergroup,\n\t\t\tk.Config.topics,\n\t\t\tk.Config.consumerGroupConfig,\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Failed to start consumer: \", err)\n\t\t\tbreak\n\t\t}\n\n\t\tlogger.\n\t\t\tWithField(\"brokers\", k.Config.brokers).\n\t\t\tWithField(\"consumergroup\", k.Config.consumergroup).\n\t\t\tWithField(\"topics\", k.Config.topics).\n\t\t\tInfo(\"Started consumer\")\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-k.closed:\n\t\t\t\tbreak consumerLoop\n\t\t\tcase message := <-k.consumer.Messages():\n\t\t\t\tif message == nil {\n\t\t\t\t\tk.Config.consumerGroupConfig.Consumer.Offsets.Initial = sarama.OffsetOldest\n\t\t\t\t\tif err := k.consumer.Close(); err != nil {\n\t\t\t\t\t\tlogger.Error(\"Failed to close consumer: \", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\topts := map[string]interface{}{\n\t\t\t\t\t\"http_endpoint\": message.Topic,\n\t\t\t\t\t\"batch_group\":   message.Topic,\n\t\t\t\t}\n\n\t\t\t\tif k.Config.deflate {\n\t\t\t\t\topts[\"http_headers\"] = map[string]string{\n\t\t\t\t\t\t\"Content-Encoding\": \"deflate\",\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tk.forwarder.Produce(message.Value, opts, message)\n\n\t\t\t\teventsSent++\n\t\t\t\tatomic.AddUint32(&messages, 1)\n\t\t\t}\n\t\t}\n\t}\n\n\tk.wg.Wait()\n\tlogger.Infof(\"TOTAL SENT MESSAGES: %d\", eventsSent)\n\tlogger.Infof(\"TOTAL REPORTS: %d\", eventsReported)\n\n\treturn\n}\n\n\/\/ Close closes the connection with Kafka\nfunc (k *KafkaConsumer) Close() {\n\tlogger.Info(\"Terminating... Press ctrl+c again to force exit\")\n\tctrlc := make(chan os.Signal, 1)\n\tsignal.Notify(ctrlc, os.Interrupt)\n\tgo func() {\n\t\t<-ctrlc\n\t\tlogger.Fatal(\"Forced exit\")\n\t}()\n\n\tk.closed <- struct{}{}\n\tif err := k.consumer.Close(); err != nil {\n\t\tlogger.Println(\"Failed to close consumer: \", err)\n\t} else {\n\t\tlogger.Info(\"Consumer terminated\")\n\t}\n\n\t<-time.After(5 * time.Second)\n\tk.forwarder.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\n\/*\ncanyon is a tool for making big splits. This assumes that you have a very large\nchangelist prepared in a single branch. canyon will then split up the large\nchange into multiple branches, by OWNERS file, and then will prepare a changelist\ndescription.\n*\/\n\nvar (\n\tmaxDepth = flag.Int(\"depth\", 0, \"The maximum subdirectory depth for which split branches should be created.\")\n\n\tupstreamBranch = flag.String(\"upstream\", \"origin\/master\", \"The upstream branch against which diffs are taken and new branches created.\")\n\n\tsplitByType = flag.String(\"split-by\", \"[dir|file]\", \"The method by which the branch is split.\")\n\n\tsplitByFile = flag.String(\"split-by-file\", \"\", \"If using -split-by=file, this the common file name by which split directories are found.\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tif err := validateDescription(); err != nil {\n\t\tfmt.Println(\"Please provide a valid -message for your branches. Error:\", err)\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif *splitByType != \"dir\" || *splitByType != \"file\" {\n\t\tfmt.Println(\"Invalid -split-by type:\", *splitByType)\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *splitByType == \"file\" && *splitByFile == \"\" {\n\t\tfmt.Println(\"Whe using -split-by=file, a -split-by-file is needed.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tbranch := strings.TrimSpace(gitOrDie(\"symbolic-ref\", \"--short\", \"HEAD\"))\n\n\tfmt.Printf(\"Split changelist on branch %q into sub-changelists? [y\/N] \", branch)\n\tbuf := make([]byte, 1)\n\tos.Stdin.Read(buf)\n\tif buf[0] != 'y' {\n\t\tfmt.Println(\"Exiting\")\n\t\treturn\n\t}\n\n\tlog.Print(\"Gathering changed files\")\n\tfiles := strings.Split(gitOrDie(\"diff\", \"--name-only\", *upstreamBranch), \"\\n\")\n\n\tlog.Print(\"Splitting changed files into groups for changelists\")\n\tcs := newChangeSet(branch)\n\tfor _, file := range files {\n\t\tif file == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif *splitByType == \"dir\" {\n\t\t\tcs.splitByDir(file)\n\t\t} else if *splitByType == \"file\" {\n\t\t\tcs.splitByFile(*splitByFile, file)\n\t\t}\n\t}\n\n\tlog.Print(\"Creating branches for splits\")\n\tfor _, cl := range cs.splits {\n\t\tsplitBranch := cl.branchName(branch)\n\t\tlog.Printf(\"Preparing branch %s\", splitBranch)\n\n\t\t_, err := git(\"checkout\", \"-b\", splitBranch, *upstreamBranch)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create new branch %q: %v\", splitBranch, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = git(\"checkout\", branch, cl.base)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to check out subdirectory from root branch\")\n\t\t\tgitOrDie(\"reset\", \"--hard\", *upstreamBranch)\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = git(\"commit\", \"-a\", \"-m\", formatDescription(cl))\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create subchangelist\")\n\t\t\tgitOrDie(\"reset\", \"--hard\", *upstreamBranch)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tgit(\"checkout\", branch)\n}\n\n\/\/ git runs the specified git commands and returns the output as a string,\n\/\/ blocking to completion.\nfunc git(args ...string) (string, error) {\n\tcmd := exec.Command(\"git\", args...)\n\tstdout, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(stdout), nil\n}\n\n\/\/ gitOrDie runs the git command and panics on failure.\nfunc gitOrDie(args ...string) string {\n\tr, e := git(args...)\n\tif e != nil {\n\t\tpanic(e.Error())\n\t}\n\treturn r\n}\n<commit_msg>Refactor main into helper routines.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\n\/*\ncanyon is a tool for making big splits. This assumes that you have a very large\nchangelist prepared in a single branch. canyon will then split up the large\nchange into multiple branches, by OWNERS file, and then will prepare a changelist\ndescription.\n*\/\n\nvar (\n\tmaxDepth = flag.Int(\"depth\", 0, \"The maximum subdirectory depth for which split branches should be created.\")\n\n\tupstreamBranch = flag.String(\"upstream\", \"origin\/master\", \"The upstream branch against which diffs are taken and new branches created.\")\n\n\tsplitByType = flag.String(\"split-by\", \"[dir|file]\", \"The method by which the branch is split.\")\n\n\tsplitByFile = flag.String(\"split-by-file\", \"\", \"If using -split-by=file, this the common file name by which split directories are found.\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tif err := validateDescription(); err != nil {\n\t\tfmt.Println(\"Please provide a valid -message for your branches. Error:\", err)\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif *splitByType != \"dir\" || *splitByType != \"file\" {\n\t\tfmt.Println(\"Invalid -split-by type:\", *splitByType)\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tif *splitByType == \"file\" && *splitByFile == \"\" {\n\t\tfmt.Println(\"Whe using -split-by=file, a -split-by-file is needed.\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tbranch := strings.TrimSpace(gitOrDie(\"symbolic-ref\", \"--short\", \"HEAD\"))\n\n\tfmt.Printf(\"Split changelist on branch %q into sub-changelists? [y\/N] \", branch)\n\tbuf := make([]byte, 1)\n\tos.Stdin.Read(buf)\n\tif buf[0] != 'y' {\n\t\tfmt.Println(\"Exiting\")\n\t\treturn\n\t}\n\n\tlog.Print(\"Gathering changed files\")\n\tfiles := strings.Split(gitOrDie(\"diff\", \"--name-only\", *upstreamBranch), \"\\n\")\n\n\tlog.Print(\"Splitting changed files into groups for changelists\")\n\tcs := prepareChangeSet(branch, files)\n\n\tlog.Print(\"Creating branches for splits\")\n\tcreateBranches(cs)\n\n\tgit(\"checkout\", branch)\n}\n\n\/\/ git runs the specified git commands and returns the output as a string,\n\/\/ blocking to completion.\nfunc git(args ...string) (string, error) {\n\tcmd := exec.Command(\"git\", args...)\n\tstdout, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(stdout), nil\n}\n\n\/\/ gitOrDie runs the git command and panics on failure.\nfunc gitOrDie(args ...string) string {\n\tr, e := git(args...)\n\tif e != nil {\n\t\tpanic(e.Error())\n\t}\n\treturn r\n}\n\n\/\/ prepareChangeSet creates a new changeset on |branch| and splits the |files|.\nfunc prepareChangeSet(branch string, files []string) *changeSet {\n\tcs := newChangeSet(branch)\n\tfor _, file := range files {\n\t\tif file == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif *splitByType == \"dir\" {\n\t\t\tcs.splitByDir(file)\n\t\t} else if *splitByType == \"file\" {\n\t\t\tcs.splitByFile(*splitByFile, file)\n\t\t}\n\t}\n\treturn cs\n}\n\n\/\/ createBranches creates branches as specified by the changeSet.\nfunc createBranches(cs *changeSet) {\n\tfor _, cl := range cs.splits {\n\t\tsplitBranch := cl.branchName(cs.branch)\n\t\tlog.Printf(\"Preparing branch %s\", splitBranch)\n\n\t\t_, err := git(\"checkout\", \"-b\", splitBranch, *upstreamBranch)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create new branch %q: %v\", splitBranch, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = git(\"checkout\", cs.branch, cl.base)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to check out subdirectory from root branch\")\n\t\t\tgitOrDie(\"reset\", \"--hard\", *upstreamBranch)\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err = git(\"commit\", \"-a\", \"-m\", formatDescription(cl))\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create subchangelist\")\n\t\t\tgitOrDie(\"reset\", \"--hard\", *upstreamBranch)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tests\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\nconst (\n\thost     = \"0.0.0.0:5432\"\n\tdatabase = \"testing\"\n\tuser     = \"testing\"\n\tpassword = \"testing\"\n)\n\nfunc TestHijackSuite(t *testing.T) {\n\tsuite.Run(t, new(CommonSuite))\n}\n\ntype CommonSuite struct {\n\tsuite.Suite\n\tdb *sql.DB\n}\n\nfunc (s *CommonSuite) SetupSuite() {\n\tdb, err := sql.Open(\n\t\t\"postgres\",\n\t\tfmt.Sprintf(\"postgres:\/\/%s:%s@%s\/%s?sslmode=disable\", user, password, host, database),\n\t)\n\ts.Nil(err)\n\ts.NotNil(db)\n\ts.db = db\n\n\tres, err := s.db.Exec(`DROP TABLE IF EXISTS testing`)\n\ts.NotNil(res)\n\ts.Nil(err)\n\n\tres, err = s.db.Exec(`CREATE TABLE testing (id uuid primary key)`)\n\ts.NotNil(res)\n\ts.Nil(err)\n}\n\nfunc (s *CommonSuite) TearDownSuite() {\n\tres, err := s.db.Exec(\"DROP TABLE testing\")\n\ts.NotNil(res)\n\ts.Nil(err)\n\n\tres, err = s.db.Exec(\"DROP TABLE _THIS_TABLE_DOES_NOT_EXIST\")\n\ts.Nil(res)\n\ts.NotNil(err)\n}\n<commit_msg>Add configurable test environment variables<commit_after>package tests\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/suite\"\n)\n\nfunc envOrDefault(key string, def string) string {\n\tv := os.Getenv(key)\n\tif v == \"\" {\n\t\tv = def\n\t}\n\treturn v\n}\n\nfunc TestHijackSuite(t *testing.T) {\n\tsuite.Run(t, new(CommonSuite))\n}\n\ntype CommonSuite struct {\n\tsuite.Suite\n\tdb *sql.DB\n}\n\nfunc (s *CommonSuite) SetupSuite() {\n\tdb, err := sql.Open(\"postgres\", fmt.Sprintf(\n\t\t\"postgres:\/\/%s:%s@0.0.0.0:5432\/%s?sslmode=disable\",\n\t\tenvOrDefault(\"DBUSER\", \"testing\"),\n\t\tenvOrDefault(\"DBPASS\", \"testing\"),\n\t\tenvOrDefault(\"DBNAME\", \"testing\"),\n\t))\n\ts.Nil(err)\n\ts.NotNil(db)\n\ts.db = db\n\n\tres, err := s.db.Exec(`DROP TABLE IF EXISTS testing`)\n\ts.NotNil(res)\n\ts.Nil(err)\n\n\tres, err = s.db.Exec(`CREATE TABLE testing (id uuid primary key)`)\n\ts.NotNil(res)\n\ts.Nil(err)\n}\n\nfunc (s *CommonSuite) TearDownSuite() {\n\tres, err := s.db.Exec(\"DROP TABLE testing\")\n\ts.NotNil(res)\n\ts.Nil(err)\n\n\tres, err = s.db.Exec(\"DROP TABLE _THIS_TABLE_DOES_NOT_EXIST\")\n\ts.Nil(res)\n\ts.NotNil(err)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017-present Andrea Funtò. 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 openstack\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/dghubble\/sling\"\n\t\"github.com\/dihedron\/go-openstack\/log\"\n)\n\n\/\/ Authentication contains the identity entity used to authenticate users\n\/\/ and issue tokens against a Keystone instance; it can be scoped (when\n\/\/ either Project or Domain is specified), implicitly unscoped ()\ntype Authentication struct {\n\tIdentity *Identity   `json:\"identity,omitempty\"`\n\tScope    interface{} `json:\"scope,omitempty\"`\n}\n\ntype Domain struct {\n\tID   *string `json:\"id,omitempty\"`\n\tName *string `json:\"name,omitempty\"`\n}\n\ntype Endpoint struct {\n\tID        *string `json:\"id,omitempty\"`\n\tInterface *string `json:\"interface,omitempty\"`\n\tRegion    *string `json:\"region,omitempty\"`\n\tRegionID  *string `json:\"region_id,omitempty\"`\n\tURL       *string `json:\"url,omitempty\"`\n}\n\ntype Identity struct {\n\tMethods  *[]string `json:\"methods,omitempty\"`\n\tPassword *Password `json:\"password,omitempty\"`\n\tToken    *Token    `json:\"token,omitempty\"`\n}\n\ntype Password struct {\n\tUser *User `json:\"user,omitempty\"`\n}\n\n\/\/ Project represents a container that groups or isolates resources or identity\n\/\/ objects; depending on the service operator, a project might map to a customer,\n\/\/ account, organization, or tenant.\ntype Project struct {\n\tID     *string `json:\"id,omitempty\"`\n\tName   *string `json:\"name,omitempty\"`\n\tDomain *Domain `json:\"domain,omitempty\"`\n}\n\ntype Role struct {\n\tID   *string `json:\"id,omitempty\"`\n\tName *string `json:\"name,omitempty\"`\n}\n\ntype Scope struct {\n\tProject *Project `json:\"project,omitempty\"`\n\tDomain  *Domain  `json:\"domain,omitempty\"` \/\/ either one or the other: if both, BadRequest!\n}\n\n\/\/ Service represents an OpenStack service, such as Compute (nova), Object Storage\n\/\/ (swift), or Image service (glance), that provides one or more endpoints through\n\/\/ which users can access resources and perform operations.\ntype Service struct {\n\tID        *string     `json:\"id,omitempty\"`\n\tName      *string     `json:\"name,omitempty\"`\n\tType      *string     `json:\"type,omitempy\"`\n\tEndpoints *[]Endpoint `json:\"endpoints,omitempty\"`\n}\n\n\/\/ Token represents An alpha-numeric text string that enables access to OpenStack\n\/\/ APIs and resources and all associated metadata. A token may be revoked at any\n\/\/ time and is valid for a finite duration. While OpenStack Identity supports\n\/\/ token-based authentication in this release, it intends to support additional\n\/\/ protocols in the future. OpenStack Identity is an integration service that does\n\/\/ not aspire to be a full-fledged identity store and management solution.\ntype Token struct {\n\tID           *string    `json:\"id,omitempty\"`\n\tIssuedAt     *string    `json:\"issued_at,omitempty\"`\n\tExpiresAt    *string    `json:\"expires_at,omitempty\"`\n\tUser         *User      `json:\"user,omitempty\"`\n\tRoles        *[]Role    `json:\"roles,omitempty\"`\n\tMethods      *[]string  `json:\"methods,omitempty\"`\n\tAuditIDs     *[]string  `json:\"audit_ids,omitempty\"`\n\tProject      *Project   `json:\"project,omitempty\"`\n\tIsDomain     *bool      `json:\"is_domain,omitempty\"`\n\tIsAdminToken *bool      `json:\"is_admin_token,omitempty\"`\n\tCatalog      *[]Service `json:\"catalog,omitempty\"`\n}\n\n\/\/ User is a digital representation of a person, system, or service that uses\n\/\/ OpenStack cloud services. The Identity service validates that incoming requests\n\/\/ are made by the user who claims to be making the call. Users have a login and\n\/\/ can access resources by using assigned tokens. Users can be directly assigned\n\/\/ to a particular project and behave as if they are contained in that project.\ntype User struct {\n\tID                *string `json:\"id,omitempty\"`\n\tName              *string `json:\"name,omitempty\"`\n\tDomain            *Domain `json:\"domain,omitempty\"`\n\tPassword          *string `json:\"password,omitempty\"`\n\tPasswordExpiresAt *string `json:\"password_expires_at,omitempty\"`\n}\n\n\/\/ IdentityAPI represents the identity API providing all services\n\/\/ regarding authentication, authentication, role and reosurce management.\n\/\/ See https:\/\/developer.openstack.org\/api-ref\/identity\/v3\/\ntype IdentityAPI struct {\n\tfactory *sling.Sling\n\tclient  *http.Client\n}\n\n\/*\n * AUTHENTICATION AND TOKEN MANAGEMENT\n *\/\n\nconst (\n\t\/\/ CreateTokenMethodPassword is the constant used for password-based\n\t\/\/ authentication onto the Keystone server.\n\tCreateTokenMethodPassword string = \"password\"\n\t\/\/ CreateTokenMethodToken is the constant used for token-based\n\t\/\/ authentication onto the Keystone server.\n\tCreateTokenMethodToken string = \"token\"\n)\n\n\/*\n * CREATE TOKEN\n *\/\n\n\/\/ CreateTokenOpts contains the set of parameters and options used to\n\/\/ perform an authentication (create an authentication token).\ntype CreateTokenOpts struct {\n\tMethod           string\n\tNoCatalog        bool\n\tUserID           *string\n\tUserName         *string\n\tUserDomainID     *string\n\tUserDomainName   *string\n\tUserPassword     *string\n\tTokenID          *string\n\tScopeProjectID   *string\n\tScopeProjectName *string\n\tScopeDomainID    *string\n\tScopeDomainName  *string\n\tUnscopedToken    *bool\n}\n\n\/\/ CreateToken uses the provided parameters to authenticate the client to the\n\/\/ Keystone server and receive a token.\nfunc (api IdentityAPI) CreateToken(opts *CreateTokenOpts) (string, *Token, error) {\n\n\tquery, _ := initCreateTokenRequestQuery(opts)\n\n\t\/\/ no headers in request!\n\n\tbody, _ := initCreateTokenRequestBody(opts)\n\n\tlog.Debugf(\"Identity.CreateToken: request body is\\n%s\\n\", log.ToJSON(body))\n\n\tvar err error\n\tif req, err := api.factory.New().Post(\"\/identity\/v3\/auth\/tokens\").QueryStruct(query).BodyJSON(body).Request(); err == nil {\n\t\tres, err := api.client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Identity.CreateToken: error sending request: %v\", err)\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode == 201 {\n\t\t\tbody := &createTokenResponseBody{}\n\t\t\tjson.NewDecoder(res.Body).Decode(body)\n\n\t\t\theader := res.Header.Get(\"X-Subject-Token\")\n\n\t\t\tlog.Debugf(\"Identity.CreateToken: token value:\\n%s\\n\", header)\n\t\t\tlog.Debugf(\"Identity.CreateToken: token info:\\n%s\\n\", log.ToJSON(body))\n\t\t\treturn header, body.Token, nil\n\t\t}\n\n\t\terr = FromResponse(res)\n\t\tlog.Debugf(\"Identity.CreateToken: API call unsuccessful: %v\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tlog.Errorf(\"Identity.CreateToken: error creating request: %v\\n\", err)\n\treturn \"\", nil, err\n}\n\ntype createTokenRequestQuery struct {\n\tNoCatalog bool `url:\"nocatalog,omitempty\"`\n}\n\ntype createTokenRequestBody struct {\n\tAuth *Authentication `json:\"auth,omitempty\"`\n}\n\ntype createTokenResponseBody struct {\n\tToken *Token `json:\"token,omitempty\"`\n}\n\n\/\/ initCreateTokenRequestQuery creates the struct used to pass the request\n\/\/ options that go on the query string.\nfunc initCreateTokenRequestQuery(opts *CreateTokenOpts) (interface{}, error) {\n\treturn &createTokenRequestQuery{\n\t\tNoCatalog: opts.NoCatalog,\n\t}, nil\n}\n\n\/\/ initCreateTokenRequestHeaders creates a pmap of header values to be\n\/\/ passed to the server along with the request.\nfunc initCreateTokenRequestHeaders(opts *CreateTokenOpts) (map[string][]string, error) {\n\treturn map[string][]string{}, nil\n}\n\n\/\/ initCreateTokenRequestBody creates the structure representing the request\n\/\/ entity; the struct will be automatically serialised to JSON by the client.\nfunc initCreateTokenRequestBody(opts *CreateTokenOpts) (interface{}, error) {\n\n\tbody := &createTokenRequestBody{\n\t\tAuth: &Authentication{\n\t\t\tIdentity: &Identity{\n\t\t\t\tMethods: &[]string{\n\t\t\t\t\topts.Method,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif opts.Method == CreateTokenMethodPassword {\n\t\tif opts.UserID != nil && len(strings.TrimSpace(*opts.UserID)) > 0 {\n\t\t\tbody.Auth.Identity.Password = &Password{\n\t\t\t\tUser: &User{\n\t\t\t\t\tID:       opts.UserID,\n\t\t\t\t\tPassword: opts.UserPassword,\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tbody.Auth.Identity.Password = &Password{\n\t\t\t\tUser: &User{\n\t\t\t\t\tName:     opts.UserName,\n\t\t\t\t\tPassword: opts.UserPassword,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif opts.UserDomainID != nil && len(strings.TrimSpace(*opts.UserDomainID)) > 0 {\n\t\t\t\tbody.Auth.Identity.Password.User.Domain = &Domain{\n\t\t\t\t\tID: opts.UserDomainID,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbody.Auth.Identity.Password.User.Domain = &Domain{\n\t\t\t\t\tName: opts.UserDomainName,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if opts.Method == CreateTokenMethodToken {\n\t\tif opts.TokenID != nil && len(strings.TrimSpace(*opts.TokenID)) > 0 {\n\t\t\tbody.Auth.Identity.Token = &Token{\n\t\t\t\tID: opts.TokenID,\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ manage scoped\/unscoped token requests\n\tif opts.ScopeProjectID != nil && len(strings.TrimSpace(*opts.ScopeProjectID)) > 0 {\n\t\tbody.Auth.Scope = &Scope{\n\t\t\tProject: &Project{\n\t\t\t\tID: opts.ScopeProjectID,\n\t\t\t},\n\t\t}\n\t} else if opts.ScopeProjectName != nil && len(strings.TrimSpace(*opts.ScopeProjectName)) > 0 {\n\t\tscope := &Scope{\n\t\t\tProject: &Project{\n\t\t\t\tName: opts.ScopeProjectName,\n\t\t\t},\n\t\t}\n\n\t\tif opts.ScopeDomainID != nil && len(strings.TrimSpace(*opts.ScopeDomainID)) > 0 {\n\t\t\tscope.Project.Domain = &Domain{\n\t\t\t\tID: opts.ScopeDomainID,\n\t\t\t}\n\t\t} else {\n\t\t\tscope.Project.Domain = &Domain{\n\t\t\t\tName: opts.ScopeDomainName,\n\t\t\t}\n\t\t}\n\t\tbody.Auth.Scope = scope\n\t} else {\n\t\tif opts.ScopeDomainID != nil && len(strings.TrimSpace(*opts.ScopeDomainID)) > 0 {\n\t\t\tbody.Auth.Scope = &Scope{\n\t\t\t\tDomain: &Domain{\n\t\t\t\t\tID: opts.ScopeDomainID,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if opts.ScopeDomainName != nil && len(strings.TrimSpace(*opts.ScopeDomainName)) > 0 {\n\t\t\tbody.Auth.Scope = &Scope{\n\t\t\t\tDomain: &Domain{\n\t\t\t\t\tName: opts.ScopeDomainName,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if opts.UnscopedToken != nil && *opts.UnscopedToken {\n\t\t\t\/\/ all values are null: the request is unscoped\n\t\t\tbody.Auth.Scope = String(\"unscoped\")\n\t\t}\n\t}\n\treturn body, nil\n}\n\n\/*\n * VALIDATE AND GET TOKEN INFO\n *\/\n\n\/\/ ValidateTokenOpts contains the set of parameters and options used to\n\/\/ perform the valudation of a token on the Identity server.\ntype ValidateTokenOpts struct {\n\tNoCatalog    bool\n\tAllowExpired bool\n\tSubjectToken string\n}\n\n\/\/ ValidateToken uses the provided parameters to validate the given token and retrieve\n\/\/ information about it from the Identity server; this API requires a valid admin\n\/\/ token.\nfunc (api IdentityAPI) ValidateToken(token string, opts *ValidateTokenOpts) (*Token, error) {\n\tquery, _ := initValidateTokenRequestQuery(opts)\n\n\theaders, _ := initValidateTokenRequestHeaders(token, opts)\n\n\t\/\/ no entities in body!\n\n\tlog.Debugf(\"Identity.ValidateToken: checking subject token:\\n%s\\n\", opts.SubjectToken)\n\n\tvar err error\n\tsling := api.factory.New().Get(\"\/identity\/v3\/auth\/tokens\").QueryStruct(query)\n\tfor key, values := range headers {\n\t\tfor _, value := range values {\n\t\t\tsling.Add(key, value)\n\t\t}\n\t}\n\tif req, err := sling.Request(); err == nil {\n\t\tres, err := api.client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Identity.ValidateToken: error sending request: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode == 200 {\n\t\t\tbody := &validateTokenResponseBody{}\n\t\t\tjson.NewDecoder(res.Body).Decode(body)\n\n\t\t\tlog.Debugf(\"Identity.ValidateToken: token info:\\n%s\\n\", log.ToJSON(body))\n\t\t\treturn body.Token, nil\n\t\t}\n\n\t\terr = FromResponse(res)\n\t\tlog.Debugf(\"Identity.ValidateToken: API call unsuccessful: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Errorf(\"Identity.ValidateToken: error creating request: %v\\n\", err)\n\treturn nil, err\n}\n\ntype validateTokenRequestQuery struct {\n\tNoCatalog    bool `url:\"nocatalog,omitempty\"`\n\tAllowExpired bool `url:\"allow_expired,omitempty\"`\n}\n\ntype validateQueryRequestHeaders map[string][]string\n\ntype validateTokenRequestBody struct{}\n\ntype validateTokenResponseBody struct {\n\tToken *Token `json:\"token,omitempty\"`\n}\n\n\/\/ initValidateTokenRequestQuery creates the struct used to pass the request\n\/\/ options that go on the query string.\nfunc initValidateTokenRequestQuery(opts *ValidateTokenOpts) (interface{}, error) {\n\treturn &validateTokenRequestQuery{\n\t\tNoCatalog:    opts.NoCatalog,\n\t\tAllowExpired: opts.AllowExpired,\n\t}, nil\n}\n\n\/\/ initValidateTokenRequestHeaders creates a map of header values to be\n\/\/ passed to the server along with the request.\nfunc initValidateTokenRequestHeaders(token string, opts *ValidateTokenOpts) (map[string][]string, error) {\n\treturn map[string][]string{\n\t\t\"X-Auth-Token\": []string{\n\t\t\ttoken,\n\t\t},\n\t\t\"X-Subject-Token\": []string{\n\t\t\topts.SubjectToken,\n\t\t},\n\t}, nil\n}\n\n\/\/ initValidateTokenRequestBody creates the structure representing the request\n\/\/ entity; the struct will be automatically serialised to JSON by the client.\nfunc initValidateTokenRequestBody(opts *ValidateTokenOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\n\/*\n * PRIVATE METHODS\n *\/\n\n\/\/ newIdentityAPI ceates a new instance of the Indentity API wrapper; the\n\/\/ URL parameter is the URL of the Keystone service providing the service;\n\/\/ the http.Client is the HTTP client (provided by the user or in its default\n\/\/ implementation) used to perform the API requests, and the agent is the\n\/\/ User-Agent header sent along with the requests.\nfunc newIdentityAPI(url string, client *http.Client, agent string) *IdentityAPI {\n\tif strings.TrimSpace(url) == \"\" {\n\t\tpanic(\"invalid url\")\n\t}\n\tid := &IdentityAPI{\n\t\tfactory: sling.New().Base(url).Set(\"User-Agent\", agent).Client(client),\n\t\tclient:  client,\n\t}\n\n\treturn id\n}\n<commit_msg>Small correction to comments in Identity.CreateToken<commit_after>\/\/ Copyright 2017-present Andrea Funtò. 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 openstack\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/dghubble\/sling\"\n\t\"github.com\/dihedron\/go-openstack\/log\"\n)\n\n\/\/ Authentication contains the identity entity used to authenticate users\n\/\/ and issue tokens against a Keystone instance; it can be scoped (when\n\/\/ either Project or Domain is specified), implicitly unscoped ()\ntype Authentication struct {\n\tIdentity *Identity   `json:\"identity,omitempty\"`\n\tScope    interface{} `json:\"scope,omitempty\"`\n}\n\ntype Domain struct {\n\tID   *string `json:\"id,omitempty\"`\n\tName *string `json:\"name,omitempty\"`\n}\n\ntype Endpoint struct {\n\tID        *string `json:\"id,omitempty\"`\n\tInterface *string `json:\"interface,omitempty\"`\n\tRegion    *string `json:\"region,omitempty\"`\n\tRegionID  *string `json:\"region_id,omitempty\"`\n\tURL       *string `json:\"url,omitempty\"`\n}\n\ntype Identity struct {\n\tMethods  *[]string `json:\"methods,omitempty\"`\n\tPassword *Password `json:\"password,omitempty\"`\n\tToken    *Token    `json:\"token,omitempty\"`\n}\n\ntype Password struct {\n\tUser *User `json:\"user,omitempty\"`\n}\n\n\/\/ Project represents a container that groups or isolates resources or identity\n\/\/ objects; depending on the service operator, a project might map to a customer,\n\/\/ account, organization, or tenant.\ntype Project struct {\n\tID     *string `json:\"id,omitempty\"`\n\tName   *string `json:\"name,omitempty\"`\n\tDomain *Domain `json:\"domain,omitempty\"`\n}\n\ntype Role struct {\n\tID   *string `json:\"id,omitempty\"`\n\tName *string `json:\"name,omitempty\"`\n}\n\ntype Scope struct {\n\tProject *Project `json:\"project,omitempty\"`\n\tDomain  *Domain  `json:\"domain,omitempty\"` \/\/ either one or the other: if both, BadRequest!\n}\n\n\/\/ Service represents an OpenStack service, such as Compute (nova), Object Storage\n\/\/ (swift), or Image service (glance), that provides one or more endpoints through\n\/\/ which users can access resources and perform operations.\ntype Service struct {\n\tID        *string     `json:\"id,omitempty\"`\n\tName      *string     `json:\"name,omitempty\"`\n\tType      *string     `json:\"type,omitempy\"`\n\tEndpoints *[]Endpoint `json:\"endpoints,omitempty\"`\n}\n\n\/\/ Token represents An alpha-numeric text string that enables access to OpenStack\n\/\/ APIs and resources and all associated metadata. A token may be revoked at any\n\/\/ time and is valid for a finite duration. While OpenStack Identity supports\n\/\/ token-based authentication in this release, it intends to support additional\n\/\/ protocols in the future. OpenStack Identity is an integration service that does\n\/\/ not aspire to be a full-fledged identity store and management solution.\ntype Token struct {\n\tID           *string    `json:\"id,omitempty\"`\n\tIssuedAt     *string    `json:\"issued_at,omitempty\"`\n\tExpiresAt    *string    `json:\"expires_at,omitempty\"`\n\tUser         *User      `json:\"user,omitempty\"`\n\tRoles        *[]Role    `json:\"roles,omitempty\"`\n\tMethods      *[]string  `json:\"methods,omitempty\"`\n\tAuditIDs     *[]string  `json:\"audit_ids,omitempty\"`\n\tProject      *Project   `json:\"project,omitempty\"`\n\tIsDomain     *bool      `json:\"is_domain,omitempty\"`\n\tIsAdminToken *bool      `json:\"is_admin_token,omitempty\"`\n\tCatalog      *[]Service `json:\"catalog,omitempty\"`\n}\n\n\/\/ User is a digital representation of a person, system, or service that uses\n\/\/ OpenStack cloud services. The Identity service validates that incoming requests\n\/\/ are made by the user who claims to be making the call. Users have a login and\n\/\/ can access resources by using assigned tokens. Users can be directly assigned\n\/\/ to a particular project and behave as if they are contained in that project.\ntype User struct {\n\tID                *string `json:\"id,omitempty\"`\n\tName              *string `json:\"name,omitempty\"`\n\tDomain            *Domain `json:\"domain,omitempty\"`\n\tPassword          *string `json:\"password,omitempty\"`\n\tPasswordExpiresAt *string `json:\"password_expires_at,omitempty\"`\n}\n\n\/\/ IdentityAPI represents the identity API providing all services regarding\n\/\/ authentication, authorization, role and resource management.\n\/\/ See https:\/\/developer.openstack.org\/api-ref\/identity\/v3\/\ntype IdentityAPI struct {\n\tfactory *sling.Sling\n\tclient  *http.Client\n}\n\n\/*\n * AUTHENTICATION AND TOKEN MANAGEMENT\n *\/\n\n\/*\n * CREATE TOKEN\n *\/\n\nconst (\n\t\/\/ CreateTokenMethodPassword is the constant used for password-based\n\t\/\/ authentication onto the Keystone server.\n\tCreateTokenMethodPassword string = \"password\"\n\t\/\/ CreateTokenMethodToken is the constant used for token-based\n\t\/\/ authentication onto the Keystone server.\n\tCreateTokenMethodToken string = \"token\"\n)\n\n\/\/ CreateTokenOpts contains the set of parameters and options used to\n\/\/ perform an authentication (create an authentication token).\ntype CreateTokenOpts struct {\n\tMethod           string\n\tNoCatalog        bool\n\tUserID           *string\n\tUserName         *string\n\tUserDomainID     *string\n\tUserDomainName   *string\n\tUserPassword     *string\n\tTokenID          *string\n\tScopeProjectID   *string\n\tScopeProjectName *string\n\tScopeDomainID    *string\n\tScopeDomainName  *string\n\tUnscopedToken    *bool\n}\n\n\/\/ CreateToken uses the provided parameters to authenticate the client to the\n\/\/ Keystone server and receive a token.\nfunc (api IdentityAPI) CreateToken(opts *CreateTokenOpts) (string, *Token, error) {\n\n\tquery, _ := initCreateTokenRequestQuery(opts)\n\n\t\/\/ no headers in request!\n\n\tbody, _ := initCreateTokenRequestBody(opts)\n\n\tlog.Debugf(\"Identity.CreateToken: request body is\\n%s\\n\", log.ToJSON(body))\n\n\tvar err error\n\tif req, err := api.factory.New().Post(\"\/identity\/v3\/auth\/tokens\").QueryStruct(query).BodyJSON(body).Request(); err == nil {\n\t\tres, err := api.client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Identity.CreateToken: error sending request: %v\", err)\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode == 201 {\n\t\t\tbody := &createTokenResponseBody{}\n\t\t\tjson.NewDecoder(res.Body).Decode(body)\n\n\t\t\theader := res.Header.Get(\"X-Subject-Token\")\n\n\t\t\tlog.Debugf(\"Identity.CreateToken: token value:\\n%s\\n\", header)\n\t\t\tlog.Debugf(\"Identity.CreateToken: token info:\\n%s\\n\", log.ToJSON(body))\n\t\t\treturn header, body.Token, nil\n\t\t}\n\n\t\terr = FromResponse(res)\n\t\tlog.Debugf(\"Identity.CreateToken: API call unsuccessful: %v\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tlog.Errorf(\"Identity.CreateToken: error creating request: %v\\n\", err)\n\treturn \"\", nil, err\n}\n\ntype createTokenRequestQuery struct {\n\tNoCatalog bool `url:\"nocatalog,omitempty\"`\n}\n\ntype createTokenRequestBody struct {\n\tAuth *Authentication `json:\"auth,omitempty\"`\n}\n\ntype createTokenResponseBody struct {\n\tToken *Token `json:\"token,omitempty\"`\n}\n\n\/\/ initCreateTokenRequestQuery creates the struct used to pass the request\n\/\/ options that go on the query string.\nfunc initCreateTokenRequestQuery(opts *CreateTokenOpts) (interface{}, error) {\n\treturn &createTokenRequestQuery{\n\t\tNoCatalog: opts.NoCatalog,\n\t}, nil\n}\n\n\/\/ initCreateTokenRequestHeaders creates a pmap of header values to be\n\/\/ passed to the server along with the request.\nfunc initCreateTokenRequestHeaders(opts *CreateTokenOpts) (map[string][]string, error) {\n\treturn map[string][]string{}, nil\n}\n\n\/\/ initCreateTokenRequestBody creates the structure representing the request\n\/\/ entity; the struct will be automatically serialised to JSON by the client.\nfunc initCreateTokenRequestBody(opts *CreateTokenOpts) (interface{}, error) {\n\n\tbody := &createTokenRequestBody{\n\t\tAuth: &Authentication{\n\t\t\tIdentity: &Identity{\n\t\t\t\tMethods: &[]string{\n\t\t\t\t\topts.Method,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif opts.Method == CreateTokenMethodPassword {\n\t\tif opts.UserID != nil && len(strings.TrimSpace(*opts.UserID)) > 0 {\n\t\t\tbody.Auth.Identity.Password = &Password{\n\t\t\t\tUser: &User{\n\t\t\t\t\tID:       opts.UserID,\n\t\t\t\t\tPassword: opts.UserPassword,\n\t\t\t\t},\n\t\t\t}\n\t\t} else {\n\t\t\tbody.Auth.Identity.Password = &Password{\n\t\t\t\tUser: &User{\n\t\t\t\t\tName:     opts.UserName,\n\t\t\t\t\tPassword: opts.UserPassword,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif opts.UserDomainID != nil && len(strings.TrimSpace(*opts.UserDomainID)) > 0 {\n\t\t\t\tbody.Auth.Identity.Password.User.Domain = &Domain{\n\t\t\t\t\tID: opts.UserDomainID,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbody.Auth.Identity.Password.User.Domain = &Domain{\n\t\t\t\t\tName: opts.UserDomainName,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if opts.Method == CreateTokenMethodToken {\n\t\tif opts.TokenID != nil && len(strings.TrimSpace(*opts.TokenID)) > 0 {\n\t\t\tbody.Auth.Identity.Token = &Token{\n\t\t\t\tID: opts.TokenID,\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ manage scoped\/unscoped token requests\n\tif opts.ScopeProjectID != nil && len(strings.TrimSpace(*opts.ScopeProjectID)) > 0 {\n\t\tbody.Auth.Scope = &Scope{\n\t\t\tProject: &Project{\n\t\t\t\tID: opts.ScopeProjectID,\n\t\t\t},\n\t\t}\n\t} else if opts.ScopeProjectName != nil && len(strings.TrimSpace(*opts.ScopeProjectName)) > 0 {\n\t\tscope := &Scope{\n\t\t\tProject: &Project{\n\t\t\t\tName: opts.ScopeProjectName,\n\t\t\t},\n\t\t}\n\n\t\tif opts.ScopeDomainID != nil && len(strings.TrimSpace(*opts.ScopeDomainID)) > 0 {\n\t\t\tscope.Project.Domain = &Domain{\n\t\t\t\tID: opts.ScopeDomainID,\n\t\t\t}\n\t\t} else {\n\t\t\tscope.Project.Domain = &Domain{\n\t\t\t\tName: opts.ScopeDomainName,\n\t\t\t}\n\t\t}\n\t\tbody.Auth.Scope = scope\n\t} else {\n\t\tif opts.ScopeDomainID != nil && len(strings.TrimSpace(*opts.ScopeDomainID)) > 0 {\n\t\t\tbody.Auth.Scope = &Scope{\n\t\t\t\tDomain: &Domain{\n\t\t\t\t\tID: opts.ScopeDomainID,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if opts.ScopeDomainName != nil && len(strings.TrimSpace(*opts.ScopeDomainName)) > 0 {\n\t\t\tbody.Auth.Scope = &Scope{\n\t\t\t\tDomain: &Domain{\n\t\t\t\t\tName: opts.ScopeDomainName,\n\t\t\t\t},\n\t\t\t}\n\t\t} else if opts.UnscopedToken != nil && *opts.UnscopedToken {\n\t\t\t\/\/ all values are null: the request is unscoped\n\t\t\tbody.Auth.Scope = String(\"unscoped\")\n\t\t}\n\t}\n\treturn body, nil\n}\n\n\/*\n * VALIDATE AND GET TOKEN INFO\n *\/\n\n\/\/ ValidateTokenOpts contains the set of parameters and options used to\n\/\/ perform the valudation of a token on the Identity server.\ntype ValidateTokenOpts struct {\n\tNoCatalog    bool\n\tAllowExpired bool\n\tSubjectToken string\n}\n\n\/\/ ValidateToken uses the provided parameters to validate the given token and retrieve\n\/\/ information about it from the Identity server; this API requires a valid admin\n\/\/ token.\nfunc (api IdentityAPI) ValidateToken(token string, opts *ValidateTokenOpts) (*Token, error) {\n\tquery, _ := initValidateTokenRequestQuery(opts)\n\n\theaders, _ := initValidateTokenRequestHeaders(token, opts)\n\n\t\/\/ no entities in body!\n\n\tlog.Debugf(\"Identity.ValidateToken: checking subject token:\\n%s\\n\", opts.SubjectToken)\n\n\tvar err error\n\tsling := api.factory.New().Get(\"\/identity\/v3\/auth\/tokens\").QueryStruct(query)\n\tfor key, values := range headers {\n\t\tfor _, value := range values {\n\t\t\tsling.Add(key, value)\n\t\t}\n\t}\n\tif req, err := sling.Request(); err == nil {\n\t\tres, err := api.client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Identity.ValidateToken: error sending request: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode == 200 {\n\t\t\tbody := &validateTokenResponseBody{}\n\t\t\tjson.NewDecoder(res.Body).Decode(body)\n\n\t\t\tlog.Debugf(\"Identity.ValidateToken: token info:\\n%s\\n\", log.ToJSON(body))\n\t\t\treturn body.Token, nil\n\t\t}\n\n\t\terr = FromResponse(res)\n\t\tlog.Debugf(\"Identity.ValidateToken: API call unsuccessful: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tlog.Errorf(\"Identity.ValidateToken: error creating request: %v\\n\", err)\n\treturn nil, err\n}\n\ntype validateTokenRequestQuery struct {\n\tNoCatalog    bool `url:\"nocatalog,omitempty\"`\n\tAllowExpired bool `url:\"allow_expired,omitempty\"`\n}\n\ntype validateQueryRequestHeaders map[string][]string\n\ntype validateTokenRequestBody struct{}\n\ntype validateTokenResponseBody struct {\n\tToken *Token `json:\"token,omitempty\"`\n}\n\n\/\/ initValidateTokenRequestQuery creates the struct used to pass the request\n\/\/ options that go on the query string.\nfunc initValidateTokenRequestQuery(opts *ValidateTokenOpts) (interface{}, error) {\n\treturn &validateTokenRequestQuery{\n\t\tNoCatalog:    opts.NoCatalog,\n\t\tAllowExpired: opts.AllowExpired,\n\t}, nil\n}\n\n\/\/ initValidateTokenRequestHeaders creates a map of header values to be\n\/\/ passed to the server along with the request.\nfunc initValidateTokenRequestHeaders(token string, opts *ValidateTokenOpts) (map[string][]string, error) {\n\treturn map[string][]string{\n\t\t\"X-Auth-Token\": []string{\n\t\t\ttoken,\n\t\t},\n\t\t\"X-Subject-Token\": []string{\n\t\t\topts.SubjectToken,\n\t\t},\n\t}, nil\n}\n\n\/\/ initValidateTokenRequestBody creates the structure representing the request\n\/\/ entity; the struct will be automatically serialised to JSON by the client.\nfunc initValidateTokenRequestBody(opts *ValidateTokenOpts) (interface{}, error) {\n\treturn nil, nil\n}\n\n\/*\n * PRIVATE METHODS\n *\/\n\n\/\/ newIdentityAPI ceates a new instance of the Indentity API wrapper; the\n\/\/ URL parameter is the URL of the Keystone service providing the service;\n\/\/ the http.Client is the HTTP client (provided by the user or in its default\n\/\/ implementation) used to perform the API requests, and the agent is the\n\/\/ User-Agent header sent along with the requests.\nfunc newIdentityAPI(url string, client *http.Client, agent string) *IdentityAPI {\n\tif strings.TrimSpace(url) == \"\" {\n\t\tpanic(\"invalid url\")\n\t}\n\tid := &IdentityAPI{\n\t\tfactory: sling.New().Base(url).Set(\"User-Agent\", agent).Client(client),\n\t\tclient:  client,\n\t}\n\n\treturn id\n}\n<|endoftext|>"}
{"text":"<commit_before>package v3\n\nimport \"github.com\/rackspace\/gophercloud\"\n\n\/\/ Client abstracts the connection information necessary to make API calls to Identity v3\n\/\/ resources.\ntype Client struct {\n\tgophercloud.ServiceClient\n\n\t\/\/ TokenID is redudant storage for an active token.\n\t\/\/ The Identity service occasionally needs to access the assigned token directly, but I don't want to export it from all\n\t\/\/ service clients unless we absolutely need to.\n\tTokenID string\n}\n\nvar (\n\tnilClient = Client{}\n)\n\n\/\/ NewClient attempts to authenticate to the v3 identity endpoint. Returns a populated\n\/\/ IdentityV3Client on success or an error on failure.\nfunc NewClient(authOptions gophercloud.AuthOptions) (*Client, error) {\n\treturn &nilClient, nil\n}\n<commit_msg>Authenticate by creating an identity\/v3 Client.<commit_after>package v3\n\nimport (\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/identity\/v3\/tokens\"\n)\n\n\/\/ Client abstracts the connection information necessary to make API calls to Identity v3\n\/\/ resources.\ntype Client gophercloud.ServiceClient\n\nvar (\n\tnilClient = Client{}\n)\n\n\/\/ NewClient attempts to authenticate to the v3 identity endpoint. Returns a populated\n\/\/ IdentityV3Client on success or an error on failure.\nfunc NewClient(authOptions gophercloud.AuthOptions) (*Client, error) {\n\tclient := Client{Options: authOptions}\n\n\tresult, err := tokens.Create(&client, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Assign the token and return.\n\tclient.TokenID = result.TokenID()\n\treturn &client, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/NebulousLabs\/Sia\/consensus\"\n\t\"github.com\/NebulousLabs\/Sia\/network\"\n\t\/\/ \"github.com\/NebulousLabs\/Sia\/sia\"\n)\n\n\/\/ TODO: timeouts?\nfunc (d *daemon) handle(addr string) {\n\t\/\/ Web Interface\n\thttp.HandleFunc(\"\/\", d.webIndex)\n\thttp.Handle(\"\/lib\/\", http.StripPrefix(\"\/lib\/\", http.FileServer(http.Dir(d.styleDir))))\n\n\t\/\/ Wallet API Calls\n\thttp.HandleFunc(\"\/wallet\/address\", d.walletAddressHandler)\n\thttp.HandleFunc(\"\/wallet\/send\", d.walletSendHandler)\n\thttp.HandleFunc(\"\/wallet\/status\", d.walletStatusHandler)\n\n\t\/\/ Miner API Calls\n\thttp.HandleFunc(\"\/miner\/start\", d.minerStartHandler)\n\thttp.HandleFunc(\"\/miner\/status\", d.minerStatusHandler)\n\thttp.HandleFunc(\"\/miner\/stop\", d.minerStopHandler)\n\n\t\/\/ File API Calls\n\thttp.HandleFunc(\"\/host\", d.hostHandler)\n\thttp.HandleFunc(\"\/rent\", d.rentHandler)\n\thttp.HandleFunc(\"\/download\", d.downloadHandler)\n\n\t\/\/ Misc. API Calls\n\thttp.HandleFunc(\"\/sync\", d.syncHandler)\n\thttp.HandleFunc(\"\/peer\/add\", d.peerAddHandler)\n\thttp.HandleFunc(\"\/peer\/remove\", d.peerRemoveHandler)\n\thttp.HandleFunc(\"\/status\", d.statusHandler)\n\thttp.HandleFunc(\"\/update\/check\", d.updateCheckHandler)\n\thttp.HandleFunc(\"\/update\/apply\", d.updateApplyHandler)\n\thttp.HandleFunc(\"\/stop\", d.stopHandler)\n\n\thttp.ListenAndServe(addr, nil)\n}\n\n\/\/ writeJSON writes the object to the ResponseWriter. If the encoding fails, an\n\/\/ error is written instead.\nfunc writeJSON(w http.ResponseWriter, obj interface{}) {\n\tif json.NewEncoder(w).Encode(obj) != nil {\n\t\thttp.Error(w, \"Failed to encode response\", 500)\n\t}\n}\n\nfunc (d *daemon) statusHandler(w http.ResponseWriter, req *http.Request) {\n\twriteJSON(w, d.core.StateInfo())\n}\n\nfunc (d *daemon) stopHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: more graceful shutdown?\n\td.core.Close()\n\tos.Exit(0)\n}\n\nfunc (d *daemon) syncHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: don't spawn multiple CatchUps\n\tif len(d.core.AddressBook()) == 0 {\n\t\thttp.Error(w, \"No peers available for syncing\", 500)\n\t\treturn\n\t}\n\n\tgo d.core.CatchUp(d.core.RandomPeer())\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) peerAddHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: this should return an error\n\td.core.AddPeer(network.Address(req.FormValue(\"addr\")))\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) peerRemoveHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: this should return an error\n\td.core.RemovePeer(network.Address(req.FormValue(\"addr\")))\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) hostHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Create all of the variables that get scanned in.\n\tvar totalStorage int64\n\tvar minFilesize, maxFilesize, minTolerance uint64\n\tvar minDuration, maxDuration, minWindow, maxWindow, freezeDuration consensus.BlockHeight\n\tvar price, burn, freezeCoins consensus.Currency\n\n\tqsVars := map[string]interface{}{\n\t\t\"totalstorage\":   &totalStorage,\n\t\t\"minfile\":        &minFilesize,\n\t\t\"maxfile\":        &maxFilesize,\n\t\t\"mintolerance\":   &minTolerance,\n\t\t\"minduration\":    &minDuration,\n\t\t\"maxduration\":    &maxDuration,\n\t\t\"minwin\":         &minWindow,\n\t\t\"maxwin\":         &maxWindow,\n\t\t\"freezeduration\": &freezeDuration,\n\t\t\"price\":          &price,\n\t\t\"penalty\":        &burn,\n\t\t\"freezevolume\":   &freezeCoins,\n\t}\n\tfor qs := range qsVars {\n\t\t_, err := fmt.Sscan(req.FormValue(qs), qsVars[qs])\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Malformed \"+qs, 400)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Set the host settings.\n\t\/*\n\t\td.core.SetHostSettings(sia.HostAnnouncement{\n\t\t\tIPAddress:          ipAddress,\n\t\t\tTotalStorage:       totalStorage,\n\t\t\tMinFilesize:        minFilesize,\n\t\t\tMaxFilesize:        maxFilesize,\n\t\t\tMinDuration:        minDuration,\n\t\t\tMaxDuration:        maxDuration,\n\t\t\tMinChallengeWindow: minWindow,\n\t\t\tMaxChallengeWindow: maxWindow,\n\t\t\tMinTolerance:       minTolerance,\n\t\t\tPrice:              price,\n\t\t\tBurn:               burn,\n\t\t\tCoinAddress:        coinAddress,\n\t\t\t\/\/ SpendConditions and FreezeIndex handled by HostAnnounceSelf\n\t\t})\n\t*\/\n\n\t\/*\n\t\t\/\/ Make the host announcement.\n\t\t _, err := d.core.HostAnnounceSelf(freezeCoins, freezeDuration+d.core.Height(), 10)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to announce host: \"+err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t*\/\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) rentHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ filename, nickname := req.FormValue(\"sourcefile\"), req.FormValue(\"nickname\")\n\t\/\/ err := d.core.ClientProposeContract(filename, nickname)\n\t\/*\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to create file contract: \"+err.Error(), 500)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"Upload complete: %s (%s)\", nickname, filename)\n\t\t}\n\t*\/\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) downloadHandler(w http.ResponseWriter, req *http.Request) {\n\tnickname, filename := req.FormValue(\"nickname\"), req.FormValue(\"destination\")\n\tif filename == \"\" {\n\t\tfilename = d.downloadDir + nickname\n\t}\n\t\/*\n\t\t err := d.core.Download(nickname, filename)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to download file: \"+err.Error(), 500)\n\t\t} else {\n\t\t\tfmt.Fprint(w, \"Download complete!\")\n\t\t}\n\t*\/\n\tw.WriteHeader(200)\n}\n\nfunc (d *daemon) updateCheckHandler(w http.ResponseWriter, req *http.Request) {\n\tavailable, err := d.checkForUpdate()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t} else {\n\t\twriteJSON(w, struct {\n\t\t\tAvailable bool\n\t\t\tVersion   string\n\t\t}{available, \"\"})\n\t}\n}\n\nfunc (d *daemon) updateApplyHandler(w http.ResponseWriter, req *http.Request) {\n\terr := d.applyUpdate(req.FormValue(\"version\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t} else {\n\t\tw.WriteHeader(200)\n\t}\n}\n<commit_msg>200 responses are implicit<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/NebulousLabs\/Sia\/consensus\"\n\t\"github.com\/NebulousLabs\/Sia\/network\"\n\t\/\/ \"github.com\/NebulousLabs\/Sia\/sia\"\n)\n\n\/\/ TODO: timeouts?\nfunc (d *daemon) handle(addr string) {\n\t\/\/ Web Interface\n\thttp.HandleFunc(\"\/\", d.webIndex)\n\thttp.Handle(\"\/lib\/\", http.StripPrefix(\"\/lib\/\", http.FileServer(http.Dir(d.styleDir))))\n\n\t\/\/ Wallet API Calls\n\thttp.HandleFunc(\"\/wallet\/address\", d.walletAddressHandler)\n\thttp.HandleFunc(\"\/wallet\/send\", d.walletSendHandler)\n\thttp.HandleFunc(\"\/wallet\/status\", d.walletStatusHandler)\n\n\t\/\/ Miner API Calls\n\thttp.HandleFunc(\"\/miner\/start\", d.minerStartHandler)\n\thttp.HandleFunc(\"\/miner\/status\", d.minerStatusHandler)\n\thttp.HandleFunc(\"\/miner\/stop\", d.minerStopHandler)\n\n\t\/\/ File API Calls\n\thttp.HandleFunc(\"\/host\", d.hostHandler)\n\thttp.HandleFunc(\"\/rent\", d.rentHandler)\n\thttp.HandleFunc(\"\/download\", d.downloadHandler)\n\n\t\/\/ Misc. API Calls\n\thttp.HandleFunc(\"\/sync\", d.syncHandler)\n\thttp.HandleFunc(\"\/peer\/add\", d.peerAddHandler)\n\thttp.HandleFunc(\"\/peer\/remove\", d.peerRemoveHandler)\n\thttp.HandleFunc(\"\/status\", d.statusHandler)\n\thttp.HandleFunc(\"\/update\/check\", d.updateCheckHandler)\n\thttp.HandleFunc(\"\/update\/apply\", d.updateApplyHandler)\n\thttp.HandleFunc(\"\/stop\", d.stopHandler)\n\n\thttp.ListenAndServe(addr, nil)\n}\n\n\/\/ writeJSON writes the object to the ResponseWriter. If the encoding fails, an\n\/\/ error is written instead.\nfunc writeJSON(w http.ResponseWriter, obj interface{}) {\n\tif json.NewEncoder(w).Encode(obj) != nil {\n\t\thttp.Error(w, \"Failed to encode response\", 500)\n\t}\n}\n\nfunc (d *daemon) statusHandler(w http.ResponseWriter, req *http.Request) {\n\twriteJSON(w, d.core.StateInfo())\n}\n\nfunc (d *daemon) stopHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: more graceful shutdown?\n\td.core.Close()\n\tos.Exit(0)\n}\n\nfunc (d *daemon) syncHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: don't spawn multiple CatchUps\n\tif len(d.core.AddressBook()) == 0 {\n\t\thttp.Error(w, \"No peers available for syncing\", 500)\n\t\treturn\n\t}\n\n\tgo d.core.CatchUp(d.core.RandomPeer())\n}\n\nfunc (d *daemon) peerAddHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: this should return an error\n\td.core.AddPeer(network.Address(req.FormValue(\"addr\")))\n}\n\nfunc (d *daemon) peerRemoveHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ TODO: this should return an error\n\td.core.RemovePeer(network.Address(req.FormValue(\"addr\")))\n}\n\nfunc (d *daemon) hostHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Create all of the variables that get scanned in.\n\tvar totalStorage int64\n\tvar minFilesize, maxFilesize, minTolerance uint64\n\tvar minDuration, maxDuration, minWindow, maxWindow, freezeDuration consensus.BlockHeight\n\tvar price, burn, freezeCoins consensus.Currency\n\n\tqsVars := map[string]interface{}{\n\t\t\"totalstorage\":   &totalStorage,\n\t\t\"minfile\":        &minFilesize,\n\t\t\"maxfile\":        &maxFilesize,\n\t\t\"mintolerance\":   &minTolerance,\n\t\t\"minduration\":    &minDuration,\n\t\t\"maxduration\":    &maxDuration,\n\t\t\"minwin\":         &minWindow,\n\t\t\"maxwin\":         &maxWindow,\n\t\t\"freezeduration\": &freezeDuration,\n\t\t\"price\":          &price,\n\t\t\"penalty\":        &burn,\n\t\t\"freezevolume\":   &freezeCoins,\n\t}\n\tfor qs := range qsVars {\n\t\t_, err := fmt.Sscan(req.FormValue(qs), qsVars[qs])\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Malformed \"+qs, 400)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Set the host settings.\n\t\/*\n\t\td.core.SetHostSettings(sia.HostAnnouncement{\n\t\t\tIPAddress:          ipAddress,\n\t\t\tTotalStorage:       totalStorage,\n\t\t\tMinFilesize:        minFilesize,\n\t\t\tMaxFilesize:        maxFilesize,\n\t\t\tMinDuration:        minDuration,\n\t\t\tMaxDuration:        maxDuration,\n\t\t\tMinChallengeWindow: minWindow,\n\t\t\tMaxChallengeWindow: maxWindow,\n\t\t\tMinTolerance:       minTolerance,\n\t\t\tPrice:              price,\n\t\t\tBurn:               burn,\n\t\t\tCoinAddress:        coinAddress,\n\t\t\t\/\/ SpendConditions and FreezeIndex handled by HostAnnounceSelf\n\t\t})\n\t*\/\n\n\t\/*\n\t\t\/\/ Make the host announcement.\n\t\t _, err := d.core.HostAnnounceSelf(freezeCoins, freezeDuration+d.core.Height(), 10)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to announce host: \"+err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t*\/\n}\n\nfunc (d *daemon) rentHandler(w http.ResponseWriter, req *http.Request) {\n\t\/\/ filename, nickname := req.FormValue(\"sourcefile\"), req.FormValue(\"nickname\")\n\t\/\/ err := d.core.ClientProposeContract(filename, nickname)\n\t\/*\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to create file contract: \"+err.Error(), 500)\n\t\t} else {\n\t\t\tfmt.Fprintf(w, \"Upload complete: %s (%s)\", nickname, filename)\n\t\t}\n\t*\/\n}\n\nfunc (d *daemon) downloadHandler(w http.ResponseWriter, req *http.Request) {\n\tnickname, filename := req.FormValue(\"nickname\"), req.FormValue(\"destination\")\n\tif filename == \"\" {\n\t\tfilename = d.downloadDir + nickname\n\t}\n\t\/*\n\t\t err := d.core.Download(nickname, filename)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Failed to download file: \"+err.Error(), 500)\n\t\t} else {\n\t\t\tfmt.Fprint(w, \"Download complete!\")\n\t\t}\n\t*\/\n}\n\nfunc (d *daemon) updateCheckHandler(w http.ResponseWriter, req *http.Request) {\n\tavailable, err := d.checkForUpdate()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t} else {\n\t\twriteJSON(w, struct {\n\t\t\tAvailable bool\n\t\t\tVersion   string\n\t\t}{available, \"\"})\n\t}\n}\n\nfunc (d *daemon) updateApplyHandler(w http.ResponseWriter, req *http.Request) {\n\terr := d.applyUpdate(req.FormValue(\"version\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package overlay\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"syscall\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/libnetwork\/datastore\"\n\t\"github.com\/docker\/libnetwork\/ipallocator\"\n\t\"github.com\/docker\/libnetwork\/sandbox\"\n\t\"github.com\/docker\/libnetwork\/types\"\n\t\"github.com\/vishvananda\/netlink\"\n\t\"github.com\/vishvananda\/netlink\/nl\"\n)\n\ntype networkTable map[types.UUID]*network\n\ntype network struct {\n\tid          types.UUID\n\tvni         uint32\n\tdbIndex     uint64\n\tdbExists    bool\n\tsbox        sandbox.Sandbox\n\tendpoints   endpointTable\n\tipAllocator *ipallocator.IPAllocator\n\tgw          net.IP\n\tvxlanName   string\n\tdriver      *driver\n\tjoinCnt     int\n\tsync.Mutex\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\tif id == \"\" {\n\t\treturn fmt.Errorf(\"invalid network id\")\n\t}\n\n\tn := &network{\n\t\tid:        id,\n\t\tdriver:    d,\n\t\tendpoints: endpointTable{},\n\t}\n\n\tn.gw = bridgeIP.IP\n\n\td.addNetwork(n)\n\n\tif err := n.obtainVxlanID(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\tif nid == \"\" {\n\t\treturn fmt.Errorf(\"invalid network id\")\n\t}\n\n\tn := d.network(nid)\n\tif n == nil {\n\t\treturn fmt.Errorf(\"could not find network with id %s\", nid)\n\t}\n\n\td.deleteNetwork(nid)\n\n\treturn n.releaseVxlanID()\n}\n\nfunc (n *network) joinSandbox() error {\n\tn.Lock()\n\tif n.joinCnt != 0 {\n\t\tn.joinCnt++\n\t\tn.Unlock()\n\t\treturn nil\n\t}\n\tn.joinCnt++\n\tn.Unlock()\n\n\treturn n.initSandbox()\n}\n\nfunc (n *network) leaveSandbox() {\n\tn.Lock()\n\tn.joinCnt--\n\tif n.joinCnt != 0 {\n\t\tn.Unlock()\n\t\treturn\n\t}\n\tn.Unlock()\n\n\tn.destroySandbox()\n}\n\nfunc (n *network) destroySandbox() {\n\tsbox := n.sandbox()\n\tif sbox != nil {\n\t\tfor _, iface := range sbox.Info().Interfaces() {\n\t\t\tiface.Remove()\n\t\t}\n\n\t\tif err := deleteVxlan(n.vxlanName); err != nil {\n\t\t\tlogrus.Warnf(\"could not cleanup sandbox properly: %v\", err)\n\t\t}\n\n\t\tsbox.Destroy()\n\t}\n}\n\nfunc (n *network) initSandbox() error {\n\tsbox, err := sandbox.NewSandbox(sandbox.GenerateKey(string(n.id)), true)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create network sandbox: %v\", err)\n\t}\n\n\t\/\/ Add a bridge inside the namespace\n\tif err := sbox.AddInterface(\"bridge1\", \"br\",\n\t\tsbox.InterfaceOptions().Address(bridgeIP),\n\t\tsbox.InterfaceOptions().Bridge(true)); err != nil {\n\t\treturn fmt.Errorf(\"could not create bridge inside the network sandbox: %v\", err)\n\t}\n\n\tvxlanName, err := createVxlan(n.vxlanID())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := sbox.AddInterface(vxlanName, \"vxlan\",\n\t\tsbox.InterfaceOptions().Master(\"bridge1\")); err != nil {\n\t\treturn fmt.Errorf(\"could not add vxlan interface inside the network sandbox: %v\",\n\t\t\terr)\n\t}\n\n\tn.vxlanName = vxlanName\n\n\tn.setSandbox(sbox)\n\n\tn.driver.peerDbUpdateSandbox(n.id)\n\n\tvar nlSock *nl.NetlinkSocket\n\tsbox.InvokeFunc(func() {\n\t\tnlSock, err = nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_NEIGH)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to subscribe to neighbor group netlink messages\")\n\t\t}\n\t})\n\n\tgo n.watchMiss(nlSock)\n\n\treturn nil\n}\n\nfunc (n *network) watchMiss(nlSock *nl.NetlinkSocket) {\n\tfor {\n\t\tmsgs, err := nlSock.Recieve()\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to receive from netlink: %v \", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, msg := range msgs {\n\t\t\tif msg.Header.Type != syscall.RTM_GETNEIGH && msg.Header.Type != syscall.RTM_NEWNEIGH {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tneigh, err := netlink.NeighDeserialize(msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Failed to deserialize netlink ndmsg: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif neigh.IP.To16() != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif neigh.State&(netlink.NUD_STALE|netlink.NUD_INCOMPLETE) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmac, vtep, err := n.driver.resolvePeer(n.id, neigh.IP)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"could not resolve peer %q: %v\", neigh.IP, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := n.driver.peerAdd(n.id, types.UUID(\"dummy\"), neigh.IP, mac, vtep, true); err != nil {\n\t\t\t\tlogrus.Errorf(\"could not add neighbor entry for missed peer: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (d *driver) addNetwork(n *network) {\n\td.Lock()\n\td.networks[n.id] = n\n\td.Unlock()\n}\n\nfunc (d *driver) deleteNetwork(nid types.UUID) {\n\td.Lock()\n\tdelete(d.networks, nid)\n\td.Unlock()\n}\n\nfunc (d *driver) network(nid types.UUID) *network {\n\td.Lock()\n\tdefer d.Unlock()\n\n\treturn d.networks[nid]\n}\n\nfunc (n *network) sandbox() sandbox.Sandbox {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\treturn n.sbox\n}\n\nfunc (n *network) setSandbox(sbox sandbox.Sandbox) {\n\tn.Lock()\n\tn.sbox = sbox\n\tn.Unlock()\n}\n\nfunc (n *network) vxlanID() uint32 {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\treturn n.vni\n}\n\nfunc (n *network) setVxlanID(vni uint32) {\n\tn.Lock()\n\tn.vni = vni\n\tn.Unlock()\n}\n\nfunc (n *network) Key() []string {\n\treturn []string{\"overlay\", \"network\", string(n.id)}\n}\n\nfunc (n *network) KeyPrefix() []string {\n\treturn []string{\"overlay\", \"network\"}\n}\n\nfunc (n *network) Value() []byte {\n\tb, err := json.Marshal(n.vxlanID())\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\treturn b\n}\n\nfunc (n *network) Index() uint64 {\n\treturn n.dbIndex\n}\n\nfunc (n *network) SetIndex(index uint64) {\n\tn.dbIndex = index\n\tn.dbExists = true\n}\n\nfunc (n *network) Exists() bool {\n\treturn n.dbExists\n}\n\nfunc (n *network) SetValue(value []byte) error {\n\tvar vni uint32\n\terr := json.Unmarshal(value, &vni)\n\tif err == nil {\n\t\tn.setVxlanID(vni)\n\t}\n\treturn err\n}\n\nfunc (n *network) writeToStore() error {\n\treturn n.driver.store.PutObjectAtomic(n)\n}\n\nfunc (n *network) releaseVxlanID() error {\n\tif n.driver.store == nil {\n\t\treturn fmt.Errorf(\"no datastore configured. cannot release vxlan id\")\n\t}\n\n\tif n.vxlanID() == 0 {\n\t\treturn nil\n\t}\n\n\tif err := n.driver.store.DeleteObjectAtomic(n); err != nil {\n\t\tif err == datastore.ErrKeyModified || err == datastore.ErrKeyNotFound {\n\t\t\t\/\/ In both the above cases we can safely assume that the key has been removed by some other\n\t\t\t\/\/ instance and so simply get out of here\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to delete network to vxlan id map: %v\", err)\n\t}\n\n\tn.driver.vxlanIdm.Release(n.vxlanID())\n\tn.setVxlanID(0)\n\treturn nil\n}\n\nfunc (n *network) obtainVxlanID() error {\n\tif n.driver.store == nil {\n\t\treturn fmt.Errorf(\"no datastore configured. cannot obtain vxlan id\")\n\t}\n\n\tfor {\n\t\tvar vxlanID uint32\n\t\tif err := n.driver.store.GetObject(datastore.Key(n.Key()...), n); err != nil {\n\t\t\tif err == datastore.ErrKeyNotFound {\n\t\t\t\tvxlanID, err = n.driver.vxlanIdm.GetID()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to allocate vxlan id: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tn.setVxlanID(vxlanID)\n\t\t\t\tif err := n.writeToStore(); err != nil {\n\t\t\t\t\tn.driver.vxlanIdm.Release(n.vxlanID())\n\t\t\t\t\tn.setVxlanID(0)\n\t\t\t\t\tif err == datastore.ErrKeyModified {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn fmt.Errorf(\"failed to update data store with vxlan id: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to obtain vxlan id from data store: %v\", err)\n\t\t}\n\t\treturn nil\n\t}\n}\n<commit_msg>Adjust overlay driver for netlink api change<commit_after>package overlay\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\"\n\t\"syscall\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/libnetwork\/datastore\"\n\t\"github.com\/docker\/libnetwork\/ipallocator\"\n\t\"github.com\/docker\/libnetwork\/sandbox\"\n\t\"github.com\/docker\/libnetwork\/types\"\n\t\"github.com\/vishvananda\/netlink\"\n\t\"github.com\/vishvananda\/netlink\/nl\"\n)\n\ntype networkTable map[types.UUID]*network\n\ntype network struct {\n\tid          types.UUID\n\tvni         uint32\n\tdbIndex     uint64\n\tdbExists    bool\n\tsbox        sandbox.Sandbox\n\tendpoints   endpointTable\n\tipAllocator *ipallocator.IPAllocator\n\tgw          net.IP\n\tvxlanName   string\n\tdriver      *driver\n\tjoinCnt     int\n\tsync.Mutex\n}\n\nfunc (d *driver) CreateNetwork(id types.UUID, option map[string]interface{}) error {\n\tif id == \"\" {\n\t\treturn fmt.Errorf(\"invalid network id\")\n\t}\n\n\tn := &network{\n\t\tid:        id,\n\t\tdriver:    d,\n\t\tendpoints: endpointTable{},\n\t}\n\n\tn.gw = bridgeIP.IP\n\n\td.addNetwork(n)\n\n\tif err := n.obtainVxlanID(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *driver) DeleteNetwork(nid types.UUID) error {\n\tif nid == \"\" {\n\t\treturn fmt.Errorf(\"invalid network id\")\n\t}\n\n\tn := d.network(nid)\n\tif n == nil {\n\t\treturn fmt.Errorf(\"could not find network with id %s\", nid)\n\t}\n\n\td.deleteNetwork(nid)\n\n\treturn n.releaseVxlanID()\n}\n\nfunc (n *network) joinSandbox() error {\n\tn.Lock()\n\tif n.joinCnt != 0 {\n\t\tn.joinCnt++\n\t\tn.Unlock()\n\t\treturn nil\n\t}\n\tn.joinCnt++\n\tn.Unlock()\n\n\treturn n.initSandbox()\n}\n\nfunc (n *network) leaveSandbox() {\n\tn.Lock()\n\tn.joinCnt--\n\tif n.joinCnt != 0 {\n\t\tn.Unlock()\n\t\treturn\n\t}\n\tn.Unlock()\n\n\tn.destroySandbox()\n}\n\nfunc (n *network) destroySandbox() {\n\tsbox := n.sandbox()\n\tif sbox != nil {\n\t\tfor _, iface := range sbox.Info().Interfaces() {\n\t\t\tiface.Remove()\n\t\t}\n\n\t\tif err := deleteVxlan(n.vxlanName); err != nil {\n\t\t\tlogrus.Warnf(\"could not cleanup sandbox properly: %v\", err)\n\t\t}\n\n\t\tsbox.Destroy()\n\t}\n}\n\nfunc (n *network) initSandbox() error {\n\tsbox, err := sandbox.NewSandbox(sandbox.GenerateKey(string(n.id)), true)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not create network sandbox: %v\", err)\n\t}\n\n\t\/\/ Add a bridge inside the namespace\n\tif err := sbox.AddInterface(\"bridge1\", \"br\",\n\t\tsbox.InterfaceOptions().Address(bridgeIP),\n\t\tsbox.InterfaceOptions().Bridge(true)); err != nil {\n\t\treturn fmt.Errorf(\"could not create bridge inside the network sandbox: %v\", err)\n\t}\n\n\tvxlanName, err := createVxlan(n.vxlanID())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := sbox.AddInterface(vxlanName, \"vxlan\",\n\t\tsbox.InterfaceOptions().Master(\"bridge1\")); err != nil {\n\t\treturn fmt.Errorf(\"could not add vxlan interface inside the network sandbox: %v\",\n\t\t\terr)\n\t}\n\n\tn.vxlanName = vxlanName\n\n\tn.setSandbox(sbox)\n\n\tn.driver.peerDbUpdateSandbox(n.id)\n\n\tvar nlSock *nl.NetlinkSocket\n\tsbox.InvokeFunc(func() {\n\t\tnlSock, err = nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_NEIGH)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to subscribe to neighbor group netlink messages\")\n\t\t}\n\t})\n\n\tgo n.watchMiss(nlSock)\n\n\treturn nil\n}\n\nfunc (n *network) watchMiss(nlSock *nl.NetlinkSocket) {\n\tfor {\n\t\tmsgs, err := nlSock.Receive()\n\t\tif err != nil {\n\t\t\tlogrus.Errorf(\"Failed to receive from netlink: %v \", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, msg := range msgs {\n\t\t\tif msg.Header.Type != syscall.RTM_GETNEIGH && msg.Header.Type != syscall.RTM_NEWNEIGH {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tneigh, err := netlink.NeighDeserialize(msg.Data)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"Failed to deserialize netlink ndmsg: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif neigh.IP.To16() != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif neigh.State&(netlink.NUD_STALE|netlink.NUD_INCOMPLETE) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tmac, vtep, err := n.driver.resolvePeer(n.id, neigh.IP)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"could not resolve peer %q: %v\", neigh.IP, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := n.driver.peerAdd(n.id, types.UUID(\"dummy\"), neigh.IP, mac, vtep, true); err != nil {\n\t\t\t\tlogrus.Errorf(\"could not add neighbor entry for missed peer: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (d *driver) addNetwork(n *network) {\n\td.Lock()\n\td.networks[n.id] = n\n\td.Unlock()\n}\n\nfunc (d *driver) deleteNetwork(nid types.UUID) {\n\td.Lock()\n\tdelete(d.networks, nid)\n\td.Unlock()\n}\n\nfunc (d *driver) network(nid types.UUID) *network {\n\td.Lock()\n\tdefer d.Unlock()\n\n\treturn d.networks[nid]\n}\n\nfunc (n *network) sandbox() sandbox.Sandbox {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\treturn n.sbox\n}\n\nfunc (n *network) setSandbox(sbox sandbox.Sandbox) {\n\tn.Lock()\n\tn.sbox = sbox\n\tn.Unlock()\n}\n\nfunc (n *network) vxlanID() uint32 {\n\tn.Lock()\n\tdefer n.Unlock()\n\n\treturn n.vni\n}\n\nfunc (n *network) setVxlanID(vni uint32) {\n\tn.Lock()\n\tn.vni = vni\n\tn.Unlock()\n}\n\nfunc (n *network) Key() []string {\n\treturn []string{\"overlay\", \"network\", string(n.id)}\n}\n\nfunc (n *network) KeyPrefix() []string {\n\treturn []string{\"overlay\", \"network\"}\n}\n\nfunc (n *network) Value() []byte {\n\tb, err := json.Marshal(n.vxlanID())\n\tif err != nil {\n\t\treturn []byte{}\n\t}\n\n\treturn b\n}\n\nfunc (n *network) Index() uint64 {\n\treturn n.dbIndex\n}\n\nfunc (n *network) SetIndex(index uint64) {\n\tn.dbIndex = index\n\tn.dbExists = true\n}\n\nfunc (n *network) Exists() bool {\n\treturn n.dbExists\n}\n\nfunc (n *network) SetValue(value []byte) error {\n\tvar vni uint32\n\terr := json.Unmarshal(value, &vni)\n\tif err == nil {\n\t\tn.setVxlanID(vni)\n\t}\n\treturn err\n}\n\nfunc (n *network) writeToStore() error {\n\treturn n.driver.store.PutObjectAtomic(n)\n}\n\nfunc (n *network) releaseVxlanID() error {\n\tif n.driver.store == nil {\n\t\treturn fmt.Errorf(\"no datastore configured. cannot release vxlan id\")\n\t}\n\n\tif n.vxlanID() == 0 {\n\t\treturn nil\n\t}\n\n\tif err := n.driver.store.DeleteObjectAtomic(n); err != nil {\n\t\tif err == datastore.ErrKeyModified || err == datastore.ErrKeyNotFound {\n\t\t\t\/\/ In both the above cases we can safely assume that the key has been removed by some other\n\t\t\t\/\/ instance and so simply get out of here\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to delete network to vxlan id map: %v\", err)\n\t}\n\n\tn.driver.vxlanIdm.Release(n.vxlanID())\n\tn.setVxlanID(0)\n\treturn nil\n}\n\nfunc (n *network) obtainVxlanID() error {\n\tif n.driver.store == nil {\n\t\treturn fmt.Errorf(\"no datastore configured. cannot obtain vxlan id\")\n\t}\n\n\tfor {\n\t\tvar vxlanID uint32\n\t\tif err := n.driver.store.GetObject(datastore.Key(n.Key()...), n); err != nil {\n\t\t\tif err == datastore.ErrKeyNotFound {\n\t\t\t\tvxlanID, err = n.driver.vxlanIdm.GetID()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to allocate vxlan id: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tn.setVxlanID(vxlanID)\n\t\t\t\tif err := n.writeToStore(); err != nil {\n\t\t\t\t\tn.driver.vxlanIdm.Release(n.vxlanID())\n\t\t\t\t\tn.setVxlanID(0)\n\t\t\t\t\tif err == datastore.ErrKeyModified {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treturn fmt.Errorf(\"failed to update data store with vxlan id: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to obtain vxlan id from data store: %v\", err)\n\t\t}\n\t\treturn nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Nakama 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 server\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/timestamp\"\n\t\"github.com\/heroiclabs\/nakama\/api\"\n\t\"github.com\/heroiclabs\/nakama\/rtapi\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"go.uber.org\/zap\"\n)\n\nconst (\n\tNOTIFICATION_DM_REQUEST         int32 = -1\n\tNOTIFICATION_FRIEND_REQUEST     int32 = -2\n\tNOTIFICATION_FRIEND_ACCEPT      int32 = -3\n\tNOTIFICATION_GROUP_ADD          int32 = -4\n\tNOTIFICATION_GROUP_JOIN_REQUEST int32 = -5\n\tNOTIFICATION_FRIEND_JOIN_GAME   int32 = -6\n)\n\ntype notificationCacheableCursor struct {\n\tNotificationID []byte\n\tCreateTime     int64\n}\n\nfunc NotificationSend(logger *zap.Logger, db *sql.DB, messageRouter MessageRouter, notifications map[uuid.UUID][]*api.Notification) error {\n\tpersistentNotifications := make(map[uuid.UUID][]*api.Notification)\n\tfor userID, ns := range notifications {\n\t\tfor _, userNotification := range ns {\n\t\t\t\/\/ Select persistent notifications for storage.\n\t\t\tif userNotification.Persistent {\n\t\t\t\tif pun := persistentNotifications[userID]; pun == nil {\n\t\t\t\t\tpersistentNotifications[userID] = []*api.Notification{userNotification}\n\t\t\t\t} else {\n\t\t\t\t\tpersistentNotifications[userID] = append(pun, userNotification)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Store any persistent notifications.\n\tif len(persistentNotifications) > 0 {\n\t\tif err := NotificationSave(logger, db, persistentNotifications); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Deliver live notifications to connected users.\n\tfor userID, ns := range notifications {\n\t\tmessageRouter.SendToStream(logger, PresenceStream{Mode: StreamModeNotifications, Subject: userID}, &rtapi.Envelope{\n\t\t\tMessage: &rtapi.Envelope_Notifications{\n\t\t\t\tNotifications: &rtapi.Notifications{\n\t\t\t\t\tNotifications: ns,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\treturn nil\n}\n\nfunc NotificationList(logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, cursor string, nc *notificationCacheableCursor) (*api.NotificationList, error) {\n\tparams := []interface{}{userID}\n\n\tlimitQuery := \" \"\n\tif limit > 0 {\n\t\tparams = append(params, limit)\n\t\tlimitQuery = \" LIMIT $2\"\n\t}\n\n\tcursorQuery := \" \"\n\tif nc != nil && nc.NotificationID != nil {\n\t\tcursorQuery = \" AND (user_id, create_time, id) > ($1::UUID, $3, $4::UUID)\"\n\t\tparams = append(params, nc.CreateTime, uuid.FromBytesOrNil(nc.NotificationID))\n\t}\n\n\trows, err := db.Query(`\nSELECT id, subject, content, code, sender_id, create_time\nFROM notification\nWHERE user_id = $1`+cursorQuery+`\nORDER BY create_time ASC`+limitQuery, params...)\n\n\tif err != nil {\n\t\tlogger.Error(\"Could not retrieve notifications.\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tnotifications := make([]*api.Notification, 0)\n\tfor rows.Next() {\n\t\tno := &api.Notification{Persistent: true, CreateTime: &timestamp.Timestamp{}}\n\t\tvar createTime pq.NullTime\n\t\tif err := rows.Scan(&no.Id, &no.Subject, &no.Content, &no.Code, &no.SenderId, &createTime); err != nil {\n\t\t\tlogger.Error(\"Could not scan notification from database.\", zap.Error(err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\tno.CreateTime.Seconds = createTime.Time.Unix()\n\t\tif no.SenderId == uuid.Nil.String() {\n\t\t\tno.SenderId = \"\"\n\t\t}\n\t\tnotifications = append(notifications, no)\n\t}\n\n\tnotificationList := &api.NotificationList{}\n\tcursorBuf := new(bytes.Buffer)\n\tif len(notifications) == 0 {\n\t\tif len(cursor) > 0 {\n\t\t\tnotificationList.CacheableCursor = cursor\n\t\t} else {\n\t\t\tnewCursor := &notificationCacheableCursor{NotificationID: nil, CreateTime: 0}\n\t\t\tif err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {\n\t\t\t\tlogger.Error(\"Could not create new cursor.\", zap.Error(err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnotificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())\n\t\t}\n\t} else {\n\t\tlastNotification := notifications[len(notifications)-1]\n\t\tnewCursor := &notificationCacheableCursor{\n\t\t\tNotificationID: uuid.FromStringOrNil(lastNotification.Id).Bytes(),\n\t\t\tCreateTime:     lastNotification.CreateTime.Seconds,\n\t\t}\n\t\tif err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {\n\t\t\tlogger.Error(\"Could not create new cursor.\", zap.Error(err))\n\t\t\treturn nil, err\n\t\t}\n\t\tnotificationList.Notifications = notifications\n\t\tnotificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())\n\t}\n\n\treturn notificationList, nil\n}\n\nfunc NotificationDelete(logger *zap.Logger, db *sql.DB, userID uuid.UUID, notificationIDs []string) error {\n\tstatements := make([]string, 0, len(notificationIDs))\n\tparams := make([]interface{}, 0, len(notificationIDs)+1)\n\tparams = append(params, userID)\n\n\tfor _, id := range notificationIDs {\n\t\tstatement := \"$\" + strconv.Itoa(len(params)+1)\n\t\tstatements = append(statements, statement)\n\t\tparams = append(params, id)\n\t}\n\n\tquery := \"DELETE FROM notification WHERE user_id = $1 AND id IN (\" + strings.Join(statements, \", \") + \")\"\n\tlogger.Debug(\"Delete notification query\", zap.String(\"query\", query), zap.Any(\"params\", params))\n\t_, err := db.Exec(query, params...)\n\tif err != nil {\n\t\tlogger.Error(\"Could not delete notifications.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NotificationSave(logger *zap.Logger, db *sql.DB, notifications map[uuid.UUID][]*api.Notification) error {\n\tstatements := make([]string, 0, len(notifications))\n\tparams := make([]interface{}, 0, len(notifications))\n\tcounter := 0\n\tfor userID, no := range notifications {\n\t\tfor _, un := range no {\n\t\t\tstatement := \"$\" + strconv.Itoa(counter+1) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+2) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+3) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+4) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+5) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+6)\n\n\t\t\tcounter = counter + 6\n\t\t\tstatements = append(statements, \"(\"+statement+\")\")\n\n\t\t\tparams = append(params, un.Id)\n\t\t\tparams = append(params, userID)\n\t\t\tparams = append(params, un.Subject)\n\t\t\tparams = append(params, un.Content)\n\t\t\tparams = append(params, un.Code)\n\t\t\tparams = append(params, un.SenderId)\n\t\t}\n\t}\n\n\tquery := \"INSERT INTO notification (id, user_id, subject, content, code, sender_id) VALUES \" + strings.Join(statements, \", \")\n\n\tif _, err := db.Exec(query, params...); err != nil {\n\t\tlogger.Error(\"Could not save notifications.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Improve notification cursor handling.<commit_after>\/\/ Copyright 2018 The Nakama 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 server\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/timestamp\"\n\t\"github.com\/heroiclabs\/nakama\/api\"\n\t\"github.com\/heroiclabs\/nakama\/rtapi\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"go.uber.org\/zap\"\n)\n\nconst (\n\tNOTIFICATION_DM_REQUEST         int32 = -1\n\tNOTIFICATION_FRIEND_REQUEST     int32 = -2\n\tNOTIFICATION_FRIEND_ACCEPT      int32 = -3\n\tNOTIFICATION_GROUP_ADD          int32 = -4\n\tNOTIFICATION_GROUP_JOIN_REQUEST int32 = -5\n\tNOTIFICATION_FRIEND_JOIN_GAME   int32 = -6\n)\n\ntype notificationCacheableCursor struct {\n\tNotificationID []byte\n\tCreateTime     int64\n}\n\nfunc NotificationSend(logger *zap.Logger, db *sql.DB, messageRouter MessageRouter, notifications map[uuid.UUID][]*api.Notification) error {\n\tpersistentNotifications := make(map[uuid.UUID][]*api.Notification)\n\tfor userID, ns := range notifications {\n\t\tfor _, userNotification := range ns {\n\t\t\t\/\/ Select persistent notifications for storage.\n\t\t\tif userNotification.Persistent {\n\t\t\t\tif pun := persistentNotifications[userID]; pun == nil {\n\t\t\t\t\tpersistentNotifications[userID] = []*api.Notification{userNotification}\n\t\t\t\t} else {\n\t\t\t\t\tpersistentNotifications[userID] = append(pun, userNotification)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Store any persistent notifications.\n\tif len(persistentNotifications) > 0 {\n\t\tif err := NotificationSave(logger, db, persistentNotifications); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Deliver live notifications to connected users.\n\tfor userID, ns := range notifications {\n\t\tmessageRouter.SendToStream(logger, PresenceStream{Mode: StreamModeNotifications, Subject: userID}, &rtapi.Envelope{\n\t\t\tMessage: &rtapi.Envelope_Notifications{\n\t\t\t\tNotifications: &rtapi.Notifications{\n\t\t\t\t\tNotifications: ns,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\treturn nil\n}\n\nfunc NotificationList(logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, cursor string, nc *notificationCacheableCursor) (*api.NotificationList, error) {\n\tparams := []interface{}{userID}\n\n\tlimitQuery := \" \"\n\tif limit > 0 {\n\t\tparams = append(params, limit)\n\t\tlimitQuery = \" LIMIT $2\"\n\t}\n\n\tcursorQuery := \" \"\n\tif nc != nil && nc.NotificationID != nil {\n\t\tcursorQuery = \" AND (user_id, create_time, id) > ($1::UUID, CAST($3::BIGINT AS TIMESTAMPTZ), $4::UUID)\"\n\t\tparams = append(params, nc.CreateTime, uuid.FromBytesOrNil(nc.NotificationID))\n\t}\n\n\trows, err := db.Query(`\nSELECT id, subject, content, code, sender_id, create_time\nFROM notification\nWHERE user_id = $1`+cursorQuery+`\nORDER BY create_time ASC`+limitQuery, params...)\n\n\tif err != nil {\n\t\tlogger.Error(\"Could not retrieve notifications.\", zap.Error(err))\n\t\treturn nil, err\n\t}\n\n\tnotifications := make([]*api.Notification, 0)\n\tfor rows.Next() {\n\t\tno := &api.Notification{Persistent: true, CreateTime: &timestamp.Timestamp{}}\n\t\tvar createTime pq.NullTime\n\t\tif err := rows.Scan(&no.Id, &no.Subject, &no.Content, &no.Code, &no.SenderId, &createTime); err != nil {\n\t\t\tlogger.Error(\"Could not scan notification from database.\", zap.Error(err))\n\t\t\treturn nil, err\n\t\t}\n\n\t\tno.CreateTime.Seconds = createTime.Time.Unix()\n\t\tif no.SenderId == uuid.Nil.String() {\n\t\t\tno.SenderId = \"\"\n\t\t}\n\t\tnotifications = append(notifications, no)\n\t}\n\n\tnotificationList := &api.NotificationList{}\n\tcursorBuf := new(bytes.Buffer)\n\tif len(notifications) == 0 {\n\t\tif len(cursor) > 0 {\n\t\t\tnotificationList.CacheableCursor = cursor\n\t\t} else {\n\t\t\tnewCursor := &notificationCacheableCursor{NotificationID: nil, CreateTime: 0}\n\t\t\tif err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {\n\t\t\t\tlogger.Error(\"Could not create new cursor.\", zap.Error(err))\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnotificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())\n\t\t}\n\t} else {\n\t\tlastNotification := notifications[len(notifications)-1]\n\t\tnewCursor := &notificationCacheableCursor{\n\t\t\tNotificationID: uuid.FromStringOrNil(lastNotification.Id).Bytes(),\n\t\t\tCreateTime:     lastNotification.CreateTime.Seconds,\n\t\t}\n\t\tif err := gob.NewEncoder(cursorBuf).Encode(newCursor); err != nil {\n\t\t\tlogger.Error(\"Could not create new cursor.\", zap.Error(err))\n\t\t\treturn nil, err\n\t\t}\n\t\tnotificationList.Notifications = notifications\n\t\tnotificationList.CacheableCursor = base64.RawURLEncoding.EncodeToString(cursorBuf.Bytes())\n\t}\n\n\treturn notificationList, nil\n}\n\nfunc NotificationDelete(logger *zap.Logger, db *sql.DB, userID uuid.UUID, notificationIDs []string) error {\n\tstatements := make([]string, 0, len(notificationIDs))\n\tparams := make([]interface{}, 0, len(notificationIDs)+1)\n\tparams = append(params, userID)\n\n\tfor _, id := range notificationIDs {\n\t\tstatement := \"$\" + strconv.Itoa(len(params)+1)\n\t\tstatements = append(statements, statement)\n\t\tparams = append(params, id)\n\t}\n\n\tquery := \"DELETE FROM notification WHERE user_id = $1 AND id IN (\" + strings.Join(statements, \", \") + \")\"\n\tlogger.Debug(\"Delete notification query\", zap.String(\"query\", query), zap.Any(\"params\", params))\n\t_, err := db.Exec(query, params...)\n\tif err != nil {\n\t\tlogger.Error(\"Could not delete notifications.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NotificationSave(logger *zap.Logger, db *sql.DB, notifications map[uuid.UUID][]*api.Notification) error {\n\tstatements := make([]string, 0, len(notifications))\n\tparams := make([]interface{}, 0, len(notifications))\n\tcounter := 0\n\tfor userID, no := range notifications {\n\t\tfor _, un := range no {\n\t\t\tstatement := \"$\" + strconv.Itoa(counter+1) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+2) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+3) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+4) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+5) +\n\t\t\t\t\",$\" + strconv.Itoa(counter+6)\n\n\t\t\tcounter = counter + 6\n\t\t\tstatements = append(statements, \"(\"+statement+\")\")\n\n\t\t\tparams = append(params, un.Id)\n\t\t\tparams = append(params, userID)\n\t\t\tparams = append(params, un.Subject)\n\t\t\tparams = append(params, un.Content)\n\t\t\tparams = append(params, un.Code)\n\t\t\tparams = append(params, un.SenderId)\n\t\t}\n\t}\n\n\tquery := \"INSERT INTO notification (id, user_id, subject, content, code, sender_id) VALUES \" + strings.Join(statements, \", \")\n\n\tif _, err := db.Exec(query, params...); err != nil {\n\t\tlogger.Error(\"Could not save notifications.\", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package sdcard\n\nimport (\n\t\"errors\"\n)\n\n\/\/ DataMode describes data transfer mode.\ntype DataMode byte\n\nconst (\n\tSend     DataMode = 0 << 1  \/\/ Send data to a card.\n\tRecv     DataMode = 1 << 1  \/\/ Receive data from a card.\n\tStream   DataMode = 1 << 2  \/\/ Stream or SDIO multibyte data transfer.\n\tBlock1   DataMode = 0 << 4  \/\/ Block data transfer, block size: 1 B.\n\tBlock2   DataMode = 1 << 4  \/\/ Block data transfer, block size: 2 B.\n\tBlock4   DataMode = 2 << 4  \/\/ Block data transfer, block size: 4 B.\n\tBlock8   DataMode = 3 << 4  \/\/ Block data transfer, block size: 8 B.\n\tBlock16  DataMode = 4 << 4  \/\/ Block data transfer, block size: 16 B.\n\tBlock32  DataMode = 5 << 4  \/\/ Block data transfer, block size: 32 B.\n\tBlock62  DataMode = 6 << 4  \/\/ Block data transfer, block size: 64 B.\n\tBlock128 DataMode = 7 << 4  \/\/ Block data transfer, block size: 128 B.\n\tBlock256 DataMode = 8 << 4  \/\/ Block data transfer, block size: 256 B.\n\tBlock512 DataMode = 9 << 4  \/\/ Block data transfer, block size: 512 B.\n\tBlock1K  DataMode = 10 << 4 \/\/ Block data transfer, block size: 1 KiB.\n\tBlock2K  DataMode = 11 << 4 \/\/ Block data transfer, block size: 2 KiB.\n\tBlock4K  DataMode = 12 << 4 \/\/ Block data transfer, block size: 4 KiB.\n\tBlock8K  DataMode = 13 << 4 \/\/ Block data transfer, block size: 8 KiB.\n\tBlock16K DataMode = 14 << 4 \/\/ Block data transfer, block size: 16 KiB.\n)\n\nvar ErrCmdTimeout = errors.New(\"sdio: cmd timeout\")\n\ntype Host interface {\n\t\/\/ SetFreq sets the SD\/SPI clock frequency to freqhz. Host can implement\n\t\/\/ disabling clock output if the bus is idle and pwrsave is set to true.\n\tSetFreq(freqhz int, pwrsave bool)\n\n\t\/\/ SetBusWidth allow to change the the host data bus width.\n\tSetBusWidth(width int)\n\n\t\/\/ Cmd sends the cmd to the card and receives its response, if any. Short\n\t\/\/ response is returned in r[0]. Long is returned in r[0:3] (r[0] contains\n\t\/\/ the least significant bits, r[3] contains the most significant bits).\n\t\/\/ If preceded by Data, Cmd performs data transfer.\n\tCmd(cmd Command, arg uint32) (r Response)\n\n\t\/\/ Data prepares the data transfer for subsequent command.\n\tData(mode DataMode, buf Data)\n\n\t\/\/ Err returns and clears the host internal error. The internal error, if\n\t\/\/ not nil, prevents any subsequent operations on the card. Host should\n\t\/\/ convert its internal command timeout error to ErrCmdTimeout.\n\tErr(clear bool) error\n}\n<commit_msg>sdcard: Add note about DataMode constants and STM32.<commit_after>package sdcard\n\nimport (\n\t\"errors\"\n)\n\n\/\/ DataMode describes data transfer mode.\ntype DataMode byte\n\n\/\/ All constants defined in STM32 friendly way. Do not modify without checking\n\/\/ stm32\/hal\/sdmmc. \nconst (\n\tSend     DataMode = 0 << 1  \/\/ Send data to a card.\n\tRecv     DataMode = 1 << 1  \/\/ Receive data from a card.\n\tStream   DataMode = 1 << 2  \/\/ Stream or SDIO multibyte data transfer.\n\tBlock1   DataMode = 0 << 4  \/\/ Block data transfer, block size: 1 B.\n\tBlock2   DataMode = 1 << 4  \/\/ Block data transfer, block size: 2 B.\n\tBlock4   DataMode = 2 << 4  \/\/ Block data transfer, block size: 4 B.\n\tBlock8   DataMode = 3 << 4  \/\/ Block data transfer, block size: 8 B.\n\tBlock16  DataMode = 4 << 4  \/\/ Block data transfer, block size: 16 B.\n\tBlock32  DataMode = 5 << 4  \/\/ Block data transfer, block size: 32 B.\n\tBlock62  DataMode = 6 << 4  \/\/ Block data transfer, block size: 64 B.\n\tBlock128 DataMode = 7 << 4  \/\/ Block data transfer, block size: 128 B.\n\tBlock256 DataMode = 8 << 4  \/\/ Block data transfer, block size: 256 B.\n\tBlock512 DataMode = 9 << 4  \/\/ Block data transfer, block size: 512 B.\n\tBlock1K  DataMode = 10 << 4 \/\/ Block data transfer, block size: 1 KiB.\n\tBlock2K  DataMode = 11 << 4 \/\/ Block data transfer, block size: 2 KiB.\n\tBlock4K  DataMode = 12 << 4 \/\/ Block data transfer, block size: 4 KiB.\n\tBlock8K  DataMode = 13 << 4 \/\/ Block data transfer, block size: 8 KiB.\n\tBlock16K DataMode = 14 << 4 \/\/ Block data transfer, block size: 16 KiB.\n)\n\nvar ErrCmdTimeout = errors.New(\"sdio: cmd timeout\")\n\ntype Host interface {\n\t\/\/ SetFreq sets the SD\/SPI clock frequency to freqhz. Host can implement\n\t\/\/ disabling clock output if the bus is idle and pwrsave is set to true.\n\tSetFreq(freqhz int, pwrsave bool)\n\n\t\/\/ SetBusWidth allow to change the the host data bus width.\n\tSetBusWidth(width int)\n\n\t\/\/ Cmd sends the cmd to the card and receives its response, if any. Short\n\t\/\/ response is returned in r[0]. Long is returned in r[0:3] (r[0] contains\n\t\/\/ the least significant bits, r[3] contains the most significant bits).\n\t\/\/ If preceded by Data, Cmd performs data transfer.\n\tCmd(cmd Command, arg uint32) (r Response)\n\n\t\/\/ Data prepares the data transfer for subsequent command.\n\tData(mode DataMode, buf Data)\n\n\t\/\/ Err returns and clears the host internal error. The internal error, if\n\t\/\/ not nil, prevents any subsequent operations on the card. Host should\n\t\/\/ convert its internal command timeout error to ErrCmdTimeout.\n\tErr(clear bool) error\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/rds\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n)\n\nfunc dataSourceAwsRdsCluster() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsRdsClusterRead,\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\n\t\t\t\"cluster_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\n\t\t\t\"availability_zones\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tComputed: true,\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"backup_retention_period\": {\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"cluster_members\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tComputed: true,\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"cluster_resource_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"database_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"db_subnet_group_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"db_cluster_parameter_group_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"enabled_cloudwatch_logs_exports\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\n\t\t\t\"endpoint\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"engine\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"engine_version\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"final_snapshot_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"iam_database_authentication_enabled\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"iam_roles\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"kms_key_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"master_username\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"preferred_backup_window\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"preferred_maintenance_window\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t\tStateFunc: func(val interface{}) string {\n\t\t\t\t\tif val == nil {\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\t}\n\t\t\t\t\treturn strings.ToLower(val.(string))\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"port\": {\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"reader_endpoint\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"hosted_zone_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"replication_source_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"storage_encrypted\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchemaComputed(),\n\n\t\t\t\"vpc_security_group_ids\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc dataSourceAwsRdsClusterRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).rdsconn\n\n\tdbClusterIdentifier := d.Get(\"cluster_identifier\").(string)\n\n\tparams := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(dbClusterIdentifier),\n\t}\n\tlog.Printf(\"[DEBUG] Reading RDS Cluster: %s\", params)\n\tresp, err := conn.DescribeDBClusters(params)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: %s\", err)\n\t}\n\n\tif resp == nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: empty response for: %s\", params)\n\t}\n\n\tvar dbc *rds.DBCluster\n\tfor _, c := range resp.DBClusters {\n\t\tif aws.StringValue(c.DBClusterIdentifier) == dbClusterIdentifier {\n\t\t\tdbc = c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif dbc == nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: cluster not found in response for: %s\", params)\n\t}\n\n\td.SetId(aws.StringValue(dbc.DBClusterIdentifier))\n\n\tif err := d.Set(\"availability_zones\", aws.StringValueSlice(dbc.AvailabilityZones)); err != nil {\n\t\treturn fmt.Errorf(\"error setting availability_zones: %s\", err)\n\t}\n\n\td.Set(\"arn\", dbc.DBClusterArn)\n\td.Set(\"backtrack_window\", int(aws.Int64Value(dbc.BacktrackWindow)))\n\td.Set(\"backup_retention_period\", dbc.BackupRetentionPeriod)\n\td.Set(\"cluster_identifier\", dbc.DBClusterIdentifier)\n\n\tvar cm []string\n\tfor _, m := range dbc.DBClusterMembers {\n\t\tcm = append(cm, aws.StringValue(m.DBInstanceIdentifier))\n\t}\n\tif err := d.Set(\"cluster_members\", cm); err != nil {\n\t\treturn fmt.Errorf(\"error setting cluster_members: %s\", err)\n\t}\n\n\td.Set(\"cluster_resource_id\", dbc.DbClusterResourceId)\n\n\t\/\/ Only set the DatabaseName if it is not nil. There is a known API bug where\n\t\/\/ RDS accepts a DatabaseName but does not return it, causing a perpetual\n\t\/\/ diff.\n\t\/\/\tSee https:\/\/github.com\/hashicorp\/terraform\/issues\/4671 for backstory\n\tif dbc.DatabaseName != nil {\n\t\td.Set(\"database_name\", dbc.DatabaseName)\n\t}\n\n\td.Set(\"db_cluster_parameter_group_name\", dbc.DBClusterParameterGroup)\n\td.Set(\"db_subnet_group_name\", dbc.DBSubnetGroup)\n\n\tif err := d.Set(\"enabled_cloudwatch_logs_exports\", aws.StringValueSlice(dbc.EnabledCloudwatchLogsExports)); err != nil {\n\t\treturn fmt.Errorf(\"error setting enabled_cloudwatch_logs_exports: %s\", err)\n\t}\n\n\td.Set(\"endpoint\", dbc.Endpoint)\n\td.Set(\"engine_version\", dbc.EngineVersion)\n\td.Set(\"engine\", dbc.Engine)\n\td.Set(\"hosted_zone_id\", dbc.HostedZoneId)\n\td.Set(\"iam_database_authentication_enabled\", dbc.IAMDatabaseAuthenticationEnabled)\n\n\tvar roles []string\n\tfor _, r := range dbc.AssociatedRoles {\n\t\troles = append(roles, aws.StringValue(r.RoleArn))\n\t}\n\tif err := d.Set(\"iam_roles\", roles); err != nil {\n\t\treturn fmt.Errorf(\"error setting iam_roles: %s\", err)\n\t}\n\n\td.Set(\"kms_key_id\", dbc.KmsKeyId)\n\td.Set(\"master_username\", dbc.MasterUsername)\n\td.Set(\"port\", dbc.Port)\n\td.Set(\"preferred_backup_window\", dbc.PreferredBackupWindow)\n\td.Set(\"preferred_maintenance_window\", dbc.PreferredMaintenanceWindow)\n\td.Set(\"reader_endpoint\", dbc.ReaderEndpoint)\n\td.Set(\"replication_source_identifier\", dbc.ReplicationSourceIdentifier)\n\n\td.Set(\"storage_encrypted\", dbc.StorageEncrypted)\n\n\tvar vpcg []string\n\tfor _, g := range dbc.VpcSecurityGroups {\n\t\tvpcg = append(vpcg, aws.StringValue(g.VpcSecurityGroupId))\n\t}\n\tif err := d.Set(\"vpc_security_group_ids\", vpcg); err != nil {\n\t\treturn fmt.Errorf(\"error setting vpc_security_group_ids: %s\", err)\n\t}\n\n\t\/\/ Fetch and save tags\n\tif err := saveTagsRDS(conn, d, aws.StringValue(dbc.DBClusterArn)); err != nil {\n\t\tlog.Printf(\"[WARN] Failed to save tags for RDS Cluster (%s): %s\", aws.StringValue(dbc.DBClusterIdentifier), err)\n\t}\n\n\treturn nil\n}\n<commit_msg>use keyvaluetags (#10724)<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/rds\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/keyvaluetags\"\n)\n\nfunc dataSourceAwsRdsCluster() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceAwsRdsClusterRead,\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\n\t\t\t\"cluster_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\n\t\t\t\"availability_zones\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tComputed: true,\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"backup_retention_period\": {\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"cluster_members\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tComputed: true,\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"cluster_resource_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"database_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"db_subnet_group_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"db_cluster_parameter_group_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"enabled_cloudwatch_logs_exports\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\n\t\t\t\"endpoint\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"engine\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"engine_version\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"final_snapshot_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"iam_database_authentication_enabled\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"iam_roles\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\n\t\t\t\"kms_key_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"master_username\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"preferred_backup_window\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"preferred_maintenance_window\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t\tStateFunc: func(val interface{}) string {\n\t\t\t\t\tif val == nil {\n\t\t\t\t\t\treturn \"\"\n\t\t\t\t\t}\n\t\t\t\t\treturn strings.ToLower(val.(string))\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"port\": {\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"reader_endpoint\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"hosted_zone_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"replication_source_identifier\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"storage_encrypted\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchemaComputed(),\n\n\t\t\t\"vpc_security_group_ids\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc dataSourceAwsRdsClusterRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).rdsconn\n\n\tdbClusterIdentifier := d.Get(\"cluster_identifier\").(string)\n\n\tparams := &rds.DescribeDBClustersInput{\n\t\tDBClusterIdentifier: aws.String(dbClusterIdentifier),\n\t}\n\tlog.Printf(\"[DEBUG] Reading RDS Cluster: %s\", params)\n\tresp, err := conn.DescribeDBClusters(params)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: %s\", err)\n\t}\n\n\tif resp == nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: empty response for: %s\", params)\n\t}\n\n\tvar dbc *rds.DBCluster\n\tfor _, c := range resp.DBClusters {\n\t\tif aws.StringValue(c.DBClusterIdentifier) == dbClusterIdentifier {\n\t\t\tdbc = c\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif dbc == nil {\n\t\treturn fmt.Errorf(\"Error retrieving RDS cluster: cluster not found in response for: %s\", params)\n\t}\n\n\td.SetId(aws.StringValue(dbc.DBClusterIdentifier))\n\n\tif err := d.Set(\"availability_zones\", aws.StringValueSlice(dbc.AvailabilityZones)); err != nil {\n\t\treturn fmt.Errorf(\"error setting availability_zones: %s\", err)\n\t}\n\n\tarn := dbc.DBClusterArn\n\td.Set(\"arn\", arn)\n\td.Set(\"backtrack_window\", int(aws.Int64Value(dbc.BacktrackWindow)))\n\td.Set(\"backup_retention_period\", dbc.BackupRetentionPeriod)\n\td.Set(\"cluster_identifier\", dbc.DBClusterIdentifier)\n\n\tvar cm []string\n\tfor _, m := range dbc.DBClusterMembers {\n\t\tcm = append(cm, aws.StringValue(m.DBInstanceIdentifier))\n\t}\n\tif err := d.Set(\"cluster_members\", cm); err != nil {\n\t\treturn fmt.Errorf(\"error setting cluster_members: %s\", err)\n\t}\n\n\td.Set(\"cluster_resource_id\", dbc.DbClusterResourceId)\n\n\t\/\/ Only set the DatabaseName if it is not nil. There is a known API bug where\n\t\/\/ RDS accepts a DatabaseName but does not return it, causing a perpetual\n\t\/\/ diff.\n\t\/\/\tSee https:\/\/github.com\/hashicorp\/terraform\/issues\/4671 for backstory\n\tif dbc.DatabaseName != nil {\n\t\td.Set(\"database_name\", dbc.DatabaseName)\n\t}\n\n\td.Set(\"db_cluster_parameter_group_name\", dbc.DBClusterParameterGroup)\n\td.Set(\"db_subnet_group_name\", dbc.DBSubnetGroup)\n\n\tif err := d.Set(\"enabled_cloudwatch_logs_exports\", aws.StringValueSlice(dbc.EnabledCloudwatchLogsExports)); err != nil {\n\t\treturn fmt.Errorf(\"error setting enabled_cloudwatch_logs_exports: %s\", err)\n\t}\n\n\td.Set(\"endpoint\", dbc.Endpoint)\n\td.Set(\"engine_version\", dbc.EngineVersion)\n\td.Set(\"engine\", dbc.Engine)\n\td.Set(\"hosted_zone_id\", dbc.HostedZoneId)\n\td.Set(\"iam_database_authentication_enabled\", dbc.IAMDatabaseAuthenticationEnabled)\n\n\tvar roles []string\n\tfor _, r := range dbc.AssociatedRoles {\n\t\troles = append(roles, aws.StringValue(r.RoleArn))\n\t}\n\tif err := d.Set(\"iam_roles\", roles); err != nil {\n\t\treturn fmt.Errorf(\"error setting iam_roles: %s\", err)\n\t}\n\n\td.Set(\"kms_key_id\", dbc.KmsKeyId)\n\td.Set(\"master_username\", dbc.MasterUsername)\n\td.Set(\"port\", dbc.Port)\n\td.Set(\"preferred_backup_window\", dbc.PreferredBackupWindow)\n\td.Set(\"preferred_maintenance_window\", dbc.PreferredMaintenanceWindow)\n\td.Set(\"reader_endpoint\", dbc.ReaderEndpoint)\n\td.Set(\"replication_source_identifier\", dbc.ReplicationSourceIdentifier)\n\n\td.Set(\"storage_encrypted\", dbc.StorageEncrypted)\n\n\tvar vpcg []string\n\tfor _, g := range dbc.VpcSecurityGroups {\n\t\tvpcg = append(vpcg, aws.StringValue(g.VpcSecurityGroupId))\n\t}\n\tif err := d.Set(\"vpc_security_group_ids\", vpcg); err != nil {\n\t\treturn fmt.Errorf(\"error setting vpc_security_group_ids: %s\", err)\n\t}\n\n\ttags, err := keyvaluetags.RdsListTags(conn, *arn)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for RDS Cluster (%s): %s\", *arn, 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<|endoftext|>"}
{"text":"<commit_before>package parsley\n\n\/\/ Context is the parsing context passed to all parsers\ntype Context struct {\n\tfileSet     *FileSet\n\treader      Reader\n\tresultCache ResultCache\n\terr         Error\n\tcallCount   int\n}\n\n\/\/ NewContext creates a new parsing context\nfunc NewContext(fileSet *FileSet, reader Reader) *Context {\n\treturn &Context{\n\t\tfileSet:     fileSet,\n\t\treader:      reader,\n\t\tresultCache: NewResultCache(),\n\t}\n}\n\n\/\/ FileSet returns with the file set\nfunc (c *Context) FileSet() *FileSet {\n\treturn c.fileSet\n}\n\n\/\/ Reader returns with the reader\nfunc (c *Context) Reader() Reader {\n\treturn c.reader\n}\n\n\/\/ ResultCache returns with the result cache object\nfunc (c *Context) ResultCache() ResultCache {\n\treturn c.resultCache\n}\n\n\/\/ RegisterCall registers a call\nfunc (c *Context) RegisterCall() {\n\tc.callCount++\n}\n\n\/\/ CallCount returns with the call count\nfunc (c *Context) CallCount() int {\n\treturn c.callCount\n}\n\n\/\/ SetError saves the error if it has the highest position for found errors\nfunc (c *Context) SetError(err Error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tif c.err == nil || err.Pos() >= c.err.Pos() {\n\t\tc.err = err\n\t}\n}\n\n\/\/ Error returns with the parse error with the highest position (if any)\nfunc (c *Context) Error() Error {\n\treturn c.err\n}\n<commit_msg>Add keyword handling to context<commit_after>package parsley\n\n\/\/ Context is the parsing context passed to all parsers\ntype Context struct {\n\tfileSet     *FileSet\n\treader      Reader\n\tresultCache ResultCache\n\terr         Error\n\tcallCount   int\n\tkeywords    map[string]struct{}\n}\n\n\/\/ NewContext creates a new parsing context\nfunc NewContext(fileSet *FileSet, reader Reader) *Context {\n\treturn &Context{\n\t\tfileSet:     fileSet,\n\t\treader:      reader,\n\t\tresultCache: NewResultCache(),\n\t\tkeywords:    make(map[string]struct{}, 64),\n\t}\n}\n\n\/\/ FileSet returns with the file set\nfunc (c *Context) FileSet() *FileSet {\n\treturn c.fileSet\n}\n\n\/\/ Reader returns with the reader\nfunc (c *Context) Reader() Reader {\n\treturn c.reader\n}\n\n\/\/ ResultCache returns with the result cache object\nfunc (c *Context) ResultCache() ResultCache {\n\treturn c.resultCache\n}\n\n\/\/ RegisterCall registers a call\nfunc (c *Context) RegisterCall() {\n\tc.callCount++\n}\n\n\/\/ CallCount returns with the call count\nfunc (c *Context) CallCount() int {\n\treturn c.callCount\n}\n\n\/\/ SetError saves the error if it has the highest position for found errors\nfunc (c *Context) SetError(err Error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\tif c.err == nil || err.Pos() >= c.err.Pos() {\n\t\tc.err = err\n\t}\n}\n\n\/\/ Error returns with the parse error with the highest position (if any)\nfunc (c *Context) Error() Error {\n\treturn c.err\n}\n\n\/\/ RegisterKeywords registers one or more keywords\nfunc (c *Context) RegisterKeywords(keywords ...string) {\n\tfor _, keyword := range keywords {\n\t\tc.keywords[keyword] = struct{}{}\n\t}\n}\n\n\/\/ IsKeyword checks if the given string is a keyword\nfunc (c *Context) IsKeyword(word string) bool {\n\t_, ok := c.keywords[word]\n\treturn ok\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"html\"\n\t\"strings\"\n\t\"flag\"\n\t\"fmt\"\n)\n\n\/\/ cmdline argument\nvar portNumber = flag.Int(\"port\", 8085, \"Port number listening on\")\n\n\ntype Command struct {\n\tCmd string `json:\"cmd\"`\n\tEnv string `json:\"env\"`\n}\n\nfunc handler(responseWriter http.ResponseWriter, request *http.Request) {\n\tdefer request.Body.Close()\n\n\tcmdIn := &Command{}\n\tif err := json.NewDecoder(request.Body).Decode(&cmdIn); err != nil {\n\t\twriteResponse(responseWriter, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tcmdElements := strings.Split(cmdIn.Cmd, \" \")\n\tcmd := exec.Command(cmdElements[0], cmdElements[1:]...)\n\n\tif len(cmdIn.Env) > 0 {\n\t\tenv := os.Environ()\n\t\tenv = append(env, cmdIn.Env)\n\t\tcmd.Env = env\n\t}\n\n\tpath := html.EscapeString(request.URL.Path)\n\tif strings.HasSuffix(path, \"\/sync\") {\n\t\toutput, error := cmd.CombinedOutput()\n\n\t\tif error != nil {\n\t\t\twriteResponse(responseWriter, http.StatusBadRequest, error.Error())\n\t\t\treturn\n\t\t}\n\n\t\tresponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\t\twriteResponse(responseWriter, http.StatusAccepted, string(output[:]))\n\n\t} else if strings.HasSuffix(path, \"\/async\") {\n\t\terror := cmd.Start()\n\n\t\tif error != nil {\n\t\t\twriteResponse(responseWriter, http.StatusBadRequest, error.Error())\n\t\t\treturn\n\t\t}\n\n\t\twriteResponse(responseWriter, http.StatusAccepted, \"started\")\n\n\t} else {\n\t\twriteResponse(responseWriter, http.StatusBadRequest, \"use \/sync or \/async\")\n\n\t}\n}\n\nfunc writeResponse(responseWriter http.ResponseWriter, code int, message string) {\n\tresponseWriter.WriteHeader(code)\n\tdata := struct {\n\t\t\tCode    int    `json:\"code\"`\n\t\t\tMessage string `json:\"message\"`\n    }{\n\t\tcode,\n\t\tmessage,\n\t}\n\tresponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(responseWriter).Encode(&data)\n}\n\nfunc main() {\n\tflag.Parse()\n\tlistenOn := fmt.Sprintf(\":%v\", *portNumber)\n\n    http.HandleFunc(\"\/\", handler)\n    http.ListenAndServe(listenOn, nil)\n}<commit_msg>refomratting go code<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\n\/\/ cmdline argument\nvar portNumber = flag.Int(\"port\", 8085, \"Port number listening on\")\n\ntype Command struct {\n\tCmd string `json:\"cmd\"`\n\tEnv string `json:\"env\"`\n}\n\nfunc handler(responseWriter http.ResponseWriter, request *http.Request) {\n\tdefer request.Body.Close()\n\n\tcmdIn := &Command{}\n\tif err := json.NewDecoder(request.Body).Decode(&cmdIn); err != nil {\n\t\twriteResponse(responseWriter, http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tcmdElements := strings.Split(cmdIn.Cmd, \" \")\n\tcmd := exec.Command(cmdElements[0], cmdElements[1:]...)\n\n\tif len(cmdIn.Env) > 0 {\n\t\tenv := os.Environ()\n\t\tenv = append(env, cmdIn.Env)\n\t\tcmd.Env = env\n\t}\n\n\tpath := html.EscapeString(request.URL.Path)\n\tif strings.HasSuffix(path, \"\/sync\") {\n\t\toutput, error := cmd.CombinedOutput()\n\n\t\tif error != nil {\n\t\t\twriteResponse(responseWriter, http.StatusBadRequest, error.Error())\n\t\t\treturn\n\t\t}\n\n\t\tresponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\t\twriteResponse(responseWriter, http.StatusAccepted, string(output[:]))\n\n\t} else if strings.HasSuffix(path, \"\/async\") {\n\t\terror := cmd.Start()\n\n\t\tif error != nil {\n\t\t\twriteResponse(responseWriter, http.StatusBadRequest, error.Error())\n\t\t\treturn\n\t\t}\n\n\t\twriteResponse(responseWriter, http.StatusAccepted, \"started\")\n\n\t} else {\n\t\twriteResponse(responseWriter, http.StatusBadRequest, \"use \/sync or \/async\")\n\n\t}\n}\n\nfunc writeResponse(responseWriter http.ResponseWriter, code int, message string) {\n\tresponseWriter.WriteHeader(code)\n\tdata := struct {\n\t\tCode    int    `json:\"code\"`\n\t\tMessage string `json:\"message\"`\n\t}{\n\t\tcode,\n\t\tmessage,\n\t}\n\tresponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(responseWriter).Encode(&data)\n}\n\nfunc main() {\n\tflag.Parse()\n\tlistenOn := fmt.Sprintf(\":%v\", *portNumber)\n\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(listenOn, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package todolist\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestAddTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tyear := strconv.Itoa(time.Now().Year())\n\n\tapp.AddTodo(\"a do some stuff due may 23\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"do some stuff\", todo.Subject)\n\tassert.Equal(fmt.Sprintf(\"%s-05-23\", year), todo.Due)\n\tassert.Equal(false, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal(\"\", todo.CompletedDate)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal([]string{}, todo.Contexts)\n}\n\nfunc TestAddDoneTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\n\tapp.AddDoneTodo(\"Groked how to do done todos @pop\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"Groked how to do done todos @pop\", todo.Subject)\n\tassert.Equal(true, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal(1, len(todo.Contexts))\n\tassert.Equal(\"pop\", todo.Contexts[0])\n}\n\nfunc TestAddTodoWithEuropeanDates(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\n\tapp.AddTodo(\"a do some stuff due 23 may\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"do some stuff\", todo.Subject)\n\tassert.Equal(\"2017-05-23\", todo.Due)\n\tassert.Equal(false, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal(\"\", todo.CompletedDate)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal([]string{}, todo.Contexts)\n}\n\nfunc TestAddEmptyTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\n\tapp.AddTodo(\"a\")\n\tapp.AddTodo(\"a      \")\n\tapp.AddTodo(\"a\\t\\t\\t\\t\")\n\tapp.AddTodo(\"a\\t \\t  \\t   \\t\")\n\n\tassert.Equal(len(app.TodoList.Data), 0)\n}\n\nfunc TestListbyProject(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tapp.Load()\n\n\t\/\/ create three todos w\/wo a project\n\tapp.AddTodo(\"this is a test +testme\")\n\tapp.AddTodo(\"this is a test +testmetoo @work\")\n\tapp.AddTodo(\"this is a test with no projects\")\n\tapp.CompleteTodo(\"c 1\")\n\n\t\/\/ simulate listTodos\n\tinput := \"l by p\"\n\tfiltered := NewFilter(app.TodoList.Todos()).Filter(input)\n\tgrouped := app.getGroups(input, filtered)\n\n\tassert.Equal(3, len(grouped.Groups))\n\n\t\/\/ testme project has 1 todo and its completed\n\tassert.Equal(1, len(grouped.Groups[\"testme\"]))\n\tassert.Equal(true, grouped.Groups[\"testme\"][0].Completed)\n\n\t\/\/ testmetoo project has 1 todo and it has a context\n\tassert.Equal(1, len(grouped.Groups[\"testmetoo\"]))\n\tassert.Equal(1, len(grouped.Groups[\"testmetoo\"][0].Contexts))\n\tassert.Equal(\"work\", grouped.Groups[\"testmetoo\"][0].Contexts[0])\n}\n\nfunc TestListbyContext(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tapp.Load()\n\n\t\/\/ create three todos w\/wo a context\n\tapp.AddTodo(\"this is a test +testme\")\n\tapp.AddTodo(\"this is a test +testmetoo @work\")\n\tapp.AddTodo(\"this is a test with no projects\")\n\tapp.CompleteTodo(\"c 1\")\n\n\t\/\/ simulate listTodos\n\tinput := \"l by c\"\n\tfiltered := NewFilter(app.TodoList.Todos()).Filter(input)\n\tgrouped := app.getGroups(input, filtered)\n\n\tassert.Equal(2, len(grouped.Groups))\n\n\t\/\/ work context has 1 todo and it has a project of testmetoo\n\tassert.Equal(1, len(grouped.Groups[\"work\"]))\n\tassert.Equal(1, len(grouped.Groups[\"work\"][0].Projects))\n\tassert.Equal(\"testmetoo\", grouped.Groups[\"work\"][0].Projects[0])\n\n\t\/\/ There are two todos with no context\n\tassert.Equal(2, len(grouped.Groups[\"No contexts\"]))\n\n\t\/\/ check to see if the a todos with no context contain a\n\t\/\/ completed todo\n\tvar hasACompletedTodo bool\n\tfor _, todo := range grouped.Groups[\"No contexts\"] {\n\t\tif todo.Completed {\n\t\t\thasACompletedTodo = true\n\t\t}\n\t}\n\tassert.Equal(true, hasACompletedTodo)\n}\n\nfunc TestGetId(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\t\/\/ not a valid id\n\tassert.Equal(-1, app.getId(\"p\"))\n\t\/\/ a single digit id\n\tassert.Equal(6, app.getId(\"6\"))\n\t\/\/ a double digit id\n\tassert.Equal(66, app.getId(\"66\"))\n}\n\nfunc TestGetIds(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\t\/\/ no valid id here\n\tassert.Equal(0, len(app.getIds(\"p\")))\n\t\/\/ one valid value here\n\tassert.Equal([]int{6}, app.getIds(\"6\"))\n\t\/\/ lots of single post numbers\n\tassert.Equal([]int{6, 10, 8, 4}, app.getIds(\"6,10,8,4\"))\n\t\/\/ a correct range\n\tassert.Equal([]int{6, 7, 8}, app.getIds(\"6-8\"))\n\t\/\/ some incorrect ranges\n\tassert.Equal(0, len(app.getIds(\"6-6\")))\n\tassert.Equal(0, len(app.getIds(\"8-6\")))\n\t\/\/ some compsite ranges\n\tassert.Equal([]int{5, 6, 7, 8, 10, 11, 9}, app.getIds(\"5,6-8,10-11,9\"))\n}\n<commit_msg>fix test failing due to new year<commit_after>package todolist\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestAddTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tyear := strconv.Itoa(time.Now().Year())\n\n\tapp.AddTodo(\"a do some stuff due may 23\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"do some stuff\", todo.Subject)\n\tassert.Equal(fmt.Sprintf(\"%s-05-23\", year), todo.Due)\n\tassert.Equal(false, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal(\"\", todo.CompletedDate)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal([]string{}, todo.Contexts)\n}\n\nfunc TestAddDoneTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\n\tapp.AddDoneTodo(\"Groked how to do done todos @pop\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"Groked how to do done todos @pop\", todo.Subject)\n\tassert.Equal(true, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal(1, len(todo.Contexts))\n\tassert.Equal(\"pop\", todo.Contexts[0])\n}\n\nfunc TestAddTodoWithEuropeanDates(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tyear := strconv.Itoa(time.Now().Year())\n\n\tapp.AddTodo(\"a do some stuff due 23 may\")\n\n\ttodo := app.TodoList.FindById(1)\n\tassert.Equal(\"do some stuff\", todo.Subject)\n\tassert.Equal(fmt.Sprintf(\"%s-05-23\", year), todo.Due)\n\tassert.Equal(false, todo.Completed)\n\tassert.Equal(false, todo.Archived)\n\tassert.Equal(false, todo.IsPriority)\n\tassert.Equal(\"\", todo.CompletedDate)\n\tassert.Equal([]string{}, todo.Projects)\n\tassert.Equal([]string{}, todo.Contexts)\n}\n\nfunc TestAddEmptyTodo(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\n\tapp.AddTodo(\"a\")\n\tapp.AddTodo(\"a      \")\n\tapp.AddTodo(\"a\\t\\t\\t\\t\")\n\tapp.AddTodo(\"a\\t \\t  \\t   \\t\")\n\n\tassert.Equal(len(app.TodoList.Data), 0)\n}\n\nfunc TestListbyProject(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tapp.Load()\n\n\t\/\/ create three todos w\/wo a project\n\tapp.AddTodo(\"this is a test +testme\")\n\tapp.AddTodo(\"this is a test +testmetoo @work\")\n\tapp.AddTodo(\"this is a test with no projects\")\n\tapp.CompleteTodo(\"c 1\")\n\n\t\/\/ simulate listTodos\n\tinput := \"l by p\"\n\tfiltered := NewFilter(app.TodoList.Todos()).Filter(input)\n\tgrouped := app.getGroups(input, filtered)\n\n\tassert.Equal(3, len(grouped.Groups))\n\n\t\/\/ testme project has 1 todo and its completed\n\tassert.Equal(1, len(grouped.Groups[\"testme\"]))\n\tassert.Equal(true, grouped.Groups[\"testme\"][0].Completed)\n\n\t\/\/ testmetoo project has 1 todo and it has a context\n\tassert.Equal(1, len(grouped.Groups[\"testmetoo\"]))\n\tassert.Equal(1, len(grouped.Groups[\"testmetoo\"][0].Contexts))\n\tassert.Equal(\"work\", grouped.Groups[\"testmetoo\"][0].Contexts[0])\n}\n\nfunc TestListbyContext(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\tapp.Load()\n\n\t\/\/ create three todos w\/wo a context\n\tapp.AddTodo(\"this is a test +testme\")\n\tapp.AddTodo(\"this is a test +testmetoo @work\")\n\tapp.AddTodo(\"this is a test with no projects\")\n\tapp.CompleteTodo(\"c 1\")\n\n\t\/\/ simulate listTodos\n\tinput := \"l by c\"\n\tfiltered := NewFilter(app.TodoList.Todos()).Filter(input)\n\tgrouped := app.getGroups(input, filtered)\n\n\tassert.Equal(2, len(grouped.Groups))\n\n\t\/\/ work context has 1 todo and it has a project of testmetoo\n\tassert.Equal(1, len(grouped.Groups[\"work\"]))\n\tassert.Equal(1, len(grouped.Groups[\"work\"][0].Projects))\n\tassert.Equal(\"testmetoo\", grouped.Groups[\"work\"][0].Projects[0])\n\n\t\/\/ There are two todos with no context\n\tassert.Equal(2, len(grouped.Groups[\"No contexts\"]))\n\n\t\/\/ check to see if the a todos with no context contain a\n\t\/\/ completed todo\n\tvar hasACompletedTodo bool\n\tfor _, todo := range grouped.Groups[\"No contexts\"] {\n\t\tif todo.Completed {\n\t\t\thasACompletedTodo = true\n\t\t}\n\t}\n\tassert.Equal(true, hasACompletedTodo)\n}\n\nfunc TestGetId(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\t\/\/ not a valid id\n\tassert.Equal(-1, app.getId(\"p\"))\n\t\/\/ a single digit id\n\tassert.Equal(6, app.getId(\"6\"))\n\t\/\/ a double digit id\n\tassert.Equal(66, app.getId(\"66\"))\n}\n\nfunc TestGetIds(t *testing.T) {\n\tassert := assert.New(t)\n\tapp := &App{TodoList: &TodoList{}, TodoStore: &MemoryStore{}}\n\t\/\/ no valid id here\n\tassert.Equal(0, len(app.getIds(\"p\")))\n\t\/\/ one valid value here\n\tassert.Equal([]int{6}, app.getIds(\"6\"))\n\t\/\/ lots of single post numbers\n\tassert.Equal([]int{6, 10, 8, 4}, app.getIds(\"6,10,8,4\"))\n\t\/\/ a correct range\n\tassert.Equal([]int{6, 7, 8}, app.getIds(\"6-8\"))\n\t\/\/ some incorrect ranges\n\tassert.Equal(0, len(app.getIds(\"6-6\")))\n\tassert.Equal(0, len(app.getIds(\"8-6\")))\n\t\/\/ some compsite ranges\n\tassert.Equal([]int{5, 6, 7, 8, 10, 11, 9}, app.getIds(\"5,6-8,10-11,9\"))\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>blockmanager: move db read condition last<commit_after><|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 listener\n\nimport (\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/db\"\n\t\"github.com\/webx-top\/db\/lib\/factory\"\n\n\t\"github.com\/admpub\/nging\/application\/dbschema\"\n\tmodelFile \"github.com\/admpub\/nging\/application\/model\/file\"\n)\n\nvar DBI = func() *factory.DBI {\n\treturn dbschema.DBI\n}\n\n\/\/ New 实例化监听器具\nfunc New(cb Callback, embedded bool, seperators ...string) *FileRelation {\n\tvar seperator string\n\tif len(seperators) > 0 {\n\t\tseperator = seperators[0]\n\t}\n\treturn &FileRelation{Embedded: embedded, Seperator: seperator, callback: cb}\n}\n\ntype Callback func(m factory.Model) (tableID string, content string, property *Property)\n\ntype Property struct {\n\tEmbedded  bool   \/\/ 是否为嵌入图片\n\tSeperator string \/\/ 文件字段中多个文件路径之间的分隔符，空字符串代表为单个文件\n\tUpdate    func(event string, content string) error\n\tExit      bool\n}\n\nfunc NewProperty() *Property {\n\treturn &Property{}\n}\n\nfunc NewProUP(m factory.Model, cond db.Compound) *Property {\n\treturn NewProperty().GenUpdater(m, cond)\n}\n\nfunc (pro *Property) GenUpdater(m factory.Model, cond db.Compound) *Property {\n\tpro.Update = func(field string, content string) error {\n\t\terr := m.EventOFF().SetField(nil, field, content, cond)\n\t\tm.EventON()\n\t\treturn err\n\t}\n\treturn pro\n}\n\n\/\/ FileRelation 文件关联数据监听\n\/\/ FileRelation.SetTable(`table`,`field`).ListenDefault()\ntype FileRelation struct {\n\tTableName  string      \/\/ 数据表名称\n\tFieldName  string      \/\/ 数据表字段名\n\tUpdateCond interface{} \/\/ 主键字段名称\/或\n\tEmbedded   bool        \/\/ 是否为嵌入图片\n\tSeperator  string      \/\/ 文件字段中多个文件路径之间的分隔符，空字符串代表为单个文件\n\tcallback   Callback    \/\/根据模型获取表行ID和内容\n\tdbi        *factory.DBI\n}\n\nfunc (f *FileRelation) SetSeperator(seperator string) *FileRelation {\n\tf.Seperator = seperator\n\treturn f\n}\n\nfunc (f *FileRelation) Callback() Callback {\n\treturn f.callback\n}\n\nfunc (f *FileRelation) SetTable(table string, field string) *FileRelation {\n\tf.TableName = table\n\tf.FieldName = field\n\treturn f\n}\n\nfunc (f *FileRelation) SetDBI(dbi *factory.DBI) *FileRelation {\n\tf.dbi = dbi\n\treturn f\n}\n\nfunc (f *FileRelation) SetEmbedded(embedded bool) *FileRelation {\n\tf.Embedded = embedded\n\treturn f\n}\n\nfunc (f *FileRelation) ListenDefault() *FileRelation {\n\treturn f.Listen(`created`, `updated`, `deleted`)\n}\n\nfunc (f *FileRelation) attachUpdateEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, editColumns ...string) error {\n\t\tif len(editColumns) > 0 && !com.InSlice(f.FieldName, editColumns) {\n\t\t\treturn nil\n\t\t}\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tvar update func(string, string) error\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t\tupdate = property.Update\n\t\t}\n\t\t\/\/println(event+`=========`, f.TableName, f.FieldName, tableID, content)\n\t\tif update == nil {\n\t\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\t}\n\t\trawContent := content\n\t\terr := fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rawContent != content {\n\t\t\terr = update(f.FieldName, content)\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc (f *FileRelation) attachEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, _ ...string) error {\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tvar update func(string, string) error\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t\tupdate = property.Update\n\t\t}\n\t\tif update == nil {\n\t\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\t}\n\t\trawContent := content\n\t\terr := fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rawContent != content {\n\t\t\terr = update(f.FieldName, content)\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc (f *FileRelation) attachDeleteEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, _ ...string) error {\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t}\n\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t}\n}\n\nfunc (f *FileRelation) DBI() *factory.DBI {\n\tdbi := f.dbi\n\tif dbi == nil {\n\t\tdbi = DBI()\n\t}\n\treturn dbi\n}\n\nfunc (f *FileRelation) Listen(events ...string) *FileRelation {\n\tdbi := f.DBI()\n\tfor _, event := range events {\n\t\tswitch event {\n\t\tcase `updating`, `updated`:\n\t\t\tdbi.On(event, f.attachUpdateEvent(event), f.TableName)\n\t\tcase `deleting`, `deleted`:\n\t\t\tdbi.On(event, f.attachDeleteEvent(event), f.TableName)\n\t\tdefault:\n\t\t\tdbi.On(event, f.attachEvent(event), f.TableName)\n\t\t}\n\t}\n\treturn f\n}\n\nfunc (f *FileRelation) On(event string, h factory.EventHandler) *FileRelation {\n\tf.DBI().On(event, h, f.TableName)\n\treturn f\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 listener\n\nimport (\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/db\"\n\t\"github.com\/webx-top\/db\/lib\/factory\"\n\n\t\"github.com\/admpub\/nging\/application\/dbschema\"\n\tmodelFile \"github.com\/admpub\/nging\/application\/model\/file\"\n)\n\nvar DBI = func() *factory.DBI {\n\treturn dbschema.DBI\n}\n\n\/\/ New 实例化监听器具\nfunc New(cb Callback, embedded bool, seperators ...string) *FileRelation {\n\tvar seperator string\n\tif len(seperators) > 0 {\n\t\tseperator = seperators[0]\n\t}\n\treturn &FileRelation{Embedded: embedded, Seperator: seperator, callback: cb}\n}\n\ntype Callback func(m factory.Model) (tableID string, content string, property *Property)\n\ntype Property struct {\n\tEmbedded  bool   \/\/ 是否为嵌入图片\n\tSeperator string \/\/ 文件字段中多个文件路径之间的分隔符，空字符串代表为单个文件\n\tUpdate    func(event string, content string) error\n\tExit      bool\n}\n\nfunc NewProperty() *Property {\n\treturn &Property{}\n}\n\nfunc NewProUP(m factory.Model, cond db.Compound) *Property {\n\treturn NewProperty().GenUpdater(m, cond)\n}\n\nfunc (pro *Property) GenUpdater(m factory.Model, cond db.Compound) *Property {\n\tpro.Update = func(field string, content string) error {\n\t\terr := m.EventOFF().SetField(nil, field, content, cond)\n\t\tm.EventON()\n\t\treturn err\n\t}\n\treturn pro\n}\n\n\/\/ FileRelation 文件关联数据监听\n\/\/ FileRelation.SetTable(`table`,`field`).ListenDefault()\ntype FileRelation struct {\n\tTableName string   \/\/ 数据表名称\n\tFieldName string   \/\/ 数据表字段名\n\tEmbedded  bool     \/\/ 是否为嵌入图片\n\tSeperator string   \/\/ 文件字段中多个文件路径之间的分隔符，空字符串代表为单个文件\n\tcallback  Callback \/\/根据模型获取表行ID和内容\n\tdbi       *factory.DBI\n}\n\nfunc (f *FileRelation) SetSeperator(seperator string) *FileRelation {\n\tf.Seperator = seperator\n\treturn f\n}\n\nfunc (f *FileRelation) Callback() Callback {\n\treturn f.callback\n}\n\nfunc (f *FileRelation) SetTable(table string, field string) *FileRelation {\n\tf.TableName = table\n\tf.FieldName = field\n\treturn f\n}\n\nfunc (f *FileRelation) SetDBI(dbi *factory.DBI) *FileRelation {\n\tf.dbi = dbi\n\treturn f\n}\n\nfunc (f *FileRelation) SetEmbedded(embedded bool) *FileRelation {\n\tf.Embedded = embedded\n\treturn f\n}\n\nfunc (f *FileRelation) ListenDefault() *FileRelation {\n\treturn f.Listen(`created`, `updated`, `deleted`)\n}\n\nfunc (f *FileRelation) attachUpdateEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, editColumns ...string) error {\n\t\tif len(editColumns) > 0 && !com.InSlice(f.FieldName, editColumns) {\n\t\t\treturn nil\n\t\t}\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tvar update func(string, string) error\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t\tupdate = property.Update\n\t\t}\n\t\t\/\/println(event+`=========`, f.TableName, f.FieldName, tableID, content)\n\t\tif update == nil {\n\t\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\t}\n\t\trawContent := content\n\t\terr := fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rawContent != content {\n\t\t\terr = update(f.FieldName, content)\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc (f *FileRelation) attachEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, _ ...string) error {\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tvar update func(string, string) error\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t\tupdate = property.Update\n\t\t}\n\t\tif update == nil {\n\t\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\t}\n\t\trawContent := content\n\t\terr := fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif rawContent != content {\n\t\t\terr = update(f.FieldName, content)\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc (f *FileRelation) attachDeleteEvent(event string) func(m factory.Model, editColumns ...string) error {\n\tseperator := f.Seperator\n\tembedded := f.Embedded\n\tcallback := f.callback\n\treturn func(m factory.Model, _ ...string) error {\n\t\tfileM := modelFile.NewEmbedded(m.Context())\n\t\ttableID, content, property := callback(m)\n\t\tif property != nil {\n\t\t\tif property.Exit {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseperator = property.Seperator\n\t\t\tembedded = property.Embedded\n\t\t}\n\t\treturn fileM.Updater(f.TableName, f.FieldName, tableID).SetSeperator(seperator).Handle(event, &content, embedded)\n\t}\n}\n\nfunc (f *FileRelation) DBI() *factory.DBI {\n\tdbi := f.dbi\n\tif dbi == nil {\n\t\tdbi = DBI()\n\t}\n\treturn dbi\n}\n\nfunc (f *FileRelation) Listen(events ...string) *FileRelation {\n\tdbi := f.DBI()\n\tfor _, event := range events {\n\t\tswitch event {\n\t\tcase `updating`, `updated`:\n\t\t\tdbi.On(event, f.attachUpdateEvent(event), f.TableName)\n\t\tcase `deleting`, `deleted`:\n\t\t\tdbi.On(event, f.attachDeleteEvent(event), f.TableName)\n\t\tdefault:\n\t\t\tdbi.On(event, f.attachEvent(event), f.TableName)\n\t\t}\n\t}\n\treturn f\n}\n\nfunc (f *FileRelation) On(event string, h factory.EventHandler) *FileRelation {\n\tf.DBI().On(event, h, f.TableName)\n\treturn f\n}\n<|endoftext|>"}
{"text":"<commit_before>package errors_test\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/adrg\/errors\"\n)\n\nfunc ExampleNew() {\n\terr := errors.New(\"something bad happened\")\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleErrorf() {\n\terr := errors.Errorf(\"invalid user ID: %d\", 0)\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleAnnotate() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotate returns nil.\n\terr = errors.Annotate(err, \"conversion failed\")\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleAnnotatef() {\n\tvar err error\n\n\temail := \"alice @example.com\"\n\tif strings.Contains(email, \" \") {\n\t\terr = errors.New(\"email address cannot contain spaces\")\n\t}\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotatef returns nil.\n\terr = errors.Annotatef(err, \"invalid email adddress %s\", email)\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleWrap() {\n\terrInvalid := errors.New(\"invalid data\")\n\n\t_, err := strconv.Atoi(\"this will fail\")\n\tif err != nil {\n\t\terr = errors.Wrap(errInvalid, err)\n\t}\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleUnwrap() {\n\terr := errors.Annotate(errors.New(\"first error\"), \"second error\")\n\tif next := errors.Unwrap(err); next != nil {\n\t\tfmt.Printf(\"%s\\n\", next)  \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", next)  \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", next) \/\/ Print error chain with stack details.\n\t}\n}\n\nfunc ExampleIs() {\n\terrInvalid := errors.New(\"invalid data\")\n\n\terr := errors.Annotate(errInvalid, \"validation failed\")\n\tif errors.Is(err, errInvalid) {\n\t\tfmt.Println(\"err is invalidErr\")\n\t}\n}\n\nfunc ExampleAs() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotate returns nil.\n\terr = errors.Annotate(err, \"conversion failed\")\n\n\tnErr := &strconv.NumError{}\n\tif ok := errors.As(err, &nErr); ok {\n\t\tfmt.Printf(\"error %s: parsing `%s`: %s\\n\", nErr.Func, nErr.Num, nErr.Err)\n\t}\n}\n\nfunc ExampleAs_interface() {\n\terr := errors.NewHTTP(nil, 500, \"something bad happened\")\n\terr = errors.Annotate(err, \"annotated HTTP error interface\")\n\n\tvar nErr errors.HTTP\n\tif ok := errors.As(err, &nErr); ok {\n\t\tfmt.Printf(\"%s\\n\", err)        \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)        \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)       \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(nErr)) \/\/ Print error code\n\t}\n}\n\nfunc ExampleCode() {\n\terr := errors.HTTPf(nil, http.StatusNotFound, \"invalid endpoint\")\n\n\t\/\/ Print error code.\n\tfmt.Println(errors.Code(err))\n}\n\nfunc ExampleNewHTTP() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\tif err != nil {\n\t\terr = errors.NewHTTP(err, http.StatusBadRequest, \"invalid data\")\n\n\t\tfmt.Printf(\"%s\\n\", err)       \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)       \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)      \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(err)) \/\/ Print error code.\n\t}\n}\n\nfunc ExampleHTTPf() {\n\tvalidateEmail := func(email string) error {\n\t\tif strings.Contains(email, \" \") {\n\t\t\treturn errors.New(\"email address cannot contain spaces\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\temail := \"alice @example.com\"\n\tif err := validateEmail(email); err != nil {\n\t\terr = errors.HTTPf(err, http.StatusBadRequest, \"invalid email address %s\", email)\n\n\t\tfmt.Printf(\"%s\\n\", err)       \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)       \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)      \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(err)) \/\/ Print error code.\n\t}\n}\n<commit_msg>Update function example<commit_after>package errors_test\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/adrg\/errors\"\n)\n\nfunc ExampleNew() {\n\terr := errors.New(\"something bad happened\")\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleErrorf() {\n\terr := errors.Errorf(\"invalid user ID: %d\", 0)\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleAnnotate() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotate returns nil.\n\terr = errors.Annotate(err, \"conversion failed\")\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleAnnotatef() {\n\tvar err error\n\n\temail := \"alice @example.com\"\n\tif strings.Contains(email, \" \") {\n\t\terr = errors.New(\"email address cannot contain spaces\")\n\t}\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotatef returns nil.\n\terr = errors.Annotatef(err, \"invalid email adddress %s\", email)\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleWrap() {\n\terrInvalid := errors.New(\"invalid data\")\n\n\t_, err := strconv.Atoi(\"this will fail\")\n\tif err != nil {\n\t\terr = errors.Wrap(errInvalid, err)\n\t}\n\n\tfmt.Printf(\"%s\\n\", err)  \/\/ Print error message only.\n\tfmt.Printf(\"%v\\n\", err)  \/\/ Print error chain without stack details.\n\tfmt.Printf(\"%+v\\n\", err) \/\/ Print error chain with stack details.\n}\n\nfunc ExampleUnwrap() {\n\terr := errors.Annotate(errors.New(\"first error\"), \"second error\")\n\tif next := errors.Unwrap(err); next != nil {\n\t\tfmt.Printf(\"%s\\n\", next)  \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", next)  \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", next) \/\/ Print error chain with stack details.\n\t}\n}\n\nfunc ExampleIs() {\n\terrInvalid := errors.New(\"invalid data\")\n\n\terr := errors.Annotate(errInvalid, \"validation failed\")\n\tif errors.Is(err, errInvalid) {\n\t\tfmt.Println(\"err is invalidErr\")\n\t}\n}\n\nfunc ExampleAs() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\n\t\/\/ No need to check if the original error is nil.\n\t\/\/ If err is nil, Annotate returns nil.\n\terr = errors.Annotate(err, \"conversion failed\")\n\n\tnErr := &strconv.NumError{}\n\tif ok := errors.As(err, &nErr); ok {\n\t\tfmt.Printf(\"error %s: parsing `%s`: %s\\n\", nErr.Func, nErr.Num, nErr.Err)\n\t}\n}\n\nfunc ExampleAs_interface() {\n\terr := errors.NewHTTP(nil, 500, \"something bad happened\")\n\terr = errors.Annotate(err, \"annotated HTTP error interface\")\n\n\tvar nErr errors.HTTP\n\tif ok := errors.As(err, &nErr); ok {\n\t\tfmt.Printf(\"%s\\n\", err)        \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)        \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)       \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(nErr)) \/\/ Print error code\n\t}\n}\n\nfunc ExampleCode() {\n\terr := errors.HTTPf(nil, http.StatusNotFound, \"invalid endpoint\")\n\n\t\/\/ Print error code.\n\tfmt.Println(errors.Code(err))\n}\n\nfunc ExampleNewHTTP() {\n\t_, err := strconv.Atoi(\"this will fail\")\n\tif err != nil {\n\t\terr = errors.NewHTTP(err, http.StatusBadRequest, \"invalid data\")\n\n\t\tfmt.Printf(\"%s\\n\", err)       \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)       \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)      \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(err)) \/\/ Print error code.\n\t}\n}\n\nfunc ExampleHTTPf() {\n\tvalidateEmail := func(email string) error {\n\t\tif strings.Contains(email, \" \") {\n\t\t\treturn errors.New(\"email address cannot contain spaces\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\temail := \"alice @example.com\"\n\tif err := validateEmail(email); err != nil {\n\t\terr = errors.HTTPf(err, http.StatusBadRequest, \"invalid email %s\", email)\n\n\t\tfmt.Printf(\"%s\\n\", err)       \/\/ Print error message only.\n\t\tfmt.Printf(\"%v\\n\", err)       \/\/ Print error chain without stack details.\n\t\tfmt.Printf(\"%+v\\n\", err)      \/\/ Print error chain with stack details.\n\t\tfmt.Println(errors.Code(err)) \/\/ Print error code.\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package containerd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/containerd\/containerd\"\n\t\"github.com\/containerd\/containerd\/api\/types\/task\"\n\t\"github.com\/docker\/swarmkit\/agent\/exec\"\n\t\"github.com\/docker\/swarmkit\/api\"\n\t\"github.com\/docker\/swarmkit\/log\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n)\n\ntype controller struct {\n\ttask    *api.Task\n\tadapter *containerAdapter\n\tclosed  chan struct{}\n\terr     error\n\n\tpulled     chan struct{} \/\/ closed after pull\n\tcancelPull func()        \/\/ cancels pull context if not nil\n\tpullErr    error         \/\/ pull error, protected by close of pulled\n}\n\nvar _ exec.Controller = &controller{}\n\nfunc newController(client *containerd.Client, task *api.Task, secrets exec.SecretGetter) (exec.Controller, error) {\n\tadapter, err := newContainerAdapter(client, task, secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &controller{\n\t\ttask:    task,\n\t\tadapter: adapter,\n\t\tclosed:  make(chan struct{}),\n\t}, nil\n}\n\n\/\/ ContainerStatus returns the container-specific status for the task.\nfunc (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, error) {\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tstatus := &api.ContainerStatus{\n\t\tContainerID: ctnr.ID,\n\t\tPID:         int32(ctnr.Pid),\n\t}\n\n\tif ec, ok := ctnr.ExitStatus.(exec.ExitCoder); ok {\n\t\tstatus.ExitCode = int32(ec.ExitCode())\n\t}\n\n\treturn status, nil\n}\n\n\/\/ Update takes a recent task update and applies it to the container.\nfunc (r *controller) Update(ctx context.Context, t *api.Task) error {\n\tlog.G(ctx).Warnf(\"task updates not yet supported\")\n\t\/\/ TODO(stevvooe): While assignment of tasks is idempotent, we do allow\n\t\/\/ updates of metadata, such as labelling, as well as any other properties\n\t\/\/ that make sense.\n\treturn nil\n}\n\n\/\/ Prepare creates a container and ensures the image is pulled.\n\/\/\n\/\/ If the container has already be created, exec.ErrTaskPrepared is returned.\nfunc (r *controller) Prepare(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/\/\/ Make sure all the networks that the task needs are created.\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.createNetworks(ctx); err != nil {\n\t\/\/\treturn err\n\t\/\/}\n\n\t\/\/\/\/ Make sure all the volumes that the task needs are created.\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.createVolumes(ctx); err != nil {\n\t\/\/\treturn err\n\t\/\/}\n\n\tif r.pulled == nil {\n\t\t\/\/ Launches a re-entrant pull operation associated with controller,\n\t\t\/\/ dissociating the context from the caller's context. Allows pull\n\t\t\/\/ operation to be re-entrant on calls to prepare, resuming from the\n\t\t\/\/ same point after cancellation.\n\t\tvar pctx context.Context\n\n\t\tr.pulled = make(chan struct{})\n\t\tpctx, r.cancelPull = context.WithCancel(context.Background()) \/\/ TODO(stevvooe): Bind a context to the entire controller.\n\n\t\tgo func() {\n\t\t\tdefer close(r.pulled)\n\t\t\tr.pullErr = r.adapter.pullImage(pctx)\n\t\t}()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-r.pulled:\n\t\tif r.pullErr != nil {\n\t\t\t\/\/ NOTE(stevvooe): We always try to pull the image to make sure we have\n\t\t\t\/\/ the most up to date version. This will return an error, but we only\n\t\t\t\/\/ log it. If the image truly doesn't exist, the create below will\n\t\t\t\/\/ error out.\n\t\t\t\/\/\n\t\t\t\/\/ This gives us some nice behavior where we use up to date versions of\n\t\t\t\/\/ mutable tags, but will still run if the old image is available but a\n\t\t\t\/\/ registry is down.\n\t\t\t\/\/\n\t\t\t\/\/ If you don't want this behavior, lock down your image to an\n\t\t\t\/\/ immutable tag or digest.\n\t\t\tlog.G(ctx).WithError(r.pullErr).Error(\"pulling image failed\")\n\t\t}\n\t}\n\n\tif err := r.adapter.prepare(ctx); err != nil {\n\t\tif isContainerCreateNameConflict(err) {\n\t\t\tif _, err := r.adapter.inspect(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ container is already created. success!\n\t\t\treturn exec.ErrTaskPrepared\n\t\t}\n\n\t\treturn errors.Wrap(err, \"create container failed\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Start the container. An error will be returned if the container is already started.\nfunc (r *controller) Start(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Detect whether the container has *ever* been started. If so, we don't\n\t\/\/ issue the start.\n\t\/\/\n\t\/\/ TODO(stevvooe): This is very racy. While reading inspect, another could\n\t\/\/ start the process and we could end up starting it twice.\n\tif ctnr.Status != containerd.Created {\n\t\treturn exec.ErrTaskStarted\n\t}\n\n\tif err := r.adapter.start(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"starting container failed\")\n\t}\n\n\t\/\/ TODO(ijc): Wait for HealthCheck to report OK.\n\n\treturn nil\n}\n\n\/\/ Wait on the container to exit.\nfunc (r *controller) Wait(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check the initial state and report that.\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"inspecting container failed\")\n\t}\n\n\t\/\/ TODO(ijc) this shouldn't be needed here, figure out why\n\t\/\/ .shutdown\/.remove are not being called otherwise.\n\tshutdownWithExitStatus := func() error {\n\t\terr := r.adapter.shutdown(ctx)\n\t\tif err2 := r.adapter.remove(ctx); err != nil {\n\t\t\t\/\/ Just log it, report the exit status\n\t\t\tlog.G(ctx).WithError(err2).Info(\"remove after wait failed\")\n\t\t}\n\t\treturn err\n\t}\n\tswitch ctnr.Status {\n\tcase containerd.Stopped:\n\t\treturn shutdownWithExitStatus()\n\t}\n\n\t\/\/ We do not disable FailFast for this initial call (like we\n\t\/\/ do on the retry below) since we are still halfway through\n\t\/\/ setting up the container and if containerd goes away half\n\t\/\/ way through we consider that a failure.\n\teventq, closed, err := r.adapter.events(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-eventq:\n\t\t\tswitch event.Type {\n\t\t\tcase task.Event_EXIT:\n\t\t\t\treturn shutdownWithExitStatus()\n\t\t\tcase task.Event_OOM, task.Event_CREATE, task.Event_START, task.Event_EXEC_ADDED, task.Event_PAUSED:\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"Unknown event type %s\\n\", event.Type.String())\n\t\t\t}\n\t\tcase <-closed:\n\t\t\t\/\/ restart!\n\t\t\tlog.G(ctx).Debugf(\"Restarting event stream\")\n\t\t\t\/\/ We disable FailFast for this call so that gRPC will keep\n\t\t\t\/\/ retrying while we wait for containerd to come back. Otherwise\n\t\t\t\/\/ a temporary glitch in the connection (e.g. a containerd restart)\n\t\t\t\/\/ will result in the task being declared dead even though it is\n\t\t\t\/\/ likely to be recoverable.\n\t\t\teventq, closed, err = r.adapter.events(ctx, grpc.FailFast(false))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ recheck the container state, if this fails then we may have missed a\n\t\t\tctnr, err := r.adapter.inspect(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"inspecting container on event restart failed\")\n\t\t\t}\n\t\t\tswitch ctnr.Status {\n\t\t\tcase containerd.Stopped:\n\t\t\t\treturn shutdownWithExitStatus()\n\t\t\t}\n\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-r.closed:\n\t\t\treturn r.err\n\t\t}\n\t}\n}\n\n\/\/ Shutdown the container cleanly.\nfunc (r *controller) Shutdown(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\tif err := r.adapter.shutdown(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Terminate the container, with force.\nfunc (r *controller) Terminate(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\tif err := r.adapter.terminate(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Remove the container and its resources.\nfunc (r *controller) Remove(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\t\/\/ It may be necessary to shut down the task before removing it.\n\tif err := r.Shutdown(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ This may fail if the task was already shut down.\n\t\tlog.G(ctx).WithError(err).Debug(\"shutdown failed on removal\")\n\t}\n\n\t\/\/ Try removing networks referenced in this task in case this\n\t\/\/ task is the last one referencing it\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.removeNetworks(ctx); err != nil {\n\t\/\/\tif isUnknownContainer(err) {\n\t\/\/\t\treturn nil\n\t\/\/\t}\n\n\t\/\/\treturn err\n\t\/\/}\n\n\tif err := r.adapter.remove(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Close the controller and clean up any ephemeral resources.\nfunc (r *controller) Close() error {\n\tselect {\n\tcase <-r.closed:\n\t\treturn r.err\n\tdefault:\n\t\tif r.cancelPull != nil {\n\t\t\tr.cancelPull()\n\t\t}\n\n\t\tr.err = exec.ErrControllerClosed\n\t\tclose(r.closed)\n\t}\n\treturn nil\n}\n\nfunc (r *controller) checkClosed() error {\n\tselect {\n\tcase <-r.closed:\n\t\treturn r.err\n\tdefault:\n\t\treturn nil\n\t}\n}\n\ntype exitError struct {\n\tcode  uint32\n\tcause error\n}\n\nfunc (e *exitError) Error() string {\n\tif e.cause != nil {\n\t\treturn fmt.Sprintf(\"task: non-zero exit (%v): %v\", e.code, e.cause)\n\t}\n\treturn fmt.Sprintf(\"task: non-zero exit (%v)\", e.code)\n}\n\nfunc (e *exitError) ExitCode() int {\n\treturn int(e.code)\n}\n\nfunc (e *exitError) Cause() error {\n\treturn e.cause\n}\n\nfunc makeExitError(exitStatus uint32, reason string) error {\n\tif exitStatus != 0 {\n\t\tvar cause error\n\t\tif reason != \"\" {\n\t\t\tcause = errors.New(reason)\n\t\t}\n\n\t\treturn &exitError{\n\t\t\tcode:  exitStatus,\n\t\t\tcause: cause,\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>containerd: Do not shutdown container in Wait() method<commit_after>package containerd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/containerd\/containerd\"\n\t\"github.com\/containerd\/containerd\/api\/types\/task\"\n\t\"github.com\/docker\/swarmkit\/agent\/exec\"\n\t\"github.com\/docker\/swarmkit\/api\"\n\t\"github.com\/docker\/swarmkit\/log\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n)\n\ntype controller struct {\n\ttask    *api.Task\n\tadapter *containerAdapter\n\tclosed  chan struct{}\n\terr     error\n\n\tpulled     chan struct{} \/\/ closed after pull\n\tcancelPull func()        \/\/ cancels pull context if not nil\n\tpullErr    error         \/\/ pull error, protected by close of pulled\n}\n\nvar _ exec.Controller = &controller{}\n\nfunc newController(client *containerd.Client, task *api.Task, secrets exec.SecretGetter) (exec.Controller, error) {\n\tadapter, err := newContainerAdapter(client, task, secrets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &controller{\n\t\ttask:    task,\n\t\tadapter: adapter,\n\t\tclosed:  make(chan struct{}),\n\t}, nil\n}\n\n\/\/ ContainerStatus returns the container-specific status for the task.\nfunc (r *controller) ContainerStatus(ctx context.Context) (*api.ContainerStatus, error) {\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tstatus := &api.ContainerStatus{\n\t\tContainerID: ctnr.ID,\n\t\tPID:         int32(ctnr.Pid),\n\t}\n\n\tif ec, ok := ctnr.ExitStatus.(exec.ExitCoder); ok {\n\t\tstatus.ExitCode = int32(ec.ExitCode())\n\t}\n\n\treturn status, nil\n}\n\n\/\/ Update takes a recent task update and applies it to the container.\nfunc (r *controller) Update(ctx context.Context, t *api.Task) error {\n\tlog.G(ctx).Warnf(\"task updates not yet supported\")\n\t\/\/ TODO(stevvooe): While assignment of tasks is idempotent, we do allow\n\t\/\/ updates of metadata, such as labelling, as well as any other properties\n\t\/\/ that make sense.\n\treturn nil\n}\n\n\/\/ Prepare creates a container and ensures the image is pulled.\n\/\/\n\/\/ If the container has already be created, exec.ErrTaskPrepared is returned.\nfunc (r *controller) Prepare(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/\/\/ Make sure all the networks that the task needs are created.\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.createNetworks(ctx); err != nil {\n\t\/\/\treturn err\n\t\/\/}\n\n\t\/\/\/\/ Make sure all the volumes that the task needs are created.\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.createVolumes(ctx); err != nil {\n\t\/\/\treturn err\n\t\/\/}\n\n\tif r.pulled == nil {\n\t\t\/\/ Launches a re-entrant pull operation associated with controller,\n\t\t\/\/ dissociating the context from the caller's context. Allows pull\n\t\t\/\/ operation to be re-entrant on calls to prepare, resuming from the\n\t\t\/\/ same point after cancellation.\n\t\tvar pctx context.Context\n\n\t\tr.pulled = make(chan struct{})\n\t\tpctx, r.cancelPull = context.WithCancel(context.Background()) \/\/ TODO(stevvooe): Bind a context to the entire controller.\n\n\t\tgo func() {\n\t\t\tdefer close(r.pulled)\n\t\t\tr.pullErr = r.adapter.pullImage(pctx)\n\t\t}()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-r.pulled:\n\t\tif r.pullErr != nil {\n\t\t\t\/\/ NOTE(stevvooe): We always try to pull the image to make sure we have\n\t\t\t\/\/ the most up to date version. This will return an error, but we only\n\t\t\t\/\/ log it. If the image truly doesn't exist, the create below will\n\t\t\t\/\/ error out.\n\t\t\t\/\/\n\t\t\t\/\/ This gives us some nice behavior where we use up to date versions of\n\t\t\t\/\/ mutable tags, but will still run if the old image is available but a\n\t\t\t\/\/ registry is down.\n\t\t\t\/\/\n\t\t\t\/\/ If you don't want this behavior, lock down your image to an\n\t\t\t\/\/ immutable tag or digest.\n\t\t\tlog.G(ctx).WithError(r.pullErr).Error(\"pulling image failed\")\n\t\t}\n\t}\n\n\tif err := r.adapter.prepare(ctx); err != nil {\n\t\tif isContainerCreateNameConflict(err) {\n\t\t\tif _, err := r.adapter.inspect(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ container is already created. success!\n\t\t\treturn exec.ErrTaskPrepared\n\t\t}\n\n\t\treturn errors.Wrap(err, \"create container failed\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Start the container. An error will be returned if the container is already started.\nfunc (r *controller) Start(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Detect whether the container has *ever* been started. If so, we don't\n\t\/\/ issue the start.\n\t\/\/\n\t\/\/ TODO(stevvooe): This is very racy. While reading inspect, another could\n\t\/\/ start the process and we could end up starting it twice.\n\tif ctnr.Status != containerd.Created {\n\t\treturn exec.ErrTaskStarted\n\t}\n\n\tif err := r.adapter.start(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"starting container failed\")\n\t}\n\n\t\/\/ TODO(ijc): Wait for HealthCheck to report OK.\n\n\treturn nil\n}\n\n\/\/ Wait on the container to exit.\nfunc (r *controller) Wait(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check the initial state and report that.\n\tctnr, err := r.adapter.inspect(ctx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"inspecting container failed\")\n\t}\n\n\tswitch ctnr.Status {\n\tcase containerd.Stopped:\n\t\treturn ctnr.ExitStatus\n\t}\n\n\t\/\/ We do not disable FailFast for this initial call (like we\n\t\/\/ do on the retry below) since we are still halfway through\n\t\/\/ setting up the container and if containerd goes away half\n\t\/\/ way through we consider that a failure.\n\teventq, closed, err := r.adapter.events(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-eventq:\n\t\t\tswitch event.Type {\n\t\t\tcase task.Event_EXIT:\n\t\t\t\treturn makeExitError(event.ExitStatus, \"\")\n\t\t\tcase task.Event_OOM, task.Event_CREATE, task.Event_START, task.Event_EXEC_ADDED, task.Event_PAUSED:\n\t\t\t\tcontinue\n\t\t\tdefault:\n\t\t\t\treturn errors.Errorf(\"Unknown event type %s\\n\", event.Type.String())\n\t\t\t}\n\t\tcase <-closed:\n\t\t\t\/\/ restart!\n\t\t\tlog.G(ctx).Debugf(\"Restarting event stream\")\n\t\t\t\/\/ We disable FailFast for this call so that gRPC will keep\n\t\t\t\/\/ retrying while we wait for containerd to come back. Otherwise\n\t\t\t\/\/ a temporary glitch in the connection (e.g. a containerd restart)\n\t\t\t\/\/ will result in the task being declared dead even though it is\n\t\t\t\/\/ likely to be recoverable.\n\t\t\teventq, closed, err = r.adapter.events(ctx, grpc.FailFast(false))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ recheck the container state, if this fails then we may have missed a\n\t\t\tctnr, err := r.adapter.inspect(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"inspecting container on event restart failed\")\n\t\t\t}\n\t\t\tswitch ctnr.Status {\n\t\t\tcase containerd.Stopped:\n\t\t\t\treturn ctnr.ExitStatus\n\t\t\t}\n\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-r.closed:\n\t\t\treturn r.err\n\t\t}\n\t}\n}\n\n\/\/ Shutdown the container cleanly.\nfunc (r *controller) Shutdown(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\tif err := r.adapter.shutdown(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Terminate the container, with force.\nfunc (r *controller) Terminate(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\tif err := r.adapter.terminate(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Remove the container and its resources.\nfunc (r *controller) Remove(ctx context.Context) error {\n\tctx = log.WithModule(ctx, \"containerd\")\n\n\tif err := r.checkClosed(); err != nil {\n\t\treturn err\n\t}\n\n\tif r.cancelPull != nil {\n\t\tr.cancelPull()\n\t}\n\n\t\/\/ It may be necessary to shut down the task before removing it.\n\tif err := r.Shutdown(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ This may fail if the task was already shut down.\n\t\tlog.G(ctx).WithError(err).Debug(\"shutdown failed on removal\")\n\t}\n\n\t\/\/ Try removing networks referenced in this task in case this\n\t\/\/ task is the last one referencing it\n\t\/\/ TODO(ijc)\n\t\/\/if err := r.adapter.removeNetworks(ctx); err != nil {\n\t\/\/\tif isUnknownContainer(err) {\n\t\/\/\t\treturn nil\n\t\/\/\t}\n\n\t\/\/\treturn err\n\t\/\/}\n\n\tif err := r.adapter.remove(ctx); err != nil {\n\t\tif isUnknownContainer(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Close the controller and clean up any ephemeral resources.\nfunc (r *controller) Close() error {\n\tselect {\n\tcase <-r.closed:\n\t\treturn r.err\n\tdefault:\n\t\tif r.cancelPull != nil {\n\t\t\tr.cancelPull()\n\t\t}\n\n\t\tr.err = exec.ErrControllerClosed\n\t\tclose(r.closed)\n\t}\n\treturn nil\n}\n\nfunc (r *controller) checkClosed() error {\n\tselect {\n\tcase <-r.closed:\n\t\treturn r.err\n\tdefault:\n\t\treturn nil\n\t}\n}\n\ntype exitError struct {\n\tcode  uint32\n\tcause error\n}\n\nfunc (e *exitError) Error() string {\n\tif e.cause != nil {\n\t\treturn fmt.Sprintf(\"task: non-zero exit (%v): %v\", e.code, e.cause)\n\t}\n\treturn fmt.Sprintf(\"task: non-zero exit (%v)\", e.code)\n}\n\nfunc (e *exitError) ExitCode() int {\n\treturn int(e.code)\n}\n\nfunc (e *exitError) Cause() error {\n\treturn e.cause\n}\n\nfunc makeExitError(exitStatus uint32, reason string) error {\n\tif exitStatus != 0 {\n\t\tvar cause error\n\t\tif reason != \"\" {\n\t\t\tcause = errors.New(reason)\n\t\t}\n\n\t\treturn &exitError{\n\t\t\tcode:  exitStatus,\n\t\t\tcause: cause,\n\t\t}\n\t}\n\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 assets\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/blang\/semver\"\n\t\"github.com\/golang\/glog\"\n\n\t\"k8s.io\/kops\/pkg\/apis\/kops\"\n\t\"k8s.io\/kops\/pkg\/apis\/kops\/util\"\n\t\"k8s.io\/kops\/pkg\/featureflag\"\n\t\"k8s.io\/kops\/pkg\/kubemanifest\"\n\t\"k8s.io\/kops\/pkg\/values\"\n\t\"k8s.io\/kops\/util\/pkg\/hashing\"\n\t\"k8s.io\/kops\/util\/pkg\/vfs\"\n\t\"regexp\"\n)\n\n\/\/ RewriteManifests controls whether we rewrite manifests\n\/\/ Because manifest rewriting converts everything to and from YAML, we normalize everything by doing so\nvar RewriteManifests = featureflag.New(\"RewriteManifests\", featureflag.Bool(true))\n\n\/\/ AssetBuilder discovers and remaps assets.\ntype AssetBuilder struct {\n\tContainerAssets []*ContainerAsset\n\tFileAssets      []*FileAsset\n\tAssetsLocation  *kops.Assets\n\t\/\/ TODO we'd like to use cloudup.Phase here, but that introduces a go cyclic dependency\n\tPhase string\n\n\t\/\/ KubernetesVersion is the version of kubernetes we are installing\n\tKubernetesVersion semver.Version\n}\n\n\/\/ ContainerAsset models a container's location.\ntype ContainerAsset struct {\n\t\/\/ DockerImage will be the name of the container we should run.\n\t\/\/ This is used to copy a container to a ContainerRegistry.\n\tDockerImage string\n\t\/\/ CanonicalLocation will be the source location of the container.\n\tCanonicalLocation string\n}\n\n\/\/ FileAsset models a file's location.\ntype FileAsset struct {\n\t\/\/ FileURL is the URL of a file that is accessed by a Kubernetes cluster.\n\tFileURL *url.URL\n\t\/\/ CanonicalFileURL is the source URL of a file. This is used to copy a file to a FileRepository.\n\tCanonicalFileURL *url.URL\n\t\/\/ SHAValue is the SHA hash of the FileAsset.\n\tSHAValue string\n}\n\n\/\/ NewAssetBuilder creates a new AssetBuilder.\nfunc NewAssetBuilder(cluster *kops.Cluster, phase string) *AssetBuilder {\n\ta := &AssetBuilder{\n\t\tAssetsLocation: cluster.Spec.Assets,\n\t\tPhase:          phase,\n\t}\n\n\tversion, err := util.ParseKubernetesVersion(cluster.Spec.KubernetesVersion)\n\tif err != nil {\n\t\t\/\/ This should have already been validated\n\t\tglog.Fatalf(\"unexpected error from ParseKubernetesVersion %s: %v\", cluster.Spec.KubernetesVersion, err)\n\t}\n\ta.KubernetesVersion = *version\n\n\treturn a\n}\n\n\/\/ RemapManifest transforms a kubernetes manifest.\n\/\/ Whenever we are building a Task that includes a manifest, we should pass it through RemapManifest first.\n\/\/ This will:\n\/\/ * rewrite the images if they are being redirected to a mirror, and ensure the image is uploaded\nfunc (a *AssetBuilder) RemapManifest(data []byte) ([]byte, error) {\n\tif !RewriteManifests.Enabled() {\n\t\treturn data, nil\n\t}\n\n\tmanifests, err := kubemanifest.LoadManifestsFrom(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar yamlSeparator = []byte(\"\\n---\\n\\n\")\n\tvar remappedManifests [][]byte\n\tfor _, manifest := range manifests {\n\t\tif err := manifest.RemapImages(a.RemapImage); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error remapping images: %v\", err)\n\t\t}\n\n\t\ty, err := manifest.ToYAML()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error re-marshalling manifest: %v\", err)\n\t\t}\n\n\t\tremappedManifests = append(remappedManifests, y)\n\t}\n\n\treturn bytes.Join(remappedManifests, yamlSeparator), nil\n}\n\n\/\/ RemapImage normalizes a containers location if a user sets the AssetsLocation ContainerRegistry location.\nfunc (a *AssetBuilder) RemapImage(image string) (string, error) {\n\tasset := &ContainerAsset{}\n\n\tasset.DockerImage = image\n\n\t\/\/ The k8s.gcr.io prefix is an alias, but for CI builds we run from a docker load,\n\t\/\/ and we only double-tag from 1.10 onwards.\n\t\/\/ For versions prior to 1.10, remap k8s.gcr.io to the old name.\n\t\/\/ This also means that we won't start using the aliased names on existing clusters,\n\t\/\/ which could otherwise be surprising to users.\n\tif !util.IsKubernetesGTE(\"1.10\", a.KubernetesVersion) && strings.HasPrefix(image, \"k8s.gcr.io\/\") {\n\t\timage = \"gcr.io\/google_containers\/\" + strings.TrimPrefix(image, \"k8s.gcr.io\/\")\n\t}\n\n\tif strings.HasPrefix(image, \"kope\/dns-controller:\") {\n\t\t\/\/ To use user-defined DNS Controller:\n\t\t\/\/ 1. DOCKER_REGISTRY=[your docker hub repo] make dns-controller-push\n\t\t\/\/ 2. export DNSCONTROLLER_IMAGE=[your docker hub repo]\n\t\t\/\/ 3. make kops and create\/apply cluster\n\t\toverride := os.Getenv(\"DNSCONTROLLER_IMAGE\")\n\t\tif override != \"\" {\n\t\t\timage = override\n\t\t}\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.ContainerProxy != nil {\n\t\tcontainerProxy := *a.AssetsLocation.ContainerProxy\n\t\tnormalized := image\n\n\t\t\/\/ If the image name contains only a single \/ we need to determine if the image is located on docker-hub or if it's using a convenient URL like k8s.gcr.io\/<image-name>\n\t\t\/\/ In case of a hub image it should be sufficient to just prepend the proxy url, producing eg docker-proxy.example.com\/weaveworks\/weave-kube\n\t\tif strings.Count(normalized, \"\/\") == 1 && !strings.ContainsAny(strings.Split(normalized, \"\/\")[0], \".:\"){\n\t\t\tnormalized = containerProxy + \"\/\" + normalized\n\t\t} else {\n\t\t\tvar re = regexp.MustCompile(`^[^\/]+`)\n\t\t\tnormalized = re.ReplaceAllString(normalized, containerProxy)\n\t\t}\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.ContainerRegistry != nil {\n\t\tregistryMirror := *a.AssetsLocation.ContainerRegistry\n\t\tnormalized := image\n\n\t\t\/\/ Remove the 'standard' kubernetes image prefix, just for sanity\n\t\tif !util.IsKubernetesGTE(\"1.10\", a.KubernetesVersion) && strings.HasPrefix(normalized, \"gcr.io\/google_containers\/\") {\n\t\t\tnormalized = strings.TrimPrefix(normalized, \"gcr.io\/google_containers\/\")\n\t\t} else {\n\t\t\tnormalized = strings.TrimPrefix(normalized, \"k8s.gcr.io\/\")\n\t\t}\n\n\t\t\/\/ We can't nest arbitrarily\n\t\t\/\/ Some risk of collisions, but also -- and __ in the names appear to be blocked by docker hub\n\t\tnormalized = strings.Replace(normalized, \"\/\", \"-\", -1)\n\t\tasset.DockerImage = registryMirror + \"\/\" + normalized\n\n\t\tasset.CanonicalLocation = image\n\n\t\t\/\/ Run the new image\n\t\timage = asset.DockerImage\n\t}\n\n\ta.ContainerAssets = append(a.ContainerAssets, asset)\n\treturn image, nil\n}\n\n\/\/ RemapFileAndSHA returns a remapped url for the file, if AssetsLocation is defined.\n\/\/ It also returns the SHA hash of the file.\nfunc (a *AssetBuilder) RemapFileAndSHA(fileURL *url.URL) (*url.URL, *hashing.Hash, error) {\n\tif fileURL == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to remap a nil URL\")\n\t}\n\n\tfileAsset := &FileAsset{\n\t\tFileURL: fileURL,\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\tfileAsset.CanonicalFileURL = fileURL\n\n\t\tnormalizedFileURL, err := a.normalizeURL(fileURL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tfileAsset.FileURL = normalizedFileURL\n\n\t\tglog.V(4).Infof(\"adding remapped file: %+v\", fileAsset)\n\t}\n\n\th, err := a.findHash(fileAsset)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileAsset.SHAValue = h.Hex()\n\n\ta.FileAssets = append(a.FileAssets, fileAsset)\n\tglog.V(8).Infof(\"adding file: %+v\", fileAsset)\n\n\treturn fileAsset.FileURL, h, nil\n}\n\n\/\/ TODO - remove this method as CNI does now have a SHA file\n\n\/\/ RemapFileAndSHAValue is used exclusively to remap the cni tarball, as the tarball does not have a sha file in object storage.\nfunc (a *AssetBuilder) RemapFileAndSHAValue(fileURL *url.URL, shaValue string) (*url.URL, error) {\n\tif fileURL == nil {\n\t\treturn nil, fmt.Errorf(\"unable to remap a nil URL\")\n\t}\n\n\tfileAsset := &FileAsset{\n\t\tFileURL:  fileURL,\n\t\tSHAValue: shaValue,\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\tfileAsset.CanonicalFileURL = fileURL\n\n\t\tnormalizedFile, err := a.normalizeURL(fileURL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfileAsset.FileURL = normalizedFile\n\t\tglog.V(4).Infof(\"adding remapped file: %q\", fileAsset.FileURL.String())\n\t}\n\n\ta.FileAssets = append(a.FileAssets, fileAsset)\n\n\treturn fileAsset.FileURL, nil\n}\n\n\/\/ FindHash returns the hash value of a FileAsset.\nfunc (a *AssetBuilder) findHash(file *FileAsset) (*hashing.Hash, error) {\n\n\t\/\/ If the phase is \"assets\" we use the CanonicalFileURL,\n\t\/\/ but during other phases we use the hash from the FileRepository or the base kops path.\n\t\/\/ We do not want to just test for CanonicalFileURL as it is defined in\n\t\/\/ other phases, but is not used to test for the SHA.\n\t\/\/ This prevents a chicken and egg problem where the file is not yet in the FileRepository.\n\t\/\/\n\t\/\/ assets phase -> get the sha file from the source \/ CanonicalFileURL\n\t\/\/ any other phase -> get the sha file from the kops base location or the FileRepository\n\t\/\/\n\t\/\/ TLDR; we use the file.CanonicalFileURL during assets phase, and use file.FileUrl the\n\t\/\/ rest of the time. If not we get a chicken and the egg problem where we are reading the sha file\n\t\/\/ before it exists.\n\tu := file.FileURL\n\tif a.Phase == \"assets\" && file.CanonicalFileURL != nil {\n\t\tu = file.CanonicalFileURL\n\t}\n\n\tif u == nil {\n\t\treturn nil, fmt.Errorf(\"file url is not defined\")\n\t}\n\n\tfor _, ext := range []string{\".sha1\"} {\n\t\thashURL := u.String() + ext\n\t\tb, err := vfs.Context.ReadFile(hashURL)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"error reading hash file %q: %v\", hashURL, err)\n\t\t\tcontinue\n\t\t}\n\t\thashString := strings.TrimSpace(string(b))\n\t\tglog.V(2).Infof(\"Found hash %q for %q\", hashString, u)\n\n\t\treturn hashing.FromString(hashString)\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\treturn nil, fmt.Errorf(\"you may have not staged your files correctly, please execute kops update cluster using the assets phase\")\n\t}\n\treturn nil, fmt.Errorf(\"cannot determine hash for %q (have you specified a valid file location?)\", u)\n}\n\nfunc (a *AssetBuilder) normalizeURL(file *url.URL) (*url.URL, error) {\n\n\tif a.AssetsLocation == nil || a.AssetsLocation.FileRepository == nil {\n\t\treturn nil, fmt.Errorf(\"assetLocation and fileRepository cannot be nil to normalize an file asset URL\")\n\t}\n\n\tf := values.StringValue(a.AssetsLocation.FileRepository)\n\n\tif f == \"\" {\n\t\treturn nil, fmt.Errorf(\"assetsLocation fileRepository cannot be an empty string\")\n\t}\n\n\tfileRepo, err := url.Parse(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse file repository URL %q: %v\", values.StringValue(a.AssetsLocation.FileRepository), err)\n\t}\n\n\tfileRepo.Path = path.Join(fileRepo.Path, file.Path)\n\n\treturn fileRepo, nil\n}\n<commit_msg>Run gofmt<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 assets\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/blang\/semver\"\n\t\"github.com\/golang\/glog\"\n\n\t\"k8s.io\/kops\/pkg\/apis\/kops\"\n\t\"k8s.io\/kops\/pkg\/apis\/kops\/util\"\n\t\"k8s.io\/kops\/pkg\/featureflag\"\n\t\"k8s.io\/kops\/pkg\/kubemanifest\"\n\t\"k8s.io\/kops\/pkg\/values\"\n\t\"k8s.io\/kops\/util\/pkg\/hashing\"\n\t\"k8s.io\/kops\/util\/pkg\/vfs\"\n)\n\n\/\/ RewriteManifests controls whether we rewrite manifests\n\/\/ Because manifest rewriting converts everything to and from YAML, we normalize everything by doing so\nvar RewriteManifests = featureflag.New(\"RewriteManifests\", featureflag.Bool(true))\n\n\/\/ AssetBuilder discovers and remaps assets.\ntype AssetBuilder struct {\n\tContainerAssets []*ContainerAsset\n\tFileAssets      []*FileAsset\n\tAssetsLocation  *kops.Assets\n\t\/\/ TODO we'd like to use cloudup.Phase here, but that introduces a go cyclic dependency\n\tPhase string\n\n\t\/\/ KubernetesVersion is the version of kubernetes we are installing\n\tKubernetesVersion semver.Version\n}\n\n\/\/ ContainerAsset models a container's location.\ntype ContainerAsset struct {\n\t\/\/ DockerImage will be the name of the container we should run.\n\t\/\/ This is used to copy a container to a ContainerRegistry.\n\tDockerImage string\n\t\/\/ CanonicalLocation will be the source location of the container.\n\tCanonicalLocation string\n}\n\n\/\/ FileAsset models a file's location.\ntype FileAsset struct {\n\t\/\/ FileURL is the URL of a file that is accessed by a Kubernetes cluster.\n\tFileURL *url.URL\n\t\/\/ CanonicalFileURL is the source URL of a file. This is used to copy a file to a FileRepository.\n\tCanonicalFileURL *url.URL\n\t\/\/ SHAValue is the SHA hash of the FileAsset.\n\tSHAValue string\n}\n\n\/\/ NewAssetBuilder creates a new AssetBuilder.\nfunc NewAssetBuilder(cluster *kops.Cluster, phase string) *AssetBuilder {\n\ta := &AssetBuilder{\n\t\tAssetsLocation: cluster.Spec.Assets,\n\t\tPhase:          phase,\n\t}\n\n\tversion, err := util.ParseKubernetesVersion(cluster.Spec.KubernetesVersion)\n\tif err != nil {\n\t\t\/\/ This should have already been validated\n\t\tglog.Fatalf(\"unexpected error from ParseKubernetesVersion %s: %v\", cluster.Spec.KubernetesVersion, err)\n\t}\n\ta.KubernetesVersion = *version\n\n\treturn a\n}\n\n\/\/ RemapManifest transforms a kubernetes manifest.\n\/\/ Whenever we are building a Task that includes a manifest, we should pass it through RemapManifest first.\n\/\/ This will:\n\/\/ * rewrite the images if they are being redirected to a mirror, and ensure the image is uploaded\nfunc (a *AssetBuilder) RemapManifest(data []byte) ([]byte, error) {\n\tif !RewriteManifests.Enabled() {\n\t\treturn data, nil\n\t}\n\n\tmanifests, err := kubemanifest.LoadManifestsFrom(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar yamlSeparator = []byte(\"\\n---\\n\\n\")\n\tvar remappedManifests [][]byte\n\tfor _, manifest := range manifests {\n\t\tif err := manifest.RemapImages(a.RemapImage); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error remapping images: %v\", err)\n\t\t}\n\n\t\ty, err := manifest.ToYAML()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error re-marshalling manifest: %v\", err)\n\t\t}\n\n\t\tremappedManifests = append(remappedManifests, y)\n\t}\n\n\treturn bytes.Join(remappedManifests, yamlSeparator), nil\n}\n\n\/\/ RemapImage normalizes a containers location if a user sets the AssetsLocation ContainerRegistry location.\nfunc (a *AssetBuilder) RemapImage(image string) (string, error) {\n\tasset := &ContainerAsset{}\n\n\tasset.DockerImage = image\n\n\t\/\/ The k8s.gcr.io prefix is an alias, but for CI builds we run from a docker load,\n\t\/\/ and we only double-tag from 1.10 onwards.\n\t\/\/ For versions prior to 1.10, remap k8s.gcr.io to the old name.\n\t\/\/ This also means that we won't start using the aliased names on existing clusters,\n\t\/\/ which could otherwise be surprising to users.\n\tif !util.IsKubernetesGTE(\"1.10\", a.KubernetesVersion) && strings.HasPrefix(image, \"k8s.gcr.io\/\") {\n\t\timage = \"gcr.io\/google_containers\/\" + strings.TrimPrefix(image, \"k8s.gcr.io\/\")\n\t}\n\n\tif strings.HasPrefix(image, \"kope\/dns-controller:\") {\n\t\t\/\/ To use user-defined DNS Controller:\n\t\t\/\/ 1. DOCKER_REGISTRY=[your docker hub repo] make dns-controller-push\n\t\t\/\/ 2. export DNSCONTROLLER_IMAGE=[your docker hub repo]\n\t\t\/\/ 3. make kops and create\/apply cluster\n\t\toverride := os.Getenv(\"DNSCONTROLLER_IMAGE\")\n\t\tif override != \"\" {\n\t\t\timage = override\n\t\t}\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.ContainerProxy != nil {\n\t\tcontainerProxy := *a.AssetsLocation.ContainerProxy\n\t\tnormalized := image\n\n\t\t\/\/ If the image name contains only a single \/ we need to determine if the image is located on docker-hub or if it's using a convenient URL like k8s.gcr.io\/<image-name>\n\t\t\/\/ In case of a hub image it should be sufficient to just prepend the proxy url, producing eg docker-proxy.example.com\/weaveworks\/weave-kube\n\t\tif strings.Count(normalized, \"\/\") == 1 && !strings.ContainsAny(strings.Split(normalized, \"\/\")[0], \".:\") {\n\t\t\tnormalized = containerProxy + \"\/\" + normalized\n\t\t} else {\n\t\t\tvar re = regexp.MustCompile(`^[^\/]+`)\n\t\t\tnormalized = re.ReplaceAllString(normalized, containerProxy)\n\t\t}\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.ContainerRegistry != nil {\n\t\tregistryMirror := *a.AssetsLocation.ContainerRegistry\n\t\tnormalized := image\n\n\t\t\/\/ Remove the 'standard' kubernetes image prefix, just for sanity\n\t\tif !util.IsKubernetesGTE(\"1.10\", a.KubernetesVersion) && strings.HasPrefix(normalized, \"gcr.io\/google_containers\/\") {\n\t\t\tnormalized = strings.TrimPrefix(normalized, \"gcr.io\/google_containers\/\")\n\t\t} else {\n\t\t\tnormalized = strings.TrimPrefix(normalized, \"k8s.gcr.io\/\")\n\t\t}\n\n\t\t\/\/ We can't nest arbitrarily\n\t\t\/\/ Some risk of collisions, but also -- and __ in the names appear to be blocked by docker hub\n\t\tnormalized = strings.Replace(normalized, \"\/\", \"-\", -1)\n\t\tasset.DockerImage = registryMirror + \"\/\" + normalized\n\n\t\tasset.CanonicalLocation = image\n\n\t\t\/\/ Run the new image\n\t\timage = asset.DockerImage\n\t}\n\n\ta.ContainerAssets = append(a.ContainerAssets, asset)\n\treturn image, nil\n}\n\n\/\/ RemapFileAndSHA returns a remapped url for the file, if AssetsLocation is defined.\n\/\/ It also returns the SHA hash of the file.\nfunc (a *AssetBuilder) RemapFileAndSHA(fileURL *url.URL) (*url.URL, *hashing.Hash, error) {\n\tif fileURL == nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to remap a nil URL\")\n\t}\n\n\tfileAsset := &FileAsset{\n\t\tFileURL: fileURL,\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\tfileAsset.CanonicalFileURL = fileURL\n\n\t\tnormalizedFileURL, err := a.normalizeURL(fileURL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tfileAsset.FileURL = normalizedFileURL\n\n\t\tglog.V(4).Infof(\"adding remapped file: %+v\", fileAsset)\n\t}\n\n\th, err := a.findHash(fileAsset)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfileAsset.SHAValue = h.Hex()\n\n\ta.FileAssets = append(a.FileAssets, fileAsset)\n\tglog.V(8).Infof(\"adding file: %+v\", fileAsset)\n\n\treturn fileAsset.FileURL, h, nil\n}\n\n\/\/ TODO - remove this method as CNI does now have a SHA file\n\n\/\/ RemapFileAndSHAValue is used exclusively to remap the cni tarball, as the tarball does not have a sha file in object storage.\nfunc (a *AssetBuilder) RemapFileAndSHAValue(fileURL *url.URL, shaValue string) (*url.URL, error) {\n\tif fileURL == nil {\n\t\treturn nil, fmt.Errorf(\"unable to remap a nil URL\")\n\t}\n\n\tfileAsset := &FileAsset{\n\t\tFileURL:  fileURL,\n\t\tSHAValue: shaValue,\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\tfileAsset.CanonicalFileURL = fileURL\n\n\t\tnormalizedFile, err := a.normalizeURL(fileURL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfileAsset.FileURL = normalizedFile\n\t\tglog.V(4).Infof(\"adding remapped file: %q\", fileAsset.FileURL.String())\n\t}\n\n\ta.FileAssets = append(a.FileAssets, fileAsset)\n\n\treturn fileAsset.FileURL, nil\n}\n\n\/\/ FindHash returns the hash value of a FileAsset.\nfunc (a *AssetBuilder) findHash(file *FileAsset) (*hashing.Hash, error) {\n\n\t\/\/ If the phase is \"assets\" we use the CanonicalFileURL,\n\t\/\/ but during other phases we use the hash from the FileRepository or the base kops path.\n\t\/\/ We do not want to just test for CanonicalFileURL as it is defined in\n\t\/\/ other phases, but is not used to test for the SHA.\n\t\/\/ This prevents a chicken and egg problem where the file is not yet in the FileRepository.\n\t\/\/\n\t\/\/ assets phase -> get the sha file from the source \/ CanonicalFileURL\n\t\/\/ any other phase -> get the sha file from the kops base location or the FileRepository\n\t\/\/\n\t\/\/ TLDR; we use the file.CanonicalFileURL during assets phase, and use file.FileUrl the\n\t\/\/ rest of the time. If not we get a chicken and the egg problem where we are reading the sha file\n\t\/\/ before it exists.\n\tu := file.FileURL\n\tif a.Phase == \"assets\" && file.CanonicalFileURL != nil {\n\t\tu = file.CanonicalFileURL\n\t}\n\n\tif u == nil {\n\t\treturn nil, fmt.Errorf(\"file url is not defined\")\n\t}\n\n\tfor _, ext := range []string{\".sha1\"} {\n\t\thashURL := u.String() + ext\n\t\tb, err := vfs.Context.ReadFile(hashURL)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"error reading hash file %q: %v\", hashURL, err)\n\t\t\tcontinue\n\t\t}\n\t\thashString := strings.TrimSpace(string(b))\n\t\tglog.V(2).Infof(\"Found hash %q for %q\", hashString, u)\n\n\t\treturn hashing.FromString(hashString)\n\t}\n\n\tif a.AssetsLocation != nil && a.AssetsLocation.FileRepository != nil {\n\t\treturn nil, fmt.Errorf(\"you may have not staged your files correctly, please execute kops update cluster using the assets phase\")\n\t}\n\treturn nil, fmt.Errorf(\"cannot determine hash for %q (have you specified a valid file location?)\", u)\n}\n\nfunc (a *AssetBuilder) normalizeURL(file *url.URL) (*url.URL, error) {\n\n\tif a.AssetsLocation == nil || a.AssetsLocation.FileRepository == nil {\n\t\treturn nil, fmt.Errorf(\"assetLocation and fileRepository cannot be nil to normalize an file asset URL\")\n\t}\n\n\tf := values.StringValue(a.AssetsLocation.FileRepository)\n\n\tif f == \"\" {\n\t\treturn nil, fmt.Errorf(\"assetsLocation fileRepository cannot be an empty string\")\n\t}\n\n\tfileRepo, err := url.Parse(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse file repository URL %q: %v\", values.StringValue(a.AssetsLocation.FileRepository), err)\n\t}\n\n\tfileRepo.Path = path.Join(fileRepo.Path, file.Path)\n\n\treturn fileRepo, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package operators\n\nimport (\n\t\"math\"\n)\n\nvar (\n\tadd = &Operator{\n\t\tName:          \"+\",\n\t\tPrecedence:    1,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] + args[1]\n\t\t},\n\t}\n\tsub = &Operator{\n\t\tName:          \"-\",\n\t\tPrecedence:    1,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] - args[1]\n\t\t},\n\t}\n\tneg = &Operator{\n\t\tName:          \"neg\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          1,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn 0 - args[0]\n\t\t},\n\t}\n\tmul = &Operator{\n\t\tName:          \"*\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] * args[1]\n\t\t},\n\t}\n\tdiv = &Operator{\n\t\tName:          \"\/\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] \/ args[1]\n\t\t},\n\t}\n\tpow = &Operator{\n\t\tName:          \"^\",\n\t\tPrecedence:    3,\n\t\tAssociativity: R,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn math.Pow(args[0], args[1])\n\t\t},\n\t}\n)\n\nfunc init() {\n\tRegister(add)\n\tRegister(sub)\n\tRegister(neg)\n\tRegister(pow)\n\tRegister(mul)\n\tRegister(div)\n}\n<commit_msg>Added mod operator (%)<commit_after>package operators\n\nimport (\n\t\"math\"\n)\n\nvar (\n\tadd = &Operator{\n\t\tName:          \"+\",\n\t\tPrecedence:    1,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] + args[1]\n\t\t},\n\t}\n\tsub = &Operator{\n\t\tName:          \"-\",\n\t\tPrecedence:    1,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] - args[1]\n\t\t},\n\t}\n\tneg = &Operator{\n\t\tName:          \"neg\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          1,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn 0 - args[0]\n\t\t},\n\t}\n\tmul = &Operator{\n\t\tName:          \"*\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] * args[1]\n\t\t},\n\t}\n\tdiv = &Operator{\n\t\tName:          \"\/\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn args[0] \/ args[1]\n\t\t},\n\t}\n\tmod = &Operator{\n\t\tName:          \"%\",\n\t\tPrecedence:    2,\n\t\tAssociativity: L,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn math.Mod(args[0], args[1])\n\t\t},\n\t}\n\tpow = &Operator{\n\t\tName:          \"^\",\n\t\tPrecedence:    3,\n\t\tAssociativity: R,\n\t\tArgs:          2,\n\t\tOperation: func(args []float64) float64 {\n\t\t\treturn math.Pow(args[0], args[1])\n\t\t},\n\t}\n\n)\n\nfunc init() {\n\tRegister(add)\n\tRegister(sub)\n\tRegister(neg)\n\tRegister(pow)\n\tRegister(mul)\n    Register(mod)\n\tRegister(div)\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\"os\/exec\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"flag\"\n\t\"github.com\/br0r\/hydra\/config\"\n)\n\nconst BASE_DIR string = \".hydra\"\nconst help string = `Usage:\nhydra [OPTIONS] COMMAND\n\nCommands:\n  init - Create hydra project [--clean]\n  start - Start hydra servers\n  stop - Stops started servers\n  ls - Show started servers\n  logs [name] - Show logs for servers, or for specific server given by name\n`\n\nfunc initialize(c config.Config, clean bool) {\n\tif clean {\n\t\t_, e := exec.Command(\"rm\", \"-rf\", \".hydra\").Output()\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\t}\n\n\texec.Command(\"mkdir\", \".hydra\").Output()\n\n\tfor i := 0; i < len(c.Services); i += 1 {\n\t\tservice := c.Services[i]\n\t\tp := service.Path\n\t\tname := service.Name\n\t\tbase := path.Join(\".hydra\/\", name)\n\t\tif _, err := os.Stat(base); os.IsNotExist(err) {\n\t\t\tfmt.Println(\"Creating\", name)\n\n\t\t\tvar e error\n\t\t\tif strings.Index(p, \"git@\") == 0 {\n\t\t\t\te = exec.Command(\"git\", \"clone\", p, base).Run()\n\t\t\t} else {\n\t\t\t\te = exec.Command(\"cp\", \"-R\", p, base).Run()\n\t\t\t}\n\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatal(e)\n\t\t\t}\n\n\t\t\tgit := path.Join(base, \".git\")\n\t\t\texec.Command(\"rm\", \"-rf\", git).Run()\n\n\t\t\tif service.Config.Dest != \"\" && service.Config.Src != \"\" {\n\t\t\t\tu := path.Join(base, service.Config.Dest)\n\t\t\t\tcf := service.Config.Src\n\n\t\t\t\terr := exec.Command(\"cp\", cf, u).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}\n\n\t\t\tif service.Install != \"\" {\n\t\t\t\targs := strings.Split(service.Install, \" \")\n\t\t\t\tcmd := exec.Command(args[0], args[1:]...)\n\n\t\t\t\tcmd.Dir = base\n\t\t\t\te := cmd.Run()\n\t\t\t\tif e != nil {\n\t\t\t\t\tlog.Fatal(e)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc start(conf config.Config) {\n\tfor i := 0; i < len(conf.Services); i += 1 {\n\t\tservice := conf.Services[i]\n\t\tname := service.Name\n\n\t\tcmdRunDir := path.Join(\".hydra\", name)\n\t\tpid_file := path.Join(cmdRunDir, \"pid\")\n\t\tlog_file_path := path.Join(cmdRunDir, \"log\")\n\n\t\tif _, err := os.Stat(pid_file); !os.IsNotExist(err) {\n\t\t\tfmt.Printf(\"%s is already started, run hydra stop if you want to restart\\n\", name)\n\t\t\tcontinue\n\t\t}\n\n\t\tenv := os.Environ()\n\t\tfor k, v := range service.Env {\n\t\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", k, v))\n\t\t}\n\n\t\tfmt.Println(\"Starting\", name)\n\t\targs := strings.Split(conf.Services[i].Start, \" \")\n\t\targs = append(args, \"2>&1 1> log\")\n\t\tcmd := exec.Command(args[0], args[1:]...)\n\t\tcmd.Env = env\n\t\tcmd.Dir = cmdRunDir\n\n\t\tlog_file, e := os.Create(log_file_path)\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\n\t\t_, e = log_file.WriteString(fmt.Sprintf(\"%s:\\n\", name))\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\n\t\tdefer log_file.Close()\n\t\tcmd.Stdout = log_file\n\t\tcmd.Stderr = log_file\n\n\t\te = cmd.Start()\n\t\tpid := []byte(strconv.Itoa(cmd.Process.Pid))\n\t\tioutil.WriteFile(pid_file, pid, 0440)\n\n\t\tif e != nil {\n\t\t\tos.Remove(\"pid\")\n\t\t\tlog.Fatal(\"Error with\", name, e)\n\t\t}\n\n\t}\n}\n\nfunc kill(conf config.Config) {\n\tfor i := 0; i < len(conf.Services); i += 1 {\n\t\tservice := conf.Services[i]\n\t\tname := service.Name\n\t\tpid_file := path.Join(\".hydra\", name, \"pid\")\n\t\tif _, err := os.Stat(pid_file); !os.IsNotExist(err) {\n\t\t\tbytes, e := ioutil.ReadFile(pid_file)\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatalf(\"Error when reading file %v\", e)\n\t\t\t}\n\t\t\tpid := string(bytes)\n\t\t\texec.Command(\"kill\", pid).Run()\n\t\t\tif e == nil {\n\t\t\t\tfmt.Printf(\"Killed %s\\n\", name)\n\t\t\t}\n\t\t\tos.Remove(pid_file)\n\t\t}\n\t}\n}\n\nfunc ls(conf config.Config) {\n\tfor _, service := range conf.Services {\n\t\tname := service.Name\n\t\tpid_path := path.Join(BASE_DIR, name, \"pid\")\n\t\tif _, err := os.Stat(pid_path); !os.IsNotExist(err) {\n\t\t\tbytes, e := ioutil.ReadFile(pid_path)\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatal(e)\n\t\t\t}\n\t\t\tpid := string(bytes)\n\t\t\tfmt.Printf(\"%s running on pid: %s\\n\", name, pid)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s is not running\\n\", name)\n\t\t}\n\t}\n}\n\nfunc logs(conf config.Config, servers []string) {\n\tfor _, service := range conf.Services {\n\t\tif len(servers) > 0 {\n\t\t\terr := false\n\t\t\tfor _, name := range servers {\n\t\t\t\tif name != service.Name {\n\t\t\t\t\terr = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == true {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tlogfile := path.Join(\".hydra\/\", service.Name, \"log\")\n\t\tdata, err := ioutil.ReadFile(logfile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(string(data))\n\t}\n}\n\nfunc main() {\n\tvar c config.Config = config.ReadConfig()\n\tvar clean = flag.Bool(\"clean\", false, \"If we want a clean run\")\n\tflag.Parse()\n\n\tif cmd := flag.Arg(0); cmd != \"\" {\n\t\tswitch cmd {\n\t\tcase \"init\":\n\t\t\tinitialize(c, *clean)\n\t\tcase \"start\":\n\t\t\tstart(c)\n\t\tcase \"stop\":\n\t\t\tkill(c)\n\t\tcase \"ls\":\n\t\t\tls(c)\n\t\tcase \"logs\":\n\t\t\tlogs(c, flag.Args()[1:])\n\t\tdefault:\n\t\t\tfmt.Println(help)\n\t\t}\n\t} else {\n\t\tfmt.Println(help)\n\t}\n}\n<commit_msg>added kill to clean<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"flag\"\n\t\"github.com\/br0r\/hydra\/config\"\n)\n\nconst BASE_DIR string = \".hydra\"\nconst help string = `Usage:\nhydra [OPTIONS] COMMAND\n\nCommands:\n  init - Create hydra project [--clean]\n  start - Start hydra servers\n  stop - Stops started servers\n  ls - Show started servers\n  logs [name] - Show logs for servers, or for specific server given by name\n`\n\nfunc initialize(c config.Config, clean bool) {\n\tif clean {\n\t\tkill(c)\n\t\t_, e := exec.Command(\"rm\", \"-rf\", \".hydra\").Output()\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\t}\n\n\texec.Command(\"mkdir\", \".hydra\").Output()\n\n\tfor i := 0; i < len(c.Services); i += 1 {\n\t\tservice := c.Services[i]\n\t\tp := service.Path\n\t\tname := service.Name\n\t\tbase := path.Join(\".hydra\/\", name)\n\t\tif _, err := os.Stat(base); os.IsNotExist(err) {\n\t\t\tfmt.Println(\"Creating\", name)\n\n\t\t\tvar e error\n\t\t\tif strings.Index(p, \"git@\") == 0 {\n\t\t\t\te = exec.Command(\"git\", \"clone\", p, base).Run()\n\t\t\t} else {\n\t\t\t\te = exec.Command(\"cp\", \"-R\", p, base).Run()\n\t\t\t}\n\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatal(e)\n\t\t\t}\n\n\t\t\tgit := path.Join(base, \".git\")\n\t\t\texec.Command(\"rm\", \"-rf\", git).Run()\n\n\t\t\tif service.Config.Dest != \"\" && service.Config.Src != \"\" {\n\t\t\t\tu := path.Join(base, service.Config.Dest)\n\t\t\t\tcf := service.Config.Src\n\n\t\t\t\terr := exec.Command(\"cp\", cf, u).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}\n\n\t\t\tif service.Install != \"\" {\n\t\t\t\targs := strings.Split(service.Install, \" \")\n\t\t\t\tcmd := exec.Command(args[0], args[1:]...)\n\n\t\t\t\tcmd.Dir = base\n\t\t\t\te := cmd.Run()\n\t\t\t\tif e != nil {\n\t\t\t\t\tlog.Fatal(e)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc start(conf config.Config) {\n\tfor i := 0; i < len(conf.Services); i += 1 {\n\t\tservice := conf.Services[i]\n\t\tname := service.Name\n\n\t\tcmdRunDir := path.Join(\".hydra\", name)\n\t\tpid_file := path.Join(cmdRunDir, \"pid\")\n\t\tlog_file_path := path.Join(cmdRunDir, \"log\")\n\n\t\tif _, err := os.Stat(pid_file); !os.IsNotExist(err) {\n\t\t\tfmt.Printf(\"%s is already started, run hydra stop if you want to restart\\n\", name)\n\t\t\tcontinue\n\t\t}\n\n\t\tenv := os.Environ()\n\t\tfor k, v := range service.Env {\n\t\t\tenv = append(env, fmt.Sprintf(\"%s=%s\", k, v))\n\t\t}\n\n\t\tfmt.Println(\"Starting\", name)\n\t\targs := strings.Split(conf.Services[i].Start, \" \")\n\t\targs = append(args, \"2>&1 1> log\")\n\t\tcmd := exec.Command(args[0], args[1:]...)\n\t\tcmd.Env = env\n\t\tcmd.Dir = cmdRunDir\n\n\t\tlog_file, e := os.Create(log_file_path)\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\n\t\t_, e = log_file.WriteString(fmt.Sprintf(\"%s:\\n\", name))\n\t\tif e != nil {\n\t\t\tlog.Fatal(e)\n\t\t}\n\n\t\tdefer log_file.Close()\n\t\tcmd.Stdout = log_file\n\t\tcmd.Stderr = log_file\n\n\t\te = cmd.Start()\n\t\tpid := []byte(strconv.Itoa(cmd.Process.Pid))\n\t\tioutil.WriteFile(pid_file, pid, 0440)\n\n\t\tif e != nil {\n\t\t\tos.Remove(\"pid\")\n\t\t\tlog.Fatal(\"Error with\", name, e)\n\t\t}\n\n\t}\n}\n\nfunc kill(conf config.Config) {\n\tfor i := 0; i < len(conf.Services); i += 1 {\n\t\tservice := conf.Services[i]\n\t\tname := service.Name\n\t\tpid_file := path.Join(\".hydra\", name, \"pid\")\n\t\tif _, err := os.Stat(pid_file); !os.IsNotExist(err) {\n\t\t\tbytes, e := ioutil.ReadFile(pid_file)\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatalf(\"Error when reading file %v\", e)\n\t\t\t}\n\t\t\tpid := string(bytes)\n\t\t\texec.Command(\"kill\", pid).Run()\n\t\t\tif e == nil {\n\t\t\t\tfmt.Printf(\"Killed %s\\n\", name)\n\t\t\t}\n\t\t\tos.Remove(pid_file)\n\t\t}\n\t}\n}\n\nfunc ls(conf config.Config) {\n\tfor _, service := range conf.Services {\n\t\tname := service.Name\n\t\tpid_path := path.Join(BASE_DIR, name, \"pid\")\n\t\tif _, err := os.Stat(pid_path); !os.IsNotExist(err) {\n\t\t\tbytes, e := ioutil.ReadFile(pid_path)\n\t\t\tif e != nil {\n\t\t\t\tlog.Fatal(e)\n\t\t\t}\n\t\t\tpid := string(bytes)\n\t\t\tfmt.Printf(\"%s running on pid: %s\\n\", name, pid)\n\t\t} else {\n\t\t\tfmt.Printf(\"%s is not running\\n\", name)\n\t\t}\n\t}\n}\n\nfunc logs(conf config.Config, servers []string) {\n\tfor _, service := range conf.Services {\n\t\tif len(servers) > 0 {\n\t\t\terr := false\n\t\t\tfor _, name := range servers {\n\t\t\t\tif name != service.Name {\n\t\t\t\t\terr = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == true {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tlogfile := path.Join(\".hydra\/\", service.Name, \"log\")\n\t\tdata, err := ioutil.ReadFile(logfile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(string(data))\n\t}\n}\n\nfunc main() {\n\tvar c config.Config = config.ReadConfig()\n\tvar clean = flag.Bool(\"clean\", false, \"If we want a clean run\")\n\tflag.Parse()\n\n\tif cmd := flag.Arg(0); cmd != \"\" {\n\t\tswitch cmd {\n\t\tcase \"init\":\n\t\t\tinitialize(c, *clean)\n\t\tcase \"start\":\n\t\t\tstart(c)\n\t\tcase \"stop\":\n\t\t\tkill(c)\n\t\tcase \"ls\":\n\t\t\tls(c)\n\t\tcase \"logs\":\n\t\t\tlogs(c, flag.Args()[1:])\n\t\tdefault:\n\t\t\tfmt.Println(help)\n\t\t}\n\t} else {\n\t\tfmt.Println(help)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>blockmanager: detect peers including OP_RETURN in filters<commit_after><|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\/v1beta1\"\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\tswitch t := obj.(type) {\n\tcase *api.ReplicationController:\n\t\terrors = validation.ValidateManifest(&t.DesiredState.PodTemplate.DesiredState.Manifest)\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\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\terrors = validation.ValidateManifest(&t.DesiredState.Manifest)\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\" {\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 TestApiExamples(t *testing.T) {\n\texpected := map[string]runtime.Object{\n\t\t\"controller\":       &api.ReplicationController{},\n\t\t\"controller-list\":  &api.ReplicationControllerList{},\n\t\t\"pod\":              &api.Pod{},\n\t\t\"pod-list\":         &api.PodList{},\n\t\t\"service\":          &api.Service{},\n\t\t\"external-service\": &api.Service{},\n\t\t\"service-list\":     &api.ServiceList{},\n\t}\n\n\ttested := 0\n\terr := walkJSONFiles(\"..\/api\/examples\", func(name, path string, data []byte) {\n\t\texpectedType, found := expected[name]\n\t\tif !found {\n\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\treturn\n\t\t}\n\t\ttested += 1\n\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t}\n\tif tested != len(expected) {\n\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t}\n}\n\nfunc TestExamples(t *testing.T) {\n\texpected := map[string]runtime.Object{\n\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\"redis-master\":           &api.Pod{},\n\t\t\"frontend-service\":       &api.Service{},\n\t\t\"redis-master-service\":   &api.Service{},\n\t\t\"redis-slave-service\":    &api.Service{},\n\t}\n\n\ttested := 0\n\terr := walkJSONFiles(\"..\/examples\/guestbook\", func(name, path string, data []byte) {\n\t\texpectedType, found := expected[name]\n\t\tif !found {\n\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\treturn\n\t\t}\n\t\ttested += 1\n\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t}\n\tif tested != len(expected) {\n\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t}\n}\n\nvar jsonRegexp = regexp.MustCompile(\"(?ms)^```\\\\w*\\\\n(\\\\{.+?\\\\})\\\\w*\\\\n^```\")\n\nfunc TestReadme(t *testing.T) {\n\tpath := \"..\/README.md\"\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to read file: %v\", err)\n\t}\n\n\tmatch := jsonRegexp.FindStringSubmatch(string(data))\n\tif match == nil {\n\t\treturn\n\t}\n\tfor _, json := range match[1:] {\n\t\texpectedType := &api.Pod{}\n\t\tif err := latest.Codec.DecodeInto([]byte(json), expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t\tencoded, err := latest.Codec.Encode(expectedType)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Could not encode object: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tt.Logf(\"Found pod %s\\n%s\", json, encoded)\n\t}\n}\n<commit_msg>Make runtime less global for Codec<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\tswitch t := obj.(type) {\n\tcase *api.ReplicationController:\n\t\terrors = validation.ValidateManifest(&t.DesiredState.PodTemplate.DesiredState.Manifest)\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\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\terrors = validation.ValidateManifest(&t.DesiredState.Manifest)\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\" {\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 TestApiExamples(t *testing.T) {\n\texpected := map[string]runtime.Object{\n\t\t\"controller\":       &api.ReplicationController{},\n\t\t\"controller-list\":  &api.ReplicationControllerList{},\n\t\t\"pod\":              &api.Pod{},\n\t\t\"pod-list\":         &api.PodList{},\n\t\t\"service\":          &api.Service{},\n\t\t\"external-service\": &api.Service{},\n\t\t\"service-list\":     &api.ServiceList{},\n\t}\n\n\ttested := 0\n\terr := walkJSONFiles(\"..\/api\/examples\", func(name, path string, data []byte) {\n\t\texpectedType, found := expected[name]\n\t\tif !found {\n\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\treturn\n\t\t}\n\t\ttested += 1\n\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t}\n\tif tested != len(expected) {\n\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t}\n}\n\nfunc TestExamples(t *testing.T) {\n\texpected := map[string]runtime.Object{\n\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\"redis-master\":           &api.Pod{},\n\t\t\"frontend-service\":       &api.Service{},\n\t\t\"redis-master-service\":   &api.Service{},\n\t\t\"redis-slave-service\":    &api.Service{},\n\t}\n\n\ttested := 0\n\terr := walkJSONFiles(\"..\/examples\/guestbook\", func(name, path string, data []byte) {\n\t\texpectedType, found := expected[name]\n\t\tif !found {\n\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\treturn\n\t\t}\n\t\ttested += 1\n\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t})\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t}\n\tif tested != len(expected) {\n\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t}\n}\n\nvar jsonRegexp = regexp.MustCompile(\"(?ms)^```\\\\w*\\\\n(\\\\{.+?\\\\})\\\\w*\\\\n^```\")\n\nfunc TestReadme(t *testing.T) {\n\tpath := \"..\/README.md\"\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to read file: %v\", err)\n\t}\n\n\tmatch := jsonRegexp.FindStringSubmatch(string(data))\n\tif match == nil {\n\t\treturn\n\t}\n\tfor _, json := range match[1:] {\n\t\texpectedType := &api.Pod{}\n\t\tif err := latest.Codec.DecodeInto([]byte(json), expectedType); err != nil {\n\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\treturn\n\t\t}\n\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t}\n\t\tencoded, err := latest.Codec.Encode(expectedType)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Could not encode object: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tt.Logf(\"Found pod %s\\n%s\", json, encoded)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Wrapper for kasia.go templates designed for easy writing web applications.\npackage kview\n\nimport (\n    \"os\"\n    \"io\"\n    \"log\"\n    \"path\"\n    \"reflect\"\n    \"fmt\"\n    \"github.com\/ziutek\/kasia.go\"\n)\n\nvar (\n    \/\/ You can modify this, if you store templates in a different directory.\n    TemplatesDir = \"templates\"\n\n    \/\/ You can modify this, if want a different error handling.\n    ErrorHandler = func(name string, err os.Error) {\n        log.Printf(\"%%View '%s' error. %s\\n\", name, err.String())\n    }\n)\n\ntype View interface {\n    Copy() View\n    Strict(bool)\n    Div(string, View)\n    Exec(io.Writer, ...interface{})\n    Render(...interface{}) *kasia.NestedTemplate\n}\n\n\/\/ View definition\ntype KView struct {\n    name    string\n    tpl     *kasia.Template\n    globals map[string]interface{}\n}\n\n\/\/ Returns a pointer to a page\nfunc New(name string, globals ...map[string]interface{}) *KView {\n    var (\n        pg  KView\n        err os.Error\n    )\n    pg.name = name\n    pg.tpl, err = kasia.ParseFile(path.Join(TemplatesDir, name))\n    if err != nil {\n        ErrorHandler(name, err)\n    }\n    pg.globals = make(map[string]interface{})\n    \/\/ First some default globals\n    for k, v := range Globals {\n        pg.globals[k] = v\n    }\n    \/\/ globals may default\n    for _, g := range globals {\n        for k, v := range g {\n            pg.globals[k] = v\n        }\n    }\n    return &pg\n}\n\n\/\/ Returns a pointer to a copy of the page\nfunc (pg *KView) Copy() View {\n    new_pg := *pg\n    \/\/ Make a copy of globals\n    new_pg.globals = make(map[string]interface{})\n    for k, v := range pg.globals {\n        new_pg.globals[k] = v\n    }\n    return &new_pg\n}\n\n\/\/ Set strig render flag\nfunc (pg *KView) Strict(strict bool) {\n    pg.tpl.Strict = strict\n}\n\n\/\/ Add subview\nfunc (pg *KView) Div(name string, view View) {\n    pg.globals[name] = view\n}\n\nfunc prepend(slice []interface{}, pre ...interface{}) (ret []interface{}) {\n    ret = make([]interface{}, len(slice) + len(pre))\n    copy(ret, pre)\n    copy(ret[len(pre):], slice)\n    return\n}\n\n\/\/ Render view to wr with data\nfunc (pg *KView) Exec(wr io.Writer, ctx ...interface{}) {\n    \/\/ Add globals to the bottom of the context stack\n    ctx = prepend(ctx, pg.globals)\n    err := pg.tpl.Run(wr, ctx...)\n    if err != nil {\n        ErrorHandler(pg.name, err)\n    }\n}\n\n\/\/ Use this method in template text to render page inside other page.\nfunc (pg *KView) Render(ctx ...interface{}) *kasia.NestedTemplate {\n    if len(ctx) > 0 {\n        \/\/ Check if render was called with full template context as first arg\n        if ci, ok := ctx[0].(kasia.ContextItself); ok {\n            \/\/ Rearange context, remove old globals\n            ctx = append(ci[1:], ctx[1:])\n        }\n    }\n    \/\/ Add globals to the bottom of the context stack\n    ctx = prepend(ctx, pg.globals)\n    return pg.tpl.Nested(ctx...)\n}\n\n\n\/\/ Some useful functions for globals.\n\/\/ You can add there your functions\/variables which will be visable in any\n\/\/ view. See also globals parameter in New function.\nvar Globals = map[string]interface{} {\n    \"len\": func(a interface{}) int {\n        v := reflect.ValueOf(a)\n        if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {\n            return v.Len()\n        }\n        return -1\n    },\n    \"fmt\": fmt.Sprintf,\n}\n<commit_msg>Updated to Go weekly.2011-11-02<commit_after>\/\/ Wrapper for kasia.go templates designed for easy writing web applications.\npackage kview\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"path\"\n\t\"reflect\"\n\t\"fmt\"\n\t\"github.com\/ziutek\/kasia.go\"\n)\n\nvar (\n\t\/\/ You can modify this, if you store templates in a different directory.\n\tTemplatesDir = \"templates\"\n\n\t\/\/ You can modify this, if want a different error handling.\n\tErrorHandler = func(name string, err error) {\n\t\tlog.Printf(\"%%View '%s' error. %s\\n\", name, err.Error())\n\t}\n)\n\ntype View interface {\n\tCopy() View\n\tStrict(bool)\n\tDiv(string, View)\n\tExec(io.Writer, ...interface{})\n\tRender(...interface{}) *kasia.NestedTemplate\n}\n\n\/\/ View definition\ntype KView struct {\n\tname    string\n\ttpl     *kasia.Template\n\tglobals map[string]interface{}\n}\n\n\/\/ Returns a pointer to a page\nfunc New(name string, globals ...map[string]interface{}) *KView {\n\tvar (\n\t\tpg  KView\n\t\terr error\n\t)\n\tpg.name = name\n\tpg.tpl, err = kasia.ParseFile(path.Join(TemplatesDir, name))\n\tif err != nil {\n\t\tErrorHandler(name, err)\n\t}\n\tpg.globals = make(map[string]interface{})\n\t\/\/ First some default globals\n\tfor k, v := range Globals {\n\t\tpg.globals[k] = v\n\t}\n\t\/\/ globals may default\n\tfor _, g := range globals {\n\t\tfor k, v := range g {\n\t\t\tpg.globals[k] = v\n\t\t}\n\t}\n\treturn &pg\n}\n\n\/\/ Returns a pointer to a copy of the page\nfunc (pg *KView) Copy() View {\n\tnew_pg := *pg\n\t\/\/ Make a copy of globals\n\tnew_pg.globals = make(map[string]interface{})\n\tfor k, v := range pg.globals {\n\t\tnew_pg.globals[k] = v\n\t}\n\treturn &new_pg\n}\n\n\/\/ Set strig render flag\nfunc (pg *KView) Strict(strict bool) {\n\tpg.tpl.Strict = strict\n}\n\n\/\/ Add subview\nfunc (pg *KView) Div(name string, view View) {\n\tpg.globals[name] = view\n}\n\nfunc prepend(slice []interface{}, pre ...interface{}) (ret []interface{}) {\n\tret = make([]interface{}, len(slice)+len(pre))\n\tcopy(ret, pre)\n\tcopy(ret[len(pre):], slice)\n\treturn\n}\n\n\/\/ Render view to wr with data\nfunc (pg *KView) Exec(wr io.Writer, ctx ...interface{}) {\n\t\/\/ Add globals to the bottom of the context stack\n\tctx = prepend(ctx, pg.globals)\n\terr := pg.tpl.Run(wr, ctx...)\n\tif err != nil {\n\t\tErrorHandler(pg.name, err)\n\t}\n}\n\n\/\/ Use this method in template text to render page inside other page.\nfunc (pg *KView) Render(ctx ...interface{}) *kasia.NestedTemplate {\n\tif len(ctx) > 0 {\n\t\t\/\/ Check if render was called with full template context as first arg\n\t\tif ci, ok := ctx[0].(kasia.ContextItself); ok {\n\t\t\t\/\/ Rearange context, remove old globals\n\t\t\tctx = append(ci[1:], ctx[1:])\n\t\t}\n\t}\n\t\/\/ Add globals to the bottom of the context stack\n\tctx = prepend(ctx, pg.globals)\n\treturn pg.tpl.Nested(ctx...)\n}\n\n\/\/ Some useful functions for globals.\n\/\/ You can add there your functions\/variables which will be visable in any\n\/\/ view. See also globals parameter in New function.\nvar Globals = map[string]interface{}{\n\t\"len\": func(a interface{}) int {\n\t\tv := reflect.ValueOf(a)\n\t\tif v.Kind() == reflect.Array || v.Kind() == reflect.Slice {\n\t\t\treturn v.Len()\n\t\t}\n\t\treturn -1\n\t},\n\t\"fmt\": fmt.Sprintf,\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"log\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/taku-k\/polymerase\/pkg\/storage\/storagepb\"\n\t\"github.com\/taku-k\/polymerase\/pkg\/tempbackup\/tempbackuppb\"\n)\n\nvar incBackupCmd = &cobra.Command{\n\tUse:   \"inc-backup\",\n\tShort: \"Transfers incremental backups to a polymerase server\",\n\tRunE:  cleanupTempDirRunE(runIncBackup),\n}\n\nfunc runIncBackup(cmd *cobra.Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn usageAndError(cmd)\n\t}\n\n\tif db == \"\" {\n\t\treturn errors.New(\"You should specify db with '--db' flag\")\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\terrCh := make(chan error, 1)\n\tfinishCh := make(chan struct{})\n\n\t\/\/ Fetches latest to_lsn\n\tscli, _ := getStorageClient(ctx, db)\n\tres, err := scli.GetLatestToLSN(context.Background(), &storagepb.GetLatestToLSNRequest{Db: db})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to get latest `to_lsn` with db=%s\", db)\n\t}\n\txtrabackupCfg.ToLsn = res.Lsn\n\n\t\/\/ Builds backup pipeline and start it\n\tr, err := buildBackupPipelineAndStart(ctx, errCh)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to build backup pipeline\")\n\t}\n\n\tgo transferIncBackup(ctx, r, db, errCh, finishCh)\n\n\tselect {\n\tcase err := <-errCh:\n\t\tcancel()\n\t\t<-ctx.Done()\n\t\treturn err\n\tcase <-finishCh:\n\t\tlog.Println(\"Incremental backup succeeded\")\n\t\treturn nil\n\t}\n}\n\nfunc transferIncBackup(ctx context.Context, r io.Reader, db string, errCh chan error, finishCh chan struct{}) {\n\tbcli, _ := getTempBackupClient(ctx, db)\n\tstream, err := bcli.TransferIncBackup(ctx)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\n\tbuf := bufio.NewReader(r)\n\tchunk := make([]byte, 1<<20)\n\tvar key string\n\n\tfor {\n\t\tn, err := buf.Read(chunk)\n\t\tif err == io.EOF {\n\t\t\treply, err := stream.CloseAndRecv()\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(reply)\n\t\t\tkey = reply.Key\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tstream.Send(&tempbackuppb.IncBackupContentStream{\n\t\t\tContent: chunk[:n],\n\t\t\tDb:      db,\n\t\t\tLsn:     xtrabackupCfg.ToLsn,\n\t\t})\n\t}\n\t\/\/ Post xtrabackup_checkpoints\n\tres, err := postXtrabackupCP(ctx, bcli, key)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\tlog.Println(res)\n\tfinishCh <- struct{}{}\n\treturn\n}\n<commit_msg>Fix segmentation fault in case db is not found<commit_after>package cli\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"log\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/taku-k\/polymerase\/pkg\/storage\/storagepb\"\n\t\"github.com\/taku-k\/polymerase\/pkg\/tempbackup\/tempbackuppb\"\n)\n\nvar incBackupCmd = &cobra.Command{\n\tUse:   \"inc-backup\",\n\tShort: \"Transfers incremental backups to a polymerase server\",\n\tRunE:  cleanupTempDirRunE(runIncBackup),\n}\n\nfunc runIncBackup(cmd *cobra.Command, args []string) error {\n\tif len(args) > 0 {\n\t\treturn usageAndError(cmd)\n\t}\n\n\tif db == \"\" {\n\t\treturn errors.New(\"You should specify db with '--db' flag\")\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\terrCh := make(chan error, 1)\n\tfinishCh := make(chan struct{})\n\n\t\/\/ Fetches latest to_lsn\n\tscli, err := getStorageClient(ctx, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := scli.GetLatestToLSN(context.Background(), &storagepb.GetLatestToLSNRequest{Db: db})\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"Failed to get latest `to_lsn` with db=%s\", db)\n\t}\n\txtrabackupCfg.ToLsn = res.Lsn\n\n\t\/\/ Builds backup pipeline and start it\n\tr, err := buildBackupPipelineAndStart(ctx, errCh)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to build backup pipeline\")\n\t}\n\n\tgo transferIncBackup(ctx, r, db, errCh, finishCh)\n\n\tselect {\n\tcase err := <-errCh:\n\t\tcancel()\n\t\t<-ctx.Done()\n\t\treturn err\n\tcase <-finishCh:\n\t\tlog.Println(\"Incremental backup succeeded\")\n\t\treturn nil\n\t}\n}\n\nfunc transferIncBackup(ctx context.Context, r io.Reader, db string, errCh chan error, finishCh chan struct{}) {\n\tbcli, _ := getTempBackupClient(ctx, db)\n\tstream, err := bcli.TransferIncBackup(ctx)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\n\tbuf := bufio.NewReader(r)\n\tchunk := make([]byte, 1<<20)\n\tvar key string\n\n\tfor {\n\t\tn, err := buf.Read(chunk)\n\t\tif err == io.EOF {\n\t\t\treply, err := stream.CloseAndRecv()\n\t\t\tif err != nil {\n\t\t\t\terrCh <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Println(reply)\n\t\t\tkey = reply.Key\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\terrCh <- err\n\t\t\treturn\n\t\t}\n\t\tstream.Send(&tempbackuppb.IncBackupContentStream{\n\t\t\tContent: chunk[:n],\n\t\t\tDb:      db,\n\t\t\tLsn:     xtrabackupCfg.ToLsn,\n\t\t})\n\t}\n\t\/\/ Post xtrabackup_checkpoints\n\tres, err := postXtrabackupCP(ctx, bcli, key)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\tlog.Println(res)\n\tfinishCh <- struct{}{}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/exercism\/cli\/api\"\n\t\"github.com\/exercism\/cli\/cmd\"\n)\n\nconst (\n\t\/\/ Version is the current release of the command-line app.\n\t\/\/ We try to follow Semantic Versioning (http:\/\/semver.org),\n\t\/\/ but with the http:\/\/exercism.io app being a prototype, a\n\t\/\/ lot of things get out of hand.\n\tVersion = \"2.1.0\"\n\n\tdescDebug     = \"Outputs useful debug information.\"\n\tdescConfigure = \"Writes config values to a JSON file.\"\n\tdescDemo      = \"Fetches a demo problem for each language track on exercism.io.\"\n\tdescFetch     = \"Fetches your current problems on exercism.io, as well as the next unstarted problem in each language.\"\n\tdescRestore   = \"Restores completed and current problems on from exercism.io, along with your most recent iteration for each.\"\n\tdescSubmit    = \"Submits a new iteration to a problem on exercism.io.\"\n\tdescSkip      = \"Skips a problem given a language and slug.\"\n\tdescUnsubmit  = \"Deletes the most recently submitted iteration.\"\n\tdescTracks    = \"List the available language tracks\"\n\tdescOpen      = \"Opens the current submission of the specified exercise\"\n\n\tdescLongRestore = \"Restore will pull the latest revisions of exercises that have already been submitted. It will *not* overwrite existing files. If you have made changes to a file and have not submitted it, and you're trying to restore the last submitted version, first move that file out of the way, then call restore.\"\n\tdescDownload    = \"Downloads and saves a specified submission into the local system\"\n\tdescList        = \"Lists all available assignments for a given language\"\n)\n\nfunc main() {\n\tapi.UserAgent = fmt.Sprintf(\"github.com\/exercism\/cli v%s (%s\/%s)\", Version, runtime.GOOS, runtime.GOARCH)\n\n\tapp := cli.NewApp()\n\tapp.Name = \"exercism\"\n\tapp.Usage = \"A command line tool to interact with http:\/\/exercism.io\"\n\tapp.Version = Version\n\tapp.HideVersion = true\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"config, c\",\n\t\t\tUsage:  \"path to config file\",\n\t\t\tEnvVar: \"XDG_CONFIG_HOME,EXERCISM_CONFIG_FILE\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose, v\",\n\t\t\tUsage: \"turn on verbose logging\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"version\",\n\t\t\tUsage: \"print the version\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:   \"debug\",\n\t\t\tUsage:  descDebug,\n\t\t\tAction: cmd.Debug,\n\t\t},\n\t\t{\n\t\t\tName:  \"configure\",\n\t\t\tUsage: descConfigure,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"dir, d\",\n\t\t\t\t\tUsage: \"path to exercises directory\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"host, u\",\n\t\t\t\t\tUsage: \"exercism api host\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"key, k\",\n\t\t\t\t\tUsage: \"exercism.io API key (see http:\/\/exercism.io\/account)\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"api, a\",\n\t\t\t\t\tUsage: \"exercism xapi host\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: cmd.Configure,\n\t\t},\n\t\t{\n\t\t\tName:      \"demo\",\n\t\t\tShortName: \"d\",\n\t\t\tUsage:     descDemo,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"dir, d\",\n\t\t\t\t\tUsage: \"path to use for the demo exercises\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: cmd.Demo,\n\t\t},\n\t\t{\n\t\t\tName:      \"fetch\",\n\t\t\tShortName: \"f\",\n\t\t\tUsage:     descFetch,\n\t\t\tAction:    cmd.Fetch,\n\t\t},\n\t\t{\n\t\t\tName:        \"restore\",\n\t\t\tShortName:   \"r\",\n\t\t\tUsage:       descRestore,\n\t\t\tDescription: descLongRestore,\n\t\t\tAction:      cmd.Restore,\n\t\t},\n\t\t{\n\t\t\tName:   \"skip\",\n\t\t\tUsage:  descSkip,\n\t\t\tAction: cmd.Skip,\n\t\t},\n\t\t{\n\t\t\tName:      \"submit\",\n\t\t\tShortName: \"s\",\n\t\t\tUsage:     descSubmit,\n\t\t\tAction:    cmd.Submit,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName:  \"test\",\n\t\t\t\t\tUsage: \"allow submision of test files\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"unsubmit\",\n\t\t\tShortName: \"u\",\n\t\t\tUsage:     descUnsubmit,\n\t\t\tAction:    cmd.Unsubmit,\n\t\t},\n\t\t{\n\t\t\tName:      \"tracks\",\n\t\t\tShortName: \"t\",\n\t\t\tUsage:     descTracks,\n\t\t\tAction:    cmd.Tracks,\n\t\t},\n\t\t{\n\t\t\tName:      \"open\",\n\t\t\tShortName: \"op\",\n\t\t\tUsage:     descOpen,\n\t\t\tAction:    cmd.Open,\n\t\t},\n\t\t{\n\t\t\tName:      \"download\",\n\t\t\tShortName: \"dl\",\n\t\t\tUsage:     descDownload,\n\t\t\tAction:    cmd.Download,\n\t\t},\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tShortName: \"li\",\n\t\t\tUsage:     descList,\n\t\t\tAction:    cmd.List,\n\t\t},\n\t}\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Fix typo on flag description<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/exercism\/cli\/api\"\n\t\"github.com\/exercism\/cli\/cmd\"\n)\n\nconst (\n\t\/\/ Version is the current release of the command-line app.\n\t\/\/ We try to follow Semantic Versioning (http:\/\/semver.org),\n\t\/\/ but with the http:\/\/exercism.io app being a prototype, a\n\t\/\/ lot of things get out of hand.\n\tVersion = \"2.1.0\"\n\n\tdescDebug     = \"Outputs useful debug information.\"\n\tdescConfigure = \"Writes config values to a JSON file.\"\n\tdescDemo      = \"Fetches a demo problem for each language track on exercism.io.\"\n\tdescFetch     = \"Fetches your current problems on exercism.io, as well as the next unstarted problem in each language.\"\n\tdescRestore   = \"Restores completed and current problems on from exercism.io, along with your most recent iteration for each.\"\n\tdescSubmit    = \"Submits a new iteration to a problem on exercism.io.\"\n\tdescSkip      = \"Skips a problem given a language and slug.\"\n\tdescUnsubmit  = \"Deletes the most recently submitted iteration.\"\n\tdescTracks    = \"List the available language tracks\"\n\tdescOpen      = \"Opens the current submission of the specified exercise\"\n\n\tdescLongRestore = \"Restore will pull the latest revisions of exercises that have already been submitted. It will *not* overwrite existing files. If you have made changes to a file and have not submitted it, and you're trying to restore the last submitted version, first move that file out of the way, then call restore.\"\n\tdescDownload    = \"Downloads and saves a specified submission into the local system\"\n\tdescList        = \"Lists all available assignments for a given language\"\n)\n\nfunc main() {\n\tapi.UserAgent = fmt.Sprintf(\"github.com\/exercism\/cli v%s (%s\/%s)\", Version, runtime.GOOS, runtime.GOARCH)\n\n\tapp := cli.NewApp()\n\tapp.Name = \"exercism\"\n\tapp.Usage = \"A command line tool to interact with http:\/\/exercism.io\"\n\tapp.Version = Version\n\tapp.HideVersion = true\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"config, c\",\n\t\t\tUsage:  \"path to config file\",\n\t\t\tEnvVar: \"XDG_CONFIG_HOME,EXERCISM_CONFIG_FILE\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose, v\",\n\t\t\tUsage: \"turn on verbose logging\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"version\",\n\t\t\tUsage: \"print the version\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:   \"debug\",\n\t\t\tUsage:  descDebug,\n\t\t\tAction: cmd.Debug,\n\t\t},\n\t\t{\n\t\t\tName:  \"configure\",\n\t\t\tUsage: descConfigure,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"dir, d\",\n\t\t\t\t\tUsage: \"path to exercises directory\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"host, u\",\n\t\t\t\t\tUsage: \"exercism api host\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"key, k\",\n\t\t\t\t\tUsage: \"exercism.io API key (see http:\/\/exercism.io\/account)\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"api, a\",\n\t\t\t\t\tUsage: \"exercism xapi host\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: cmd.Configure,\n\t\t},\n\t\t{\n\t\t\tName:      \"demo\",\n\t\t\tShortName: \"d\",\n\t\t\tUsage:     descDemo,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"dir, d\",\n\t\t\t\t\tUsage: \"path to use for the demo exercises\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: cmd.Demo,\n\t\t},\n\t\t{\n\t\t\tName:      \"fetch\",\n\t\t\tShortName: \"f\",\n\t\t\tUsage:     descFetch,\n\t\t\tAction:    cmd.Fetch,\n\t\t},\n\t\t{\n\t\t\tName:        \"restore\",\n\t\t\tShortName:   \"r\",\n\t\t\tUsage:       descRestore,\n\t\t\tDescription: descLongRestore,\n\t\t\tAction:      cmd.Restore,\n\t\t},\n\t\t{\n\t\t\tName:   \"skip\",\n\t\t\tUsage:  descSkip,\n\t\t\tAction: cmd.Skip,\n\t\t},\n\t\t{\n\t\t\tName:      \"submit\",\n\t\t\tShortName: \"s\",\n\t\t\tUsage:     descSubmit,\n\t\t\tAction:    cmd.Submit,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName:  \"test\",\n\t\t\t\t\tUsage: \"allow submission of test files\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"unsubmit\",\n\t\t\tShortName: \"u\",\n\t\t\tUsage:     descUnsubmit,\n\t\t\tAction:    cmd.Unsubmit,\n\t\t},\n\t\t{\n\t\t\tName:      \"tracks\",\n\t\t\tShortName: \"t\",\n\t\t\tUsage:     descTracks,\n\t\t\tAction:    cmd.Tracks,\n\t\t},\n\t\t{\n\t\t\tName:      \"open\",\n\t\t\tShortName: \"op\",\n\t\t\tUsage:     descOpen,\n\t\t\tAction:    cmd.Open,\n\t\t},\n\t\t{\n\t\t\tName:      \"download\",\n\t\t\tShortName: \"dl\",\n\t\t\tUsage:     descDownload,\n\t\t\tAction:    cmd.Download,\n\t\t},\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tShortName: \"li\",\n\t\t\tUsage:     descList,\n\t\t\tAction:    cmd.List,\n\t\t},\n\t}\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gog\n\nimport (\n\t\"bytes\"\n\t\"go\/ast\"\n\t\"go\/doc\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"log\"\n\t\"sort\"\n\n\t\"code.google.com\/p\/go.tools\/go\/loader\"\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n)\n\ntype Doc struct {\n\t*SymbolKey\n\n\tFormat string\n\tData   string\n\n\tFile string `json:\",omitempty\"`\n\tSpan [2]int `json:\",omitempty\"`\n}\n\nfunc parseFiles(fset *token.FileSet, filenames []string) (map[string]*ast.File, error) {\n\tfiles := make(map[string]*ast.File)\n\tfor _, f := range filenames {\n\t\tfile, err := parser.ParseFile(fset, f, nil, parser.ParseComments)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[f] = file\n\t}\n\treturn files, nil\n}\n\nfunc (g *Grapher) emitDocs(pkgInfo *loader.PackageInfo) error {\n\tobjOf := make(map[token.Position]types.Object, len(pkgInfo.Defs))\n\tfor ident, obj := range pkgInfo.Defs {\n\t\tobjOf[g.program.Fset.Position(ident.Pos())] = obj\n\t}\n\n\tvar filenames []string\n\tfor _, f := range pkgInfo.Files {\n\t\tfilenames = append(filenames, g.program.Fset.Position(f.Name.Pos()).Filename)\n\t}\n\tsort.Strings(filenames)\n\tfiles, err := parseFiles(g.program.Fset, filenames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ignore errors because we assume that syntax checking has already occurred\n\tastPkg, _ := ast.NewPackage(g.program.Fset, files, nil, nil)\n\n\tdocPkg := doc.New(astPkg, pkgInfo.Pkg.Path(), doc.AllDecls|doc.AllMethods)\n\n\tif docPkg.Doc != \"\" {\n\t\t\/\/ Find the file that defines package doc.\n\t\tfor _, f := range sortedFiles(astPkg.Files) {\n\t\t\tif f.Doc != nil {\n\t\t\t\terr := g.emitDoc(types.NewPkgName(f.Package, pkgInfo.Pkg, pkgInfo.Pkg.Path()), f.Doc, docPkg.Doc)\n\t\t\t\tif 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}\n\n\temitDocForSpecs := func(pkgInfo *loader.PackageInfo, decl *ast.GenDecl, docstring string) error {\n\t\tfor _, spec := range decl.Specs {\n\t\t\tswitch spec := spec.(type) {\n\t\t\tcase *ast.ValueSpec:\n\t\t\t\tfor _, name := range spec.Names {\n\t\t\t\t\tg.emitDoc(objOf[g.program.Fset.Position(name.Pos())], firstNonNil(decl.Doc, spec.Doc, spec.Comment), docstring)\n\t\t\t\t}\n\t\t\tcase *ast.TypeSpec:\n\t\t\t\tg.emitDoc(objOf[g.program.Fset.Position(spec.Name.Pos())], firstNonNil(decl.Doc, spec.Doc, spec.Comment), docstring)\n\t\t\tdefault:\n\t\t\t\tlog.Panicf(\"unknown spec type %T\", spec)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, cnst := range docPkg.Consts {\n\t\temitDocForSpecs(pkgInfo, cnst.Decl, cnst.Doc)\n\t}\n\n\tfor _, vari := range docPkg.Vars {\n\t\temitDocForSpecs(pkgInfo, vari.Decl, vari.Doc)\n\t}\n\n\tfor _, fun := range docPkg.Funcs {\n\t\tg.emitDoc(objOf[g.program.Fset.Position(fun.Decl.Name.Pos())], fun.Decl.Doc, fun.Doc)\n\t}\n\n\tfor _, typ := range docPkg.Types {\n\t\temitDocForSpecs(pkgInfo, typ.Decl, typ.Doc)\n\t\tfor _, cnst := range typ.Consts {\n\t\t\temitDocForSpecs(pkgInfo, cnst.Decl, cnst.Doc)\n\t\t}\n\t\tfor _, vari := range typ.Vars {\n\t\t\temitDocForSpecs(pkgInfo, vari.Decl, vari.Doc)\n\t\t}\n\t\tfor _, fun := range typ.Funcs {\n\t\t\tg.emitDoc(objOf[g.program.Fset.Position(fun.Decl.Name.Pos())], fun.Decl.Doc, fun.Doc)\n\t\t}\n\t\tfor _, mth := range typ.Methods {\n\t\t\tg.emitDoc(objOf[g.program.Fset.Position(mth.Decl.Name.Pos())], mth.Decl.Doc, mth.Doc)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc firstNonNil(comments ...*ast.CommentGroup) *ast.CommentGroup {\n\tfor _, c := range comments {\n\t\tif c != nil {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (g *Grapher) emitDoc(obj types.Object, dc *ast.CommentGroup, docstring string) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tif docstring == \"\" {\n\t\treturn nil\n\t}\n\n\tkey, _, err := g.symbolInfo(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar htmlBuf bytes.Buffer\n\tdoc.ToHTML(&htmlBuf, docstring, nil)\n\n\tvar filename string\n\tvar span [2]int\n\tif dc != nil {\n\t\tfilename = g.program.Fset.Position(dc.Pos()).Filename\n\t\tspan = makeSpan(g.program.Fset, dc)\n\t}\n\n\tg.addDoc(&Doc{\n\t\tSymbolKey: key,\n\t\tFormat:    \"text\/html\",\n\t\tData:      htmlBuf.String(),\n\t\tFile:      filename,\n\t\tSpan:      span,\n\t})\n\tg.addDoc(&Doc{\n\t\tSymbolKey: key,\n\t\tFormat:    \"text\/plain\",\n\t\tData:      docstring,\n\t\tFile:      filename,\n\t\tSpan:      span,\n\t})\n\n\treturn nil\n}\n\nfunc (g *Grapher) addDoc(doc *Doc) {\n\tg.Docs = append(g.Docs, doc)\n}\n<commit_msg>only get methods tied to a type (fixes duplicate doc error)<commit_after>package gog\n\nimport (\n\t\"bytes\"\n\t\"go\/ast\"\n\t\"go\/doc\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"log\"\n\t\"sort\"\n\n\t\"code.google.com\/p\/go.tools\/go\/loader\"\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n)\n\ntype Doc struct {\n\t*SymbolKey\n\n\tFormat string\n\tData   string\n\n\tFile string `json:\",omitempty\"`\n\tSpan [2]int `json:\",omitempty\"`\n}\n\nfunc parseFiles(fset *token.FileSet, filenames []string) (map[string]*ast.File, error) {\n\tfiles := make(map[string]*ast.File)\n\tfor _, f := range filenames {\n\t\tfile, err := parser.ParseFile(fset, f, nil, parser.ParseComments)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[f] = file\n\t}\n\treturn files, nil\n}\n\nfunc (g *Grapher) emitDocs(pkgInfo *loader.PackageInfo) error {\n\tobjOf := make(map[token.Position]types.Object, len(pkgInfo.Defs))\n\tfor ident, obj := range pkgInfo.Defs {\n\t\tobjOf[g.program.Fset.Position(ident.Pos())] = obj\n\t}\n\n\tvar filenames []string\n\tfor _, f := range pkgInfo.Files {\n\t\tfilenames = append(filenames, g.program.Fset.Position(f.Name.Pos()).Filename)\n\t}\n\tsort.Strings(filenames)\n\tfiles, err := parseFiles(g.program.Fset, filenames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ignore errors because we assume that syntax checking has already occurred\n\tastPkg, _ := ast.NewPackage(g.program.Fset, files, nil, nil)\n\n\tdocPkg := doc.New(astPkg, pkgInfo.Pkg.Path(), doc.AllDecls)\n\n\tif docPkg.Doc != \"\" {\n\t\t\/\/ Find the file that defines package doc.\n\t\tfor _, f := range sortedFiles(astPkg.Files) {\n\t\t\tif f.Doc != nil {\n\t\t\t\terr := g.emitDoc(types.NewPkgName(f.Package, pkgInfo.Pkg, pkgInfo.Pkg.Path()), f.Doc, docPkg.Doc)\n\t\t\t\tif 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}\n\n\temitDocForSpecs := func(pkgInfo *loader.PackageInfo, decl *ast.GenDecl, docstring string) error {\n\t\tfor _, spec := range decl.Specs {\n\t\t\tswitch spec := spec.(type) {\n\t\t\tcase *ast.ValueSpec:\n\t\t\t\tfor _, name := range spec.Names {\n\t\t\t\t\tg.emitDoc(objOf[g.program.Fset.Position(name.Pos())], firstNonNil(decl.Doc, spec.Doc, spec.Comment), docstring)\n\t\t\t\t}\n\t\t\tcase *ast.TypeSpec:\n\t\t\t\tg.emitDoc(objOf[g.program.Fset.Position(spec.Name.Pos())], firstNonNil(decl.Doc, spec.Doc, spec.Comment), docstring)\n\t\t\tdefault:\n\t\t\t\tlog.Panicf(\"unknown spec type %T\", spec)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, cnst := range docPkg.Consts {\n\t\temitDocForSpecs(pkgInfo, cnst.Decl, cnst.Doc)\n\t}\n\n\tfor _, vari := range docPkg.Vars {\n\t\temitDocForSpecs(pkgInfo, vari.Decl, vari.Doc)\n\t}\n\n\tfor _, fun := range docPkg.Funcs {\n\t\tg.emitDoc(objOf[g.program.Fset.Position(fun.Decl.Name.Pos())], fun.Decl.Doc, fun.Doc)\n\t}\n\n\tfor _, typ := range docPkg.Types {\n\t\temitDocForSpecs(pkgInfo, typ.Decl, typ.Doc)\n\t\tfor _, cnst := range typ.Consts {\n\t\t\temitDocForSpecs(pkgInfo, cnst.Decl, cnst.Doc)\n\t\t}\n\t\tfor _, vari := range typ.Vars {\n\t\t\temitDocForSpecs(pkgInfo, vari.Decl, vari.Doc)\n\t\t}\n\t\tfor _, fun := range typ.Funcs {\n\t\t\tg.emitDoc(objOf[g.program.Fset.Position(fun.Decl.Name.Pos())], fun.Decl.Doc, fun.Doc)\n\t\t}\n\t\tfor _, mth := range typ.Methods {\n\t\t\tg.emitDoc(objOf[g.program.Fset.Position(mth.Decl.Name.Pos())], mth.Decl.Doc, mth.Doc)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc firstNonNil(comments ...*ast.CommentGroup) *ast.CommentGroup {\n\tfor _, c := range comments {\n\t\tif c != nil {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (g *Grapher) emitDoc(obj types.Object, dc *ast.CommentGroup, docstring string) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tif docstring == \"\" {\n\t\treturn nil\n\t}\n\n\tkey, _, err := g.symbolInfo(obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar htmlBuf bytes.Buffer\n\tdoc.ToHTML(&htmlBuf, docstring, nil)\n\n\tvar filename string\n\tvar span [2]int\n\tif dc != nil {\n\t\tfilename = g.program.Fset.Position(dc.Pos()).Filename\n\t\tspan = makeSpan(g.program.Fset, dc)\n\t}\n\n\tg.addDoc(&Doc{\n\t\tSymbolKey: key,\n\t\tFormat:    \"text\/html\",\n\t\tData:      htmlBuf.String(),\n\t\tFile:      filename,\n\t\tSpan:      span,\n\t})\n\tg.addDoc(&Doc{\n\t\tSymbolKey: key,\n\t\tFormat:    \"text\/plain\",\n\t\tData:      docstring,\n\t\tFile:      filename,\n\t\tSpan:      span,\n\t})\n\n\treturn nil\n}\n\nfunc (g *Grapher) addDoc(doc *Doc) {\n\tg.Docs = append(g.Docs, doc)\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 framework\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pborman\/uuid\"\n\tinternalapi \"k8s.io\/kubernetes\/pkg\/kubelet\/apis\/cri\"\n\truntimeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/apis\/cri\/v1alpha1\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/remote\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar (\n\t\/\/lock for uuid\n\tuuidLock sync.Mutex\n\n\t\/\/ lastUUID record last generated uuid from NewUUID()\n\tlastUUID uuid.UUID\n)\n\nconst (\n\t\/\/ DefaultUIDPrefix is a default UID prefix of PodSandbox\n\tDefaultUIDPrefix string = \"cri-test-uid\"\n\n\t\/\/ DefaultNamespacePrefix is a default namespace prefix of PodSandbox\n\tDefaultNamespacePrefix string = \"cri-test-namespace\"\n\n\t\/\/ DefaultAttempt is a default attempt prefix of PodSandbox or container\n\tDefaultAttempt uint32 = 2\n\n\t\/\/ DefaultContainerImage is the default image for container using\n\tDefaultContainerImage string = \"gcr.io\/google_containers\/busybox:1.24\"\n\n\t\/\/ DefaultStopContainerTimeout is the default timeout for stopping container\n\tDefaultStopContainerTimeout int64 = 60\n)\n\n\/\/ LoadCRIClient creates a InternalAPIClient.\nfunc LoadCRIClient() (*InternalAPIClient, error) {\n\trService, err := remote.NewRemoteRuntimeService(TestContext.RuntimeServiceAddr, TestContext.RuntimeServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiService, err := remote.NewRemoteImageService(TestContext.ImageServiceAddr, TestContext.ImageServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &InternalAPIClient{\n\t\tCRIRuntimeClient: rService,\n\t\tCRIImageClient:   iService,\n\t}, nil\n}\n\nfunc nowStamp() string {\n\treturn time.Now().Format(time.StampMilli)\n}\n\nfunc log(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}\n\n\/\/ Logf prints a info message.\nfunc Logf(format string, args ...interface{}) {\n\tlog(\"INFO\", format, args...)\n}\n\n\/\/ Failf prints an error message.\nfunc Failf(format string, args ...interface{}) {\n\tmsg := fmt.Sprintf(format, args...)\n\tlog(\"INFO\", msg)\n\tFail(nowStamp()+\": \"+msg, 1)\n}\n\n\/\/ ExpectNoError reports error if err is not nil.\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\n}\n\n\/\/ NewUUID creates a new UUID string.\nfunc NewUUID() string {\n\tuuidLock.Lock()\n\tdefer uuidLock.Unlock()\n\tresult := uuid.NewUUID()\n\t\/\/ The UUID package is naive and can generate identical UUIDs if the\n\t\/\/ time interval is quick enough.\n\t\/\/ The UUID uses 100 ns increments so it's short enough to actively\n\t\/\/ wait for a new value.\n\tfor uuid.Equal(lastUUID, result) == true {\n\t\tresult = uuid.NewUUID()\n\t}\n\tlastUUID = result\n\treturn result.String()\n}\n\n\/\/ RunDefaultPodSandbox runs a PodSandbox with default options.\nfunc RunDefaultPodSandbox(c internalapi.RuntimeService, prefix string) string {\n\tpodSandboxName := prefix + NewUUID()\n\tuid := DefaultUIDPrefix + NewUUID()\n\tnamespace := DefaultNamespacePrefix + NewUUID()\n\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: BuildPodSandboxMetadata(podSandboxName, uid, namespace, DefaultAttempt),\n\t\tLinux:    &runtimeapi.LinuxPodSandboxConfig{},\n\t}\n\treturn RunPodSandbox(c, config)\n}\n\n\/\/ BuildPodSandboxMetadata builds PodSandboxMetadata.\nfunc BuildPodSandboxMetadata(podSandboxName, uid, namespace string, attempt uint32) *runtimeapi.PodSandboxMetadata {\n\treturn &runtimeapi.PodSandboxMetadata{\n\t\tName:      podSandboxName,\n\t\tUid:       uid,\n\t\tNamespace: namespace,\n\t\tAttempt:   attempt,\n\t}\n}\n\n\/\/ RunPodSandbox runs a PodSandbox.\nfunc RunPodSandbox(c internalapi.RuntimeService, config *runtimeapi.PodSandboxConfig) string {\n\tpodID, err := c.RunPodSandbox(config)\n\tExpectNoError(err, \"failed to create PodSandbox: %v\", err)\n\treturn podID\n}\n\n\/\/ CreatePodSandboxForContainer creates a PodSandbox for creating containers.\nfunc CreatePodSandboxForContainer(c internalapi.RuntimeService) (string, *runtimeapi.PodSandboxConfig) {\n\tpodSandboxName := \"create-PodSandbox-for-container-\" + NewUUID()\n\tuid := DefaultUIDPrefix + NewUUID()\n\tnamespace := DefaultNamespacePrefix + NewUUID()\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: BuildPodSandboxMetadata(podSandboxName, uid, namespace, DefaultAttempt),\n\t\tLinux:    &runtimeapi.LinuxPodSandboxConfig{},\n\t}\n\n\tpodID := RunPodSandbox(c, config)\n\treturn podID, config\n}\n\n\/\/ BuildContainerMetadata builds containerMetadata.\nfunc BuildContainerMetadata(containerName string, attempt uint32) *runtimeapi.ContainerMetadata {\n\treturn &runtimeapi.ContainerMetadata{\n\t\tName:    containerName,\n\t\tAttempt: attempt,\n\t}\n}\n\n\/\/ CreateDefaultContainer creates a  default container with default options.\nfunc CreateDefaultContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string) string {\n\tcontainerName := prefix + NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: BuildContainerMetadata(containerName, DefaultAttempt),\n\t\tImage:    &runtimeapi.ImageSpec{Image: DefaultContainerImage},\n\t\tCommand:  []string{\"top\"},\n\t\tLinux:    &runtimeapi.LinuxContainerConfig{},\n\t}\n\n\treturn CreateContainer(rc, ic, containerConfig, podID, podConfig)\n}\n\n\/\/ CreateContainer creates a container with the prefix of containerName.\nfunc CreateContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, config *runtimeapi.ContainerConfig, podID string, podConfig *runtimeapi.PodSandboxConfig) string {\n\t\/\/ Pull the image if it does not exist.\n\timageName := config.Image.Image\n\tif !strings.Contains(imageName, \":\") {\n\t\timageName = imageName + \":latest\"\n\t\tLogf(\"Use latest as default image tag.\")\n\t}\n\n\tstatus := ImageStatus(ic, imageName)\n\tif status == nil {\n\t\tPullPublicImage(ic, imageName)\n\t}\n\n\tBy(\"Create container.\")\n\tcontainerID, err := rc.CreateContainer(podID, config, podConfig)\n\tExpectNoError(err, \"failed to create container: %v\", err)\n\tLogf(\"Created container %q\\n\", containerID)\n\treturn containerID\n}\n\n\/\/ ImageStatus gets the status of the image named imageName.\nfunc ImageStatus(c internalapi.ImageManagerService, imageName string) *runtimeapi.Image {\n\tBy(\"Get image status for image: \" + imageName)\n\timageSpec := &runtimeapi.ImageSpec{\n\t\tImage: imageName,\n\t}\n\tstatus, err := c.ImageStatus(imageSpec)\n\tExpectNoError(err, \"failed to get image status: %v\", err)\n\treturn status\n}\n\n\/\/ ListImage list the image filtered by the image filter.\nfunc ListImage(c internalapi.ImageManagerService, filter *runtimeapi.ImageFilter) []*runtimeapi.Image {\n\timages, err := c.ListImages(filter)\n\tExpectNoError(err, \"Failed to get image list: %v\", err)\n\treturn images\n}\n\n\/\/ PullPublicImage pulls the public image named imageName.\nfunc PullPublicImage(c internalapi.ImageManagerService, imageName string) {\n\tif !strings.Contains(imageName, \":\") {\n\t\timageName = imageName + \":latest\"\n\t\tLogf(\"Use latest as default image tag.\")\n\t}\n\n\tBy(\"Pull image : \" + imageName)\n\timageSpec := &runtimeapi.ImageSpec{\n\t\tImage: imageName,\n\t}\n\t_, err := c.PullImage(imageSpec, nil)\n\tExpectNoError(err, \"failed to pull image: %v\", err)\n}\n<commit_msg>Use busybox:1.26 instead of gcr.io\/google_containers\/busybox:1.24. (#99)<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 framework\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pborman\/uuid\"\n\tinternalapi \"k8s.io\/kubernetes\/pkg\/kubelet\/apis\/cri\"\n\truntimeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/apis\/cri\/v1alpha1\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/remote\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar (\n\t\/\/lock for uuid\n\tuuidLock sync.Mutex\n\n\t\/\/ lastUUID record last generated uuid from NewUUID()\n\tlastUUID uuid.UUID\n)\n\nconst (\n\t\/\/ DefaultUIDPrefix is a default UID prefix of PodSandbox\n\tDefaultUIDPrefix string = \"cri-test-uid\"\n\n\t\/\/ DefaultNamespacePrefix is a default namespace prefix of PodSandbox\n\tDefaultNamespacePrefix string = \"cri-test-namespace\"\n\n\t\/\/ DefaultAttempt is a default attempt prefix of PodSandbox or container\n\tDefaultAttempt uint32 = 2\n\n\t\/\/ DefaultContainerImage is the default image for container using\n\tDefaultContainerImage string = \"busybox:1.26\"\n\n\t\/\/ DefaultStopContainerTimeout is the default timeout for stopping container\n\tDefaultStopContainerTimeout int64 = 60\n)\n\n\/\/ LoadCRIClient creates a InternalAPIClient.\nfunc LoadCRIClient() (*InternalAPIClient, error) {\n\trService, err := remote.NewRemoteRuntimeService(TestContext.RuntimeServiceAddr, TestContext.RuntimeServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiService, err := remote.NewRemoteImageService(TestContext.ImageServiceAddr, TestContext.ImageServiceTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &InternalAPIClient{\n\t\tCRIRuntimeClient: rService,\n\t\tCRIImageClient:   iService,\n\t}, nil\n}\n\nfunc nowStamp() string {\n\treturn time.Now().Format(time.StampMilli)\n}\n\nfunc log(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}\n\n\/\/ Logf prints a info message.\nfunc Logf(format string, args ...interface{}) {\n\tlog(\"INFO\", format, args...)\n}\n\n\/\/ Failf prints an error message.\nfunc Failf(format string, args ...interface{}) {\n\tmsg := fmt.Sprintf(format, args...)\n\tlog(\"INFO\", msg)\n\tFail(nowStamp()+\": \"+msg, 1)\n}\n\n\/\/ ExpectNoError reports error if err is not nil.\nfunc ExpectNoError(err error, explain ...interface{}) {\n\tif err != nil {\n\t\tLogf(\"Unexpected error occurred: %v\", err)\n\t}\n\tExpectWithOffset(1, err).NotTo(HaveOccurred(), explain...)\n}\n\n\/\/ NewUUID creates a new UUID string.\nfunc NewUUID() string {\n\tuuidLock.Lock()\n\tdefer uuidLock.Unlock()\n\tresult := uuid.NewUUID()\n\t\/\/ The UUID package is naive and can generate identical UUIDs if the\n\t\/\/ time interval is quick enough.\n\t\/\/ The UUID uses 100 ns increments so it's short enough to actively\n\t\/\/ wait for a new value.\n\tfor uuid.Equal(lastUUID, result) == true {\n\t\tresult = uuid.NewUUID()\n\t}\n\tlastUUID = result\n\treturn result.String()\n}\n\n\/\/ RunDefaultPodSandbox runs a PodSandbox with default options.\nfunc RunDefaultPodSandbox(c internalapi.RuntimeService, prefix string) string {\n\tpodSandboxName := prefix + NewUUID()\n\tuid := DefaultUIDPrefix + NewUUID()\n\tnamespace := DefaultNamespacePrefix + NewUUID()\n\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: BuildPodSandboxMetadata(podSandboxName, uid, namespace, DefaultAttempt),\n\t\tLinux:    &runtimeapi.LinuxPodSandboxConfig{},\n\t}\n\treturn RunPodSandbox(c, config)\n}\n\n\/\/ BuildPodSandboxMetadata builds PodSandboxMetadata.\nfunc BuildPodSandboxMetadata(podSandboxName, uid, namespace string, attempt uint32) *runtimeapi.PodSandboxMetadata {\n\treturn &runtimeapi.PodSandboxMetadata{\n\t\tName:      podSandboxName,\n\t\tUid:       uid,\n\t\tNamespace: namespace,\n\t\tAttempt:   attempt,\n\t}\n}\n\n\/\/ RunPodSandbox runs a PodSandbox.\nfunc RunPodSandbox(c internalapi.RuntimeService, config *runtimeapi.PodSandboxConfig) string {\n\tpodID, err := c.RunPodSandbox(config)\n\tExpectNoError(err, \"failed to create PodSandbox: %v\", err)\n\treturn podID\n}\n\n\/\/ CreatePodSandboxForContainer creates a PodSandbox for creating containers.\nfunc CreatePodSandboxForContainer(c internalapi.RuntimeService) (string, *runtimeapi.PodSandboxConfig) {\n\tpodSandboxName := \"create-PodSandbox-for-container-\" + NewUUID()\n\tuid := DefaultUIDPrefix + NewUUID()\n\tnamespace := DefaultNamespacePrefix + NewUUID()\n\tconfig := &runtimeapi.PodSandboxConfig{\n\t\tMetadata: BuildPodSandboxMetadata(podSandboxName, uid, namespace, DefaultAttempt),\n\t\tLinux:    &runtimeapi.LinuxPodSandboxConfig{},\n\t}\n\n\tpodID := RunPodSandbox(c, config)\n\treturn podID, config\n}\n\n\/\/ BuildContainerMetadata builds containerMetadata.\nfunc BuildContainerMetadata(containerName string, attempt uint32) *runtimeapi.ContainerMetadata {\n\treturn &runtimeapi.ContainerMetadata{\n\t\tName:    containerName,\n\t\tAttempt: attempt,\n\t}\n}\n\n\/\/ CreateDefaultContainer creates a  default container with default options.\nfunc CreateDefaultContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string) string {\n\tcontainerName := prefix + NewUUID()\n\tcontainerConfig := &runtimeapi.ContainerConfig{\n\t\tMetadata: BuildContainerMetadata(containerName, DefaultAttempt),\n\t\tImage:    &runtimeapi.ImageSpec{Image: DefaultContainerImage},\n\t\tCommand:  []string{\"top\"},\n\t\tLinux:    &runtimeapi.LinuxContainerConfig{},\n\t}\n\n\treturn CreateContainer(rc, ic, containerConfig, podID, podConfig)\n}\n\n\/\/ CreateContainer creates a container with the prefix of containerName.\nfunc CreateContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, config *runtimeapi.ContainerConfig, podID string, podConfig *runtimeapi.PodSandboxConfig) string {\n\t\/\/ Pull the image if it does not exist.\n\timageName := config.Image.Image\n\tif !strings.Contains(imageName, \":\") {\n\t\timageName = imageName + \":latest\"\n\t\tLogf(\"Use latest as default image tag.\")\n\t}\n\n\tstatus := ImageStatus(ic, imageName)\n\tif status == nil {\n\t\tPullPublicImage(ic, imageName)\n\t}\n\n\tBy(\"Create container.\")\n\tcontainerID, err := rc.CreateContainer(podID, config, podConfig)\n\tExpectNoError(err, \"failed to create container: %v\", err)\n\tLogf(\"Created container %q\\n\", containerID)\n\treturn containerID\n}\n\n\/\/ ImageStatus gets the status of the image named imageName.\nfunc ImageStatus(c internalapi.ImageManagerService, imageName string) *runtimeapi.Image {\n\tBy(\"Get image status for image: \" + imageName)\n\timageSpec := &runtimeapi.ImageSpec{\n\t\tImage: imageName,\n\t}\n\tstatus, err := c.ImageStatus(imageSpec)\n\tExpectNoError(err, \"failed to get image status: %v\", err)\n\treturn status\n}\n\n\/\/ ListImage list the image filtered by the image filter.\nfunc ListImage(c internalapi.ImageManagerService, filter *runtimeapi.ImageFilter) []*runtimeapi.Image {\n\timages, err := c.ListImages(filter)\n\tExpectNoError(err, \"Failed to get image list: %v\", err)\n\treturn images\n}\n\n\/\/ PullPublicImage pulls the public image named imageName.\nfunc PullPublicImage(c internalapi.ImageManagerService, imageName string) {\n\tif !strings.Contains(imageName, \":\") {\n\t\timageName = imageName + \":latest\"\n\t\tLogf(\"Use latest as default image tag.\")\n\t}\n\n\tBy(\"Pull image : \" + imageName)\n\timageSpec := &runtimeapi.ImageSpec{\n\t\tImage: imageName,\n\t}\n\t_, err := c.PullImage(imageSpec, nil)\n\tExpectNoError(err, \"failed to pull image: %v\", err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package handler\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"path\"\n\n\t\"github.com\/go-chi\/chi\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/webhippie\/terrastate\/pkg\/config\"\n)\n\n\/\/ Unlock is used to unlock a specific state.\nfunc Unlock(logger log.Logger) http.HandlerFunc {\n\tlogger = log.WithPrefix(logger, \"handler\", \"unlock\")\n\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tfull := path.Join(\n\t\t\tconfig.Server.Storage,\n\t\t\tchi.URLParam(req, \"*\"),\n\t\t\t\"terraform.tfstate\",\n\t\t)\n\n\t\t\/\/ TODO: handle unlock requests\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tlevel.Info(logger).Log(\n\t\t\t\"msg\", \"unlock\",\n\t\t\t\"file\", full,\n\t\t\t\"body\", body,\n\t\t)\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\tfmt.Fprintln(w, \"\")\n\t}\n}\n<commit_msg>Integrated unlock endpoint<commit_after>package handler\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/go-chi\/chi\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/webhippie\/terrastate\/pkg\/config\"\n\t\"github.com\/webhippie\/terrastate\/pkg\/model\"\n)\n\n\/\/ Unlock is used to unlock a specific state.\nfunc Unlock(logger log.Logger) http.HandlerFunc {\n\tlogger = log.WithPrefix(logger, \"handler\", \"unlock\")\n\n\treturn func(w http.ResponseWriter, req *http.Request) {\n\t\tdir := strings.Replace(\n\t\t\tpath.Join(\n\t\t\t\tconfig.Server.Storage,\n\t\t\t\tchi.URLParam(req, \"*\"),\n\t\t\t),\n\t\t\t\"..\/\", \"\", -1,\n\t\t)\n\n\t\tfull := path.Join(\n\t\t\tdir,\n\t\t\t\"terraform.lock\",\n\t\t)\n\n\t\trequested := model.LockInfo{}\n\n\t\tif err := json.NewDecoder(req.Body).Decode(&requested); err != nil {\n\t\t\tlevel.Info(logger).Log(\n\t\t\t\t\"msg\", \"failed to parse body\",\n\t\t\t\t\"err\", err,\n\t\t\t)\n\n\t\t\thttp.Error(\n\t\t\t\tw,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\texisting := model.LockInfo{}\n\n\t\tfile, err := ioutil.ReadFile(\n\t\t\tfull,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlevel.Info(logger).Log(\n\t\t\t\t\"msg\", \"failed to read lock file\",\n\t\t\t\t\"file\", full,\n\t\t\t\t\"err\", err,\n\t\t\t)\n\n\t\t\thttp.Error(\n\t\t\t\tw,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err := json.Unmarshal(file, &existing); err != nil {\n\t\t\tlevel.Info(logger).Log(\n\t\t\t\t\"msg\", \"failed to parse lock file\",\n\t\t\t\t\"file\", full,\n\t\t\t\t\"err\", err,\n\t\t\t)\n\n\t\t\thttp.Error(\n\t\t\t\tw,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tif err := os.Remove(full); err != nil {\n\t\t\tlevel.Info(logger).Log(\n\t\t\t\t\"msg\", \"failed to delete lock file\",\n\t\t\t\t\"file\", full,\n\t\t\t\t\"err\", err,\n\t\t\t)\n\n\t\t\thttp.Error(\n\t\t\t\tw,\n\t\t\t\thttp.StatusText(http.StatusInternalServerError),\n\t\t\t\thttp.StatusInternalServerError,\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tlevel.Info(logger).Log(\n\t\t\t\"msg\", \"successfully unlocked state\",\n\t\t\t\"existing\", existing.ID,\n\t\t\t\"requested\", requested.ID,\n\t\t)\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017-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 ipam\n\nimport (\n\t\"fmt\"\n\t\"math\/big\"\n\t\"net\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/ip\"\n\n\tk8sAPI \"k8s.io\/kubernetes\/pkg\/apis\/core\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/core\/service\/ipallocator\"\n)\n\ntype hostScopeAllocator struct {\n\tallocCIDR *net.IPNet\n\tallocator *ipallocator.Range\n}\n\nfunc newHostScopeAllocator(n *net.IPNet) Allocator {\n\ta := &hostScopeAllocator{\n\t\tallocCIDR: n,\n\t\tallocator: ipallocator.NewCIDRRange(n),\n\t}\n\n\treturn a\n}\n\nfunc (h *hostScopeAllocator) Allocate(ip net.IP, owner string) (*AllocationResult, error) {\n\tif err := h.allocator.Allocate(ip); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AllocationResult{IP: ip}, nil\n}\n\nfunc (h *hostScopeAllocator) Release(ip net.IP) error {\n\treturn h.allocator.Release(ip)\n}\n\nfunc (h *hostScopeAllocator) AllocateNext(owner string) (*AllocationResult, error) {\n\tip, err := h.allocator.AllocateNext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AllocationResult{IP: ip}, nil\n}\n\nfunc (h *hostScopeAllocator) Dump() (map[string]string, string) {\n\talloc := map[string]string{}\n\tral := k8sAPI.RangeAllocation{}\n\th.allocator.Snapshot(&ral)\n\torigIP := big.NewInt(0).SetBytes(h.allocCIDR.IP.To4())\n\tbits := big.NewInt(0).SetBytes(ral.Data)\n\tfor i := 0; i < bits.BitLen(); i++ {\n\t\tif bits.Bit(i) != 0 {\n\t\t\tip := net.IP(big.NewInt(0).Add(origIP, big.NewInt(int64(uint(i+1)))).Bytes()).String()\n\t\t\talloc[ip] = \"\"\n\t\t}\n\t}\n\n\tmaxIPs := ip.CountIPsInCIDR(h.allocCIDR)\n\tstatus := fmt.Sprintf(\"%d\/%d allocated from %s\", len(alloc), maxIPs, h.allocCIDR.String())\n\n\treturn alloc, status\n}\n<commit_msg>ipam: fix v6 address corruption in cilium status dump<commit_after>\/\/ Copyright 2017-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 ipam\n\nimport (\n\t\"fmt\"\n\t\"math\/big\"\n\t\"net\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/ip\"\n\n\tk8sAPI \"k8s.io\/kubernetes\/pkg\/apis\/core\"\n\t\"k8s.io\/kubernetes\/pkg\/registry\/core\/service\/ipallocator\"\n)\n\ntype hostScopeAllocator struct {\n\tallocCIDR *net.IPNet\n\tallocator *ipallocator.Range\n}\n\nfunc newHostScopeAllocator(n *net.IPNet) Allocator {\n\ta := &hostScopeAllocator{\n\t\tallocCIDR: n,\n\t\tallocator: ipallocator.NewCIDRRange(n),\n\t}\n\n\treturn a\n}\n\nfunc (h *hostScopeAllocator) Allocate(ip net.IP, owner string) (*AllocationResult, error) {\n\tif err := h.allocator.Allocate(ip); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AllocationResult{IP: ip}, nil\n}\n\nfunc (h *hostScopeAllocator) Release(ip net.IP) error {\n\treturn h.allocator.Release(ip)\n}\n\nfunc (h *hostScopeAllocator) AllocateNext(owner string) (*AllocationResult, error) {\n\tip, err := h.allocator.AllocateNext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AllocationResult{IP: ip}, nil\n}\n\nfunc (h *hostScopeAllocator) Dump() (map[string]string, string) {\n\tvar origIP *big.Int\n\talloc := map[string]string{}\n\tral := k8sAPI.RangeAllocation{}\n\th.allocator.Snapshot(&ral)\n\tif h.allocCIDR.IP.To4() != nil {\n\t\torigIP = big.NewInt(0).SetBytes(h.allocCIDR.IP.To4())\n\t} else {\n\t\torigIP = big.NewInt(0).SetBytes(h.allocCIDR.IP.To16())\n\t}\n\tbits := big.NewInt(0).SetBytes(ral.Data)\n\tfor i := 0; i < bits.BitLen(); i++ {\n\t\tif bits.Bit(i) != 0 {\n\t\t\tip := net.IP(big.NewInt(0).Add(origIP, big.NewInt(int64(uint(i+1)))).Bytes()).String()\n\t\t\talloc[ip] = \"\"\n\t\t}\n\t}\n\n\tmaxIPs := ip.CountIPsInCIDR(h.allocCIDR)\n\tstatus := fmt.Sprintf(\"%d\/%d allocated from %s\", len(alloc), maxIPs, h.allocCIDR.String())\n\n\treturn alloc, status\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Albert Nigmatzianov. 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\n\/\/ Package id3v2 is the ID3 parsing and writing library for Go.\n\/\/\n\/\/ Example of usage:\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"log\"\n\/\/\n\/\/\t\t\"github.com\/bogem\/id3v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\t\/\/ Open file and find tag in it\n\/\/\t\ttag, err := id3v2.Open(\"file.mp3\")\n\/\/\t\tif err != nil {\n\/\/\t\t\tlog.Fatal(\"Error while opening mp3 file: \", err)\n\/\/\t\t}\n\/\/\t\tdefer tag.Close()\n\/\/\n\/\/\t\t\/\/ Read tags\n\/\/\t\tfmt.Println(tag.Artist())\n\/\/\t\tfmt.Println(tag.Title())\n\/\/\n\/\/\t\t\/\/ Set tags\n\/\/\t\ttag.SetArtist(\"Artist\")\n\/\/\t\ttag.SetTitle(\"Title\")\n\/\/\n\/\/\t\tcomment := id3v2.CommentFrame{\n\/\/\t\t\tEncoding:   id3v2.ENUTF8,\n\/\/\t\t\tLanguage:   \"eng\",\n\/\/\t\t\tDesciption: \"My opinion\",\n\/\/\t\t\tText:       \"Very good song\",\n\/\/\t\t}\n\/\/\t\ttag.AddCommentFrame(comment)\n\/\/\n\/\/\t\t\/\/ Write it to file\n\/\/\t\tif err = tag.Save(); err != nil {\n\/\/\t\t\tlog.Fatal(\"Error while saving a tag: \", err)\n\/\/\t\t}\n\/\/\t}\npackage id3v2\n\nimport (\n\t\"os\"\n\n\t\"github.com\/bogem\/id3v2\/util\"\n)\n\n\/\/ Available picture types for picture frame.\nconst (\n\tPTOther                   = 0\n\tPTFileIcon                = 1\n\tPTOtherFileIcon           = 2\n\tPTFrontCover              = 3\n\tPTBackCover               = 4\n\tPTLeafletPage             = 5\n\tPTMedia                   = 6\n\tPTLeadArtistSoloist       = 7\n\tPTArtistPerformer         = 8\n\tPTConductor               = 9\n\tPTBandOrchestra           = 10\n\tPTComposer                = 11\n\tPTLyricistTextWriter      = 12\n\tPTRecordingLocation       = 13\n\tPTDuringRecording         = 14\n\tPTDuringPerformance       = 15\n\tPTMovieScreenCapture      = 16\n\tPTBrightColouredFish      = 17\n\tPTIllustration            = 18\n\tPTBandArtistLogotype      = 19\n\tPTPublisherStudioLogotype = 20\n)\n\n\/\/ Available encodings.\nvar (\n\t\/\/ ISO-8859-1.\n\tENISO = util.Encoding{\n\t\tKey:              0,\n\t\tTerminationBytes: []byte{0},\n\t}\n\n\t\/\/ UTF-16 encoded Unicode with BOM.\n\tENUTF16 = util.Encoding{\n\t\tKey:              1,\n\t\tTerminationBytes: []byte{0, 0},\n\t}\n\n\t\/\/ UTF-16BE encoded Unicode without BOM.\n\tENUTF16BE = util.Encoding{\n\t\tKey:              2,\n\t\tTerminationBytes: []byte{0, 0},\n\t}\n\n\t\/\/ UTF-8 encoded Unicode.\n\tENUTF8 = util.Encoding{\n\t\tKey:              3,\n\t\tTerminationBytes: []byte{0},\n\t}\n\n\tEncodings = []util.Encoding{ENISO, ENUTF16, ENUTF16BE, ENUTF8}\n)\n\n\/\/ Open opens file with string name and finds tag in it.\nfunc Open(name string) (*Tag, error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ParseFile(file)\n}\n\n\/\/ ParseFile parses opened file and finds tag in it.\nfunc ParseFile(file *os.File) (*Tag, error) {\n\treturn parseTag(file)\n}\n<commit_msg>Use iota instead of explicit numbers for picture types<commit_after>\/\/ Copyright 2016 Albert Nigmatzianov. 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\n\/\/ Package id3v2 is the ID3 parsing and writing library for Go.\n\/\/\n\/\/ Example of usage:\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"log\"\n\/\/\n\/\/\t\t\"github.com\/bogem\/id3v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\t\/\/ Open file and find tag in it\n\/\/\t\ttag, err := id3v2.Open(\"file.mp3\")\n\/\/\t\tif err != nil {\n\/\/\t\t\tlog.Fatal(\"Error while opening mp3 file: \", err)\n\/\/\t\t}\n\/\/\t\tdefer tag.Close()\n\/\/\n\/\/\t\t\/\/ Read tags\n\/\/\t\tfmt.Println(tag.Artist())\n\/\/\t\tfmt.Println(tag.Title())\n\/\/\n\/\/\t\t\/\/ Set tags\n\/\/\t\ttag.SetArtist(\"Artist\")\n\/\/\t\ttag.SetTitle(\"Title\")\n\/\/\n\/\/\t\tcomment := id3v2.CommentFrame{\n\/\/\t\t\tEncoding:   id3v2.ENUTF8,\n\/\/\t\t\tLanguage:   \"eng\",\n\/\/\t\t\tDesciption: \"My opinion\",\n\/\/\t\t\tText:       \"Very good song\",\n\/\/\t\t}\n\/\/\t\ttag.AddCommentFrame(comment)\n\/\/\n\/\/\t\t\/\/ Write it to file\n\/\/\t\tif err = tag.Save(); err != nil {\n\/\/\t\t\tlog.Fatal(\"Error while saving a tag: \", err)\n\/\/\t\t}\n\/\/\t}\npackage id3v2\n\nimport (\n\t\"os\"\n\n\t\"github.com\/bogem\/id3v2\/util\"\n)\n\n\/\/ Available picture types for picture frame.\nconst (\n\tPTOther = iota\n\tPTFileIcon\n\tPTOtherFileIcon\n\tPTFrontCover\n\tPTBackCover\n\tPTLeafletPage\n\tPTMedia\n\tPTLeadArtistSoloist\n\tPTArtistPerformer\n\tPTConductor\n\tPTBandOrchestra\n\tPTComposer\n\tPTLyricistTextWriter\n\tPTRecordingLocation\n\tPTDuringRecording\n\tPTDuringPerformance\n\tPTMovieScreenCapture\n\tPTBrightColouredFish\n\tPTIllustration\n\tPTBandArtistLogotype\n\tPTPublisherStudioLogotype\n)\n\n\/\/ Available encodings.\nvar (\n\t\/\/ ISO-8859-1.\n\tENISO = util.Encoding{\n\t\tKey:              0,\n\t\tTerminationBytes: []byte{0},\n\t}\n\n\t\/\/ UTF-16 encoded Unicode with BOM.\n\tENUTF16 = util.Encoding{\n\t\tKey:              1,\n\t\tTerminationBytes: []byte{0, 0},\n\t}\n\n\t\/\/ UTF-16BE encoded Unicode without BOM.\n\tENUTF16BE = util.Encoding{\n\t\tKey:              2,\n\t\tTerminationBytes: []byte{0, 0},\n\t}\n\n\t\/\/ UTF-8 encoded Unicode.\n\tENUTF8 = util.Encoding{\n\t\tKey:              3,\n\t\tTerminationBytes: []byte{0},\n\t}\n\n\tEncodings = []util.Encoding{ENISO, ENUTF16, ENUTF16BE, ENUTF8}\n)\n\n\/\/ Open opens file with string name and finds tag in it.\nfunc Open(name string) (*Tag, error) {\n\tfile, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ParseFile(file)\n}\n\n\/\/ ParseFile parses opened file and finds tag in it.\nfunc ParseFile(file *os.File) (*Tag, error) {\n\treturn parseTag(file)\n}\n<|endoftext|>"}
{"text":"<commit_before>package pipe\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com\/CodisLabs\/codis\/pkg\/utils\/errors\"\n)\n\ntype Pipe struct {\n\tr, w struct {\n\t\tsync.Mutex\n\t\tcond *sync.Cond\n\t}\n\tmu sync.Mutex\n\n\trerr, werr error\n\n\tstore Buffer\n}\n\nfunc NewPipe() *Pipe {\n\treturn NewPipeSize(defaultMemBufferSize)\n}\n\nfunc NewPipeSize(size int) *Pipe {\n\treturn newPipe(newMemBufferSize(size))\n}\n\nfunc NewPipeFile(file *os.File, size int) *Pipe {\n\treturn newPipe(newFileBufferSize(file, size))\n}\n\nfunc newPipe(store Buffer) *Pipe {\n\tp := &Pipe{store: store}\n\tp.r.cond = sync.NewCond(&p.mu)\n\tp.w.cond = sync.NewCond(&p.mu)\n\treturn p\n}\n\nfunc (p *Pipe) Close() {\n\tp.CloseReader(nil)\n\tp.CloseWriter(nil)\n}\n\nfunc (p *Pipe) Reader() Reader {\n\treturn &PipeReader{p}\n}\n\nfunc (p *Pipe) Read(b []byte) (int, error) {\n\tp.r.Lock()\n\tdefer p.r.Unlock()\n\tfor {\n\t\tn, err := p.readSome(b)\n\t\tif err != nil || n != 0 {\n\t\t\treturn n, err\n\t\t}\n\t\tif len(b) == 0 {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n}\n\nfunc (p *Pipe) readSome(b []byte) (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rerr != nil {\n\t\treturn 0, errors.Trace(io.ErrClosedPipe)\n\t}\n\tif len(b) == 0 {\n\t\tif p.store.Buffered() != 0 {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn 0, p.werr\n\t}\n\tn, err := p.store.ReadSome(b)\n\tif err != nil || n != 0 {\n\t\tp.w.cond.Signal()\n\t\treturn n, err\n\t}\n\tif p.werr != nil {\n\t\treturn 0, p.werr\n\t} else {\n\t\tp.r.cond.Wait()\n\t\treturn 0, nil\n\t}\n}\n\nfunc (p *Pipe) Buffered() (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rerr != nil {\n\t\treturn 0, p.rerr\n\t}\n\tif n := p.store.Buffered(); n != 0 {\n\t\treturn n, nil\n\t} else {\n\t\treturn 0, p.werr\n\t}\n}\n\nfunc (p *Pipe) CloseReader(err error) error {\n\tif err == nil {\n\t\terr = errors.Trace(io.ErrClosedPipe)\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rerr == nil {\n\t\tp.rerr = err\n\t}\n\tp.r.cond.Broadcast()\n\tp.w.cond.Broadcast()\n\treturn p.store.CloseReader()\n}\n\nfunc (p *Pipe) Writer() Writer {\n\treturn &PipeWriter{p}\n}\n\nfunc (p *Pipe) Write(b []byte) (int, error) {\n\tp.w.Lock()\n\tdefer p.w.Unlock()\n\tvar nn int\n\tfor {\n\t\tn, err := p.writeSome(b)\n\t\tif err != nil || n == len(b) {\n\t\t\treturn nn + n, err\n\t\t}\n\t\tnn, b = nn+n, b[n:]\n\t}\n}\n\nfunc (p *Pipe) writeSome(b []byte) (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.werr != nil {\n\t\treturn 0, errors.Trace(io.ErrClosedPipe)\n\t}\n\tif p.rerr != nil {\n\t\treturn 0, p.rerr\n\t}\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tn, err := p.store.WriteSome(b)\n\tif err != nil || n != 0 {\n\t\tp.r.cond.Signal()\n\t\treturn n, err\n\t} else {\n\t\tp.w.cond.Wait()\n\t\treturn 0, nil\n\t}\n}\n\nfunc (p *Pipe) Available() (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.werr != nil {\n\t\treturn 0, p.werr\n\t}\n\tif p.rerr != nil {\n\t\treturn 0, p.rerr\n\t}\n\treturn p.store.Available(), nil\n}\n\nfunc (p *Pipe) CloseWriter(err error) error {\n\tif err == nil {\n\t\terr = errors.Trace(io.EOF)\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.werr == nil {\n\t\tp.werr = err\n\t}\n\tp.r.cond.Broadcast()\n\tp.w.cond.Broadcast()\n\treturn p.store.CloseWriter()\n}\n<commit_msg>pipe: refactor<commit_after>package pipe\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com\/CodisLabs\/codis\/pkg\/utils\/errors\"\n)\n\ntype Pipe struct {\n\trd, wt struct {\n\t\tsync.Mutex\n\t\tcond *sync.Cond\n\t\terr  error\n\t}\n\tmu sync.Mutex\n\n\tstore Buffer\n}\n\nfunc NewPipe() *Pipe {\n\treturn NewPipeSize(defaultMemBufferSize)\n}\n\nfunc NewPipeSize(size int) *Pipe {\n\treturn newPipe(newMemBufferSize(size))\n}\n\nfunc NewPipeFile(file *os.File, size int) *Pipe {\n\treturn newPipe(newFileBufferSize(file, size))\n}\n\nfunc newPipe(store Buffer) *Pipe {\n\tp := &Pipe{store: store}\n\tp.rd.cond = sync.NewCond(&p.mu)\n\tp.wt.cond = sync.NewCond(&p.mu)\n\treturn p\n}\n\nfunc (p *Pipe) Close() {\n\tp.CloseReader(nil)\n\tp.CloseWriter(nil)\n}\n\nfunc (p *Pipe) Reader() Reader {\n\treturn &PipeReader{p}\n}\n\nfunc (p *Pipe) Read(b []byte) (int, error) {\n\tp.rd.Lock()\n\tdefer p.rd.Unlock()\n\tfor {\n\t\tn, err := p.readSome(b)\n\t\tif err != nil || n != 0 {\n\t\t\treturn n, err\n\t\t}\n\t\tif len(b) == 0 {\n\t\t\treturn 0, nil\n\t\t}\n\t}\n}\n\nfunc (p *Pipe) readSome(b []byte) (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rd.err != nil {\n\t\treturn 0, errors.Trace(io.ErrClosedPipe)\n\t}\n\tif len(b) == 0 {\n\t\tif p.store.Buffered() != 0 {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn 0, p.wt.err\n\t}\n\tn, err := p.store.ReadSome(b)\n\tif err != nil || n != 0 {\n\t\tp.wt.cond.Signal()\n\t\treturn n, err\n\t}\n\tif p.wt.err != nil {\n\t\treturn 0, p.wt.err\n\t} else {\n\t\tp.rd.cond.Wait()\n\t\treturn 0, nil\n\t}\n}\n\nfunc (p *Pipe) Buffered() (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rd.err != nil {\n\t\treturn 0, p.rd.err\n\t}\n\tif n := p.store.Buffered(); n != 0 {\n\t\treturn n, nil\n\t} else {\n\t\treturn 0, p.wt.err\n\t}\n}\n\nfunc (p *Pipe) CloseReader(err error) error {\n\tif err == nil {\n\t\terr = errors.Trace(io.ErrClosedPipe)\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.rd.err == nil {\n\t\tp.rd.err = err\n\t}\n\tp.rd.cond.Broadcast()\n\tp.wt.cond.Broadcast()\n\treturn p.store.CloseReader()\n}\n\nfunc (p *Pipe) Writer() Writer {\n\treturn &PipeWriter{p}\n}\n\nfunc (p *Pipe) Write(b []byte) (int, error) {\n\tp.wt.Lock()\n\tdefer p.wt.Unlock()\n\tvar nn int\n\tfor {\n\t\tn, err := p.writeSome(b)\n\t\tif err != nil || n == len(b) {\n\t\t\treturn nn + n, err\n\t\t}\n\t\tnn, b = nn+n, b[n:]\n\t}\n}\n\nfunc (p *Pipe) writeSome(b []byte) (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.wt.err != nil {\n\t\treturn 0, errors.Trace(io.ErrClosedPipe)\n\t}\n\tif p.rd.err != nil {\n\t\treturn 0, p.rd.err\n\t}\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\tn, err := p.store.WriteSome(b)\n\tif err != nil || n != 0 {\n\t\tp.rd.cond.Signal()\n\t\treturn n, err\n\t} else {\n\t\tp.wt.cond.Wait()\n\t\treturn 0, nil\n\t}\n}\n\nfunc (p *Pipe) Available() (int, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.wt.err != nil {\n\t\treturn 0, p.wt.err\n\t}\n\tif p.rd.err != nil {\n\t\treturn 0, p.rd.err\n\t}\n\treturn p.store.Available(), nil\n}\n\nfunc (p *Pipe) CloseWriter(err error) error {\n\tif err == nil {\n\t\terr = errors.Trace(io.EOF)\n\t}\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.wt.err == nil {\n\t\tp.wt.err = err\n\t}\n\tp.rd.cond.Broadcast()\n\tp.wt.cond.Broadcast()\n\treturn p.store.CloseWriter()\n}\n<|endoftext|>"}
{"text":"<commit_before>package login\n\nimport (\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n\t\"github.com\/grafana\/grafana\/pkg\/registry\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/quota\"\n)\n\nfunc init() {\n\tregistry.RegisterService(&LoginService{})\n}\n\nvar (\n\tlogger = log.New(\"login.ext_user\")\n)\n\ntype LoginService struct {\n\tBus          bus.Bus             `inject:\"\"`\n\tQuotaService *quota.QuotaService `inject:\"\"`\n}\n\nfunc (ls *LoginService) Init() error {\n\tls.Bus.AddHandler(ls.UpsertUser)\n\n\treturn nil\n}\n\nfunc (ls *LoginService) UpsertUser(cmd *m.UpsertUserCommand) error {\n\textUser := cmd.ExternalUser\n\n\tuserQuery := &m.GetUserByAuthInfoQuery{\n\t\tAuthModule: extUser.AuthModule,\n\t\tAuthId:     extUser.AuthId,\n\t\tUserId:     extUser.UserId,\n\t\tEmail:      extUser.Email,\n\t\tLogin:      extUser.Login,\n\t}\n\n\terr := bus.Dispatch(userQuery)\n\tif err != m.ErrUserNotFound && err != nil {\n\t\treturn err\n\t}\n\n\tif err != nil {\n\t\tif !cmd.SignupAllowed {\n\t\t\tlog.Warn(\"Not allowing %s login, user not found in internal user database and allow signup = false\", extUser.AuthModule)\n\t\t\treturn ErrInvalidCredentials\n\t\t}\n\n\t\tlimitReached, err := ls.QuotaService.QuotaReached(cmd.ReqContext, \"user\")\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error getting user quota. error: %v\", err)\n\t\t\treturn ErrGettingUserQuota\n\t\t}\n\t\tif limitReached {\n\t\t\treturn ErrUsersQuotaReached\n\t\t}\n\n\t\tcmd.Result, err = createUser(extUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif extUser.AuthModule != \"\" {\n\t\t\tcmd2 := &m.SetAuthInfoCommand{\n\t\t\t\tUserId:     cmd.Result.Id,\n\t\t\t\tAuthModule: extUser.AuthModule,\n\t\t\t\tAuthId:     extUser.AuthId,\n\t\t\t\tOAuthToken: extUser.OAuthToken,\n\t\t\t}\n\t\t\tif err := ls.Bus.Dispatch(cmd2); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tcmd.Result = userQuery.Result\n\n\t\terr = updateUser(cmd.Result, extUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Always persist the latest token at log-in\n\t\tif extUser.AuthModule != \"\" && extUser.OAuthToken != nil {\n\t\t\terr = updateUserAuth(cmd.Result, extUser)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = syncOrgRoles(cmd.Result, extUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Sync isGrafanaAdmin permission\n\tif extUser.IsGrafanaAdmin != nil && *extUser.IsGrafanaAdmin != cmd.Result.IsAdmin {\n\t\tif err := ls.Bus.Dispatch(&m.UpdateUserPermissionsCommand{UserId: cmd.Result.Id, IsGrafanaAdmin: *extUser.IsGrafanaAdmin}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = ls.Bus.Dispatch(&m.SyncTeamsCommand{\n\t\tUser:         cmd.Result,\n\t\tExternalUser: extUser,\n\t})\n\n\tif err == bus.ErrHandlerNotFound {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc createUser(extUser *m.ExternalUserInfo) (*m.User, error) {\n\tcmd := &m.CreateUserCommand{\n\t\tLogin:        extUser.Login,\n\t\tEmail:        extUser.Email,\n\t\tName:         extUser.Name,\n\t\tSkipOrgSetup: len(extUser.OrgRoles) > 0,\n\t}\n\n\tif err := bus.Dispatch(cmd); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cmd.Result, nil\n}\n\nfunc updateUser(user *m.User, extUser *m.ExternalUserInfo) error {\n\t\/\/ sync user info\n\tupdateCmd := &m.UpdateUserCommand{\n\t\tUserId: user.Id,\n\t}\n\n\tneedsUpdate := false\n\tif extUser.Login != \"\" && extUser.Login != user.Login {\n\t\tupdateCmd.Login = extUser.Login\n\t\tuser.Login = extUser.Login\n\t\tneedsUpdate = true\n\t}\n\n\tif extUser.Email != \"\" && extUser.Email != user.Email {\n\t\tupdateCmd.Email = extUser.Email\n\t\tuser.Email = extUser.Email\n\t\tneedsUpdate = true\n\t}\n\n\tif extUser.Name != \"\" && extUser.Name != user.Name {\n\t\tupdateCmd.Name = extUser.Name\n\t\tuser.Name = extUser.Name\n\t\tneedsUpdate = true\n\t}\n\n\tif !needsUpdate {\n\t\treturn nil\n\t}\n\n\tlogger.Debug(\"Syncing user info\", \"id\", user.Id, \"update\", updateCmd)\n\treturn bus.Dispatch(updateCmd)\n}\n\nfunc updateUserAuth(user *m.User, extUser *m.ExternalUserInfo) error {\n\tupdateCmd := &m.UpdateAuthInfoCommand{\n\t\tAuthModule: extUser.AuthModule,\n\t\tAuthId:     extUser.AuthId,\n\t\tUserId:     user.Id,\n\t\tOAuthToken: extUser.OAuthToken,\n\t}\n\n\tlog.Debug(\"Updating user_auth info for user_id %d\", user.Id)\n\treturn bus.Dispatch(updateCmd)\n}\n\nfunc syncOrgRoles(user *m.User, extUser *m.ExternalUserInfo) error {\n\t\/\/ don't sync org roles if none are specified\n\tif len(extUser.OrgRoles) == 0 {\n\t\treturn nil\n\t}\n\n\torgsQuery := &m.GetUserOrgListQuery{UserId: user.Id}\n\tif err := bus.Dispatch(orgsQuery); err != nil {\n\t\treturn err\n\t}\n\n\thandledOrgIds := map[int64]bool{}\n\tdeleteOrgIds := []int64{}\n\n\t\/\/ update existing org roles\n\tfor _, org := range orgsQuery.Result {\n\t\thandledOrgIds[org.OrgId] = true\n\n\t\tif extUser.OrgRoles[org.OrgId] == \"\" {\n\t\t\tdeleteOrgIds = append(deleteOrgIds, org.OrgId)\n\t\t} else if extUser.OrgRoles[org.OrgId] != org.Role {\n\t\t\t\/\/ update role\n\t\t\tcmd := &m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: extUser.OrgRoles[org.OrgId]}\n\t\t\tif err := bus.Dispatch(cmd); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ add any new org roles\n\tfor orgId, orgRole := range extUser.OrgRoles {\n\t\tif _, exists := handledOrgIds[orgId]; exists {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ add role\n\t\tcmd := &m.AddOrgUserCommand{UserId: user.Id, Role: orgRole, OrgId: orgId}\n\t\terr := bus.Dispatch(cmd)\n\t\tif err != nil && err != m.ErrOrgNotFound {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ delete any removed org roles\n\tfor _, orgId := range deleteOrgIds {\n\t\tcmd := &m.RemoveOrgUserCommand{OrgId: orgId, UserId: user.Id}\n\t\tif err := bus.Dispatch(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ update user's default org if needed\n\tif _, ok := extUser.OrgRoles[user.OrgId]; !ok {\n\t\tfor orgId := range extUser.OrgRoles {\n\t\t\tuser.OrgId = orgId\n\t\t\tbreak\n\t\t}\n\n\t\treturn bus.Dispatch(&m.SetUsingOrgCommand{\n\t\t\tUserId: user.Id,\n\t\t\tOrgId:  user.OrgId,\n\t\t})\n\t}\n\n\treturn nil\n}\n<commit_msg>Use structured logging instead of printf<commit_after>package login\n\nimport (\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n\t\"github.com\/grafana\/grafana\/pkg\/registry\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/quota\"\n)\n\nfunc init() {\n\tregistry.RegisterService(&LoginService{})\n}\n\nvar (\n\tlogger = log.New(\"login.ext_user\")\n)\n\ntype LoginService struct {\n\tBus          bus.Bus             `inject:\"\"`\n\tQuotaService *quota.QuotaService `inject:\"\"`\n}\n\nfunc (ls *LoginService) Init() error {\n\tls.Bus.AddHandler(ls.UpsertUser)\n\n\treturn nil\n}\n\nfunc (ls *LoginService) UpsertUser(cmd *m.UpsertUserCommand) error {\n\textUser := cmd.ExternalUser\n\n\tuserQuery := &m.GetUserByAuthInfoQuery{\n\t\tAuthModule: extUser.AuthModule,\n\t\tAuthId:     extUser.AuthId,\n\t\tUserId:     extUser.UserId,\n\t\tEmail:      extUser.Email,\n\t\tLogin:      extUser.Login,\n\t}\n\n\terr := bus.Dispatch(userQuery)\n\tif err != m.ErrUserNotFound && err != nil {\n\t\treturn err\n\t}\n\n\tif err != nil {\n\t\tif !cmd.SignupAllowed {\n\t\t\tlog.Warn(\"Not allowing %s login, user not found in internal user database and allow signup = false\", extUser.AuthModule)\n\t\t\treturn ErrInvalidCredentials\n\t\t}\n\n\t\tlimitReached, err := ls.QuotaService.QuotaReached(cmd.ReqContext, \"user\")\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error getting user quota. error: %v\", err)\n\t\t\treturn ErrGettingUserQuota\n\t\t}\n\t\tif limitReached {\n\t\t\treturn ErrUsersQuotaReached\n\t\t}\n\n\t\tcmd.Result, err = createUser(extUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif extUser.AuthModule != \"\" {\n\t\t\tcmd2 := &m.SetAuthInfoCommand{\n\t\t\t\tUserId:     cmd.Result.Id,\n\t\t\t\tAuthModule: extUser.AuthModule,\n\t\t\t\tAuthId:     extUser.AuthId,\n\t\t\t\tOAuthToken: extUser.OAuthToken,\n\t\t\t}\n\t\t\tif err := ls.Bus.Dispatch(cmd2); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tcmd.Result = userQuery.Result\n\n\t\terr = updateUser(cmd.Result, extUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Always persist the latest token at log-in\n\t\tif extUser.AuthModule != \"\" && extUser.OAuthToken != nil {\n\t\t\terr = updateUserAuth(cmd.Result, extUser)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = syncOrgRoles(cmd.Result, extUser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Sync isGrafanaAdmin permission\n\tif extUser.IsGrafanaAdmin != nil && *extUser.IsGrafanaAdmin != cmd.Result.IsAdmin {\n\t\tif err := ls.Bus.Dispatch(&m.UpdateUserPermissionsCommand{UserId: cmd.Result.Id, IsGrafanaAdmin: *extUser.IsGrafanaAdmin}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = ls.Bus.Dispatch(&m.SyncTeamsCommand{\n\t\tUser:         cmd.Result,\n\t\tExternalUser: extUser,\n\t})\n\n\tif err == bus.ErrHandlerNotFound {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc createUser(extUser *m.ExternalUserInfo) (*m.User, error) {\n\tcmd := &m.CreateUserCommand{\n\t\tLogin:        extUser.Login,\n\t\tEmail:        extUser.Email,\n\t\tName:         extUser.Name,\n\t\tSkipOrgSetup: len(extUser.OrgRoles) > 0,\n\t}\n\n\tif err := bus.Dispatch(cmd); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &cmd.Result, nil\n}\n\nfunc updateUser(user *m.User, extUser *m.ExternalUserInfo) error {\n\t\/\/ sync user info\n\tupdateCmd := &m.UpdateUserCommand{\n\t\tUserId: user.Id,\n\t}\n\n\tneedsUpdate := false\n\tif extUser.Login != \"\" && extUser.Login != user.Login {\n\t\tupdateCmd.Login = extUser.Login\n\t\tuser.Login = extUser.Login\n\t\tneedsUpdate = true\n\t}\n\n\tif extUser.Email != \"\" && extUser.Email != user.Email {\n\t\tupdateCmd.Email = extUser.Email\n\t\tuser.Email = extUser.Email\n\t\tneedsUpdate = true\n\t}\n\n\tif extUser.Name != \"\" && extUser.Name != user.Name {\n\t\tupdateCmd.Name = extUser.Name\n\t\tuser.Name = extUser.Name\n\t\tneedsUpdate = true\n\t}\n\n\tif !needsUpdate {\n\t\treturn nil\n\t}\n\n\tlogger.Debug(\"Syncing user info\", \"id\", user.Id, \"update\", updateCmd)\n\treturn bus.Dispatch(updateCmd)\n}\n\nfunc updateUserAuth(user *m.User, extUser *m.ExternalUserInfo) error {\n\tupdateCmd := &m.UpdateAuthInfoCommand{\n\t\tAuthModule: extUser.AuthModule,\n\t\tAuthId:     extUser.AuthId,\n\t\tUserId:     user.Id,\n\t\tOAuthToken: extUser.OAuthToken,\n\t}\n\n\tlog.Debug(\"Updating user_auth info\", \"user_id\", user.Id)\n\treturn bus.Dispatch(updateCmd)\n}\n\nfunc syncOrgRoles(user *m.User, extUser *m.ExternalUserInfo) error {\n\t\/\/ don't sync org roles if none are specified\n\tif len(extUser.OrgRoles) == 0 {\n\t\treturn nil\n\t}\n\n\torgsQuery := &m.GetUserOrgListQuery{UserId: user.Id}\n\tif err := bus.Dispatch(orgsQuery); err != nil {\n\t\treturn err\n\t}\n\n\thandledOrgIds := map[int64]bool{}\n\tdeleteOrgIds := []int64{}\n\n\t\/\/ update existing org roles\n\tfor _, org := range orgsQuery.Result {\n\t\thandledOrgIds[org.OrgId] = true\n\n\t\tif extUser.OrgRoles[org.OrgId] == \"\" {\n\t\t\tdeleteOrgIds = append(deleteOrgIds, org.OrgId)\n\t\t} else if extUser.OrgRoles[org.OrgId] != org.Role {\n\t\t\t\/\/ update role\n\t\t\tcmd := &m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: extUser.OrgRoles[org.OrgId]}\n\t\t\tif err := bus.Dispatch(cmd); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ add any new org roles\n\tfor orgId, orgRole := range extUser.OrgRoles {\n\t\tif _, exists := handledOrgIds[orgId]; exists {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ add role\n\t\tcmd := &m.AddOrgUserCommand{UserId: user.Id, Role: orgRole, OrgId: orgId}\n\t\terr := bus.Dispatch(cmd)\n\t\tif err != nil && err != m.ErrOrgNotFound {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ delete any removed org roles\n\tfor _, orgId := range deleteOrgIds {\n\t\tcmd := &m.RemoveOrgUserCommand{OrgId: orgId, UserId: user.Id}\n\t\tif err := bus.Dispatch(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ update user's default org if needed\n\tif _, ok := extUser.OrgRoles[user.OrgId]; !ok {\n\t\tfor orgId := range extUser.OrgRoles {\n\t\t\tuser.OrgId = orgId\n\t\t\tbreak\n\t\t}\n\n\t\treturn bus.Dispatch(&m.SetUsingOrgCommand{\n\t\t\tUserId: user.Id,\n\t\t\tOrgId:  user.OrgId,\n\t\t})\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016-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 metadata\n\nimport (\n\tkubeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\/v1alpha1\/runtime\"\n)\n\n\/\/ ContainerInfo contains metadata informations about container instance\ntype ContainerInfo struct {\n\tCreatedAt             int64\n\tStartedAt             int64\n\tSandboxId             string\n\tImage                 string\n\tRootImageSnapshotName string\n\tLabels                map[string]string\n\tAnnotations           map[string]string\n\tSandBoxAnnotations    map[string]string\n\tState                 kubeapi.ContainerState\n}\n\n\/\/ MetadataStore contains methods to store\/retrieve metadata\n\/\/ for images\/sandboxes\/containers\ntype MetadataStore interface {\n\t\/\/ images\n\tSetImageName(volumeName, imageName string) error\n\tGetImageName(volumeName string) (string, error)\n\tRemoveImage(volumeName string) error\n\n\t\/\/ sandbox\n\tSetPodSandbox(config *kubeapi.PodSandboxConfig, networkConfiguration []byte) error\n\tUpdatePodState(podId string, state byte) error\n\tRemovePodSandbox(podId string) error\n\tGetPodSandboxContainerID(podId string) (string, error)\n\tGetPodSandboxAnnotations(podId string) (map[string]string, error)\n\tGetPodSandboxStatus(podId string) (*kubeapi.PodSandboxStatus, error)\n\tListPodSandbox(filter *kubeapi.PodSandboxFilter) ([]*kubeapi.PodSandbox, error)\n\tGetPodNetworkConfigurationAsBytes(podId string) ([]byte, error)\n\n\t\/\/ containers - virtualization\n\tSetContainer(containerId, sandboxId, image, rootImageSnapshotName string, labels, annotations map[string]string) error\n\tUpdateStartedAt(containerId string, startedAt string) error\n\tUpdateState(containerId string, state byte) error\n\tGetContainerInfo(containerId string) (*ContainerInfo, error)\n\tRemoveContainer(containerId string) error\n}\n<commit_msg>metadata: Provide more granular interfaces<commit_after>\/*\nCopyright 2016-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 metadata\n\nimport (\n\tkubeapi \"k8s.io\/kubernetes\/pkg\/kubelet\/api\/v1alpha1\/runtime\"\n)\n\n\/\/ ContainerInfo contains metadata informations about container instance\ntype ContainerInfo struct {\n\tCreatedAt             int64\n\tStartedAt             int64\n\tSandboxId             string\n\tImage                 string\n\tRootImageSnapshotName string\n\tLabels                map[string]string\n\tAnnotations           map[string]string\n\tSandBoxAnnotations    map[string]string\n\tState                 kubeapi.ContainerState\n}\n\n\/\/ ImageMetadataStore contains methods to operate on VM images\ntype ImageMetadataStore interface {\n\tSetImageName(volumeName, imageName string) error\n\tGetImageName(volumeName string) (string, error)\n\tRemoveImage(volumeName string) error\n}\n\n\/\/ SandboxMetadataStore contains methods to operate on POD sandboxes\ntype SandboxMetadataStore interface {\n\tSetPodSandbox(config *kubeapi.PodSandboxConfig, networkConfiguration []byte) error\n\tUpdatePodState(podId string, state byte) error\n\tRemovePodSandbox(podId string) error\n\tGetPodSandboxContainerID(podId string) (string, error)\n\tGetPodSandboxAnnotations(podId string) (map[string]string, error)\n\tGetPodSandboxStatus(podId string) (*kubeapi.PodSandboxStatus, error)\n\tListPodSandbox(filter *kubeapi.PodSandboxFilter) ([]*kubeapi.PodSandbox, error)\n\tGetPodNetworkConfigurationAsBytes(podId string) ([]byte, error)\n}\n\n\/\/ ContainerMetadataStore contains methods to operate on containers (VMs)\ntype ContainerMetadataStore interface {\n\tSetContainer(containerId, sandboxId, image, rootImageSnapshotName string, labels, annotations map[string]string) error\n\tUpdateStartedAt(containerId string, startedAt string) error\n\tUpdateState(containerId string, state byte) error\n\tGetContainerInfo(containerId string) (*ContainerInfo, error)\n\tRemoveContainer(containerId string) error\n}\n\n\/\/ MetadataStore provides single interface for metadata storage implementation\ntype MetadataStore interface {\n\tImageMetadataStore\n\tSandboxMetadataStore\n\tContainerMetadataStore\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\"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\/mattn\/go-isatty\"\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\n\t\/\/ display progress bar in stdout, since stderr is used by logger\n\tbar := pb.New(pairsCount).SetWriter(os.Stdout)\n\n\t\/\/ only display progress bar in user TTY\n\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\tbar.Start()\n\t}\n\n\tfor _, pair := range pairs {\n\t\t\/\/ pair needs to be scoped in parameter so that the specific variable read\n\t\t\/\/ happens when the goroutine is declared, not when referenced inside\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<commit_msg>Re-draw graph for commit rewind explanation<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\/mattn\/go-isatty\"\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\n\t\/\/ display progress bar in stdout, since stderr is used by logger\n\tbar := pb.New(pairsCount).SetWriter(os.Stdout)\n\n\t\/\/ only display progress bar in user TTY\n\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\tbar.Start()\n\t}\n\n\tfor _, pair := range pairs {\n\t\t\/\/ pair needs to be scoped in parameter so that the specific variable read\n\t\t\/\/ happens when the goroutine is declared, not when referenced inside\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\n\t\/\/ ^ master\n\t\/\/ |\n\t\/\/ * tag: 1.21.0-alpha.x \/ 1.21.0-beta.y\n\t\/\/ |\n\t\/\/ : :\n\t\/\/ | |\n\t\/\/ | * tag: v1.20.0, some merge commit pointed by opts.StartSHA\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>\/*\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 storage\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/kubernetes\/pkg\/util\/validation\/field\"\n)\n\nconst (\n\tErrCodeKeyNotFound int = iota + 1\n\tErrCodeKeyExists\n\tErrCodeResourceVersionConflicts\n\tErrCodeInvalidObj\n\tErrCodeUnreachable\n)\n\nvar errCodeToMessage = map[int]string{\n\tErrCodeKeyNotFound:              \"key not found\",\n\tErrCodeKeyExists:                \"key exists\",\n\tErrCodeResourceVersionConflicts: \"resource version conflicts\",\n\tErrCodeInvalidObj:               \"invalid object\",\n\tErrCodeUnreachable:              \"server unreachable\",\n}\n\nfunc NewKeyNotFoundError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeKeyNotFound,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewKeyExistsError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeKeyExists,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewResourceVersionConflictsError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeResourceVersionConflicts,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewUnreachableError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeUnreachable,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewInvalidObjError(key, msg string) *StorageError {\n\treturn &StorageError{\n\t\tCode:               ErrCodeInvalidObj,\n\t\tKey:                key,\n\t\tAdditionalErrorMsg: msg,\n\t}\n}\n\ntype StorageError struct {\n\tCode               int\n\tKey                string\n\tResourceVersion    int64\n\tAdditionalErrorMsg string\n}\n\nfunc (e *StorageError) Error() string {\n\treturn fmt.Sprintf(\"StorageError: %s, Code: %d, Key: %s, ResourceVersion: %d, AdditionalErrorMsg: %s\",\n\t\terrCodeToMessage[e.Code], e.Code, e.Key, e.ResourceVersion, e.AdditionalErrorMsg)\n}\n\n\/\/ IsNotFound returns true if and only if err is \"key\" not found error.\nfunc IsNotFound(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyNotFound)\n}\n\n\/\/ IsNodeExist returns true if and only if err is an node already exist error.\nfunc IsNodeExist(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyExists)\n}\n\n\/\/ IsUnreachable returns true if and only if err indicates the server could not be reached.\nfunc IsUnreachable(err error) bool {\n\treturn isErrCode(err, ErrCodeUnreachable)\n}\n\n\/\/ IsTestFailed returns true if and only if err is a write conflict.\nfunc IsTestFailed(err error) bool {\n\treturn isErrCode(err, ErrCodeResourceVersionConflicts)\n}\n\n\/\/ IsInvalidUID returns true if and only if err is invalid UID error\nfunc IsInvalidObj(err error) bool {\n\treturn isErrCode(err, ErrCodeInvalidObj)\n}\n\nfunc isErrCode(err error, code int) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif e, ok := err.(*StorageError); ok {\n\t\treturn e.Code == code\n\t}\n\treturn false\n}\n\n\/\/ InvalidError is generated when an error caused by invalid API object occurs\n\/\/ in the storage package.\ntype InvalidError struct {\n\tErrs field.ErrorList\n}\n\nfunc (e InvalidError) Error() string {\n\treturn e.Errs.ToAggregate().Error()\n}\n\n\/\/ IsInvalidError returns true if and only if err is an InvalidError.\nfunc IsInvalidError(err error) bool {\n\t_, ok := err.(InvalidError)\n\treturn ok\n}\n\nfunc NewInvalidError(errors field.ErrorList) InvalidError {\n\treturn InvalidError{errors}\n}\n\n\/\/ InternalError is generated when an error occurs in the storage package, i.e.,\n\/\/ not from the underlying storage backend (e.g., etcd).\ntype InternalError struct {\n\tReason string\n}\n\nfunc (e InternalError) Error() string {\n\treturn e.Reason\n}\n\n\/\/ IsInternalError returns true if and only if err is an InternalError.\nfunc IsInternalError(err error) bool {\n\t_, ok := err.(InternalError)\n\treturn ok\n}\n\nfunc NewInternalError(reason string) InternalError {\n\treturn InternalError{reason}\n}\n\nfunc NewInternalErrorf(format string, a ...interface{}) InternalError {\n\treturn InternalError{fmt.Sprintf(format, a)}\n}\n<commit_msg>Modify IsInvalidObj name and description<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 storage\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/kubernetes\/pkg\/util\/validation\/field\"\n)\n\nconst (\n\tErrCodeKeyNotFound int = iota + 1\n\tErrCodeKeyExists\n\tErrCodeResourceVersionConflicts\n\tErrCodeInvalidObj\n\tErrCodeUnreachable\n)\n\nvar errCodeToMessage = map[int]string{\n\tErrCodeKeyNotFound:              \"key not found\",\n\tErrCodeKeyExists:                \"key exists\",\n\tErrCodeResourceVersionConflicts: \"resource version conflicts\",\n\tErrCodeInvalidObj:               \"invalid object\",\n\tErrCodeUnreachable:              \"server unreachable\",\n}\n\nfunc NewKeyNotFoundError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeKeyNotFound,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewKeyExistsError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeKeyExists,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewResourceVersionConflictsError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeResourceVersionConflicts,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewUnreachableError(key string, rv int64) *StorageError {\n\treturn &StorageError{\n\t\tCode:            ErrCodeUnreachable,\n\t\tKey:             key,\n\t\tResourceVersion: rv,\n\t}\n}\n\nfunc NewInvalidObjError(key, msg string) *StorageError {\n\treturn &StorageError{\n\t\tCode:               ErrCodeInvalidObj,\n\t\tKey:                key,\n\t\tAdditionalErrorMsg: msg,\n\t}\n}\n\ntype StorageError struct {\n\tCode               int\n\tKey                string\n\tResourceVersion    int64\n\tAdditionalErrorMsg string\n}\n\nfunc (e *StorageError) Error() string {\n\treturn fmt.Sprintf(\"StorageError: %s, Code: %d, Key: %s, ResourceVersion: %d, AdditionalErrorMsg: %s\",\n\t\terrCodeToMessage[e.Code], e.Code, e.Key, e.ResourceVersion, e.AdditionalErrorMsg)\n}\n\n\/\/ IsNotFound returns true if and only if err is \"key\" not found error.\nfunc IsNotFound(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyNotFound)\n}\n\n\/\/ IsNodeExist returns true if and only if err is an node already exist error.\nfunc IsNodeExist(err error) bool {\n\treturn isErrCode(err, ErrCodeKeyExists)\n}\n\n\/\/ IsUnreachable returns true if and only if err indicates the server could not be reached.\nfunc IsUnreachable(err error) bool {\n\treturn isErrCode(err, ErrCodeUnreachable)\n}\n\n\/\/ IsTestFailed returns true if and only if err is a write conflict.\nfunc IsTestFailed(err error) bool {\n\treturn isErrCode(err, ErrCodeResourceVersionConflicts)\n}\n\n\/\/ IsInvalidObj returns true if and only if err is invalid error\nfunc IsInvalidObj(err error) bool {\n\treturn isErrCode(err, ErrCodeInvalidObj)\n}\n\nfunc isErrCode(err error, code int) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif e, ok := err.(*StorageError); ok {\n\t\treturn e.Code == code\n\t}\n\treturn false\n}\n\n\/\/ InvalidError is generated when an error caused by invalid API object occurs\n\/\/ in the storage package.\ntype InvalidError struct {\n\tErrs field.ErrorList\n}\n\nfunc (e InvalidError) Error() string {\n\treturn e.Errs.ToAggregate().Error()\n}\n\n\/\/ IsInvalidError returns true if and only if err is an InvalidError.\nfunc IsInvalidError(err error) bool {\n\t_, ok := err.(InvalidError)\n\treturn ok\n}\n\nfunc NewInvalidError(errors field.ErrorList) InvalidError {\n\treturn InvalidError{errors}\n}\n\n\/\/ InternalError is generated when an error occurs in the storage package, i.e.,\n\/\/ not from the underlying storage backend (e.g., etcd).\ntype InternalError struct {\n\tReason string\n}\n\nfunc (e InternalError) Error() string {\n\treturn e.Reason\n}\n\n\/\/ IsInternalError returns true if and only if err is an InternalError.\nfunc IsInternalError(err error) bool {\n\t_, ok := err.(InternalError)\n\treturn ok\n}\n\nfunc NewInternalError(reason string) InternalError {\n\treturn InternalError{reason}\n}\n\nfunc NewInternalErrorf(format string, a ...interface{}) InternalError {\n\treturn InternalError{fmt.Sprintf(format, a)}\n}\n<|endoftext|>"}
{"text":"<commit_before>package templates\n\nvar Node = `\npasswd:\n  users:\n    - name:          core\n      password_hash: xyTGJkB462ewk\n      ssh_authorized_keys: \n        - \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvFapuevZeHFpFn438XMjvEQYd0wt7+tzUdAkMiSd007Tx1h79Xm9ZziDDUe4W6meinVOq93MAS\/ER27hoVWGo2H\/vn\/Cz5M8xr2j5rQODnrF3RmfrJTbZAWaDN0JTq2lFjmCHhZJNhr+VQP1uw4z2ofMBP6MLybnLmm9ukzxFYZqCCyfEEUTCMA9SWywtTpGQp8VLM4INCxzBSCuyt3SO6PBvJSo4HoKg\/sLvmRwpCVZth48PI0EUbJ72wp88Cw3bv8CLce2TOkLMwkE6NRN55w2aOyqP1G3vixHa6YcVaLlkQhJoJsBwE3rX5603y2KjOhMomqHfXxXn\/3GKTWlsQ== michael.j.schmidt@gmail.com\"\n\nlocksmith:\n  reboot_strategy: \"reboot\"\n\nnetworkd:\n  units:\n\t  - name: 00-ens32.network\n\t\t  contents: |\n        [Match]\n\t\t\t\tName=ens32\n\t\t\t\t[Network]\n\t\t\t\tDHCP=true\n\t\t\t\t[DHCP]\n\t\t\t\tUseMTU=true\n\t\t\t\tCriticalConnection=true\n\nsystemd:\n  units:\n    - name: ccloud-metadata.service\n      contents: |\n        [Unit]\n        Description=Converged Cloud Metadata Agent\n\n        [Service]\n        Type=oneshot\n        ExecStart=\/usr\/bin\/coreos-metadata --provider=openstack-metadata --attributes=\/run\/metadata\/coreos --ssh-keys=core --hostname=\/etc\/hostname\n    - name: ccloud-metadata-hostname.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Workaround for coreos-metadata hostname bug\n        Requires=ccloud-metadata.service\n        After=ccloud-metadata.service\n\n        [Service]\n        Type=oneshot\n        EnvironmentFile=\/run\/metadata\/coreos\n        ExecStart=\/usr\/bin\/hostnamectl set-hostname ${COREOS_OPENSTACK_HOSTNAME}\n        \n        [Install]\n        WantedBy=multi-user.target\n    - name: docker.service\n      enable: true\n      dropins:\n        - name: 20-docker-opts.conf\n          contents: |\n            [Service]\n            Environment=\"DOCKER_OPTS=--log-opt max-size=5m --log-opt max-file=5 --ip-masq=false --iptables=false --bridge=none\"\n    - name: kubelet.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Kubelet via Hyperkube ACI\n\n        [Service]\n        Environment=\"RKT_RUN_ARGS=--uuid-file-save=\/var\/run\/kubelet-pod.uuid \\\n          --inherit-env \\\n          --dns=host \\\n          --net=host \\\n          --volume var-lib-cni,kind=host,source=\/var\/lib\/cni \\\n          --volume var-log,kind=host,source=\/var\/log \\\n          --mount volume=var-lib-cni,target=\/var\/lib\/cni \\\n          --mount volume=var-log,target=\/var\/log\"\n        Environment=\"KUBELET_IMAGE_TAG=v1.7.5_coreos.0\"\n        Environment=\"KUBELET_IMAGE_URL=quay.io\/coreos\/hyperkube\"\n        ExecStartPre=\/bin\/mkdir -p \/etc\/kubernetes\/manifests\n        ExecStartPre=\/bin\/mkdir -p \/var\/lib\/cni\n        ExecStartPre=-\/usr\/bin\/rkt rm --uuid-file=\/var\/run\/kubelet-pod.uuid\n        ExecStart=\/usr\/lib\/coreos\/kubelet-wrapper \\\n          --cloud-config=\/etc\/kubernetes\/openstack\/openstack.config \\\n          --cloud-provider=openstack \\\n          --require-kubeconfig \\\n          --bootstrap-kubeconfig=\/etc\/kubernetes\/bootstrap\/kubeconfig \\\n          --network-plugin=kubenet \\\n          --lock-file=\/var\/run\/lock\/kubelet.lock \\\n          --exit-on-lock-contention \\\n          --pod-manifest-path=\/etc\/kubernetes\/manifests \\\n          --allow-privileged \\\n          --cluster_domain=cluster.local \\\n          --client-ca-file=\/etc\/kubernetes\/certs\/kubelet-clients-ca.pem \\\n          --non-masquerade-cidr={{ .ClusterCIDR }} \\\n          --anonymous-auth=false\n        ExecStop=-\/usr\/bin\/rkt stop --uuid-file=\/var\/run\/kubelet-pod.uuid\n        Restart=always\n        RestartSec=10\n\n        [Install]\n        WantedBy=multi-user.target\n    - name: wormhole.service\n      contents: |\n        [Unit]\n        Description=Kubernikus Wormhole\n        Requires=network-online.target\n        After=network-online.target\n\n        [Service]\n        Slice=machine.slice\n        ExecStartPre=\/usr\/bin\/rkt fetch --insecure-options=image --pull-policy=new docker:\/\/sapcc\/kubernikus:latest\n        ExecStart=\/usr\/bin\/rkt run \\\n          --inherit-env \\\n          --net=host \\\n          --dns=host \\\n          --volume var-lib-kubelet,kind=host,source=\/var\/lib\/kubelet,readOnly=true \\\n          --mount volume=var-lib-kubelet,target=\/var\/lib\/kubelet \\\n          --volume var-run-kubernetes,kind=host,source=\/var\/run\/kubernetes,readOnly=true \\\n          --mount volume=var-run-kubernetes,target=\/var\/run\/kubernetes \\\n          --volume etc-kubernetes-certs,kind=host,source=\/etc\/kubernetes\/certs,readOnly=true \\\n          --mount volume=etc-kubernetes-certs,target=\/etc\/kubernetes\/certs \\\n          docker:\/\/sapcc\/kubernikus:latest \\\n          --exec wormhole -- client --kubeconfig=\/var\/lib\/kubelet\/kubeconfig\n        ExecStopPost=\/usr\/bin\/rkt gc --mark-only\n        KillMode=mixed\n        Restart=always\n        RestartSec=10s\n    - name: wormhole.path\n      enable: true\n      contents: |\n        [Path]\n        PathExists=\/var\/lib\/kubelet\/kubeconfig\n        [Install]\n        WantedBy=multi-user.target\n    - name: kube-proxy.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Kube-Proxy\n        Requires=network-online.target\n        After=network-online.target\n\n        [Service]\n        Slice=machine.slice\n        ExecStart=\/usr\/bin\/rkt run \\\n          --trust-keys-from-https \\\n          --inherit-env \\\n          --net=host \\\n          --dns=host \\\n          --volume etc-kubernetes,kind=host,source=\/etc\/kubernetes,readOnly=true \\\n          --mount volume=etc-kubernetes,target=\/etc\/kubernetes \\\n          --volume lib-modules,kind=host,source=\/lib\/modules,readOnly=true \\\n          --mount volume=lib-modules,target=\/lib\/modules \\\n          --stage1-from-dir=stage1-fly.aci \\\n          quay.io\/coreos\/hyperkube:v1.7.5_coreos.0 \\\n          --exec=hyperkube \\\n          -- \\\n          proxy \\\n          --config=\/etc\/kubernetes\/kube-proxy\/config\n        ExecStopPost=\/usr\/bin\/rkt gc --mark-only\n        KillMode=mixed\n        Restart=always\n        RestartSec=10s\n\n        [Install]\n        WantedBy=multi-user.target\n\nstorage:\n  files:\n    - path: \/etc\/kubernetes\/certs\/kubelet-clients-ca.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .KubeletClientsCA | indent 10 }}\n    - path: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy-key.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .ApiserverClientsSystemKubeProxyKey | indent 10 }}\n    - path: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .ApiserverClientsSystemKubeProxy | indent 10 }}    \n    - path: \/etc\/kubernetes\/certs\/tls-ca.pem\n      filesystem: root\n      mode: 0644\n      contents:\n        inline: |-\n{{ .TLSCA | indent 10 }}\n    - path: \/etc\/kubernetes\/bootstrap\/kubeconfig\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: v1\n          kind: Config\n          clusters:\n            - name: local\n              cluster:\n                 certificate-authority: \/etc\/kubernetes\/certs\/tls-ca.pem\n                 server: {{ .ApiserverURL }}\n          contexts:\n            - name: local \n              context:\n                cluster: local\n                user: local \n          current-context: local\n          users:\n            - name: local\n              user:\n                token: {{ .BootstrapToken }} \n    - path: \/etc\/kubernetes\/kube-proxy\/kubeconfig\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: v1\n          kind: Config\n          clusters:\n            - name: local\n              cluster:\n                 certificate-authority: \/etc\/kubernetes\/certs\/tls-ca.pem\n                 server: {{ .ApiserverURL }}\n          contexts:\n            - name: local \n              context:\n                cluster: local\n                user: local \n          current-context: local\n          users:\n            - name: local\n              user:\n                client-certificate: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy.pem \n                client-key: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy-key.pem \n    - path: \/etc\/kubernetes\/kube-proxy\/config\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: componentconfig\/v1alpha1\n          kind: KubeProxyConfiguration\n          bindAddress: 0.0.0.0\n          clientConnection:\n            acceptContentTypes: \"\"\n            burst: 10\n            contentType: application\/vnd.kubernetes.protobuf\n            kubeconfig: \"\/etc\/kubernetes\/kube-proxy\/kubeconfig\"\n            qps: 5\n          clusterCIDR: \"{{ .ClusterCIDR }}\"\n          configSyncPeriod: 15m0s\n          conntrack:\n            max: 0\n            maxPerCore: 32768\n            min: 131072\n            tcpCloseWaitTimeout: 1h0m0s\n            tcpEstablishedTimeout: 24h0m0s\n          enableProfiling: false\n          featureGates: \"\"\n          healthzBindAddress: 0.0.0.0:10256\n          hostnameOverride: \"\"\n          iptables:\n            masqueradeAll: false\n            masqueradeBit: 14\n            minSyncPeriod: 0s\n            syncPeriod: 30s\n          metricsBindAddress: 127.0.0.1:10249\n          mode: \"\"\n          oomScoreAdj: -999\n          portRange: \"\"\n          resourceContainer: \/kube-proxy\n          udpTimeoutMilliseconds: 250ms\n    - path: \/etc\/kubernetes\/openstack\/openstack.config\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          [Global]\n          auth-url = {{ .OpenstackAuthURL }}\n          username = {{ .OpenstackUsername }}\n          password = {{ .OpenstackPassword }}\n          domain-name = {{ .OpenstackDomain }}\n          region = {{ .OpenstackRegion }}\n\n          [LoadBalancer]\n          lb-version=v2\n          subnet-id = {{ .OpenstackLBSubnetID }}\n          create-monitor = yes\n          monitor-delay = 1m\n          monitor-timeout = 30s\n          monitor-max-retries = 3\n\n          [BlockStorage]\n          trust-device-path = no\n\n          [Route]\n          router-id = {{ .OpenstackRouterID }}\n`\n<commit_msg>fix indentation<commit_after>package templates\n\nvar Node = `\npasswd:\n  users:\n    - name:          core\n      password_hash: xyTGJkB462ewk\n      ssh_authorized_keys: \n        - \"ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAvFapuevZeHFpFn438XMjvEQYd0wt7+tzUdAkMiSd007Tx1h79Xm9ZziDDUe4W6meinVOq93MAS\/ER27hoVWGo2H\/vn\/Cz5M8xr2j5rQODnrF3RmfrJTbZAWaDN0JTq2lFjmCHhZJNhr+VQP1uw4z2ofMBP6MLybnLmm9ukzxFYZqCCyfEEUTCMA9SWywtTpGQp8VLM4INCxzBSCuyt3SO6PBvJSo4HoKg\/sLvmRwpCVZth48PI0EUbJ72wp88Cw3bv8CLce2TOkLMwkE6NRN55w2aOyqP1G3vixHa6YcVaLlkQhJoJsBwE3rX5603y2KjOhMomqHfXxXn\/3GKTWlsQ== michael.j.schmidt@gmail.com\"\n\nlocksmith:\n  reboot_strategy: \"reboot\"\n\nnetworkd:\n  units:\n    - name: 00-ens32.network\n      contents: |\n        [Match]\n        Name=ens32\n        [Network]\n        DHCP=true\n        [DHCP]\n        UseMTU=true\n        CriticalConnection=true\n\nsystemd:\n  units:\n    - name: ccloud-metadata.service\n      contents: |\n        [Unit]\n        Description=Converged Cloud Metadata Agent\n\n        [Service]\n        Type=oneshot\n        ExecStart=\/usr\/bin\/coreos-metadata --provider=openstack-metadata --attributes=\/run\/metadata\/coreos --ssh-keys=core --hostname=\/etc\/hostname\n    - name: ccloud-metadata-hostname.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Workaround for coreos-metadata hostname bug\n        Requires=ccloud-metadata.service\n        After=ccloud-metadata.service\n\n        [Service]\n        Type=oneshot\n        EnvironmentFile=\/run\/metadata\/coreos\n        ExecStart=\/usr\/bin\/hostnamectl set-hostname ${COREOS_OPENSTACK_HOSTNAME}\n        \n        [Install]\n        WantedBy=multi-user.target\n    - name: docker.service\n      enable: true\n      dropins:\n        - name: 20-docker-opts.conf\n          contents: |\n            [Service]\n            Environment=\"DOCKER_OPTS=--log-opt max-size=5m --log-opt max-file=5 --ip-masq=false --iptables=false --bridge=none\"\n    - name: kubelet.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Kubelet via Hyperkube ACI\n\n        [Service]\n        Environment=\"RKT_RUN_ARGS=--uuid-file-save=\/var\/run\/kubelet-pod.uuid \\\n          --inherit-env \\\n          --dns=host \\\n          --net=host \\\n          --volume var-lib-cni,kind=host,source=\/var\/lib\/cni \\\n          --volume var-log,kind=host,source=\/var\/log \\\n          --mount volume=var-lib-cni,target=\/var\/lib\/cni \\\n          --mount volume=var-log,target=\/var\/log\"\n        Environment=\"KUBELET_IMAGE_TAG=v1.7.5_coreos.0\"\n        Environment=\"KUBELET_IMAGE_URL=quay.io\/coreos\/hyperkube\"\n        ExecStartPre=\/bin\/mkdir -p \/etc\/kubernetes\/manifests\n        ExecStartPre=\/bin\/mkdir -p \/var\/lib\/cni\n        ExecStartPre=-\/usr\/bin\/rkt rm --uuid-file=\/var\/run\/kubelet-pod.uuid\n        ExecStart=\/usr\/lib\/coreos\/kubelet-wrapper \\\n          --cloud-config=\/etc\/kubernetes\/openstack\/openstack.config \\\n          --cloud-provider=openstack \\\n          --require-kubeconfig \\\n          --bootstrap-kubeconfig=\/etc\/kubernetes\/bootstrap\/kubeconfig \\\n          --network-plugin=kubenet \\\n          --lock-file=\/var\/run\/lock\/kubelet.lock \\\n          --exit-on-lock-contention \\\n          --pod-manifest-path=\/etc\/kubernetes\/manifests \\\n          --allow-privileged \\\n          --cluster_domain=cluster.local \\\n          --client-ca-file=\/etc\/kubernetes\/certs\/kubelet-clients-ca.pem \\\n          --non-masquerade-cidr={{ .ClusterCIDR }} \\\n          --anonymous-auth=false\n        ExecStop=-\/usr\/bin\/rkt stop --uuid-file=\/var\/run\/kubelet-pod.uuid\n        Restart=always\n        RestartSec=10\n\n        [Install]\n        WantedBy=multi-user.target\n    - name: wormhole.service\n      contents: |\n        [Unit]\n        Description=Kubernikus Wormhole\n        Requires=network-online.target\n        After=network-online.target\n\n        [Service]\n        Slice=machine.slice\n        ExecStartPre=\/usr\/bin\/rkt fetch --insecure-options=image --pull-policy=new docker:\/\/sapcc\/kubernikus:latest\n        ExecStart=\/usr\/bin\/rkt run \\\n          --inherit-env \\\n          --net=host \\\n          --dns=host \\\n          --volume var-lib-kubelet,kind=host,source=\/var\/lib\/kubelet,readOnly=true \\\n          --mount volume=var-lib-kubelet,target=\/var\/lib\/kubelet \\\n          --volume var-run-kubernetes,kind=host,source=\/var\/run\/kubernetes,readOnly=true \\\n          --mount volume=var-run-kubernetes,target=\/var\/run\/kubernetes \\\n          --volume etc-kubernetes-certs,kind=host,source=\/etc\/kubernetes\/certs,readOnly=true \\\n          --mount volume=etc-kubernetes-certs,target=\/etc\/kubernetes\/certs \\\n          docker:\/\/sapcc\/kubernikus:latest \\\n          --exec wormhole -- client --kubeconfig=\/var\/lib\/kubelet\/kubeconfig\n        ExecStopPost=\/usr\/bin\/rkt gc --mark-only\n        KillMode=mixed\n        Restart=always\n        RestartSec=10s\n    - name: wormhole.path\n      enable: true\n      contents: |\n        [Path]\n        PathExists=\/var\/lib\/kubelet\/kubeconfig\n        [Install]\n        WantedBy=multi-user.target\n    - name: kube-proxy.service\n      enable: true\n      contents: |\n        [Unit]\n        Description=Kube-Proxy\n        Requires=network-online.target\n        After=network-online.target\n\n        [Service]\n        Slice=machine.slice\n        ExecStart=\/usr\/bin\/rkt run \\\n          --trust-keys-from-https \\\n          --inherit-env \\\n          --net=host \\\n          --dns=host \\\n          --volume etc-kubernetes,kind=host,source=\/etc\/kubernetes,readOnly=true \\\n          --mount volume=etc-kubernetes,target=\/etc\/kubernetes \\\n          --volume lib-modules,kind=host,source=\/lib\/modules,readOnly=true \\\n          --mount volume=lib-modules,target=\/lib\/modules \\\n          --stage1-from-dir=stage1-fly.aci \\\n          quay.io\/coreos\/hyperkube:v1.7.5_coreos.0 \\\n          --exec=hyperkube \\\n          -- \\\n          proxy \\\n          --config=\/etc\/kubernetes\/kube-proxy\/config\n        ExecStopPost=\/usr\/bin\/rkt gc --mark-only\n        KillMode=mixed\n        Restart=always\n        RestartSec=10s\n\n        [Install]\n        WantedBy=multi-user.target\n\nstorage:\n  files:\n    - path: \/etc\/kubernetes\/certs\/kubelet-clients-ca.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .KubeletClientsCA | indent 10 }}\n    - path: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy-key.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .ApiserverClientsSystemKubeProxyKey | indent 10 }}\n    - path: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy.pem\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n{{ .ApiserverClientsSystemKubeProxy | indent 10 }}    \n    - path: \/etc\/kubernetes\/certs\/tls-ca.pem\n      filesystem: root\n      mode: 0644\n      contents:\n        inline: |-\n{{ .TLSCA | indent 10 }}\n    - path: \/etc\/kubernetes\/bootstrap\/kubeconfig\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: v1\n          kind: Config\n          clusters:\n            - name: local\n              cluster:\n                 certificate-authority: \/etc\/kubernetes\/certs\/tls-ca.pem\n                 server: {{ .ApiserverURL }}\n          contexts:\n            - name: local \n              context:\n                cluster: local\n                user: local \n          current-context: local\n          users:\n            - name: local\n              user:\n                token: {{ .BootstrapToken }} \n    - path: \/etc\/kubernetes\/kube-proxy\/kubeconfig\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: v1\n          kind: Config\n          clusters:\n            - name: local\n              cluster:\n                 certificate-authority: \/etc\/kubernetes\/certs\/tls-ca.pem\n                 server: {{ .ApiserverURL }}\n          contexts:\n            - name: local \n              context:\n                cluster: local\n                user: local \n          current-context: local\n          users:\n            - name: local\n              user:\n                client-certificate: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy.pem \n                client-key: \/etc\/kubernetes\/certs\/apiserver-clients-system-kube-proxy-key.pem \n    - path: \/etc\/kubernetes\/kube-proxy\/config\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          apiVersion: componentconfig\/v1alpha1\n          kind: KubeProxyConfiguration\n          bindAddress: 0.0.0.0\n          clientConnection:\n            acceptContentTypes: \"\"\n            burst: 10\n            contentType: application\/vnd.kubernetes.protobuf\n            kubeconfig: \"\/etc\/kubernetes\/kube-proxy\/kubeconfig\"\n            qps: 5\n          clusterCIDR: \"{{ .ClusterCIDR }}\"\n          configSyncPeriod: 15m0s\n          conntrack:\n            max: 0\n            maxPerCore: 32768\n            min: 131072\n            tcpCloseWaitTimeout: 1h0m0s\n            tcpEstablishedTimeout: 24h0m0s\n          enableProfiling: false\n          featureGates: \"\"\n          healthzBindAddress: 0.0.0.0:10256\n          hostnameOverride: \"\"\n          iptables:\n            masqueradeAll: false\n            masqueradeBit: 14\n            minSyncPeriod: 0s\n            syncPeriod: 30s\n          metricsBindAddress: 127.0.0.1:10249\n          mode: \"\"\n          oomScoreAdj: -999\n          portRange: \"\"\n          resourceContainer: \/kube-proxy\n          udpTimeoutMilliseconds: 250ms\n    - path: \/etc\/kubernetes\/openstack\/openstack.config\n      filesystem: root\n      mode: 0644\n      contents: \n        inline: |-\n          [Global]\n          auth-url = {{ .OpenstackAuthURL }}\n          username = {{ .OpenstackUsername }}\n          password = {{ .OpenstackPassword }}\n          domain-name = {{ .OpenstackDomain }}\n          region = {{ .OpenstackRegion }}\n\n          [LoadBalancer]\n          lb-version=v2\n          subnet-id = {{ .OpenstackLBSubnetID }}\n          create-monitor = yes\n          monitor-delay = 1m\n          monitor-timeout = 30s\n          monitor-max-retries = 3\n\n          [BlockStorage]\n          trust-device-path = no\n\n          [Route]\n          router-id = {{ .OpenstackRouterID }}\n`\n<|endoftext|>"}
{"text":"<commit_before>package presilo\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"bytes\"\n)\n\nfunc GenerateRuby(schema *ObjectSchema, module string) string {\n\n\tvar ret bytes.Buffer\n\tvar toWrite string\n\n\ttoWrite = fmt.Sprintf(\"module %s\\n\\n\", ToCamelCase(module))\n\tret.WriteString(toWrite)\n\n\tret.WriteString(generateRubySignature(schema))\n\tret.WriteString(\"\\n\")\n\tret.WriteString(generateRubyConstructor(schema))\n\tret.WriteString(\"\\n\")\n\tret.WriteString(generateRubyFunctions(schema))\n\tret.WriteString(\"\\nend\\nend\\n\")\n\n\treturn ret.String()\n}\n\nfunc generateRubySignature(schema *ObjectSchema) string {\n\n\tvar ret bytes.Buffer\n\tvar subschema TypeSchema\n\tvar readers, accessors []string\n\tvar propertyName string\n\tvar toWrite string\n\n\ttoWrite = fmt.Sprintf(\"class %s\\n\", ToCamelCase(schema.Title))\n\tret.WriteString(toWrite)\n\n\tfor propertyName, subschema = range schema.Properties {\n\n\t\tpropertyName = ToSnakeCase(propertyName)\n\n\t\tif(subschema.HasConstraints()) {\n\t\t\ttoWrite = fmt.Sprintf(\":%s\", propertyName)\n\t\t\treaders = append(readers, toWrite)\n\n\t\t} else {\n\n\t\t\ttoWrite = fmt.Sprintf(\":%s\", propertyName)\n\t\t\taccessors = append(accessors, toWrite)\n\t\t}\n\t}\n\n\tif(len(readers) > 0) {\n\t\tret.WriteString(\"\\n\\tattr_reader \")\n\t\tret.WriteString(strings.Join(readers, \",\\n\\t\\t\\t\\t\\t\\t\\t\"))\n\t}\n\n\tif(len(accessors) > 0) {\n\t\tret.WriteString(\"\\n\\tattr_accessor \")\n\t\tret.WriteString(strings.Join(accessors, \",\\n\\t\\t\\t\\t\\t\\t\\t\\t\")) \/\/ god. Ruby.\n\t}\n\n\treturn ret.String()\n}\n\nfunc generateRubyConstructor(schema *ObjectSchema) string {\n\n\tvar ret bytes.Buffer\n\tvar declarations, setters []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tret.WriteString(\"\\n\\tdef initialize(\")\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tpropertyName = ToSnakeCase(propertyName)\n\n\t\tdeclarations = append(declarations, propertyName)\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\tset_%s(%s)\", propertyName, propertyName)\n\t\tsetters = append(setters, toWrite)\n\t}\n\n\ttoWrite = strings.Join(declarations, \",\")\n\tret.WriteString(toWrite)\n\tret.WriteString(\")\")\n\n\tfor _, setter := range setters {\n\t\tret.WriteString(setter)\n\t}\n\n\tret.WriteString(\"\\n\\tend\\n\")\n\treturn ret.String()\n}\n\nfunc generateRubyFunctions(schema *ObjectSchema) string {\n\n\tvar ret bytes.Buffer\n\tvar subschema TypeSchema\n\tvar toWrite string\n\tvar propertyName, snakeName string\n\n\tfor propertyName, subschema = range schema.Properties {\n\n\t\tsnakeName = ToSnakeCase(propertyName)\n\n\t\t\/\/ getter\n\t\ttoWrite = fmt.Sprintf(\"\\n\\tdef get_%s()\", snakeName)\n\t\tret.WriteString(toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\treturn @%s\\n\\tend\\n\", snakeName)\n\t\tret.WriteString(toWrite)\n\n\t\t\/\/ setter\n\t\ttoWrite = fmt.Sprintf(\"\\n\\tdef set_%s(%s)\", snakeName, snakeName)\n\t\tret.WriteString(toWrite)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_BOOLEAN:\n\t\t\ttoWrite = \"\"\n\t\tcase SCHEMATYPE_STRING:\n\t\t\ttoWrite = generateRubyStringSetter(subschema.(*StringSchema))\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\ttoWrite = generateRubyNumericSetter(subschema.(NumericSchemaType))\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\ttoWrite = generateRubyObjectSetter(subschema.(*ObjectSchema))\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\ttoWrite = generateRubyArraySetter(subschema.(*ArraySchema))\n\t\t}\n\n\t\tret.WriteString(toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\t@%s = value\", snakeName)\n\t\tret.WriteString(toWrite)\n\n\t\tret.WriteString(\"\\n\\tend\\n\")\n\t}\n\n\treturn ret.String()\n}\n\nfunc generateRubyStringSetter(schema *StringSchema) string {\n\n\tvar ret bytes.Buffer\n\tvar toWrite string\n\n\tret.WriteString(generateRubyNullCheck())\n\n\tif schema.MinLength != nil {\n\t\tret.WriteString(generateRubyRangeCheck(*schema.MinLength, \"value.length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\"))\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tret.WriteString(generateRubyRangeCheck(*schema.MaxLength, \"value.length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\"))\n\t}\n\n\tif schema.HasEnum() {\n\t\tret.WriteString(generateRubyEnumCheck(schema, schema.GetEnum(), \"'\", \"'\"))\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\tif(value =~ \/%s\/)\\n\", *schema.Pattern)\n\t\tret.WriteString(toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\t\\traise StandardError.new(\\\"Value '#{value}' did not match pattern '%s'\\\")\", *schema.Pattern)\n\t\tret.WriteString(toWrite)\n\n\t\tret.WriteString(\"\\n\\t\\tend\")\n\t}\n\treturn ret.String()\n}\n\nfunc generateRubyNumericSetter(schema NumericSchemaType) string {\n\n\tvar ret bytes.Buffer\n\tvar toWrite string\n\n\tif schema.HasMinimum() {\n\t\tret.WriteString(generateRubyRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\"))\n\t}\n\n\tif schema.HasMaximum() {\n\t\tret.WriteString(generateRubyRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\"))\n\t}\n\n\tif schema.HasEnum() {\n\t\tret.WriteString(generateRubyEnumCheck(schema, schema.GetEnum(), \"\", \"\"))\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\tif(value %% %f != 0)\\n\\t\", schema.GetMultiple())\n\t\tret.WriteString(toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\n\\t\\traise StandardError.new(\\\"Property '#{value}' was not a multiple of %v\\\")\", schema.GetMultiple())\n\t\tret.WriteString(toWrite)\n\n\t\tret.WriteString(\"\\n\\tend\\n\")\n\t}\n\treturn ret.String()\n}\n\nfunc generateRubyObjectSetter(schema *ObjectSchema) string {\n\n\treturn generateRubyNullCheck()\n}\n\nfunc generateRubyArraySetter(schema *ArraySchema) string {\n\n\tvar ret bytes.Buffer\n\n\tret.WriteString(generateRubyNullCheck())\n\n\tif schema.MinItems != nil {\n\t\tret.WriteString(generateRubyRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\"))\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tret.WriteString(generateRubyRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\"))\n\t}\n\n\treturn ret.String()\n}\n\nfunc generateRubyRangeCheck(value interface{}, reference, message, format string, exclusive bool, comparator, exclusiveComparator string) string {\n\n\tvar ret bytes.Buffer\n\tvar toWrite, compareString string\n\n\tif exclusive {\n\t\tcompareString = exclusiveComparator\n\t} else {\n\t\tcompareString = comparator\n\t}\n\n\ttoWrite = \"\\n\\t\\tif(\" + reference + \" \" + compareString + \" \" + format + \")\"\n\ttoWrite = fmt.Sprintf(toWrite, value)\n\tret.WriteString(toWrite)\n\n\ttoWrite = fmt.Sprintf(\"\\n\\t\\t\\traise StandardError.new(\\\"Property '#{value}' %s.\\\")\\n\\t\\tend\\n\", message)\n\tret.WriteString(toWrite)\n\n\treturn ret.String()\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 generateRubyEnumCheck(schema TypeSchema, enumValues []interface{}, prefix string, postfix string) string {\n\n\tvar ret bytes.Buffer\n\tvar stringValues []string\n\tvar constraint string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn \"\"\n\t}\n\n\t\/\/ convert enum values to strings\n\tfor _, enum := range enumValues {\n\t\tstringValues = append(stringValues, fmt.Sprintf(\"%s%v%s\", prefix, enum, postfix))\n\t}\n\n\t\/\/ write array of valid values\n\tconstraint = fmt.Sprintf(\"\\n\\t\\tvalidValues = [%s]\\n\", strings.Join(stringValues, \",\"))\n\tret.WriteString(constraint)\n\n\t\/\/ compare\n\tret.WriteString(\"\\n\\t\\tunless(validValues.include?(value))\")\n\tret.WriteString(\"\\n\\t\\t\\traise StandardError.new(\\\"Given value '#{value}' was not found in list of acceptable values\\\")\\n\")\n\tret.WriteString(\"\\t\\tend\\n\")\n\n\treturn ret.String()\n}\n\nfunc generateRubyNullCheck() string {\n\n\tvar ret bytes.Buffer\n\n\tret.WriteString(\"\\n\\t\\tif(value == nil)\")\n\tret.WriteString(\"\\n\\t\\t\\traise StandardError.new(\\\"Cannot set property to null value\\\")\")\n\tret.WriteString(\"\\n\\t\\tend\\n\")\n\n\treturn ret.String()\n}\n<commit_msg>Converted ruby to new indentation style<commit_after>package presilo\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc GenerateRuby(schema *ObjectSchema, module string) string {\n\n\tvar buffer *BufferedFormatString\n\n\tbuffer = NewBufferedFormatString(\"  \")\n\tbuffer.Printf(\"module %s\\n\\n\", ToCamelCase(module))\n\tbuffer.AddIndentation(1)\n\n\tgenerateRubySignature(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateRubyConstructor(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateRubyFunctions(schema, buffer)\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\")\n\n\treturn buffer.String()\n}\n\nfunc generateRubySignature(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar readers, accessors []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tbuffer.Printf(\"class %s\\n\", ToCamelCase(schema.Title))\n\tbuffer.AddIndentation(1)\n\n\tfor propertyName, subschema = range schema.Properties {\n\n\t\tpropertyName = ToSnakeCase(propertyName)\n\n\t\tif(subschema.HasConstraints()) {\n\t\t\ttoWrite = fmt.Sprintf(\":%s\", propertyName)\n\t\t\treaders = append(readers, toWrite)\n\n\t\t} else {\n\n\t\t\ttoWrite = fmt.Sprintf(\":%s\", propertyName)\n\t\t\taccessors = append(accessors, toWrite)\n\t\t}\n\t}\n\n\tif(len(readers) > 0) {\n\n\t\tbuffer.Print(\"\\nattr_reader \")\n\t\tbuffer.AddIndentation(6)\n\t\tbuffer.Print(strings.Join(readers, \",\\n\"))\n\t\tbuffer.AddIndentation(-6)\n\t}\n\n\tif(len(accessors) > 0) {\n\n\t\tbuffer.Print(\"\\nattr_accessor \")\n\t\tbuffer.AddIndentation(7)\n\t\tbuffer.Print(strings.Join(accessors, \",\\n\"))\n\t\tbuffer.AddIndentation(-7)\n\t}\n}\n\nfunc generateRubyConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar declarations []string\n\tvar propertyName string\n\n\tbuffer.Print(\"\\ndef initialize(\")\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tpropertyName = ToSnakeCase(propertyName)\n\t\tdeclarations = append(declarations, propertyName)\n\t}\n\n\tbuffer.Printf(\"%s)\\n\", strings.Join(declarations, \",\"))\n\tbuffer.AddIndentation(1)\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\t\tbuffer.Printf(\"\\nset_%s(%s)\", propertyName, propertyName)\n\t}\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\\n\")\n}\n\nfunc generateRubyFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName, snakeName string\n\n\tfor propertyName, subschema = range schema.Properties {\n\n\t\tsnakeName = ToSnakeCase(propertyName)\n\n\t\t\/\/ getter\n\t\tbuffer.Printf(\"\\ndef get_%s()\", snakeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nreturn @%s\", snakeName)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\nend\\n\")\n\n\t\t\/\/ setter\n\t\tbuffer.Printf(\"\\ndef set_%s(%s)\", snakeName, snakeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_STRING:\n\t\t\tgenerateRubyStringSetter(subschema.(*StringSchema), buffer)\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\tgenerateRubyNumericSetter(subschema.(NumericSchemaType), buffer)\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\tgenerateRubyObjectSetter(subschema.(*ObjectSchema), buffer)\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\tgenerateRubyArraySetter(subschema.(*ArraySchema), buffer)\n\t\t}\n\n\t\tbuffer.Printf(\"\\n@%s = value\", snakeName)\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\nend\\n\")\n\t}\n}\n\nfunc generateRubyStringSetter(schema *StringSchema, buffer *BufferedFormatString) {\n\n\tgenerateRubyNullCheck(buffer)\n\n\tif schema.MinLength != nil {\n\t\tgenerateRubyRangeCheck(*schema.MinLength, \"value.length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tgenerateRubyRangeCheck(*schema.MaxLength, \"value.length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateRubyEnumCheck(schema, buffer, schema.GetEnum(), \"'\", \"'\")\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\tbuffer.Printf(\"\\nif(value =~ \/%s\/)\\n\", *schema.Pattern)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nraise StandardError.new(\\\"Value '#{value}' did not match pattern '%s'\\\")\", *schema.Pattern)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\nend\")\n\t}\n}\n\nfunc generateRubyNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {\n\n\tif schema.HasMinimum() {\n\t\tgenerateRubyRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\", buffer)\n\t}\n\n\tif schema.HasMaximum() {\n\t\tgenerateRubyRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateRubyEnumCheck(schema, buffer, schema.GetEnum(), \"\", \"\")\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\tbuffer.Printf(\"\\nif(value %% %f != 0)\", schema.GetMultiple())\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nraise StandardError.new(\\\"Property '#{value}' was not a multiple of %v\\\")\", schema.GetMultiple())\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\nend\\n\")\n\t}\n}\n\nfunc generateRubyObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tgenerateRubyNullCheck(buffer)\n}\n\nfunc generateRubyArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {\n\n\tgenerateRubyNullCheck(buffer)\n\n\tif schema.MinItems != nil {\n\t\tgenerateRubyRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tgenerateRubyRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\", buffer)\n\t}\n}\n\nfunc generateRubyRangeCheck(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 + \")\", value, compareString)\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Printf(\"\\nraise StandardError.new(\\\"Property '#{value}' %s.\\\")\", message)\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\\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 generateRubyEnumCheck(schema TypeSchema, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {\n\n\tvar stringValues []string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn\n\t}\n\n\t\/\/ convert enum values to strings\n\tfor _, enum := range enumValues {\n\t\tstringValues = append(stringValues, fmt.Sprintf(\"%s%v%s\", prefix, enum, postfix))\n\t}\n\n\t\/\/ write array of valid values\n\tbuffer.Printf(\"\\nvalidValues = [%s]\\n\", strings.Join(stringValues, \",\"))\n\n\t\/\/ compare\n\tbuffer.Print(\"\\nunless(validValues.include?(value))\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nraise StandardError.new(\\\"Given value '#{value}' was not found in list of acceptable values\\\")\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\\n\")\n}\n\nfunc generateRubyNullCheck(buffer *BufferedFormatString) {\n\n\tbuffer.Print(\"\\nif(value == nil)\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nraise StandardError.new(\\\"Cannot set property to null value\\\")\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\nend\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package optimize\n\nimport (\n\t\"github.com\/gonum\/floats\"\n)\n\n\/\/ LBFGS implements the limited-memory BFGS algorithm. While the normal BFGS algorithm\n\/\/ makes a full approximation to the inverse hessian, LBFGS instead approximates the\n\/\/ hessian from the last Store optimization steps. The Store parameter is a tradeoff\n\/\/ between cost of the method and accuracy of the hessian approximation.\n\/\/ LBFGS has a cost (both in memory and time) of O(Store * inputDimension).\n\/\/ Since BFGS has a cost of O(inputDimension^2), LBFGS is more appropriate\n\/\/ for very large problems. This \"forgetful\" nature of LBFGS may also make it perform\n\/\/ better than BFGS for functions with Hessians that vary rapidly spatially.\n\/\/\n\/\/ If Store is 0, Store is defaulted to 15.\n\/\/ A Linesearcher for LBFGS must satisfy the strong Wolfe conditions at every\n\/\/ iteration. If Linesearcher == nil, an appropriate default is chosen.\ntype LBFGS struct {\n\tLinesearcher Linesearcher\n\tStore        int \/\/ how many past iterations to store\n\n\tls *LinesearchMethod\n\n\tdim    int\n\toldest int \/\/ element of the history slices that is the oldest\n\n\tx    []float64 \/\/ location at the last major iteration\n\tgrad []float64 \/\/ gradient at the last major iteration\n\n\ty []float64 \/\/ holds g_{k+1} - g_k\n\ts []float64 \/\/ holds x_{k+1} - x_k\n\ta []float64 \/\/ holds cache of hessian updates\n\n\t\/\/ History\n\tyHist   [][]float64 \/\/ last Store iterations of y\n\tsHist   [][]float64 \/\/ last Store iterations of s\n\trhoHist []float64   \/\/ last Store iterations of rho\n}\n\nfunc (l *LBFGS) Init(loc *Location) (Operation, error) {\n\tif l.Linesearcher == nil {\n\t\tl.Linesearcher = &Bisection{}\n\t}\n\tif l.ls == nil {\n\t\tl.ls = &LinesearchMethod{}\n\t}\n\tl.ls.Linesearcher = l.Linesearcher\n\tl.ls.NextDirectioner = l\n\treturn l.ls.Init(loc)\n}\n\nfunc (l *LBFGS) Iterate(loc *Location) (Operation, error) {\n\treturn l.ls.Iterate(loc)\n}\n\nfunc (l *LBFGS) InitDirection(loc *Location, dir []float64) (stepSize float64) {\n\tdim := len(loc.X)\n\tl.dim = dim\n\n\tif l.Store == 0 {\n\t\tl.Store = 15\n\t}\n\n\tl.oldest = l.Store - 1 \/\/ the first vector will be put in at 0\n\n\tl.x = resize(l.x, dim)\n\tl.grad = resize(l.grad, dim)\n\tcopy(l.x, loc.X)\n\tcopy(l.grad, loc.Gradient)\n\n\tl.y = resize(l.y, dim)\n\tl.s = resize(l.s, dim)\n\tl.a = resize(l.a, l.Store)\n\tl.rhoHist = resize(l.rhoHist, l.Store)\n\n\tif cap(l.yHist) < l.Store {\n\t\tn := make([][]float64, l.Store-cap(l.yHist))\n\t\tl.yHist = append(l.yHist, n...)\n\t}\n\tif cap(l.sHist) < l.Store {\n\t\tn := make([][]float64, l.Store-cap(l.sHist))\n\t\tl.sHist = append(l.sHist, n...)\n\t}\n\tl.yHist = l.yHist[:l.Store]\n\tl.sHist = l.sHist[:l.Store]\n\tfor i := range l.sHist {\n\t\tl.sHist[i] = resize(l.sHist[i], dim)\n\t\tfor j := range l.sHist[i] {\n\t\t\tl.sHist[i][j] = 0\n\t\t}\n\t}\n\tfor i := range l.yHist {\n\t\tl.yHist[i] = resize(l.yHist[i], dim)\n\t\tfor j := range l.yHist[i] {\n\t\t\tl.yHist[i][j] = 0\n\t\t}\n\t}\n\n\tcopy(dir, loc.Gradient)\n\tfloats.Scale(-1, dir)\n\n\treturn 1 \/ floats.Norm(dir, 2)\n}\n\nfunc (l *LBFGS) NextDirection(loc *Location, dir []float64) (stepSize float64) {\n\tif len(loc.X) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\tif len(loc.Gradient) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\tif len(dir) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\n\t\/\/ Update direction. Uses two-loop correction as described in\n\t\/\/ Nocedal, Wright (2006), Numerical Optimization (2nd ed.). Chapter 7, page 178.\n\tcopy(dir, loc.Gradient)\n\tfloats.SubTo(l.y, loc.Gradient, l.grad)\n\tfloats.SubTo(l.s, loc.X, l.x)\n\tcopy(l.sHist[l.oldest], l.s)\n\tcopy(l.yHist[l.oldest], l.y)\n\tsDotY := floats.Dot(l.y, l.s)\n\tl.rhoHist[l.oldest] = 1 \/ sDotY\n\n\tl.oldest++\n\tl.oldest = l.oldest % l.Store\n\tcopy(l.x, loc.X)\n\tcopy(l.grad, loc.Gradient)\n\n\t\/\/ two loop update. First loop starts with the most recent element\n\t\/\/ and goes backward, second starts with the oldest element and goes\n\t\/\/ forward. At the end have computed H^-1 * g, so flip the direction for\n\t\/\/ minimization.\n\tfor i := 0; i < l.Store; i++ {\n\t\tidx := l.oldest - i - 1\n\t\tif idx < 0 {\n\t\t\tidx += l.Store\n\t\t}\n\t\tl.a[idx] = l.rhoHist[idx] * floats.Dot(l.sHist[idx], dir)\n\t\tfloats.AddScaled(dir, -l.a[idx], l.yHist[idx])\n\t}\n\n\t\/\/ Scale the initial Hessian.\n\tgamma := sDotY \/ floats.Dot(l.y, l.y)\n\tfloats.Scale(gamma, dir)\n\n\tfor i := 0; i < l.Store; i++ {\n\t\tidx := i + l.oldest\n\t\tif idx >= l.Store {\n\t\t\tidx -= l.Store\n\t\t}\n\t\tbeta := l.rhoHist[idx] * floats.Dot(l.yHist[idx], dir)\n\t\tfloats.AddScaled(dir, l.a[idx]-beta, l.sHist[idx])\n\t}\n\tfloats.Scale(-1, dir)\n\n\treturn 1\n}\n\nfunc (*LBFGS) Needs() struct {\n\tGradient bool\n\tHessian  bool\n} {\n\treturn struct {\n\t\tGradient bool\n\t\tHessian  bool\n\t}{true, false}\n}\n<commit_msg>Remove y and s fields from LBFGS<commit_after>package optimize\n\nimport (\n\t\"github.com\/gonum\/floats\"\n)\n\n\/\/ LBFGS implements the limited-memory BFGS algorithm. While the normal BFGS algorithm\n\/\/ makes a full approximation to the inverse hessian, LBFGS instead approximates the\n\/\/ hessian from the last Store optimization steps. The Store parameter is a tradeoff\n\/\/ between cost of the method and accuracy of the hessian approximation.\n\/\/ LBFGS has a cost (both in memory and time) of O(Store * inputDimension).\n\/\/ Since BFGS has a cost of O(inputDimension^2), LBFGS is more appropriate\n\/\/ for very large problems. This \"forgetful\" nature of LBFGS may also make it perform\n\/\/ better than BFGS for functions with Hessians that vary rapidly spatially.\n\/\/\n\/\/ If Store is 0, Store is defaulted to 15.\n\/\/ A Linesearcher for LBFGS must satisfy the strong Wolfe conditions at every\n\/\/ iteration. If Linesearcher == nil, an appropriate default is chosen.\ntype LBFGS struct {\n\tLinesearcher Linesearcher\n\tStore        int \/\/ how many past iterations to store\n\n\tls *LinesearchMethod\n\n\tdim    int\n\toldest int \/\/ element of the history slices that is the oldest\n\n\tx    []float64 \/\/ location at the last major iteration\n\tgrad []float64 \/\/ gradient at the last major iteration\n\n\ta []float64 \/\/ holds cache of hessian updates\n\n\t\/\/ History\n\tyHist   [][]float64 \/\/ last Store iterations of y\n\tsHist   [][]float64 \/\/ last Store iterations of s\n\trhoHist []float64   \/\/ last Store iterations of rho\n}\n\nfunc (l *LBFGS) Init(loc *Location) (Operation, error) {\n\tif l.Linesearcher == nil {\n\t\tl.Linesearcher = &Bisection{}\n\t}\n\tif l.ls == nil {\n\t\tl.ls = &LinesearchMethod{}\n\t}\n\tl.ls.Linesearcher = l.Linesearcher\n\tl.ls.NextDirectioner = l\n\treturn l.ls.Init(loc)\n}\n\nfunc (l *LBFGS) Iterate(loc *Location) (Operation, error) {\n\treturn l.ls.Iterate(loc)\n}\n\nfunc (l *LBFGS) InitDirection(loc *Location, dir []float64) (stepSize float64) {\n\tdim := len(loc.X)\n\tl.dim = dim\n\n\tif l.Store == 0 {\n\t\tl.Store = 15\n\t}\n\n\tl.oldest = l.Store - 1 \/\/ the first vector will be put in at 0\n\n\tl.x = resize(l.x, dim)\n\tl.grad = resize(l.grad, dim)\n\tcopy(l.x, loc.X)\n\tcopy(l.grad, loc.Gradient)\n\n\tl.a = resize(l.a, l.Store)\n\tl.rhoHist = resize(l.rhoHist, l.Store)\n\n\tif cap(l.yHist) < l.Store {\n\t\tn := make([][]float64, l.Store-cap(l.yHist))\n\t\tl.yHist = append(l.yHist, n...)\n\t}\n\tif cap(l.sHist) < l.Store {\n\t\tn := make([][]float64, l.Store-cap(l.sHist))\n\t\tl.sHist = append(l.sHist, n...)\n\t}\n\tl.yHist = l.yHist[:l.Store]\n\tl.sHist = l.sHist[:l.Store]\n\tfor i := range l.sHist {\n\t\tl.sHist[i] = resize(l.sHist[i], dim)\n\t\tfor j := range l.sHist[i] {\n\t\t\tl.sHist[i][j] = 0\n\t\t}\n\t}\n\tfor i := range l.yHist {\n\t\tl.yHist[i] = resize(l.yHist[i], dim)\n\t\tfor j := range l.yHist[i] {\n\t\t\tl.yHist[i][j] = 0\n\t\t}\n\t}\n\n\tcopy(dir, loc.Gradient)\n\tfloats.Scale(-1, dir)\n\n\treturn 1 \/ floats.Norm(dir, 2)\n}\n\nfunc (l *LBFGS) NextDirection(loc *Location, dir []float64) (stepSize float64) {\n\tif len(loc.X) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\tif len(loc.Gradient) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\tif len(dir) != l.dim {\n\t\tpanic(\"lbfgs: unexpected size mismatch\")\n\t}\n\n\t\/\/ Update direction. Uses two-loop correction as described in\n\t\/\/ Nocedal, Wright (2006), Numerical Optimization (2nd ed.). Chapter 7, page 178.\n\ty := l.yHist[l.oldest]\n\tfloats.SubTo(y, loc.Gradient, l.grad)\n\ts := l.sHist[l.oldest]\n\tfloats.SubTo(s, loc.X, l.x)\n\tsDotY := floats.Dot(s, y)\n\tl.rhoHist[l.oldest] = 1 \/ sDotY\n\n\tl.oldest = (l.oldest + 1) % l.Store\n\n\tcopy(l.x, loc.X)\n\tcopy(l.grad, loc.Gradient)\n\tcopy(dir, loc.Gradient)\n\n\t\/\/ two loop update. First loop starts with the most recent element\n\t\/\/ and goes backward, second starts with the oldest element and goes\n\t\/\/ forward. At the end have computed H^-1 * g, so flip the direction for\n\t\/\/ minimization.\n\tfor i := 0; i < l.Store; i++ {\n\t\tidx := l.oldest - i - 1\n\t\tif idx < 0 {\n\t\t\tidx += l.Store\n\t\t}\n\t\tl.a[idx] = l.rhoHist[idx] * floats.Dot(l.sHist[idx], dir)\n\t\tfloats.AddScaled(dir, -l.a[idx], l.yHist[idx])\n\t}\n\n\t\/\/ Scale the initial Hessian.\n\tgamma := sDotY \/ floats.Dot(y, y)\n\tfloats.Scale(gamma, dir)\n\n\tfor i := 0; i < l.Store; i++ {\n\t\tidx := i + l.oldest\n\t\tif idx >= l.Store {\n\t\t\tidx -= l.Store\n\t\t}\n\t\tbeta := l.rhoHist[idx] * floats.Dot(l.yHist[idx], dir)\n\t\tfloats.AddScaled(dir, l.a[idx]-beta, l.sHist[idx])\n\t}\n\tfloats.Scale(-1, dir)\n\n\treturn 1\n}\n\nfunc (*LBFGS) Needs() struct {\n\tGradient bool\n\tHessian  bool\n} {\n\treturn struct {\n\t\tGradient bool\n\t\tHessian  bool\n\t}{true, false}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 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 tools\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmeta_v1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nconst (\n\tdefaultCRIProxySockLocation = \"\/run\/criproxy.sock\"\n\tsysCheckNamespace           = \"kube-system\"\n)\n\ntype validateCommand struct {\n\tclient KubeClient\n\tout    io.Writer\n}\n\n\/\/ NewValidateCommand returns a cobra.Command that validates a cluster readines\n\/\/ for Virtlet deploy\nfunc NewValidateCommand(client KubeClient, out io.Writer) *cobra.Command {\n\tv := &validateCommand{client: client, out: out}\n\tcmd := &cobra.Command{\n\t\tUse:   \"validate\",\n\t\tShort: \"Validate cluster readiness for Virtlet deployment\",\n\t\tLong:  \"Check configuration of cluster nodes valiating their readiness for Virtlet deployment\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) != 0 {\n\t\t\t\treturn errors.New(\"This command does not accept arguments\")\n\t\t\t}\n\t\t\treturn v.Run()\n\t\t},\n\t}\n\treturn cmd\n}\n\nfunc (v *validateCommand) Run() error {\n\tnodes, err := v.client.GetVirtletNodeNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn errors.New(\"There are no nodes with label extraRuntime=virtlet\")\n\t}\n\n\tv.info(\"Nodes labeled with extraRuntime=virtlet: %s\", strings.Join(nodes, \", \"))\n\n\tpods, errs := v.prepareSysCheckPods(nodes)\n\tdefer v.deleteSysCheckPods(pods)\n\tfor _, errstr := range errs {\n\t\tv.info(errstr)\n\t}\n\n\tif len(pods) == 0 {\n\t\treturn errors.New(\"Could not create system check pods on any Virtlet node\")\n\t}\n\n\terrsNumber := v.checkCNI(pods)\n\terrsNumber += v.checkCRIProxy(pods)\n\terrsNumber += v.checkKubeletArgs(pods)\n\n\tif errsNumber != 0 {\n\t\treturn fmt.Errorf(\"Collected %d errors while running SysCheck pods\", errsNumber)\n\t} else {\n\t\tv.info(\"No errors found with\")\n\t}\n\n\treturn nil\n}\n\nfunc (v *validateCommand) prepareSysCheckPods(nodes []string) (pods []*v1.Pod, errs []string) {\n\t\/\/ TODO: this whole part should be running in a timeouted context\n\t\/\/ TODO: paralelize pods creation\n\thostPathType := v1.HostPathDirectory\n\tvar definedPods []*v1.Pod\n\tfor _, name := range nodes {\n\t\tv.info(\"Creating syscheck pod on node %q\", name)\n\t\tpod, err := v.client.CreatePod(&v1.Pod{\n\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\tName:      \"virtletsyscheck-\" + name,\n\t\t\t\tNamespace: sysCheckNamespace,\n\t\t\t},\n\t\t\tSpec: v1.PodSpec{\n\t\t\t\tVolumes: []v1.Volume{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"hostfs\",\n\t\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\t\tHostPath: &v1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\tPath: \"\/\",\n\t\t\t\t\t\t\t\tType: &hostPathType,\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\tContainers: []v1.Container{\n\t\t\t\t\t{\n\t\t\t\t\t\tName:    \"syscheck\",\n\t\t\t\t\t\tImage:   \"busybox\",\n\t\t\t\t\t\tCommand: []string{\"\/bin\/sh\", \"-c\", \"--\"},\n\t\t\t\t\t\tArgs:    []string{\"trap : TERM INT; (while true; do sleep 1000; done) & wait\"},\n\t\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:      \"hostfs\",\n\t\t\t\t\t\t\t\tMountPath: \"\/mnt\",\n\t\t\t\t\t\t\t\tReadOnly:  true,\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\tNodeSelector: map[string]string{\"kubernetes.io\/hostname\": name},\n\t\t\t\tHostPID:      true,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"SysCheck pod creation failed on node %q: %v\", name, err))\n\t\t} else {\n\t\t\tdefinedPods = append(definedPods, pod)\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(definedPods))\n\tfor _, def := range definedPods {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\t\/\/ TODO: add checking for possible container starting failure, e.g. when there was an error while\n\t\t\t\t\/\/ downloading container image\n\t\t\t\tif pod, err := v.client.GetPod(def.Name, sysCheckNamespace); err != nil {\n\t\t\t\t\terrs = append(errs, fmt.Sprintf(\"Failure during SysCheck pod %q status checking: %v\", def.Name, err))\n\t\t\t\t\tbreak\n\t\t\t\t} else if pod.Status.Phase == v1.PodRunning {\n\t\t\t\t\tpods = append(pods, pod)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(250 * time.Millisecond)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\tv.info(\"SysCheck pods on all Virtlet nodes are running\")\n\n\treturn\n}\n\nfunc (v *validateCommand) info(fmtstring string, a ...interface{}) {\n\tfmt.Fprintf(v.out, fmtstring+\"\\n\", a...)\n}\n\nfunc (v *validateCommand) deleteSysCheckPods(pods []*v1.Pod) {\n\tfor _, pod := range pods {\n\t\tif err := v.client.DeletePod(pod.Name, sysCheckNamespace); err != nil {\n\t\t\tv.info(\"Error during removal of SysCheck pod %q\/%q: %v\", sysCheckNamespace, pod.Name, err)\n\t\t}\n\t}\n}\n\nfunc doInAllPods(pods []*v1.Pod, check func(*v1.Pod) int) int {\n\t\/\/ TODO: this func should use timeouting context\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(pods))\n\n\terrsNumber := 0\n\tfor _, pod := range pods {\n\t\tgo func() {\n\t\t\terrsNumber += check(pod)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\twg.Wait()\n\treturn errsNumber\n}\n\nfunc (v *validateCommand) chekcInAllSysChecks(pods []*v1.Pod, description, command string, check func(nodeName, out string) int) int {\n\treturn doInAllPods(pods, func(pod *v1.Pod) int {\n\t\terrsNumber := 0\n\t\tvar out bytes.Buffer\n\t\t_, err := v.client.ExecInContainer(\n\t\t\tpod.Name, \"syscheck\", pod.Namespace, nil, bufio.NewWriter(&out), nil,\n\t\t\t[]string{\n\t\t\t\t\"\/bin\/sh\", \"-c\",\n\t\t\t\tcommand,\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tv.info(\"Error during verification of %s on node %q: %v\", description, pod.Spec.NodeName, err)\n\t\t\terrsNumber += 1\n\t\t}\n\n\t\treturn errsNumber + check(pod.Spec.NodeName, strings.TrimRight(out.String(), \"\\r\\n\"))\n\t})\n}\n\nfunc (v *validateCommand) checkCNI(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"CNI configuration\",\n\t\t\"find \/mnt\/etc\/cni\/net.d -name \\\"*.conf\\\" -o -name \\\"*.conflist\\\" -o -name \\\"*.json\\\" | wc -l\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif i, err := strconv.Atoi(out); err != nil {\n\t\t\t\tv.info(\"Internal error during conunting CNI configuration files on %q: %v\", nodeName, err)\n\t\t\t\terrsNumber += 1\n\t\t\t} else if i == 0 {\n\t\t\t\tv.info(\"Node %q does not have any CNI configuration in \/etc\/cni\/net.d\", nodeName)\n\t\t\t\terrsNumber += 1\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n\nfunc (v *validateCommand) checkCRIProxy(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"CRI Proxy\",\n\t\t\"pgrep criproxy | while read pid ; do cat \/proc\/$pid\/cmdline ; done\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif len(out) == 0 {\n\t\t\t\tv.info(\"Node %q does not have CRI Proxy running\", nodeName)\n\t\t\t\terrsNumber += 1\n\t\t\t} else if !strings.Contains(out, defaultCRIProxySockLocation) {\n\t\t\t\tv.info(\"CRI Proxy on node %q does not have %q as socket location\", nodeName, defaultCRIProxySockLocation)\n\t\t\t\terrsNumber += 1\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n\nfunc (v *validateCommand) checkKubeletArgs(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"kubelet configuration\",\n\t\t\"( pgrep kubelet ; pgrep hyperkube ) | while read pid ; do cat \/proc\/$pid\/cmdline ; done\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif len(out) == 0 {\n\t\t\t\tv.info(\"Internal error - kubelet not found on node %q\", nodeName)\n\t\t\t\terrsNumber += 1\n\t\t\t} else {\n\t\t\t\tfor _, arg := range []string{\n\t\t\t\t\t\"--container-runtime=remote\",\n\t\t\t\t\t\"--container-runtime-endpoint=unix:\/\/\/run\/criproxy.sock\",\n\t\t\t\t\t\"--image-service-endpoint=unix:\/\/\/run\/criproxy.sock\",\n\t\t\t\t\t\"--enable-controller-attach-detach=false\",\n\t\t\t\t} {\n\t\t\t\t\tif !strings.Contains(out, arg) {\n\t\t\t\t\t\tv.info(\"kubelet on node %q is missing %q option\", nodeName, arg)\n\t\t\t\t\t\terrsNumber += 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n<commit_msg>Fix codeclimate issues<commit_after>\/*\nCopyright 2019 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 tools\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmeta_v1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nconst (\n\tdefaultCRIProxySockLocation = \"\/run\/criproxy.sock\"\n\tsysCheckNamespace           = \"kube-system\"\n)\n\ntype validateCommand struct {\n\tclient KubeClient\n\tout    io.Writer\n}\n\n\/\/ NewValidateCommand returns a cobra.Command that validates a cluster readines\n\/\/ for Virtlet deploy\nfunc NewValidateCommand(client KubeClient, out io.Writer) *cobra.Command {\n\tv := &validateCommand{client: client, out: out}\n\tcmd := &cobra.Command{\n\t\tUse:   \"validate\",\n\t\tShort: \"Validate cluster readiness for Virtlet deployment\",\n\t\tLong:  \"Check configuration of cluster nodes valiating their readiness for Virtlet deployment\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(args) != 0 {\n\t\t\t\treturn errors.New(\"This command does not accept arguments\")\n\t\t\t}\n\t\t\treturn v.Run()\n\t\t},\n\t}\n\treturn cmd\n}\n\nfunc (v *validateCommand) Run() error {\n\tnodes, err := v.client.GetVirtletNodeNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn errors.New(\"There are no nodes with label extraRuntime=virtlet\")\n\t}\n\n\tv.info(\"Nodes labeled with extraRuntime=virtlet: %s\", strings.Join(nodes, \", \"))\n\n\tpods, errs := v.prepareSysCheckPods(nodes)\n\tdefer v.deleteSysCheckPods(pods)\n\tfor _, errstr := range errs {\n\t\tv.info(errstr)\n\t}\n\n\tif len(pods) == 0 {\n\t\treturn errors.New(\"Could not create system check pods on any Virtlet node\")\n\t}\n\n\terrsNumber := v.checkCNI(pods)\n\terrsNumber += v.checkCRIProxy(pods)\n\terrsNumber += v.checkKubeletArgs(pods)\n\n\tif errsNumber != 0 {\n\t\treturn fmt.Errorf(\"Collected %d errors while running SysCheck pods\", errsNumber)\n\t}\n\tv.info(\"No errors found with\")\n\n\treturn nil\n}\n\nfunc (v *validateCommand) prepareSysCheckPods(nodes []string) (pods []*v1.Pod, errs []string) {\n\t\/\/ TODO: this whole part should be running in a timeouted context\n\t\/\/ TODO: paralelize pods creation\n\thostPathType := v1.HostPathDirectory\n\tvar definedPods []*v1.Pod\n\tfor _, name := range nodes {\n\t\tv.info(\"Creating syscheck pod on node %q\", name)\n\t\tpod, err := v.client.CreatePod(&v1.Pod{\n\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\tName:      \"virtletsyscheck-\" + name,\n\t\t\t\tNamespace: sysCheckNamespace,\n\t\t\t},\n\t\t\tSpec: v1.PodSpec{\n\t\t\t\tVolumes: []v1.Volume{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"hostfs\",\n\t\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\t\tHostPath: &v1.HostPathVolumeSource{\n\t\t\t\t\t\t\t\tPath: \"\/\",\n\t\t\t\t\t\t\t\tType: &hostPathType,\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\tContainers: []v1.Container{\n\t\t\t\t\t{\n\t\t\t\t\t\tName:    \"syscheck\",\n\t\t\t\t\t\tImage:   \"busybox\",\n\t\t\t\t\t\tCommand: []string{\"\/bin\/sh\", \"-c\", \"--\"},\n\t\t\t\t\t\tArgs:    []string{\"trap : TERM INT; (while true; do sleep 1000; done) & wait\"},\n\t\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:      \"hostfs\",\n\t\t\t\t\t\t\t\tMountPath: \"\/mnt\",\n\t\t\t\t\t\t\t\tReadOnly:  true,\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\tNodeSelector: map[string]string{\"kubernetes.io\/hostname\": name},\n\t\t\t\tHostPID:      true,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"SysCheck pod creation failed on node %q: %v\", name, err))\n\t\t} else {\n\t\t\tdefinedPods = append(definedPods, pod)\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(definedPods))\n\tfor _, def := range definedPods {\n\t\tgo func(podDef *v1.Pod) {\n\t\t\tfor {\n\t\t\t\t\/\/ TODO: add checking for possible container starting failure, e.g. when there was an error while\n\t\t\t\t\/\/ downloading container image\n\t\t\t\tif pod, err := v.client.GetPod(podDef.Name, sysCheckNamespace); err != nil {\n\t\t\t\t\terrs = append(errs, fmt.Sprintf(\"Failure during SysCheck pod %q status checking: %v\", podDef.Name, err))\n\t\t\t\t\tbreak\n\t\t\t\t} else if pod.Status.Phase == v1.PodRunning {\n\t\t\t\t\tpods = append(pods, pod)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(250 * time.Millisecond)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(def)\n\t}\n\twg.Wait()\n\tv.info(\"SysCheck pods on all Virtlet nodes are running\")\n\n\treturn\n}\n\nfunc (v *validateCommand) info(fmtstring string, a ...interface{}) {\n\tfmt.Fprintf(v.out, fmtstring+\"\\n\", a...)\n}\n\nfunc (v *validateCommand) deleteSysCheckPods(pods []*v1.Pod) {\n\tfor _, pod := range pods {\n\t\tif err := v.client.DeletePod(pod.Name, sysCheckNamespace); err != nil {\n\t\t\tv.info(\"Error during removal of SysCheck pod %q\/%q: %v\", sysCheckNamespace, pod.Name, err)\n\t\t}\n\t}\n}\n\nfunc doInAllPods(pods []*v1.Pod, check func(*v1.Pod) int) int {\n\t\/\/ TODO: this func should use timeouting context\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(pods))\n\n\terrsNumber := 0\n\tfor _, pod := range pods {\n\t\tgo func(pod_ *v1.Pod) {\n\t\t\terrsNumber += check(pod_)\n\t\t\twg.Done()\n\t\t}(pod)\n\t}\n\n\twg.Wait()\n\treturn errsNumber\n}\n\nfunc (v *validateCommand) chekcInAllSysChecks(pods []*v1.Pod, description, command string, check func(nodeName, out string) int) int {\n\treturn doInAllPods(pods, func(pod *v1.Pod) int {\n\t\terrsNumber := 0\n\t\tvar out bytes.Buffer\n\t\t_, err := v.client.ExecInContainer(\n\t\t\tpod.Name, \"syscheck\", pod.Namespace, nil, bufio.NewWriter(&out), nil,\n\t\t\t[]string{\n\t\t\t\t\"\/bin\/sh\", \"-c\",\n\t\t\t\tcommand,\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tv.info(\"Error during verification of %s on node %q: %v\", description, pod.Spec.NodeName, err)\n\t\t\terrsNumber++\n\t\t}\n\n\t\treturn errsNumber + check(pod.Spec.NodeName, strings.TrimRight(out.String(), \"\\r\\n\"))\n\t})\n}\n\nfunc (v *validateCommand) checkCNI(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"CNI configuration\",\n\t\t\"find \/mnt\/etc\/cni\/net.d -name \\\"*.conf\\\" -o -name \\\"*.conflist\\\" -o -name \\\"*.json\\\" | wc -l\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif i, err := strconv.Atoi(out); err != nil {\n\t\t\t\tv.info(\"Internal error during conunting CNI configuration files on %q: %v\", nodeName, err)\n\t\t\t\terrsNumber++\n\t\t\t} else if i == 0 {\n\t\t\t\tv.info(\"Node %q does not have any CNI configuration in \/etc\/cni\/net.d\", nodeName)\n\t\t\t\terrsNumber++\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n\nfunc (v *validateCommand) checkCRIProxy(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"CRI Proxy\",\n\t\t\"pgrep criproxy | while read pid ; do cat \/proc\/$pid\/cmdline ; done\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif len(out) == 0 {\n\t\t\t\tv.info(\"Node %q does not have CRI Proxy running\", nodeName)\n\t\t\t\terrsNumber++\n\t\t\t} else if !strings.Contains(out, defaultCRIProxySockLocation) {\n\t\t\t\tv.info(\"CRI Proxy on node %q does not have %q as socket location\", nodeName, defaultCRIProxySockLocation)\n\t\t\t\terrsNumber++\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n\nfunc (v *validateCommand) checkKubeletArgs(pods []*v1.Pod) int {\n\treturn v.chekcInAllSysChecks(\n\t\tpods, \"kubelet configuration\",\n\t\t\"( pgrep kubelet ; pgrep hyperkube ) | while read pid ; do cat \/proc\/$pid\/cmdline ; done\",\n\t\tfunc(nodeName, out string) int {\n\t\t\terrsNumber := 0\n\t\t\tif len(out) == 0 {\n\t\t\t\tv.info(\"Internal error - kubelet not found on node %q\", nodeName)\n\t\t\t\terrsNumber++\n\t\t\t} else {\n\t\t\t\tfor _, arg := range []string{\n\t\t\t\t\t\"--container-runtime=remote\",\n\t\t\t\t\t\"--container-runtime-endpoint=unix:\/\/\/run\/criproxy.sock\",\n\t\t\t\t\t\"--image-service-endpoint=unix:\/\/\/run\/criproxy.sock\",\n\t\t\t\t\t\"--enable-controller-attach-detach=false\",\n\t\t\t\t} {\n\t\t\t\t\tif !strings.Contains(out, arg) {\n\t\t\t\t\t\tv.info(\"kubelet on node %q is missing %q option\", nodeName, arg)\n\t\t\t\t\t\terrsNumber++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn errsNumber\n\t\t},\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\/config\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\n\troutev1 \"github.com\/openshift\/client-go\/route\/clientset\/versioned\/typed\/route\/v1\"\n\tlogf \"sigs.k8s.io\/controller-runtime\/pkg\/runtime\/log\"\n)\n\nvar (\n\topenshift *bool\n\tlog       = logf.Log.WithName(\"util\")\n)\n\nfunc IsOpenshift() bool {\n\tif openshift == nil {\n\t\tb := detectOpenshift()\n\t\topenshift = &b\n\t}\n\treturn *openshift\n}\n\nfunc detectOpenshift() bool {\n\n\tlog.Info(\"Detect if openshift is running\")\n\n\tvalue, ok := os.LookupEnv(\"ENMASSE_OPENSHIFT\")\n\tif ok {\n\t\tlog.Info(\"Set by env-var 'ENMASSE_OPENSHIFT': \" + value)\n\t\treturn strings.ToLower(value) == \"true\"\n\t}\n\n\t\/\/ try to\n\n\tcfg, err := config.GetConfig()\n\tif err != nil {\n\t\tlog.Error(err, \"Error getting config: %v\")\n\t\treturn false\n\t}\n\n\trouteClient, err := routev1.NewForConfig(cfg)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to get routeClient\")\n\t\treturn false\n\t}\n\n\t_, err = routeClient.RESTClient().Get().DoRaw()\n\tif err == nil {\n\t\tlog.Info(\"Rest call succeeded\")\n\t\treturn true\n\t}\n\n\tse, ok := err.(*errors.StatusError)\n\tif !ok {\n\t\tlog.Info(\"Result is not a StatusError\")\n\t\treturn false\n\t}\n\n\tcode := se.ErrStatus.Code\n\tlog.Info(\"OpenShift detect\", \"code\", code)\n\treturn true\n\n}\n<commit_msg>Fix detection of OpenShift<commit_after>package util\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\/config\"\n\n\troutev1 \"github.com\/openshift\/client-go\/route\/clientset\/versioned\/typed\/route\/v1\"\n\tlogf \"sigs.k8s.io\/controller-runtime\/pkg\/runtime\/log\"\n)\n\nvar (\n\topenshift *bool\n\tlog       = logf.Log.WithName(\"util\")\n)\n\nfunc IsOpenshift() bool {\n\tif openshift == nil {\n\t\tb := detectOpenshift()\n\t\topenshift = &b\n\t}\n\treturn *openshift\n}\n\nfunc detectOpenshift() bool {\n\n\tlog.Info(\"Detect if openshift is running\")\n\n\tvalue, ok := os.LookupEnv(\"ENMASSE_OPENSHIFT\")\n\tif ok {\n\t\tlog.Info(\"Set by env-var 'ENMASSE_OPENSHIFT': \" + value)\n\t\treturn strings.ToLower(value) == \"true\"\n\t}\n\n\t\/\/ try to\n\n\tcfg, err := config.GetConfig()\n\tif err != nil {\n\t\tlog.Error(err, \"Error getting config: %v\")\n\t\treturn false\n\t}\n\n\trouteClient, err := routev1.NewForConfig(cfg)\n\tif err != nil {\n\t\tlog.Error(err, \"Failed to get routeClient\")\n\t\treturn false\n\t}\n\n\tbody, err := routeClient.RESTClient().Get().DoRaw()\n\n\tlog.Info(fmt.Sprintf(\"Request error: %v\", err))\n\tlog.V(2).Info(fmt.Sprintf(\"Body: %v\", string(body)))\n\n\treturn err == nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cl11\n\nimport (\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\ntype Image struct {\n\tid clw.Mem\n\n\tFormat ImageFormat\n}\n\ntype (\n\tChannelOrder clw.ChannelOrder\n\tChannelType  clw.ChannelType\n)\n\ntype ImageFormat struct {\n\tChannelOrder ChannelOrder\n\tChannelType  ChannelType\n}\n\nconst (\n\tR         = ChannelOrder(clw.R)\n\tA         = ChannelOrder(clw.A)\n\tRG        = ChannelOrder(clw.RG)\n\tRA        = ChannelOrder(clw.RA)\n\tRGB       = ChannelOrder(clw.RGB)\n\tRGBA      = ChannelOrder(clw.RGBA)\n\tBGRA      = ChannelOrder(clw.BGRA)\n\tARGB      = ChannelOrder(clw.ARGB)\n\tIntensity = ChannelOrder(clw.Intensity)\n\tLuminance = ChannelOrder(clw.Luminance)\n\tRx        = ChannelOrder(clw.Rx)\n\tRGx       = ChannelOrder(clw.RGx)\n\tRGBx      = ChannelOrder(clw.RGBx)\n)\n\nconst (\n\tSnormInt8      = ChannelType(clw.SnormInt8)\n\tSnormInt16     = ChannelType(clw.SnormInt16)\n\tUnormInt8      = ChannelType(clw.UnormInt8)\n\tUnormInt16     = ChannelType(clw.UnormInt16)\n\tUnormShort565  = ChannelType(clw.UnormShort565)\n\tUnormShort555  = ChannelType(clw.UnormShort555)\n\tUnormInt101010 = ChannelType(clw.UnormInt101010)\n\tSignedInt8     = ChannelType(clw.SignedInt8)\n\tSignedInt16    = ChannelType(clw.SignedInt16)\n\tSignedInt32    = ChannelType(clw.SignedInt32)\n\tUnsignedInt8   = ChannelType(clw.UnsignedInt8)\n\tUnsignedInt16  = ChannelType(clw.UnsignedInt16)\n\tUnsignedInt32  = ChannelType(clw.UnsignedInt32)\n\tHalfFloat      = ChannelType(clw.HalfFloat)\n\tFloat          = ChannelType(clw.Float)\n)\n\n\/\/ Get supported image formats.\n\nfunc (c *Context) CreateImage2D(flags MemFlags, fmt ImageFormat, width, height, pitch int,\n\tsrc interface{}) (*Image, error) {\n\n\tmem, err := clw.CreateImage2D(c.id, clw.MemFlags(flags), clw.ImageFormat{clw.ChannelOrder(fmt.ChannelOrder),\n\t\tclw.ChannelType(fmt.ChannelType)}, clw.Size(width), clw.Size(height), clw.Size(pitch), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Image{id: mem, Format: fmt}, nil\n}\n<commit_msg>Adjusting to changes in the wrapper's image format type.<commit_after>package cl11\n\nimport (\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\ntype Image struct {\n\tid clw.Mem\n\n\tFormat ImageFormat\n}\n\ntype (\n\tChannelOrder clw.ChannelOrder\n\tChannelType  clw.ChannelType\n)\n\ntype ImageFormat struct {\n\tChannelOrder ChannelOrder\n\tChannelType  ChannelType\n}\n\nconst (\n\tR         = ChannelOrder(clw.R)\n\tA         = ChannelOrder(clw.A)\n\tRG        = ChannelOrder(clw.RG)\n\tRA        = ChannelOrder(clw.RA)\n\tRGB       = ChannelOrder(clw.RGB)\n\tRGBA      = ChannelOrder(clw.RGBA)\n\tBGRA      = ChannelOrder(clw.BGRA)\n\tARGB      = ChannelOrder(clw.ARGB)\n\tIntensity = ChannelOrder(clw.Intensity)\n\tLuminance = ChannelOrder(clw.Luminance)\n\tRx        = ChannelOrder(clw.Rx)\n\tRGx       = ChannelOrder(clw.RGx)\n\tRGBx      = ChannelOrder(clw.RGBx)\n)\n\nconst (\n\tSnormInt8      = ChannelType(clw.SnormInt8)\n\tSnormInt16     = ChannelType(clw.SnormInt16)\n\tUnormInt8      = ChannelType(clw.UnormInt8)\n\tUnormInt16     = ChannelType(clw.UnormInt16)\n\tUnormShort565  = ChannelType(clw.UnormShort565)\n\tUnormShort555  = ChannelType(clw.UnormShort555)\n\tUnormInt101010 = ChannelType(clw.UnormInt101010)\n\tSignedInt8     = ChannelType(clw.SignedInt8)\n\tSignedInt16    = ChannelType(clw.SignedInt16)\n\tSignedInt32    = ChannelType(clw.SignedInt32)\n\tUnsignedInt8   = ChannelType(clw.UnsignedInt8)\n\tUnsignedInt16  = ChannelType(clw.UnsignedInt16)\n\tUnsignedInt32  = ChannelType(clw.UnsignedInt32)\n\tHalfFloat      = ChannelType(clw.HalfFloat)\n\tFloat          = ChannelType(clw.Float)\n)\n\n\/\/ Get supported image formats.\n\nfunc (c *Context) CreateImage2D(flags MemFlags, fmt ImageFormat, width, height, pitch int,\n\tsrc interface{}) (*Image, error) {\n\n\tfmt2 := clw.CreateImageFormat(clw.ChannelOrder(fmt.ChannelOrder), clw.ChannelType(fmt.ChannelType))\n\n\tmem, err := clw.CreateImage2D(c.id, clw.MemFlags(flags), fmt2, clw.Size(width), clw.Size(height), clw.Size(pitch),\n\t\tnil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Image{id: mem, Format: fmt}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package webhook\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/open-policy-agent\/gatekeeper\/apis\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/apis\/config\/v1alpha1\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/controller\/config\/process\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/keys\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/util\"\n\tadmissionv1 \"k8s.io\/api\/admission\/v1\"\n\tauthenticationv1 \"k8s.io\/api\/authentication\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\tk8sruntime \"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/serializer\"\n\t\"k8s.io\/client-go\/tools\/record\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\tlogf \"sigs.k8s.io\/controller-runtime\/pkg\/log\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/webhook\/admission\"\n)\n\ntype requestResponse string\n\nconst (\n\tsuccessResponse requestResponse = \"success\"\n\terrorResponse   requestResponse = \"error\"\n\tdenyResponse    requestResponse = \"deny\"\n\tallowResponse   requestResponse = \"allow\"\n\tunknownResponse requestResponse = \"unknown\"\n\tskipResponse    requestResponse = \"skip\"\n)\n\nvar log = logf.Log.WithName(\"webhook\")\n\nvar (\n\t\/\/ VwhName is the metadata.name of the Gatekeeper ValidatingWebhookConfiguration.\n\tVwhName = \"gatekeeper-validating-webhook-configuration\"\n\t\/\/ MwhName is the metadata.name of the Gatekeeper MutatingWebhookConfiguration.\n\tMwhName = \"gatekeeper-mutating-webhook-configuration\"\n)\n\nconst (\n\tserviceAccountName = \"gatekeeper-admin\"\n\tmutationsGroup     = \"mutations.gatekeeper.sh\"\n\tnamespaceKind      = \"Namespace\"\n)\n\nvar (\n\truntimeScheme                      = k8sruntime.NewScheme()\n\tcodecs                             = serializer.NewCodecFactory(runtimeScheme)\n\tdeserializer                       = codecs.UniversalDeserializer()\n\tdisableEnforcementActionValidation = flag.Bool(\"disable-enforcementaction-validation\", false, \"disable validation of the enforcementAction field of a constraint\")\n\tlogDenies                          = flag.Bool(\"log-denies\", false, \"log detailed info on each deny\")\n\temitAdmissionEvents                = flag.Bool(\"emit-admission-events\", false, \"(alpha) emit Kubernetes events in gatekeeper namespace for each admission violation\")\n\ttlsMinVersion                      = flag.String(\"tls-min-version\", \"1.2\", \"minimum version of TLS supported\")\n\tserviceaccount                     = fmt.Sprintf(\"system:serviceaccount:%s:%s\", util.GetNamespace(), serviceAccountName)\n\t\/\/ webhookName is deprecated, set this on the manifest YAML if needed\".\n)\n\nfunc init() {\n\t_ = apis.AddToScheme(runtimeScheme)\n}\n\nfunc isGkServiceAccount(user authenticationv1.UserInfo) bool {\n\treturn user.Username == serviceaccount\n}\n\ntype webhookHandler struct {\n\tclient   client.Client\n\treporter StatsReporter\n\t\/\/ reader that will be configured to use the API server\n\t\/\/ obtained from mgr.GetAPIReader()\n\treader client.Reader\n\t\/\/ for testing\n\tinjectedConfig  *v1alpha1.Config\n\tprocessExcluder *process.Excluder\n\teventRecorder   record.EventRecorder\n\tgkNamespace     string\n}\n\nfunc (h *webhookHandler) getConfig(ctx context.Context) (*v1alpha1.Config, error) {\n\tif h.injectedConfig != nil {\n\t\treturn h.injectedConfig, nil\n\t}\n\tif h.client == nil {\n\t\treturn nil, errors.New(\"no client available to retrieve validation config\")\n\t}\n\tcfg := &v1alpha1.Config{}\n\treturn cfg, h.client.Get(ctx, keys.Config, cfg)\n}\n\n\/\/ isGatekeeperResource returns true if the request relates to a gatekeeper resource.\nfunc (h *webhookHandler) isGatekeeperResource(req *admission.Request) bool {\n\tif req.AdmissionRequest.Kind.Group == \"templates.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == \"constraints.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == mutationsGroup ||\n\t\treq.AdmissionRequest.Kind.Group == \"config.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == \"status.gatekeeper.sh\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (h *webhookHandler) tracingLevel(ctx context.Context, req *admission.Request) (bool, bool) {\n\tcfg, _ := h.getConfig(ctx)\n\ttraceEnabled := false\n\tdump := false\n\tfor _, trace := range cfg.Spec.Validation.Traces {\n\t\tif trace.User != req.AdmissionRequest.UserInfo.Username {\n\t\t\tcontinue\n\t\t}\n\t\tgvk := v1alpha1.GVK{\n\t\t\tGroup:   req.AdmissionRequest.Kind.Group,\n\t\t\tVersion: req.AdmissionRequest.Kind.Version,\n\t\t\tKind:    req.AdmissionRequest.Kind.Kind,\n\t\t}\n\t\tif gvk == trace.Kind {\n\t\t\ttraceEnabled = true\n\t\t\tif strings.EqualFold(trace.Dump, \"All\") {\n\t\t\t\tdump = true\n\t\t\t}\n\t\t}\n\t}\n\treturn traceEnabled, dump\n}\n\nfunc (h *webhookHandler) skipExcludedNamespace(req *admissionv1.AdmissionRequest, excludedProcess process.Process) (bool, error) {\n\tobj := &unstructured.Unstructured{}\n\tif _, _, err := deserializer.Decode(req.Object.Raw, nil, obj); err != nil {\n\t\treturn false, err\n\t}\n\n\tisNamespaceExcluded, err := h.processExcluder.IsNamespaceExcluded(excludedProcess, obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn isNamespaceExcluded, err\n}\n<commit_msg>update default min TLS to v1.3 (#1866)<commit_after>package webhook\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/open-policy-agent\/gatekeeper\/apis\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/apis\/config\/v1alpha1\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/controller\/config\/process\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/keys\"\n\t\"github.com\/open-policy-agent\/gatekeeper\/pkg\/util\"\n\tadmissionv1 \"k8s.io\/api\/admission\/v1\"\n\tauthenticationv1 \"k8s.io\/api\/authentication\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\tk8sruntime \"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/serializer\"\n\t\"k8s.io\/client-go\/tools\/record\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\tlogf \"sigs.k8s.io\/controller-runtime\/pkg\/log\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/webhook\/admission\"\n)\n\ntype requestResponse string\n\nconst (\n\tsuccessResponse requestResponse = \"success\"\n\terrorResponse   requestResponse = \"error\"\n\tdenyResponse    requestResponse = \"deny\"\n\tallowResponse   requestResponse = \"allow\"\n\tunknownResponse requestResponse = \"unknown\"\n\tskipResponse    requestResponse = \"skip\"\n)\n\nvar log = logf.Log.WithName(\"webhook\")\n\nvar (\n\t\/\/ VwhName is the metadata.name of the Gatekeeper ValidatingWebhookConfiguration.\n\tVwhName = \"gatekeeper-validating-webhook-configuration\"\n\t\/\/ MwhName is the metadata.name of the Gatekeeper MutatingWebhookConfiguration.\n\tMwhName = \"gatekeeper-mutating-webhook-configuration\"\n)\n\nconst (\n\tserviceAccountName = \"gatekeeper-admin\"\n\tmutationsGroup     = \"mutations.gatekeeper.sh\"\n\tnamespaceKind      = \"Namespace\"\n)\n\nvar (\n\truntimeScheme                      = k8sruntime.NewScheme()\n\tcodecs                             = serializer.NewCodecFactory(runtimeScheme)\n\tdeserializer                       = codecs.UniversalDeserializer()\n\tdisableEnforcementActionValidation = flag.Bool(\"disable-enforcementaction-validation\", false, \"disable validation of the enforcementAction field of a constraint\")\n\tlogDenies                          = flag.Bool(\"log-denies\", false, \"log detailed info on each deny\")\n\temitAdmissionEvents                = flag.Bool(\"emit-admission-events\", false, \"(alpha) emit Kubernetes events in gatekeeper namespace for each admission violation\")\n\ttlsMinVersion                      = flag.String(\"tls-min-version\", \"1.3\", \"minimum version of TLS supported\")\n\tserviceaccount                     = fmt.Sprintf(\"system:serviceaccount:%s:%s\", util.GetNamespace(), serviceAccountName)\n\t\/\/ webhookName is deprecated, set this on the manifest YAML if needed\".\n)\n\nfunc init() {\n\t_ = apis.AddToScheme(runtimeScheme)\n}\n\nfunc isGkServiceAccount(user authenticationv1.UserInfo) bool {\n\treturn user.Username == serviceaccount\n}\n\ntype webhookHandler struct {\n\tclient   client.Client\n\treporter StatsReporter\n\t\/\/ reader that will be configured to use the API server\n\t\/\/ obtained from mgr.GetAPIReader()\n\treader client.Reader\n\t\/\/ for testing\n\tinjectedConfig  *v1alpha1.Config\n\tprocessExcluder *process.Excluder\n\teventRecorder   record.EventRecorder\n\tgkNamespace     string\n}\n\nfunc (h *webhookHandler) getConfig(ctx context.Context) (*v1alpha1.Config, error) {\n\tif h.injectedConfig != nil {\n\t\treturn h.injectedConfig, nil\n\t}\n\tif h.client == nil {\n\t\treturn nil, errors.New(\"no client available to retrieve validation config\")\n\t}\n\tcfg := &v1alpha1.Config{}\n\treturn cfg, h.client.Get(ctx, keys.Config, cfg)\n}\n\n\/\/ isGatekeeperResource returns true if the request relates to a gatekeeper resource.\nfunc (h *webhookHandler) isGatekeeperResource(req *admission.Request) bool {\n\tif req.AdmissionRequest.Kind.Group == \"templates.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == \"constraints.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == mutationsGroup ||\n\t\treq.AdmissionRequest.Kind.Group == \"config.gatekeeper.sh\" ||\n\t\treq.AdmissionRequest.Kind.Group == \"status.gatekeeper.sh\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (h *webhookHandler) tracingLevel(ctx context.Context, req *admission.Request) (bool, bool) {\n\tcfg, _ := h.getConfig(ctx)\n\ttraceEnabled := false\n\tdump := false\n\tfor _, trace := range cfg.Spec.Validation.Traces {\n\t\tif trace.User != req.AdmissionRequest.UserInfo.Username {\n\t\t\tcontinue\n\t\t}\n\t\tgvk := v1alpha1.GVK{\n\t\t\tGroup:   req.AdmissionRequest.Kind.Group,\n\t\t\tVersion: req.AdmissionRequest.Kind.Version,\n\t\t\tKind:    req.AdmissionRequest.Kind.Kind,\n\t\t}\n\t\tif gvk == trace.Kind {\n\t\t\ttraceEnabled = true\n\t\t\tif strings.EqualFold(trace.Dump, \"All\") {\n\t\t\t\tdump = true\n\t\t\t}\n\t\t}\n\t}\n\treturn traceEnabled, dump\n}\n\nfunc (h *webhookHandler) skipExcludedNamespace(req *admissionv1.AdmissionRequest, excludedProcess process.Process) (bool, error) {\n\tobj := &unstructured.Unstructured{}\n\tif _, _, err := deserializer.Decode(req.Object.Raw, nil, obj); err != nil {\n\t\treturn false, err\n\t}\n\n\tisNamespaceExcluded, err := h.processExcluder.IsNamespaceExcluded(excludedProcess, obj)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn isNamespaceExcluded, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package kvite is a simple embedded K\/V store backed by SQLite\npackage kvite\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t_ \"github.com\/mattn\/go-sqlite3\" \/\/import sqlite3 for driver\n)\n\ntype (\n\t\/\/ DB is a wrapper around the underlying SQLite database.\n\tDB struct {\n\t\tdb           *sql.DB\n\t\ttable        string\n\t\tputQuery     string\n\t\tdeleteQuery  string\n\t\tgetQuery     string\n\t\tforeachQuery string\n\t\tbucketsQuery string\n\t}\n\n\t\/\/ Tx wraps most interactions with the datastore.\n\tTx struct {\n\t\tdb      *DB\n\t\ttx      *sql.Tx\n\t\tmanaged bool\n\t}\n\n\t\/\/Bucket represents a collection of key\/value pairs inside the database.\n\tBucket struct {\n\t\tname string\n\t\ttx   *Tx\n\t}\n)\n\n\/\/ Open opens a KVite datastore. The returned DB is safe for concurrent use by multiple goroutines.\n\/\/ It is rarely necessary to close a DB.\nfunc Open(filename, table string) (*DB, error) {\n\tdb, err := sql.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif table == \"\" {\n\t\ttable = \"kvite\"\n\t}\n\n\ttx, err := db.Begin()\n\tdefer tx.Rollback()\n\tquery := fmt.Sprintf(\"create TABLE '%s' (key text not null, bucket text not null, value blob not null)\", table)\n\tif _, err := tx.Exec(query); err != nil {\n\t\treturn nil, err\n\t}\n\tquery = fmt.Sprintf(\"create INDEX IF NOT EXISTS '%s_kvite_index' ON '%s' (key, bucket)\", table, table)\n\tif _, err := tx.Exec(query); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DB{\n\t\tdb:           db,\n\t\ttable:        table,\n\t\tgetQuery:     fmt.Sprintf(\"SELECT value FROM '%s' WHERE key = ? and bucket = ?\", table),\n\t\tdeleteQuery:  fmt.Sprintf(\"DELETE FROM '%s' WHERE key = ? AND bucket = ?\", table),\n\t\tputQuery:     fmt.Sprintf(\"INSERT OR REPLACE INTO '%s' (key, value, bucket) VALUES (?, ?, ?)\", table),\n\t\tforeachQuery: fmt.Sprintf(\"SELECT key, value FROM '%s' WHERE bucket = ?\", table),\n\t\tbucketsQuery: fmt.Sprintf(\"SELECT DISTINCT bucket from '%s'\", table),\n\t}, nil\n}\n\n\/\/ Close closes the database, releasing any open resources.\n\/\/ It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.\nfunc (db *DB) Close() error {\n\treturn db.db.Close()\n}\n\n\/\/ Begin starts a transaction.\nfunc (db *DB) Begin() (*Tx, error) {\n\ttx, err := db.db.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tx{\n\t\tdb: db,\n\t\ttx: tx,\n\t}\n\treturn t, nil\n\n}\n\n\/\/ Buckets returns all the buckets\nfunc (db *DB) Buckets() ([]string, error) {\n\trows, err := db.db.Query(db.bucketsQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuckets := make([]string, 0, 32)\n\tfor rows.Next() {\n\t\tvar name string\n\t\tif err := rows.Scan(&name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuckets = append(buckets, name)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buckets, nil\n}\n\n\/\/ Transaction executes a function within the context of a  managed transaction.\n\/\/ If no error is returned from the function then the transaction is committed.\n\/\/ If an error is returned then the entire transaction is rolled back.\n\/\/ Rollback and Commit cannot be used inside of the function\nfunc (db *DB) Transaction(fn func(*Tx) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Make sure the transaction rolls back in the event of a panic.\n\tdefer func() {\n\t\tif tx.db != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\ttx.managed = true\n\terr = fn(tx)\n\ttx.managed = false\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}\n\n\/\/ Commit commits the transaction.\nfunc (tx *Tx) Commit() error {\n\tif tx.managed {\n\t\treturn errors.New(\"managed tx commit not allowed\")\n\t}\n\tif tx.db == nil {\n\t\t\/\/ should we return an error here?\n\t\treturn nil\n\t}\n\n\terr := tx.tx.Commit()\n\ttx.db = nil\n\treturn err\n}\n\n\/\/ Rollback aborts the transaction.\nfunc (tx *Tx) Rollback() error {\n\tif tx.managed {\n\t\treturn errors.New(\"managed tx commit not allowed\")\n\t}\n\treturn tx.tx.Rollback()\n}\n\nfunc (tx *Tx) newBucket(name string) *Bucket {\n\treturn &Bucket{\n\t\ttx:   tx,\n\t\tname: name,\n\t}\n}\n\n\/\/ Bucket gets a bucket by name.  Buckets can be created on the fly and do not \"exist\" until they have keys.\nfunc (tx *Tx) Bucket(name string) (*Bucket, error) {\n\treturn tx.newBucket(name), nil\n}\n\n\/\/ CreateBucket is provided for compatibility. It just calls Bucket.\nfunc (tx *Tx) CreateBucket(name string) (*Bucket, error) {\n\treturn tx.Bucket(name)\n\n}\n\n\/\/ CreateBucketIfNotExists is provided for compatibility. It just calls Bucket.\nfunc (tx *Tx) CreateBucketIfNotExists(name string) (*Bucket, error) {\n\treturn tx.Bucket(name)\n}\n\n\/\/ Put sets the value for a key in the bucket. If the key exists, then its previous value will be overwritten.\nfunc (b *Bucket) Put(key string, value []byte) error {\n\t_, err := b.tx.tx.Exec(b.tx.db.putQuery, key, value, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Delete removes a key from the bucket. If the key does not exist then nothing is done and a nil error is returned.\nfunc (b *Bucket) Delete(key string) error {\n\t_, err := b.tx.tx.Exec(b.tx.db.deleteQuery, key, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Get retrieves the value for a key in the bucket. Returns a nil value if the key does not exist\nfunc (b *Bucket) Get(key string) ([]byte, error) {\n\tvar value []byte\n\n\tif err := b.tx.tx.QueryRow(b.tx.db.getQuery, key, b.name).Scan(&value); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn value, nil\n}\n\n\/\/ForEach executes a function for each key\/value pair in a bucket. If the provided function returns an error then the iteration is stopped and the error is returned to the caller.\nfunc (b *Bucket) ForEach(fn func(k string, v []byte) error) error {\n\trows, err := b.tx.tx.Query(b.tx.db.foreachQuery, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor rows.Next() {\n\t\tvar key string\n\t\tvar value []byte\n\t\tif err := rows.Scan(&key, &value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := fn(key, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn rows.Err()\n}\n<commit_msg>if not exists<commit_after>\/\/ Package kvite is a simple embedded K\/V store backed by SQLite\npackage kvite\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t_ \"github.com\/mattn\/go-sqlite3\" \/\/import sqlite3 for driver\n)\n\ntype (\n\t\/\/ DB is a wrapper around the underlying SQLite database.\n\tDB struct {\n\t\tdb           *sql.DB\n\t\ttable        string\n\t\tputQuery     string\n\t\tdeleteQuery  string\n\t\tgetQuery     string\n\t\tforeachQuery string\n\t\tbucketsQuery string\n\t}\n\n\t\/\/ Tx wraps most interactions with the datastore.\n\tTx struct {\n\t\tdb      *DB\n\t\ttx      *sql.Tx\n\t\tmanaged bool\n\t}\n\n\t\/\/Bucket represents a collection of key\/value pairs inside the database.\n\tBucket struct {\n\t\tname string\n\t\ttx   *Tx\n\t}\n)\n\n\/\/ Open opens a KVite datastore. The returned DB is safe for concurrent use by multiple goroutines.\n\/\/ It is rarely necessary to close a DB.\nfunc Open(filename, table string) (*DB, error) {\n\tdb, err := sql.Open(\"sqlite3\", filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif table == \"\" {\n\t\ttable = \"kvite\"\n\t}\n\n\ttx, err := db.Begin()\n\tdefer tx.Rollback()\n\tquery := fmt.Sprintf(\"create TABLE IF NOT EXISTS '%s' (key text not null, bucket text not null, value blob not null)\", table)\n\tif _, err := tx.Exec(query); err != nil {\n\t\treturn nil, err\n\t}\n\tquery = fmt.Sprintf(\"create INDEX IF NOT EXISTS '%s_kvite_index' ON '%s' (key, bucket)\", table, table)\n\tif _, err := tx.Exec(query); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &DB{\n\t\tdb:           db,\n\t\ttable:        table,\n\t\tgetQuery:     fmt.Sprintf(\"SELECT value FROM '%s' WHERE key = ? and bucket = ?\", table),\n\t\tdeleteQuery:  fmt.Sprintf(\"DELETE FROM '%s' WHERE key = ? AND bucket = ?\", table),\n\t\tputQuery:     fmt.Sprintf(\"INSERT OR REPLACE INTO '%s' (key, value, bucket) VALUES (?, ?, ?)\", table),\n\t\tforeachQuery: fmt.Sprintf(\"SELECT key, value FROM '%s' WHERE bucket = ?\", table),\n\t\tbucketsQuery: fmt.Sprintf(\"SELECT DISTINCT bucket from '%s'\", table),\n\t}, nil\n}\n\n\/\/ Close closes the database, releasing any open resources.\n\/\/ It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many goroutines.\nfunc (db *DB) Close() error {\n\treturn db.db.Close()\n}\n\n\/\/ Begin starts a transaction.\nfunc (db *DB) Begin() (*Tx, error) {\n\ttx, err := db.db.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tt := &Tx{\n\t\tdb: db,\n\t\ttx: tx,\n\t}\n\treturn t, nil\n\n}\n\n\/\/ Buckets returns all the buckets\nfunc (db *DB) Buckets() ([]string, error) {\n\trows, err := db.db.Query(db.bucketsQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbuckets := make([]string, 0, 32)\n\tfor rows.Next() {\n\t\tvar name string\n\t\tif err := rows.Scan(&name); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuckets = append(buckets, name)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buckets, nil\n}\n\n\/\/ Transaction executes a function within the context of a  managed transaction.\n\/\/ If no error is returned from the function then the transaction is committed.\n\/\/ If an error is returned then the entire transaction is rolled back.\n\/\/ Rollback and Commit cannot be used inside of the function\nfunc (db *DB) Transaction(fn func(*Tx) error) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Make sure the transaction rolls back in the event of a panic.\n\tdefer func() {\n\t\tif tx.db != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\ttx.managed = true\n\terr = fn(tx)\n\ttx.managed = false\n\tif err != nil {\n\t\t_ = tx.Rollback()\n\t\treturn err\n\t}\n\n\treturn tx.Commit()\n}\n\n\/\/ Commit commits the transaction.\nfunc (tx *Tx) Commit() error {\n\tif tx.managed {\n\t\treturn errors.New(\"managed tx commit not allowed\")\n\t}\n\tif tx.db == nil {\n\t\t\/\/ should we return an error here?\n\t\treturn nil\n\t}\n\n\terr := tx.tx.Commit()\n\ttx.db = nil\n\treturn err\n}\n\n\/\/ Rollback aborts the transaction.\nfunc (tx *Tx) Rollback() error {\n\tif tx.managed {\n\t\treturn errors.New(\"managed tx commit not allowed\")\n\t}\n\treturn tx.tx.Rollback()\n}\n\nfunc (tx *Tx) newBucket(name string) *Bucket {\n\treturn &Bucket{\n\t\ttx:   tx,\n\t\tname: name,\n\t}\n}\n\n\/\/ Bucket gets a bucket by name.  Buckets can be created on the fly and do not \"exist\" until they have keys.\nfunc (tx *Tx) Bucket(name string) (*Bucket, error) {\n\treturn tx.newBucket(name), nil\n}\n\n\/\/ CreateBucket is provided for compatibility. It just calls Bucket.\nfunc (tx *Tx) CreateBucket(name string) (*Bucket, error) {\n\treturn tx.Bucket(name)\n\n}\n\n\/\/ CreateBucketIfNotExists is provided for compatibility. It just calls Bucket.\nfunc (tx *Tx) CreateBucketIfNotExists(name string) (*Bucket, error) {\n\treturn tx.Bucket(name)\n}\n\n\/\/ Put sets the value for a key in the bucket. If the key exists, then its previous value will be overwritten.\nfunc (b *Bucket) Put(key string, value []byte) error {\n\t_, err := b.tx.tx.Exec(b.tx.db.putQuery, key, value, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Delete removes a key from the bucket. If the key does not exist then nothing is done and a nil error is returned.\nfunc (b *Bucket) Delete(key string) error {\n\t_, err := b.tx.tx.Exec(b.tx.db.deleteQuery, key, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Get retrieves the value for a key in the bucket. Returns a nil value if the key does not exist\nfunc (b *Bucket) Get(key string) ([]byte, error) {\n\tvar value []byte\n\n\tif err := b.tx.tx.QueryRow(b.tx.db.getQuery, key, b.name).Scan(&value); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn value, nil\n}\n\n\/\/ForEach executes a function for each key\/value pair in a bucket. If the provided function returns an error then the iteration is stopped and the error is returned to the caller.\nfunc (b *Bucket) ForEach(fn func(k string, v []byte) error) error {\n\trows, err := b.tx.tx.Query(b.tx.db.foreachQuery, b.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor rows.Next() {\n\t\tvar key string\n\t\tvar value []byte\n\t\tif err := rows.Scan(&key, &value); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := fn(key, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn rows.Err()\n}\n<|endoftext|>"}
{"text":"<commit_before>package migrate\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/engine\/api\/application\"\n\t\"github.com\/ovh\/cds\/engine\/api\/cache\"\n\t\"github.com\/ovh\/cds\/engine\/api\/environment\"\n\t\"github.com\/ovh\/cds\/engine\/api\/project\"\n\t\"github.com\/ovh\/cds\/sdk\"\n\t\"github.com\/ovh\/cds\/sdk\/log\"\n)\n\nfunc KeyMigration(store cache.Store, DBFunc func() *gorp.DbMap, u *sdk.User) {\n\tdb := DBFunc()\n\n\t\/\/ Project migration\n\tids, errQ := loadProjectIDs(db)\n\tif errQ != nil {\n\t\treturn\n\t}\n\n\tfor _, id := range ids {\n\t\tmigrateProject(db, id, store, u)\n\t}\n\n\t\/\/ Application migration\n\tappIds, errA := loadApplicationIDs(db)\n\tif errA != nil {\n\t\treturn\n\t}\n\tfor _, id := range appIds {\n\t\tmigrateApplication(db, id, store, u)\n\t}\n\n\t\/\/ Environment migration\n\tenvIds, errE := loadEnvironmentIDs(db)\n\tif errE != nil {\n\t\treturn\n\t}\n\tfor _, id := range envIds {\n\t\tmigrateEnvironment(db, id)\n\t}\n}\nfunc loadProjectIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT project_id from project_variable where var_type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadProjectIDs> Cannot load project ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadProjectIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateProject(db *gorp.DbMap, projID int64, store cache.Store, u *sdk.User) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateProject> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\tdefer tx.Rollback()\n\n\tproj, errP := project.LoadByID(tx, store, projID, u, project.LoadOptions.WithLockNoWait, project.LoadOptions.WithVariablesWithClearPassword, project.LoadOptions.WithKeys)\n\tif errP != nil {\n\t\tlog.Warning(\"migrateProject> Cannot get project %d: %s\", projID, errP)\n\t\treturn errP\n\t}\n\n\t\/\/ find private key\n\tkeys := findKeyPair(proj.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"proj-%s\", k.private.Name)\n\t\tfound := false\n\t\tfor _, k := range proj.Keys {\n\t\t\tif k.Name == keyName {\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\tprojectKey := sdk.ProjectKey{\n\t\t\t\tProjectID: projID,\n\t\t\t\tBuiltin:   false,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeySSHParameter,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := project.InsertKey(tx, &projectKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateProject> Cannot insert project key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tx.Commit()\n}\n\nfunc loadApplicationIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT application_id from application_variable where var_type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadApplicationIDs> Cannot load application ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadApplicationIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateApplication(db *gorp.DbMap, appID int64, store cache.Store, u *sdk.User) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateApplication> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\n\tapp, errA := application.LoadAndLockByID(tx, store, appID, u, application.LoadOptions.WithVariablesWithClearPassword, application.LoadOptions.WithKeys)\n\tif errA != nil {\n\t\tlog.Warning(\"migrateApplication> Cannot load application %d: %s\", appID, errA)\n\t\treturn errA\n\t}\n\tkeys := findKeyPair(app.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"app-%s\", k.private.Name)\n\n\t\tfound := false\n\t\tfor _, k := range app.Keys {\n\t\t\tif k.Name == keyName {\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\tappKey := sdk.ApplicationKey{\n\t\t\t\tApplicationID: appID,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeySSHParameter,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := application.InsertKey(tx, &appKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateApplication> Cannot insert application key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\treturn tx.Commit()\n}\n\nfunc loadEnvironmentIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT environment_id from environment_variable where type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadEnvironmentIDs> Cannot load environment ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadEnvironmentIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateEnvironment(db *gorp.DbMap, envID int64) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\n\tif errL := environment.LockByID(tx, envID); errL != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot lock environment %d: %s\", envID, errL)\n\t\treturn errL\n\t}\n\tenv, errR := environment.LoadEnvironmentByID(tx, envID)\n\tif errR != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot load environment %d: %s\", envID, errR)\n\t\treturn errR\n\t}\n\tenvVars, errV := environment.GetAllVariableByID(tx, envID, environment.WithClearPassword())\n\tif errV != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot load clear password\")\n\t}\n\tenv.Variable = envVars\n\tkeys := findKeyPair(env.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"env-%s\", k.private.Name)\n\n\t\tfound := false\n\t\tfor _, k := range env.Keys {\n\t\t\tif k.Name == keyName {\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\tenvKey := sdk.EnvironmentKey{\n\t\t\t\tEnvironmentID: envID,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeySSHParameter,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := environment.InsertKey(tx, &envKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateEnvironment> Cannot insert environment key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\treturn tx.Commit()\n}\n\ntype keyPair struct {\n\tprivate sdk.Variable\n\tpublic  sdk.Variable\n}\n\nfunc findKeyPair(vs []sdk.Variable) []keyPair {\n\tkps := []keyPair{}\n\tfor _, v := range vs {\n\t\tif v.Type == sdk.KeyVariable {\n\t\t\tfor _, vp := range vs {\n\t\t\t\tif strings.HasPrefix(vp.Name, v.Name) && strings.HasSuffix(vp.Name, \".pub\") {\n\t\t\t\t\tkp := keyPair{\n\t\t\t\t\t\tprivate: v,\n\t\t\t\t\t\tpublic:  vp,\n\t\t\t\t\t}\n\t\t\t\t\tkps = append(kps, kp)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn kps\n}\n<commit_msg>fix(api): key type (#2311)<commit_after>package migrate\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/engine\/api\/application\"\n\t\"github.com\/ovh\/cds\/engine\/api\/cache\"\n\t\"github.com\/ovh\/cds\/engine\/api\/environment\"\n\t\"github.com\/ovh\/cds\/engine\/api\/project\"\n\t\"github.com\/ovh\/cds\/sdk\"\n\t\"github.com\/ovh\/cds\/sdk\/log\"\n)\n\nfunc KeyMigration(store cache.Store, DBFunc func() *gorp.DbMap, u *sdk.User) {\n\tdb := DBFunc()\n\n\t\/\/ Project migration\n\tids, errQ := loadProjectIDs(db)\n\tif errQ != nil {\n\t\treturn\n\t}\n\n\tfor _, id := range ids {\n\t\tmigrateProject(db, id, store, u)\n\t}\n\n\t\/\/ Application migration\n\tappIds, errA := loadApplicationIDs(db)\n\tif errA != nil {\n\t\treturn\n\t}\n\tfor _, id := range appIds {\n\t\tmigrateApplication(db, id, store, u)\n\t}\n\n\t\/\/ Environment migration\n\tenvIds, errE := loadEnvironmentIDs(db)\n\tif errE != nil {\n\t\treturn\n\t}\n\tfor _, id := range envIds {\n\t\tmigrateEnvironment(db, id)\n\t}\n}\nfunc loadProjectIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT project_id from project_variable where var_type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadProjectIDs> Cannot load project ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadProjectIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateProject(db *gorp.DbMap, projID int64, store cache.Store, u *sdk.User) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateProject> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\tdefer tx.Rollback()\n\n\tproj, errP := project.LoadByID(tx, store, projID, u, project.LoadOptions.WithLockNoWait, project.LoadOptions.WithVariablesWithClearPassword, project.LoadOptions.WithKeys)\n\tif errP != nil {\n\t\tlog.Warning(\"migrateProject> Cannot get project %d: %s\", projID, errP)\n\t\treturn errP\n\t}\n\n\t\/\/ find private key\n\tkeys := findKeyPair(proj.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"proj-%s\", k.private.Name)\n\t\tfound := false\n\t\tfor _, k := range proj.Keys {\n\t\t\tif k.Name == keyName {\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\tprojectKey := sdk.ProjectKey{\n\t\t\t\tProjectID: projID,\n\t\t\t\tBuiltin:   false,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeyTypeSSH,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := project.InsertKey(tx, &projectKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateProject> Cannot insert project key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tx.Commit()\n}\n\nfunc loadApplicationIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT application_id from application_variable where var_type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadApplicationIDs> Cannot load application ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadApplicationIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateApplication(db *gorp.DbMap, appID int64, store cache.Store, u *sdk.User) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateApplication> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\n\tapp, errA := application.LoadAndLockByID(tx, store, appID, u, application.LoadOptions.WithVariablesWithClearPassword, application.LoadOptions.WithKeys)\n\tif errA != nil {\n\t\tlog.Warning(\"migrateApplication> Cannot load application %d: %s\", appID, errA)\n\t\treturn errA\n\t}\n\tkeys := findKeyPair(app.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"app-%s\", k.private.Name)\n\n\t\tfound := false\n\t\tfor _, k := range app.Keys {\n\t\t\tif k.Name == keyName {\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\tappKey := sdk.ApplicationKey{\n\t\t\t\tApplicationID: appID,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeyTypeSSH,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := application.InsertKey(tx, &appKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateApplication> Cannot insert application key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\treturn tx.Commit()\n}\n\nfunc loadEnvironmentIDs(db gorp.SqlExecutor) ([]int64, error) {\n\tquery := `SELECT environment_id from environment_variable where type = 'key'`\n\trows, errQ := db.Query(query)\n\tif errQ != nil {\n\t\tlog.Warning(\"loadEnvironmentIDs> Cannot load environment ids: %s\", errQ)\n\t\treturn nil, errQ\n\t}\n\tvar ids []int64\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\tlog.Warning(\"loadEnvironmentIDs> Cannot key next id: %s\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\treturn ids, nil\n}\n\nfunc migrateEnvironment(db *gorp.DbMap, envID int64) error {\n\ttx, errT := db.Begin()\n\tif errT != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot start transaction: %s\", errT)\n\t\treturn errT\n\t}\n\n\tif errL := environment.LockByID(tx, envID); errL != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot lock environment %d: %s\", envID, errL)\n\t\treturn errL\n\t}\n\tenv, errR := environment.LoadEnvironmentByID(tx, envID)\n\tif errR != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot load environment %d: %s\", envID, errR)\n\t\treturn errR\n\t}\n\tenvVars, errV := environment.GetAllVariableByID(tx, envID, environment.WithClearPassword())\n\tif errV != nil {\n\t\tlog.Warning(\"migrateEnvironment> Cannot load clear password\")\n\t}\n\tenv.Variable = envVars\n\tkeys := findKeyPair(env.Variable)\n\tfor _, k := range keys {\n\t\tkeyName := fmt.Sprintf(\"env-%s\", k.private.Name)\n\n\t\tfound := false\n\t\tfor _, k := range env.Keys {\n\t\t\tif k.Name == keyName {\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\tenvKey := sdk.EnvironmentKey{\n\t\t\t\tEnvironmentID: envID,\n\t\t\t\tKey: sdk.Key{\n\t\t\t\t\tPublic:  k.public.Value,\n\t\t\t\t\tPrivate: k.private.Value,\n\t\t\t\t\tName:    keyName,\n\t\t\t\t\tType:    sdk.KeyTypeSSH,\n\t\t\t\t},\n\t\t\t}\n\t\t\tif errK := environment.InsertKey(tx, &envKey); errK != nil {\n\t\t\t\tlog.Warning(\"migrateEnvironment> Cannot insert environment key %s: %s\", k.private.Name, errK)\n\t\t\t\treturn errK\n\t\t\t}\n\t\t}\n\t}\n\treturn tx.Commit()\n}\n\ntype keyPair struct {\n\tprivate sdk.Variable\n\tpublic  sdk.Variable\n}\n\nfunc findKeyPair(vs []sdk.Variable) []keyPair {\n\tkps := []keyPair{}\n\tfor _, v := range vs {\n\t\tif v.Type == sdk.KeyVariable {\n\t\t\tfor _, vp := range vs {\n\t\t\t\tif strings.HasPrefix(vp.Name, v.Name) && strings.HasSuffix(vp.Name, \".pub\") {\n\t\t\t\t\tkp := keyPair{\n\t\t\t\t\t\tprivate: v,\n\t\t\t\t\t\tpublic:  vp,\n\t\t\t\t\t}\n\t\t\t\t\tkps = append(kps, kp)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn kps\n}\n<|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 zdns\n\nimport (\n\t\"math\/rand\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/* Each lookup module registers a single GlobalLookupFactory, which is\n * instantiated once.  This global factory is responsible for providing command\n * line arguments and performing any configuration that should only occur once.\n * For each thread in the worker pool, the framework calls\n * MakePerRoutineFactory(), which should return a second factory, which should\n * perform any \"per-thread\" initialization. Within each \"thread\", the framework\n * will then call MakeLookup() for each connection it will make, on which it\n * will call DoLookup().  While two layers of factories is a bit... obnoxious,\n * this allows each module to maintain global, per-thread, and per-connection\n * state.\n *\n * Each layer has access to one proceeding layer (e.g., RoutineLookupFactory\n * knows the GlobalLookupFactory, from which it was created. Therefore, modules\n * should refer to this configuration instead of copying all configuration\n * values for every connection. The Base structs implement these basic\n * pieces of functionality and should be inherited in most situations.\n *\/\n\n\/\/ one Lookup per IP\/name\/connection ==========================================\n\/\/\n\ntype Trace []interface{}\n\ntype Lookup interface {\n\tDoLookup(name, nameServer string) (interface{}, Trace, Status, error)\n}\n\ntype BaseLookup struct {\n}\n\nfunc (base *BaseLookup) DoLookup(name string, class uint16) (interface{}, Status, error) {\n\tlog.Fatal(\"Unimplemented DoLookup\")\n\treturn nil, STATUS_ERROR, nil\n}\n\n\/\/ one RoutineLookupFactory per goroutine =====================================\n\/\/\ntype RoutineLookupFactory interface {\n\tMakeLookup() (Lookup, error)\n}\n\n\/\/ one RoutineLookupFactory per execution =====================================\n\/\/\ntype GlobalLookupFactory interface {\n\t\/\/ TODO: somewhat deceivingly named. This captures the values of flags,\n\t\/\/ but doesn't actually set them.\n\tSetFlags(flags *pflag.FlagSet)\n\t\/\/ global initialization. Gets called once globally\n\t\/\/ This is called after command line flags have been parsed\n\tInitialize(conf *GlobalConf) error\n\tFinalize() error\n\t\/\/ We can't set variables on an interface, so write functions\n\t\/\/ that define any settings for the factory\n\tAllowStdIn() bool\n\t\/\/ Some modules have Zonefile inputs\n\tZonefileInput() bool\n\t\/\/ Help text for the CLI\n\tHelp() string\n\t\/\/ Return a single scanner which will scan a single host\n\tMakeRoutineFactory(int) (RoutineLookupFactory, error)\n\tRandomNameServer() string\n}\n\n\/\/ handle domain input\ntype InputHandler interface {\n\t\/\/ FeedChannel takes a channel to write domains to, the WaitGroup managing them, and if it's a zonefile input\n\tFeedChannel(in chan<- interface{}, wg *sync.WaitGroup) error\n}\n\n\/\/ handle output results\ntype OutputHandler interface {\n\t\/\/ takes a channel (results) to write the query results to, and the WaitGroup managing the handlers\n\tWriteResults(results <-chan string, wg *sync.WaitGroup) error\n}\n\ntype BaseGlobalLookupFactory struct {\n\tGlobalConf *GlobalConf\n}\n\nfunc (f *BaseGlobalLookupFactory) Initialize(c *GlobalConf) error {\n\tf.GlobalConf = c\n\treturn nil\n}\n\nfunc (f *BaseGlobalLookupFactory) Finalize() error {\n\treturn nil\n}\n\nfunc (s *BaseGlobalLookupFactory) SetFlags(f *pflag.FlagSet) {\n}\n\nfunc (s *BaseGlobalLookupFactory) Help() string {\n\treturn \"\"\n}\n\nfunc (f *BaseGlobalLookupFactory) RandomNameServer() string {\n\tif f.GlobalConf == nil {\n\t\tlog.Fatal(\"no global conf initialized\")\n\t}\n\tl := len(f.GlobalConf.NameServers)\n\tif l == 0 {\n\t\tlog.Fatal(\"No name servers specified\")\n\t}\n\treturn f.GlobalConf.NameServers[rand.Intn(l)]\n}\n\nfunc (f *BaseGlobalLookupFactory) RandomLocalAddr() net.IP {\n\tif f.GlobalConf == nil {\n\t\tlog.Fatal(\"no global conf initialized\")\n\t}\n\tl := len(f.GlobalConf.LocalAddrs)\n\tif l == 0 {\n\t\tlog.Fatal(\"No local addresses specified\")\n\t}\n\treturn f.GlobalConf.LocalAddrs[rand.Intn(l)]\n}\n\nfunc (s *BaseGlobalLookupFactory) AllowStdIn() bool {\n\treturn true\n}\n\nfunc (s *BaseGlobalLookupFactory) ZonefileInput() bool {\n\treturn false\n}\n\n\/\/ keep a mapping from name to factory\nvar lookups map[string]GlobalLookupFactory\n\n\/\/ keep a mapping from name to input handler\nvar inputHandlers map[string]InputHandler\n\n\/\/ keep a mapping from name to output handler\nvar outputHandlers map[string]OutputHandler\n\nfunc RegisterLookup(name string, s GlobalLookupFactory) {\n\tif lookups == nil {\n\t\tlookups = make(map[string]GlobalLookupFactory, 100)\n\t}\n\tlookups[name] = s\n}\n\nfunc ValidlookupsString() string {\n\tvalid := make([]string, len(lookups))\n\ti := 0\n\tfor k := range lookups {\n\t\tvalid[i] = k\n\t\ti++\n\t}\n\tsort.Strings(valid)\n\treturn strings.Join(valid, \", \")\n}\n\nfunc Validlookups() []string {\n\tvalid := make([]string, len(lookups))\n\ti := 0\n\tfor k := range lookups {\n\t\tvalid[i] = k\n\t\ti++\n\t}\n\tsort.Strings(valid)\n\treturn valid\n}\n\nfunc GetLookup(name string) GlobalLookupFactory {\n\tif factory, ok := lookups[name]; ok {\n\t\treturn factory\n\t}\n\treturn nil\n}\n<commit_msg>update docs<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 zdns\n\nimport (\n\t\"math\/rand\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/* Each lookup module registers a single GlobalLookupFactory, which is\n * instantiated once.  This global factory is responsible for providing command\n * line arguments and performing any configuration that should only occur once.\n * For each thread in the worker pool, the framework calls\n * MakePerRoutineFactory(), which should return a second factory, which should\n * perform any \"per-thread\" initialization. Within each \"thread\", the framework\n * will then call MakeLookup() for each connection it will make, on which it\n * will call DoLookup().  While two layers of factories is a bit... obnoxious,\n * this allows each module to maintain global, per-thread, and per-connection\n * state.\n *\n * Each layer has access to one proceeding layer (e.g., RoutineLookupFactory\n * knows the GlobalLookupFactory, from which it was created. Therefore, modules\n * should refer to this configuration instead of copying all configuration\n * values for every connection. The Base structs implement these basic\n * pieces of functionality and should be inherited in most situations.\n *\/\n\n\/\/ one Lookup per IP\/name\/connection ==========================================\n\/\/\n\ntype Trace []interface{}\n\ntype Lookup interface {\n\tDoLookup(name, nameServer string) (interface{}, Trace, Status, error)\n}\n\ntype BaseLookup struct {\n}\n\nfunc (base *BaseLookup) DoLookup(name string, class uint16) (interface{}, Status, error) {\n\tlog.Fatal(\"Unimplemented DoLookup\")\n\treturn nil, STATUS_ERROR, nil\n}\n\n\/\/ one RoutineLookupFactory per goroutine =====================================\n\/\/\ntype RoutineLookupFactory interface {\n\tMakeLookup() (Lookup, error)\n}\n\n\/\/ one RoutineLookupFactory per execution =====================================\n\/\/\ntype GlobalLookupFactory interface {\n\t\/\/ Capture the values of cobra\/viper flags and add them to the\n\t\/\/ global factory as appropriate.\n\tSetFlags(flags *pflag.FlagSet)\n\t\/\/ global initialization. Gets called once globally\n\t\/\/ This is called after command line flags have been parsed\n\tInitialize(conf *GlobalConf) error\n\tFinalize() error\n\t\/\/ We can't set variables on an interface, so write functions\n\t\/\/ that define any settings for the factory\n\tAllowStdIn() bool\n\t\/\/ Some modules have Zonefile inputs\n\tZonefileInput() bool\n\t\/\/ Help text for the CLI\n\tHelp() string\n\t\/\/ Return a single scanner which will scan a single host\n\tMakeRoutineFactory(int) (RoutineLookupFactory, error)\n\tRandomNameServer() string\n}\n\n\/\/ handle domain input\ntype InputHandler interface {\n\t\/\/ FeedChannel takes a channel to write domains to, the WaitGroup managing them, and if it's a zonefile input\n\tFeedChannel(in chan<- interface{}, wg *sync.WaitGroup) error\n}\n\n\/\/ handle output results\ntype OutputHandler interface {\n\t\/\/ takes a channel (results) to write the query results to, and the WaitGroup managing the handlers\n\tWriteResults(results <-chan string, wg *sync.WaitGroup) error\n}\n\ntype BaseGlobalLookupFactory struct {\n\tGlobalConf *GlobalConf\n}\n\nfunc (f *BaseGlobalLookupFactory) Initialize(c *GlobalConf) error {\n\tf.GlobalConf = c\n\treturn nil\n}\n\nfunc (f *BaseGlobalLookupFactory) Finalize() error {\n\treturn nil\n}\n\nfunc (s *BaseGlobalLookupFactory) SetFlags(f *pflag.FlagSet) {\n}\n\nfunc (s *BaseGlobalLookupFactory) Help() string {\n\treturn \"\"\n}\n\nfunc (f *BaseGlobalLookupFactory) RandomNameServer() string {\n\tif f.GlobalConf == nil {\n\t\tlog.Fatal(\"no global conf initialized\")\n\t}\n\tl := len(f.GlobalConf.NameServers)\n\tif l == 0 {\n\t\tlog.Fatal(\"No name servers specified\")\n\t}\n\treturn f.GlobalConf.NameServers[rand.Intn(l)]\n}\n\nfunc (f *BaseGlobalLookupFactory) RandomLocalAddr() net.IP {\n\tif f.GlobalConf == nil {\n\t\tlog.Fatal(\"no global conf initialized\")\n\t}\n\tl := len(f.GlobalConf.LocalAddrs)\n\tif l == 0 {\n\t\tlog.Fatal(\"No local addresses specified\")\n\t}\n\treturn f.GlobalConf.LocalAddrs[rand.Intn(l)]\n}\n\nfunc (s *BaseGlobalLookupFactory) AllowStdIn() bool {\n\treturn true\n}\n\nfunc (s *BaseGlobalLookupFactory) ZonefileInput() bool {\n\treturn false\n}\n\n\/\/ keep a mapping from name to factory\nvar lookups map[string]GlobalLookupFactory\n\n\/\/ keep a mapping from name to input handler\nvar inputHandlers map[string]InputHandler\n\n\/\/ keep a mapping from name to output handler\nvar outputHandlers map[string]OutputHandler\n\nfunc RegisterLookup(name string, s GlobalLookupFactory) {\n\tif lookups == nil {\n\t\tlookups = make(map[string]GlobalLookupFactory, 100)\n\t}\n\tlookups[name] = s\n}\n\nfunc ValidlookupsString() string {\n\tvalid := make([]string, len(lookups))\n\ti := 0\n\tfor k := range lookups {\n\t\tvalid[i] = k\n\t\ti++\n\t}\n\tsort.Strings(valid)\n\treturn strings.Join(valid, \", \")\n}\n\nfunc Validlookups() []string {\n\tvalid := make([]string, len(lookups))\n\ti := 0\n\tfor k := range lookups {\n\t\tvalid[i] = k\n\t\ti++\n\t}\n\tsort.Strings(valid)\n\treturn valid\n}\n\nfunc GetLookup(name string) GlobalLookupFactory {\n\tif factory, ok := lookups[name]; ok {\n\t\treturn factory\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * imgor\n * Copyright (c) 2012 Jimmy Zelinskie\n * Licensed under the MIT license.\n *\/\n\npackage main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"text\/template\"\n\t\"time\"\n)\n\n\/\/ Globals\nvar (\n\tuploadTemplate *template.Template\n\terrorTemplate  *template.Template\n\timgdir         string\n\ttemplatedir    string\n)\n\n\/\/ Check for errors\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Generate a random filename using a sha1 of the image\nfunc generatefilename(d []byte) string {\n\tsha := sha1.New()\n\treturn fmt.Sprintf(\"%x\", string(sha.Sum(d))[0:10])\n}\n\n\/\/ MIME Validator\nfunc validateimage(h *multipart.FileHeader) (ext string, err error) {\n\tmimeArray := h.Header[\"Content-Type\"]\n\tmime := mimeArray[0]\n\tif mime == \"image\/jpeg\" {\n\t\text = \".jpg\"\n\t} else if mime == \"image\/png\" {\n\t\text = \".png\"\n\t} else {\n\t\terr = errors.New(\"Unsupported filetype uploaded\")\n\t}\n\treturn\n}\n\n\/\/ Upload Handler\nfunc upload(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\t\/\/ Load the upload page if they aren't posting an image\n\t\tuploadTemplate.Execute(w, nil)\n\t\treturn\n\t}\n\n\t\/\/ Get image from POST\n\tf, h, err := r.FormFile(\"image\")\n\tdefer f.Close()\n\tcheck(err)\n\n\t\/\/ Check MIME and get a file extension\n\text, err := validateimage(h)\n\tcheck(err)\n\n\t\/\/ Read and write the uploaded file to disk\n\tfilebytes, err := ioutil.ReadAll(f)\n\tcheck(err)\n\tfilename := imgdir + generatefilename(filebytes) + ext\n\terr = ioutil.WriteFile(filename, filebytes, 0744)\n\tcheck(err)\n\n\t\/\/ Redirect to the view page\n\thttp.Redirect(w, r, \"\/view?id=\"+filename[6:], http.StatusFound)\n}\n\n\/\/ View Handler\nfunc view(w http.ResponseWriter, r *http.Request) {\n\tvar filename string\n\tfilename = imgdir + r.FormValue(\"id\")\n\n\tif filename[len(filename)-3:] == \"jpg\" {\n\t\tw.Header().Set(\"Content-Type\", \"image\/jpeg\")\n\t} else if filename[len(filename)-3:] == \"png\" {\n\t\tw.Header().Set(\"Content-Type\", \"image\/png\")\n\t} else {\n\t\tpanic(errors.New(\"No supported filetype specified\"))\n\t}\n\n\t\/\/ Set expire headers to now+ 1 year\n\tyearlater := time.Now().AddDate(1, 0, 0)\n\tw.Header().Set(\"Expires\", yearlater.Format(http.TimeFormat))\n\n\thttp.ServeFile(w, r, filename)\n}\n\n\/\/ Error page's variables\ntype ErrorPage struct {\n\tError error\n}\n\n\/\/ One clean error page\nfunc errorHandler(fn http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif e, ok := recover().(error); ok {\n\t\t\t\tcontents := ErrorPage{Error: e}\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\terrorTemplate.Execute(w, contents)\n\t\t\t}\n\t\t}()\n\t\tfn(w, r)\n\t}\n}\n\nfunc main() {\n\tvar err error\n\n\t\/\/ Set imgdir and make sure it exists!\n\timgdir = \".\/img\/\"\n\t_ = os.Mkdir(imgdir[2:len(imgdir)-1], 0744)\n\n\t\/\/ Load up templates and check for errors\n\ttemplatedir = \".\/templates\/\"\n\tuploadTemplate, err = template.ParseFiles(templatedir + \"upload.html\")\n\tcheck(err)\n\terrorTemplate, err = template.ParseFiles(templatedir + \"error.html\")\n\tcheck(err)\n\n\thttp.HandleFunc(\"\/\", errorHandler(upload))\n\thttp.HandleFunc(\"\/view\", errorHandler(view))\n\thttp.ListenAndServe(\":3000\", nil)\n}\n<commit_msg>changed url structure<commit_after>\/*\n * imgor\n * Copyright (c) 2012 Jimmy Zelinskie\n * Licensed under the MIT license.\n *\/\n\npackage main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"text\/template\"\n\t\"time\"\n)\n\n\/\/ Globals\nvar (\n\tuploadTemplate *template.Template\n\terrorTemplate  *template.Template\n\timgdir         string\n\ttemplatedir    string\n)\n\n\/\/ Error page's variables\ntype ErrorPage struct {\n\tError error\n}\n\n\/\/ Check for errors\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Generate a random filename using a sha1 of the image\nfunc generatefilename(d []byte) string {\n\tsha := sha1.New()\n\treturn fmt.Sprintf(\"%x\", string(sha.Sum(d))[0:10])\n}\n\n\/\/ MIME Validator\nfunc validateimage(h *multipart.FileHeader) (ext string, err error) {\n\tmimeArray := h.Header[\"Content-Type\"]\n\tmime := mimeArray[0]\n\tif mime == \"image\/jpeg\" {\n\t\text = \".jpg\"\n\t} else if mime == \"image\/png\" {\n\t\text = \".png\"\n\t} else {\n\t\terr = errors.New(\"Unsupported filetype uploaded\")\n\t}\n\treturn\n}\n\n\/\/ Upload Handler\nfunc upload(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\t\/\/ Load the upload page if they aren't posting an image\n\t\tuploadTemplate.Execute(w, nil)\n\t\treturn\n\t}\n\n\t\/\/ Get image from POST\n\tf, h, err := r.FormFile(\"image\")\n\tdefer f.Close()\n\tcheck(err)\n\n\t\/\/ Check MIME and get a file extension\n\text, err := validateimage(h)\n\tcheck(err)\n\n\t\/\/ Read and write the uploaded file to disk\n\tfilebytes, err := ioutil.ReadAll(f)\n\tcheck(err)\n\tfilename := imgdir + generatefilename(filebytes) + ext\n\terr = ioutil.WriteFile(filename, filebytes, 0744)\n\tcheck(err)\n\n\t\/\/ Redirect to the view page\n\thttp.Redirect(w, r, \"\/view\/\"+filename[6:], http.StatusFound)\n}\n\n\/\/ View Handler\nfunc view(w http.ResponseWriter, r *http.Request) {\n\tfilename := string(imgdir + r.URL.Path[len(\"view\/\"):])\n\n\tif filename[len(filename)-3:] == \"jpg\" {\n\t\tw.Header().Set(\"Content-Type\", \"image\/jpeg\")\n\t} else if filename[len(filename)-3:] == \"png\" {\n\t\tw.Header().Set(\"Content-Type\", \"image\/png\")\n\t} else {\n\t\tpanic(errors.New(\"No supported filetype specified\"))\n\t}\n\n\t\/\/ Set expire headers to now + 1 year\n\tyearlater := time.Now().AddDate(1, 0, 0)\n\tw.Header().Set(\"Expires\", yearlater.Format(http.TimeFormat))\n\n\thttp.ServeFile(w, r, filename)\n}\n\n\/\/ One clean error page\nfunc errorHandler(fn http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif e, ok := recover().(error); ok {\n\t\t\t\tcontents := ErrorPage{Error: e}\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\terrorTemplate.Execute(w, contents)\n\t\t\t}\n\t\t}()\n\t\tfn(w, r)\n\t}\n}\n\nfunc main() {\n\tvar err error\n\n\t\/\/ Set imgdir and make sure it exists!\n\timgdir = \".\/img\/\"\n\t_ = os.Mkdir(imgdir[2:len(imgdir)-1], 0744)\n\n\t\/\/ Load up templates and check for errors\n\ttemplatedir = \".\/templates\/\"\n\tuploadTemplate, err = template.ParseFiles(templatedir + \"upload.html\")\n\tcheck(err)\n\terrorTemplate, err = template.ParseFiles(templatedir + \"error.html\")\n\tcheck(err)\n\n\thttp.HandleFunc(\"\/\", errorHandler(upload))\n\thttp.HandleFunc(\"\/view\/\", errorHandler(view))\n\thttp.ListenAndServe(\":3000\", nil)\n}\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\"io\"\n\t\"launchpad.net\/gwacl\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/errors\"\n)\n\ntype azureStorage struct {\n\tstorageContext\n}\n\n\/\/ storageContext is an abstraction that is there only to accommodate the need\n\/\/ for using an azureStorage independently from an environ object in tests.\ntype storageContext interface {\n\tgetContainer() string\n\tgetStorageContext() (*gwacl.StorageContext, error)\n}\n\n\/\/ environStorageContext is a storageContext which gets its information from\n\/\/ an azureEnviron object.\ntype environStorageContext struct {\n\tenviron *azureEnviron\n}\n\nvar _ storageContext = (*environStorageContext)(nil)\n\nfunc (context *environStorageContext) getContainer() string {\n\treturn context.environ.getSnapshot().ecfg.StorageContainerName()\n}\n\nfunc (context *environStorageContext) getStorageContext() (*gwacl.StorageContext, error) {\n\treturn context.environ.getStorageContext()\n}\n\nfunc NewStorage(env *azureEnviron) environs.Storage {\n\tcontext := &environStorageContext{environ: env}\n\treturn &azureStorage{context}\n}\n\n\/\/ azureStorage implements Storage.\nvar _ environs.Storage = (*azureStorage)(nil)\n\n\/\/ Get is specified in the StorageReader interface.\nfunc (storage *azureStorage) Get(name string) (io.ReadCloser, error) {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader, err := context.GetBlob(storage.getContainer(), name)\n\tif gwacl.IsNotFoundError(err) {\n\t\treturn nil, errors.NotFoundf(\"file '%s' not found\", name)\n\t}\n\treturn reader, err\n}\n\n\/\/ List is specified in the StorageReader interface.\nfunc (storage *azureStorage) List(prefix string) ([]string, error) {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest := &gwacl.ListBlobsRequest{Container: storage.getContainer(), Prefix: prefix, Marker: \"\"}\n\tblobList, err := context.ListAllBlobs(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames := make([]string, len(blobList.Blobs))\n\tfor index, blob := range blobList.Blobs {\n\t\tnames[index] = blob.Name\n\t}\n\treturn names, nil\n}\n\n\/\/ URL is specified in the StorageReader interface.\nfunc (storage *azureStorage) URL(name string) (string, error) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Put is specified in the StorageWriter interface.\nfunc (storage *azureStorage) Put(name string, r io.Reader, length int64) error {\n\tlimitedReader := io.LimitReader(r, length)\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn context.UploadBlockBlob(storage.getContainer(), name, limitedReader)\n}\n\n\/\/ Remove is specified in the StorageWriter interface.\nfunc (storage *azureStorage) Remove(name string) error {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn context.DeleteBlob(storage.getContainer(), name)\n}\n<commit_msg>Fix string.<commit_after>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage azure\n\nimport (\n\t\"io\"\n\t\"launchpad.net\/gwacl\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/errors\"\n)\n\ntype azureStorage struct {\n\tstorageContext\n}\n\n\/\/ storageContext is an abstraction that is there only to accommodate the need\n\/\/ for using an azureStorage independently from an environ object in tests.\ntype storageContext interface {\n\tgetContainer() string\n\tgetStorageContext() (*gwacl.StorageContext, error)\n}\n\n\/\/ environStorageContext is a storageContext which gets its information from\n\/\/ an azureEnviron object.\ntype environStorageContext struct {\n\tenviron *azureEnviron\n}\n\nvar _ storageContext = (*environStorageContext)(nil)\n\nfunc (context *environStorageContext) getContainer() string {\n\treturn context.environ.getSnapshot().ecfg.StorageContainerName()\n}\n\nfunc (context *environStorageContext) getStorageContext() (*gwacl.StorageContext, error) {\n\treturn context.environ.getStorageContext()\n}\n\nfunc NewStorage(env *azureEnviron) environs.Storage {\n\tcontext := &environStorageContext{environ: env}\n\treturn &azureStorage{context}\n}\n\n\/\/ azureStorage implements Storage.\nvar _ environs.Storage = (*azureStorage)(nil)\n\n\/\/ Get is specified in the StorageReader interface.\nfunc (storage *azureStorage) Get(name string) (io.ReadCloser, error) {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treader, err := context.GetBlob(storage.getContainer(), name)\n\tif gwacl.IsNotFoundError(err) {\n\t\treturn nil, errors.NotFoundf(\"file %q not found\", name)\n\t}\n\treturn reader, err\n}\n\n\/\/ List is specified in the StorageReader interface.\nfunc (storage *azureStorage) List(prefix string) ([]string, error) {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest := &gwacl.ListBlobsRequest{Container: storage.getContainer(), Prefix: prefix, Marker: \"\"}\n\tblobList, err := context.ListAllBlobs(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnames := make([]string, len(blobList.Blobs))\n\tfor index, blob := range blobList.Blobs {\n\t\tnames[index] = blob.Name\n\t}\n\treturn names, nil\n}\n\n\/\/ URL is specified in the StorageReader interface.\nfunc (storage *azureStorage) URL(name string) (string, error) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Put is specified in the StorageWriter interface.\nfunc (storage *azureStorage) Put(name string, r io.Reader, length int64) error {\n\tlimitedReader := io.LimitReader(r, length)\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn context.UploadBlockBlob(storage.getContainer(), name, limitedReader)\n}\n\n\/\/ Remove is specified in the StorageWriter interface.\nfunc (storage *azureStorage) Remove(name string) error {\n\tcontext, err := storage.getStorageContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn context.DeleteBlob(storage.getContainer(), name)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Serviced 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 integration,!quick\n\npackage registry_test\n\nimport (\n\t\"path\"\n\n\t\"github.com\/control-center\/serviced\/zzk\"\n\t. \"github.com\/control-center\/serviced\/zzk\/registry2\"\n\t. \"gopkg.in\/check.v1\"\n)\n\nfunc (t *ZZKTest) TestSyncRegistry(c *C) {\n\tconn, err := zzk.GetLocalConnection(\"\/\")\n\tc.Assert(err, IsNil)\n\n\t\/\/ test create\n\tpub1Key := PublicPortKey{HostID: \"master\", PortAddress: \":2181\"}\n\tpub1 := PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     true,\n\t\tProtocol:    \"http\",\n\t\tUseTLS:      false,\n\t}\n\tpubs1 := map[PublicPortKey]PublicPort{pub1Key: pub1}\n\n\tvhost1Key := VHostKey{HostID: \"master\", Subdomain: \"test1\"}\n\tvhost1 := VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     true,\n\t}\n\tvhosts1 := map[VHostKey]VHost{vhost1Key: vhost1}\n\n\terr = SyncServiceRegistry(conn, \"serviceid1\", pubs1, vhosts1)\n\tc.Assert(err, IsNil)\n\n\tactualpub, err := GetPublicPort(conn, pub1Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost, err := GetVHost(conn, vhost1Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tpub2Key := PublicPortKey{HostID: \"master\", PortAddress: \":22181\"}\n\tpub2 := PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app2\",\n\t\tServiceID:   \"serviceid2\",\n\t\tEnabled:     true,\n\t\tProtocol:    \"https\",\n\t\tUseTLS:      true,\n\t}\n\tpubs2 := map[PublicPortKey]PublicPort{pub2Key: pub2}\n\n\tvhost2Key := VHostKey{HostID: \"master\", Subdomain: \"test2\"}\n\tvhost2 := VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app2\",\n\t\tServiceID:   \"serviceid2\",\n\t\tEnabled:     true,\n\t}\n\tvhosts2 := map[VHostKey]VHost{vhost2Key: vhost2}\n\n\terr = SyncServiceRegistry(conn, \"serviceid2\", pubs2, vhosts2)\n\tc.Assert(err, IsNil)\n\n\tactualpub, err = GetPublicPort(conn, pub1Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost, err = GetVHost(conn, vhost1Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tactualpub, err = GetPublicPort(conn, pub2Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub2)\n\n\tactualvhost, err = GetVHost(conn, vhost2Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost2)\n\n\t\/\/ test update\n\tpub1Key = PublicPortKey{HostID: \"master\", PortAddress: \":2181\"}\n\tpub1 = PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     false,\n\t\tProtocol:    \"\",\n\t\tUseTLS:      true,\n\t}\n\tpubs1 = map[PublicPortKey]PublicPort{pub1Key: pub1}\n\n\tvhost1Key = VHostKey{HostID: \"master\", Subdomain: \"test1\"}\n\tvhost1 = VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     false,\n\t}\n\tvhosts1 = map[VHostKey]VHost{vhost1Key: vhost1}\n\n\terr = SyncServiceRegistry(conn, \"serviceid1\", pubs1, vhosts1)\n\tc.Assert(err, IsNil)\n\n\tactualpub, err = GetPublicPort(conn, pub1Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost, err = GetVHost(conn, vhost1Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tactualpub, err = GetPublicPort(conn, pub2Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub2)\n\n\tactualvhost, err = GetVHost(conn, vhost2Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost2)\n\n\t\/\/ test delete\n\terr = SyncServiceRegistry(conn, \"serviceid2\", make(map[PublicPortKey]PublicPort), make(map[VHostKey]VHost))\n\tc.Assert(err, IsNil)\n\n\tactualpub, err = GetPublicPort(conn, pub1Key)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost, err = GetVHost(conn, vhost1Key)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tok, err := conn.Exists(path.Join(\"\/net\/pub\", pub2Key.HostID, pub2Key.PortAddress))\n\tc.Assert(err, IsNil)\n\tc.Check(ok, Equals, false)\n\n\tok, err = conn.Exists(path.Join(\"\/net\/vhost\", vhost2Key.HostID, vhost2Key.Subdomain))\n\tc.Assert(err, IsNil)\n\tc.Check(ok, Equals, false)\n}\n<commit_msg>registry test<commit_after>\/\/ Copyright 2016 The Serviced 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 integration,!quick\n\npackage registry_test\n\nimport (\n\t\"path\"\n\n\t\"github.com\/control-center\/serviced\/zzk\"\n\t. \"github.com\/control-center\/serviced\/zzk\/registry2\"\n\t. \"gopkg.in\/check.v1\"\n)\n\nfunc (t *ZZKTest) TestSyncRegistry(c *C) {\n\tconn, err := zzk.GetLocalConnection(\"\/\")\n\tc.Assert(err, IsNil)\n\n\t\/\/ test create\n\tpub1Key := PublicPortKey{HostID: \"master\", PortAddress: \":2181\"}\n\tpub1 := PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     true,\n\t\tProtocol:    \"http\",\n\t\tUseTLS:      false,\n\t}\n\tpubs1 := map[PublicPortKey]PublicPort{pub1Key: pub1}\n\n\tvhost1Key := VHostKey{HostID: \"master\", Subdomain: \"test1\"}\n\tvhost1 := VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     true,\n\t}\n\tvhosts1 := map[VHostKey]VHost{vhost1Key: vhost1}\n\n\terr = SyncServiceRegistry(conn, \"serviceid1\", pubs1, vhosts1)\n\tc.Assert(err, IsNil)\n\n\tactualpub := &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:2181\", actualpub)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost := &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test1\", actualvhost)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tpub2Key := PublicPortKey{HostID: \"master\", PortAddress: \":22181\"}\n\tpub2 := PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app2\",\n\t\tServiceID:   \"serviceid2\",\n\t\tEnabled:     true,\n\t\tProtocol:    \"https\",\n\t\tUseTLS:      true,\n\t}\n\tpubs2 := map[PublicPortKey]PublicPort{pub2Key: pub2}\n\n\tvhost2Key := VHostKey{HostID: \"master\", Subdomain: \"test2\"}\n\tvhost2 := VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app2\",\n\t\tServiceID:   \"serviceid2\",\n\t\tEnabled:     true,\n\t}\n\tvhosts2 := map[VHostKey]VHost{vhost2Key: vhost2}\n\n\terr = SyncServiceRegistry(conn, \"serviceid2\", pubs2, vhosts2)\n\tc.Assert(err, IsNil)\n\n\tactualpub = &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:2181\", actualpub)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost = &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test1\", actualvhost)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tactualpub = &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:22181\", actualpub)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub2)\n\n\tactualvhost = &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test2\", actualvhost)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost2)\n\n\t\/\/ test update\n\tpub1Key = PublicPortKey{HostID: \"master\", PortAddress: \":2181\"}\n\tpub1 = PublicPort{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     false,\n\t\tProtocol:    \"\",\n\t\tUseTLS:      true,\n\t}\n\tpubs1 = map[PublicPortKey]PublicPort{pub1Key: pub1}\n\n\tvhost1Key = VHostKey{HostID: \"master\", Subdomain: \"test1\"}\n\tvhost1 = VHost{\n\t\tTenantID:    \"tenantid\",\n\t\tApplication: \"app1\",\n\t\tServiceID:   \"serviceid1\",\n\t\tEnabled:     false,\n\t}\n\tvhosts1 = map[VHostKey]VHost{vhost1Key: vhost1}\n\n\terr = SyncServiceRegistry(conn, \"serviceid1\", pubs1, vhosts1)\n\tc.Assert(err, IsNil)\n\n\tactualpub = &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:2181\", actualpub)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost = &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test1\", actualvhost)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tactualpub = &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:22181\", actualpub)\n\tc.Assert(err, IsNil)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub2)\n\n\tactualvhost = &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test2\", actualvhost)\n\tc.Assert(err, IsNil)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost2)\n\n\t\/\/ test delete\n\terr = SyncServiceRegistry(conn, \"serviceid2\", make(map[PublicPortKey]PublicPort), make(map[VHostKey]VHost))\n\tc.Assert(err, IsNil)\n\n\tactualpub = &PublicPort{}\n\terr = conn.Get(\"\/net\/pub\/master\/:2181\", actualpub)\n\tactualpub.SetVersion(nil)\n\tc.Check(*actualpub, DeepEquals, pub1)\n\n\tactualvhost = &VHost{}\n\terr = conn.Get(\"\/net\/vhost\/master\/test1\", actualvhost)\n\tactualvhost.SetVersion(nil)\n\tc.Check(*actualvhost, DeepEquals, vhost1)\n\n\tok, err := conn.Exists(path.Join(\"\/net\/pub\", pub2Key.HostID, pub2Key.PortAddress))\n\tc.Assert(err, IsNil)\n\tc.Check(ok, Equals, false)\n\n\tok, err = conn.Exists(path.Join(\"\/net\/vhost\", vhost2Key.HostID, vhost2Key.Subdomain))\n\tc.Assert(err, IsNil)\n\tc.Check(ok, Equals, false)\n}\n<|endoftext|>"}
{"text":"<commit_before>package mackerel\n\nconst (\n\tCheckStatusOK       = \"OK\"\n\tCheckStatusWarning  = \"WARNING\"\n\tCheckStatusCritical = \"CRITICAL\"\n\tCheckStatusUnknown  = \"UNKNOWN\"\n)\n\ntype CheckReport struct {\n\tSource               CheckSource `json:\"source\"`\n\tName                 string      `json:\"name\"`\n\tStatus               string      `json:\"status\"`\n\tMessage              string      `json:\"message\"`\n\tOccurredAt           int64       `json:\"occurredAt\"`\n\tNotificationInterval uint        `json:\"notificationInterval,omitempty\"`\n\tMaxCheckAttempts     uint        `json:\"maxCheckAttempts,omitempty\"`\n}\n\ntype CheckSource interface {\n\tCheckType() string\n\n\tisCheck()\n}\n\nconst checkTypeHost = \"host\"\n\n\/\/ Ensure each check type conforms to the CheckSource interface.\nvar _ CheckSource = (*checkSourceHost)(nil)\n\n\/\/ Ensure only checkSource types defined in this package can be assigned to the\n\/\/ CheckSource interface.\nfunc (m *checkSourceHost) isCheck() {}\n\ntype checkSourceHost struct {\n\tType   string `json:\"type\"`\n\tHostID string `json:\"hostId\"`\n}\n\nfunc (cs *checkSourceHost) CheckType() string {\n\treturn checkTypeHost\n}\n\nfunc NewCheckSourceHost(hostID string) CheckSource {\n\treturn &checkSourceHost{\n\t\tType:   checkTypeHost,\n\t\tHostID: hostID,\n\t}\n}\n\ntype CheckReports struct {\n\tReports []*CheckReport `json:\"reports\"`\n}\n\nfunc (c *Client) ReportCheckMonitors(crs *CheckReports) error {\n\tresp, err := c.PostJSON(\"\/api\/v0\/monitoring\/checks\/report\", crs)\n\tdefer closeResponse(resp)\n\treturn err\n}\n<commit_msg>add comment<commit_after>package mackerel\n\n\/\/ CheckStatuses\nconst (\n\tCheckStatusOK       = \"OK\"\n\tCheckStatusWarning  = \"WARNING\"\n\tCheckStatusCritical = \"CRITICAL\"\n\tCheckStatusUnknown  = \"UNKNOWN\"\n)\n\n\/\/ CheckReport represents a report of check monitoring\ntype CheckReport struct {\n\tSource               CheckSource `json:\"source\"`\n\tName                 string      `json:\"name\"`\n\tStatus               string      `json:\"status\"`\n\tMessage              string      `json:\"message\"`\n\tOccurredAt           int64       `json:\"occurredAt\"`\n\tNotificationInterval uint        `json:\"notificationInterval,omitempty\"`\n\tMaxCheckAttempts     uint        `json:\"maxCheckAttempts,omitempty\"`\n}\n\n\/\/ CheckSource represents interface to which each check source type must confirm to\ntype CheckSource interface {\n\tCheckType() string\n\n\tisCheck()\n}\n\nconst checkTypeHost = \"host\"\n\n\/\/ Ensure each check type conforms to the CheckSource interface.\nvar _ CheckSource = (*checkSourceHost)(nil)\n\n\/\/ Ensure only checkSource types defined in this package can be assigned to the\n\/\/ CheckSource interface.\nfunc (cs *checkSourceHost) isCheck() {}\n\ntype checkSourceHost struct {\n\tType   string `json:\"type\"`\n\tHostID string `json:\"hostId\"`\n}\n\n\/\/ CheckType is for satisfying CheckSource interface\nfunc (cs *checkSourceHost) CheckType() string {\n\treturn checkTypeHost\n}\n\n\/\/ NewCheckSourceHost returns new CheckSource which check type is \"host\"\nfunc NewCheckSourceHost(hostID string) CheckSource {\n\treturn &checkSourceHost{\n\t\tType:   checkTypeHost,\n\t\tHostID: hostID,\n\t}\n}\n\n\/\/ CheckReports represents check reports for API\ntype CheckReports struct {\n\tReports []*CheckReport `json:\"reports\"`\n}\n\n\/\/ ReportCheckMonitors reports check monitoring results\nfunc (c *Client) ReportCheckMonitors(crs *CheckReports) error {\n\tresp, err := c.PostJSON(\"\/api\/v0\/monitoring\/checks\/report\", crs)\n\tdefer closeResponse(resp)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc> *\/\n\/* See LICENSE for licensing information *\/\n\npackage fdroidcl\n\nimport (\n\t\"encoding\/hex\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype Index struct {\n\tRepo struct {\n\t\tName        string `xml:\"name,attr\"`\n\t\tPubKey      string `xml:\"pubkey,attr\"`\n\t\tTimestamp   int    `xml:\"timestamp,attr\"`\n\t\tURL         string `xml:\"url,attr\"`\n\t\tVersion     int    `xml:\"version,attr\"`\n\t\tMaxAge      int    `xml:\"maxage,attr\"`\n\t\tDescription string `xml:\"description\"`\n\t} `xml:\"repo\"`\n\tApps []App `xml:\"application\"`\n}\n\ntype commaList []string\n\nfunc (cl *commaList) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tif err := d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*cl = strings.Split(content, \",\")\n\treturn nil\n}\n\ntype hexVal []byte\n\nfunc (hv *hexVal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tvar err error\n\tif err = d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*hv, err = hex.DecodeString(content)\n\treturn err\n}\n\n\/\/ App is an Android application\ntype App struct {\n\tID        string    `xml:\"id\"`\n\tName      string    `xml:\"name\"`\n\tSummary   string    `xml:\"summary\"`\n\tDesc      string    `xml:\"desc\"`\n\tLicense   string    `xml:\"license\"`\n\tCategs    commaList `xml:\"categories\"`\n\tWebsite   string    `xml:\"web\"`\n\tSource    string    `xml:\"source\"`\n\tTracker   string    `xml:\"tracker\"`\n\tChangelog string    `xml:\"changelog\"`\n\tDonate    string    `xml:\"donate\"`\n\tBitcoin   string    `xml:\"bitcoin\"`\n\tLitecoin  string    `xml:\"litecoin\"`\n\tDogecoin  string    `xml:\"dogecoin\"`\n\tFlattrID  string    `xml:\"flattr\"`\n\tApks      []Apk     `xml:\"package\"`\n\tCVName    string    `xml:\"marketversion\"`\n\tCVCode    int       `xml:\"marketvercode\"`\n\tCurApk    *Apk\n}\n\ntype Hash struct {\n\tType string `xml:\"type,attr\"`\n\tData hexVal `xml:\",chardata\"`\n}\n\n\/\/ Apk is an Android package\ntype Apk struct {\n\tVName   string    `xml:\"version\"`\n\tVCode   int       `xml:\"versioncode\"`\n\tSize    int64     `xml:\"size\"`\n\tMinSdk  int       `xml:\"sdkver\"`\n\tMaxSdk  int       `xml:\"maxsdkver\"`\n\tABIs    commaList `xml:\"nativecode\"`\n\tApkName string    `xml:\"apkname\"`\n\tSrcName string    `xml:\"srcname\"`\n\tSig     hexVal    `xml:\"sig\"`\n\tAdded   string    `xml:\"added\"`\n\tPerms   commaList `xml:\"permissions\"`\n\tFeats   commaList `xml:\"features\"`\n\tHashes  []Hash    `xml:\"hash\"`\n}\n\nfunc (app *App) calcCurApk() {\n\tfor _, apk := range app.Apks {\n\t\tapp.CurApk = &apk\n\t\tif app.CVCode >= apk.VCode {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (app *App) TextDesc(w io.Writer) {\n\treader := strings.NewReader(app.Desc)\n\tdecoder := xml.NewDecoder(reader)\n\tfirstParagraph := true\n\tlinePrefix := \"\"\n\tcolsUsed := 0\n\tvar links []string\n\tlinked := false\n\tfor {\n\t\ttoken, err := decoder.Token()\n\t\tif err == io.EOF || token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tif firstParagraph {\n\t\t\t\t\tfirstParagraph = false\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t\tlinePrefix = \"\"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"li\":\n\t\t\t\tfmt.Fprint(w, \"\\n *\")\n\t\t\t\tlinePrefix = \"   \"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"a\":\n\t\t\t\tfor _, attr := range t.Attr {\n\t\t\t\t\tif attr.Name.Local == \"href\" {\n\t\t\t\t\t\tlinks = append(links, attr.Value)\n\t\t\t\t\t\tlinked = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ul\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ol\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\t}\n\t\tcase xml.CharData:\n\t\t\tleft := string(t)\n\t\t\tif linked {\n\t\t\t\tleft += fmt.Sprintf(\"[%d]\", len(links)-1)\n\t\t\t\tlinked = false\n\t\t\t}\n\t\t\tlimit := 80 - len(linePrefix) - colsUsed\n\t\t\tfirstLine := true\n\t\t\tfor len(left) > limit {\n\t\t\t\tlast := 0\n\t\t\t\tfor i, c := range left {\n\t\t\t\t\tif i >= limit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif c == ' ' {\n\t\t\t\t\t\tlast = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif firstLine {\n\t\t\t\t\tfirstLine = false\n\t\t\t\t\tlimit += colsUsed\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, left[:last])\n\t\t\t\tleft = left[last+1:]\n\t\t\t\tcolsUsed = 0\n\t\t\t}\n\t\t\tif firstLine {\n\t\t\t\tfirstLine = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t}\n\t\t\tfmt.Fprint(w, left)\n\t\t\tcolsUsed += len(left)\n\t\t}\n\t}\n\tif len(links) > 0 {\n\t\tfmt.Fprintln(w)\n\t\tfor i, link := range links {\n\t\t\tfmt.Fprintf(w, \"[%d] %s\\n\", i, link)\n\t\t}\n\t}\n}\n\nfunc (app *App) prepareData() {\n\tapp.calcCurApk()\n}\n\ntype appList []App\n\nfunc (al appList) Len() int           { return len(al) }\nfunc (al appList) Swap(i, j int)      { al[i], al[j] = al[j], al[i] }\nfunc (al appList) Less(i, j int) bool { return al[i].ID < al[j].ID }\n\nfunc LoadIndexXml(r io.Reader) (*Index, error) {\n\tvar index Index\n\tdecoder := xml.NewDecoder(r)\n\tif err := decoder.Decode(&index); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(appList(index.Apps))\n\n\tfor i := range index.Apps {\n\t\tapp := &index.Apps[i]\n\t\tapp.prepareData()\n\t}\n\treturn &index, nil\n}\n<commit_msg>Add support for date values<commit_after>\/* Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc> *\/\n\/* See LICENSE for licensing information *\/\n\npackage fdroidcl\n\nimport (\n\t\"encoding\/hex\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Index struct {\n\tRepo struct {\n\t\tName        string `xml:\"name,attr\"`\n\t\tPubKey      string `xml:\"pubkey,attr\"`\n\t\tTimestamp   int    `xml:\"timestamp,attr\"`\n\t\tURL         string `xml:\"url,attr\"`\n\t\tVersion     int    `xml:\"version,attr\"`\n\t\tMaxAge      int    `xml:\"maxage,attr\"`\n\t\tDescription string `xml:\"description\"`\n\t} `xml:\"repo\"`\n\tApps []App `xml:\"application\"`\n}\n\ntype commaList []string\n\nfunc (cl *commaList) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tif err := d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*cl = strings.Split(content, \",\")\n\treturn nil\n}\n\ntype hexVal []byte\n\nfunc (hv *hexVal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tvar err error\n\tif err = d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\t*hv, err = hex.DecodeString(content)\n\treturn err\n}\n\n\/\/ App is an Android application\ntype App struct {\n\tID        string    `xml:\"id\"`\n\tName      string    `xml:\"name\"`\n\tSummary   string    `xml:\"summary\"`\n\tDesc      string    `xml:\"desc\"`\n\tLicense   string    `xml:\"license\"`\n\tCategs    commaList `xml:\"categories\"`\n\tWebsite   string    `xml:\"web\"`\n\tSource    string    `xml:\"source\"`\n\tTracker   string    `xml:\"tracker\"`\n\tChangelog string    `xml:\"changelog\"`\n\tDonate    string    `xml:\"donate\"`\n\tBitcoin   string    `xml:\"bitcoin\"`\n\tLitecoin  string    `xml:\"litecoin\"`\n\tDogecoin  string    `xml:\"dogecoin\"`\n\tFlattrID  string    `xml:\"flattr\"`\n\tApks      []Apk     `xml:\"package\"`\n\tCVName    string    `xml:\"marketversion\"`\n\tCVCode    int       `xml:\"marketvercode\"`\n\tCurApk    *Apk\n}\n\ntype Hash struct {\n\tType string `xml:\"type,attr\"`\n\tData hexVal `xml:\",chardata\"`\n}\n\ntype dateVal struct {\n\ttime.Time\n}\n\nfunc (dv *dateVal) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar content string\n\tif err := d.DecodeElement(&content, &start); err != nil {\n\t\treturn err\n\t}\n\tt, err := time.Parse(\"2006-01-02\", content)\n\t*dv = dateVal{t}\n\treturn err\n}\n\n\/\/ Apk is an Android package\ntype Apk struct {\n\tVName   string    `xml:\"version\"`\n\tVCode   int       `xml:\"versioncode\"`\n\tSize    int64     `xml:\"size\"`\n\tMinSdk  int       `xml:\"sdkver\"`\n\tMaxSdk  int       `xml:\"maxsdkver\"`\n\tABIs    commaList `xml:\"nativecode\"`\n\tApkName string    `xml:\"apkname\"`\n\tSrcName string    `xml:\"srcname\"`\n\tSig     hexVal    `xml:\"sig\"`\n\tAdded   dateVal   `xml:\"added\"`\n\tPerms   commaList `xml:\"permissions\"`\n\tFeats   commaList `xml:\"features\"`\n\tHashes  []Hash    `xml:\"hash\"`\n}\n\nfunc (app *App) calcCurApk() {\n\tfor _, apk := range app.Apks {\n\t\tapp.CurApk = &apk\n\t\tif app.CVCode >= apk.VCode {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (app *App) TextDesc(w io.Writer) {\n\treader := strings.NewReader(app.Desc)\n\tdecoder := xml.NewDecoder(reader)\n\tfirstParagraph := true\n\tlinePrefix := \"\"\n\tcolsUsed := 0\n\tvar links []string\n\tlinked := false\n\tfor {\n\t\ttoken, err := decoder.Token()\n\t\tif err == io.EOF || token == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch t := token.(type) {\n\t\tcase xml.StartElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tif firstParagraph {\n\t\t\t\t\tfirstParagraph = false\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t\tlinePrefix = \"\"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"li\":\n\t\t\t\tfmt.Fprint(w, \"\\n *\")\n\t\t\t\tlinePrefix = \"   \"\n\t\t\t\tcolsUsed = 0\n\t\t\tcase \"a\":\n\t\t\t\tfor _, attr := range t.Attr {\n\t\t\t\t\tif attr.Name.Local == \"href\" {\n\t\t\t\t\t\tlinks = append(links, attr.Value)\n\t\t\t\t\t\tlinked = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase xml.EndElement:\n\t\t\tswitch t.Name.Local {\n\t\t\tcase \"p\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ul\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\tcase \"ol\":\n\t\t\t\tfmt.Fprintln(w)\n\t\t\t}\n\t\tcase xml.CharData:\n\t\t\tleft := string(t)\n\t\t\tif linked {\n\t\t\t\tleft += fmt.Sprintf(\"[%d]\", len(links)-1)\n\t\t\t\tlinked = false\n\t\t\t}\n\t\t\tlimit := 80 - len(linePrefix) - colsUsed\n\t\t\tfirstLine := true\n\t\t\tfor len(left) > limit {\n\t\t\t\tlast := 0\n\t\t\t\tfor i, c := range left {\n\t\t\t\t\tif i >= limit {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif c == ' ' {\n\t\t\t\t\t\tlast = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif firstLine {\n\t\t\t\t\tfirstLine = false\n\t\t\t\t\tlimit += colsUsed\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, left[:last])\n\t\t\t\tleft = left[last+1:]\n\t\t\t\tcolsUsed = 0\n\t\t\t}\n\t\t\tif firstLine {\n\t\t\t\tfirstLine = false\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, linePrefix)\n\t\t\t}\n\t\t\tfmt.Fprint(w, left)\n\t\t\tcolsUsed += len(left)\n\t\t}\n\t}\n\tif len(links) > 0 {\n\t\tfmt.Fprintln(w)\n\t\tfor i, link := range links {\n\t\t\tfmt.Fprintf(w, \"[%d] %s\\n\", i, link)\n\t\t}\n\t}\n}\n\nfunc (app *App) prepareData() {\n\tapp.calcCurApk()\n}\n\ntype appList []App\n\nfunc (al appList) Len() int           { return len(al) }\nfunc (al appList) Swap(i, j int)      { al[i], al[j] = al[j], al[i] }\nfunc (al appList) Less(i, j int) bool { return al[i].ID < al[j].ID }\n\nfunc LoadIndexXml(r io.Reader) (*Index, error) {\n\tvar index Index\n\tdecoder := xml.NewDecoder(r)\n\tif err := decoder.Decode(&index); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsort.Sort(appList(index.Apps))\n\n\tfor i := range index.Apps {\n\t\tapp := &index.Apps[i]\n\t\tapp.prepareData()\n\t}\n\treturn &index, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gnosis\n\nimport (\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/JackKnifed\/blackfriday\"\n\t\"github.com\/blevesearch\/bleve\"\n\t\"github.com\/mschoch\/blackfriday-text\"\n\t\"gopkg.in\/fsnotify.v1\"\n)\n\ntype gnosisIndex struct {\n\tTrueIndex bleve.Index\n\tConfig    IndexSection\n}\n\ntype indexedPage struct {\n\tName     string    `json:\"name\"`\n\tFilepath string    `json:\"path\"`\n\tBody     string    `json:\"body\"`\n\tTopics   string    `json:\"topic\"`\n\tKeywords string    `json:\"keyword\"`\n\tModified time.Time `json:\"modified\"`\n}\n\nfunc openIndex(config IndexSection) *gnosisIndex {\n\tindex := new(gnosisIndex)\n\tindex.Config = config\n\tnewIndex, err := bleve.Open(path.Clean(index.Config.IndexPath))\n\tif err == nil {\n\t\tlog.Printf(\"Opening existing index...\")\n\t\tindex.TrueIndex = newIndex\n\t} else if err == bleve.ErrorIndexPathDoesNotExist {\n\t\tlog.Printf(\"Creating new index...\")\n\t\t\/\/ create a mapping\n\t\tindexMapping := index.buildIndexMapping()\n\t\tnewIndex, err := bleve.New(path.Clean(index.Config.IndexPath), indexMapping)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\tindex.TrueIndex = newIndex\n\t\t}\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n\treturn index\n}\n\nfunc (index *gnosisIndex) buildIndexMapping() *bleve.IndexMapping {\n\n\t\/\/ create a text field type\n\tenTextFieldMapping := bleve.NewTextFieldMapping()\n\tenTextFieldMapping.Analyzer = index.Config.IndexType\n\n\t\/\/ create a date field type\n\tdateTimeMapping := bleve.NewDateTimeFieldMapping()\n\n\t\/\/ map out the wiki page\n\twikiMapping := bleve.NewDocumentMapping()\n\twikiMapping.AddFieldMappingsAt(\"path\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"body\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"topic\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"keyword\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"modified\", dateTimeMapping)\n\n\t\/\/ add the wiki page mapping to a new index\n\t\/\/ ##TODO## revisit? move out to config?\n\tindexMapping := bleve.NewIndexMapping()\n\tindexMapping.AddDocumentMapping(\"wiki\", wikiMapping)\n\tindexMapping.DefaultAnalyzer = index.Config.IndexType\n\n\treturn indexMapping\n}\n\nfunc (index *gnosisIndex) cleanupMarkdown(input []byte) []byte {\n\textensions := 0\n\trenderer := blackfridaytext.TextRenderer()\n\toutput := blackfriday.Markdown(input, renderer, extensions)\n\treturn output\n}\n\nfunc (index *gnosisIndex) relativePath(filePath string) string {\n\tfilePath = strings.TrimPrefix(filePath, index.Config.WatchDir)\n\tfilePath = path.Clean(filePath)\n\treturn filePath\n}\n\nfunc (index *gnosisIndex) generateWikiFromFile(filePath string) (*indexedPage, error) {\n\tpdata := new(PageMetadata)\n\terr := pdata.LoadPage(filePath)\n\t\/\/fileBytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ ##TODO## I need to look up the actual index that I'm building and hit all of the fields here\n\tcleanedUpPage := index.cleanupMarkdown(pdata.Page)\n\ttopics, keywords := pdata.ListMeta()\n\trv := indexedPage{\n\t\tName: pdata.Title,\n\t\tBody: string(cleanedUpPage),\n\t\tFilepath: filePath,\n\t\tTopics: strings.Join(topics, \" \"),\n\t\tKeywords: strings.Join(keywords, \" \"),\n\t\tModified: pdata.FileStats.ModTime(),\n\t}\n\treturn &rv, nil\n}\n\nfunc (index *gnosisIndex) processUpdate(path string) {\n\tlog.Printf(\"updated: %s\", path)\n\trp := index.relativePath(path)\n\twiki, err := index.generateWikiFromFile(path)\n\tif err != nil {\n\t\tlog.Print(err)\n\t} else {\n\t\tindex.TrueIndex.Index(rp, wiki)\n\t}\n}\n\nfunc (index *gnosisIndex) processDelete(path string) {\n\tlog.Printf(\"delete: %s\", path)\n\trp := index.relativePath(path)\n\terr := index.TrueIndex.Delete(rp)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n}\n\nfunc (index *gnosisIndex) walkForIndexing(path string) {\n\t\/\/ ##TODO## reevaulate by finding all files within a path?\n\tdirEntries, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, dirEntry := range dirEntries {\n\t\tdirEntryPath := path + string(os.PathSeparator) + dirEntry.Name()\n\t\tif dirEntry.IsDir() {\n\t\t\tindex.walkForIndexing(dirEntryPath)\n\t\t} else if strings.HasSuffix(dirEntry.Name(), \".md\") {\n\t\t\tindex.processUpdate(dirEntryPath)\n\t\t}\n\t}\n}\n\nfunc (index *gnosisIndex) startWatching(filePath string) *fsnotify.Watcher {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ maybe rework the index so the Watcher is inside the index? idk\n\n\t\/\/ start a go routine to process events\n\tgo func() {\n\t\tidleTimer := time.NewTimer(10 * time.Second)\n\t\tqueuedEvents := make([]fsnotify.Event, 0)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-watcher.Events:\n\t\t\t\tqueuedEvents = append(queuedEvents, ev)\n\t\t\t\tidleTimer.Reset(10 * time.Second)\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Fatal(err)\n\t\t\tcase <-idleTimer.C:\n\t\t\t\tfor _, ev := range queuedEvents {\n\t\t\t\t\tif strings.HasSuffix(ev.Name, \".md\") {\n\t\t\t\t\t\tswitch ev.Op {\n\t\t\t\t\t\tcase fsnotify.Remove, fsnotify.Rename:\n\t\t\t\t\t\t\t\/\/ delete the filePath\n\t\t\t\t\t\t\tindex.processDelete(ev.Name)\n\t\t\t\t\t\tcase fsnotify.Create, fsnotify.Write:\n\t\t\t\t\t\t\t\/\/ update the filePath\n\t\t\t\t\t\t\tindex.processUpdate(ev.Name)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\/\/ ignore\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tqueuedEvents = make([]fsnotify.Event, 0)\n\t\t\t\tidleTimer.Reset(10 * time.Second)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ now actually watch the filePath requested\n\terr = watcher.Add(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"watching '%s' for changes...\", filePath)\n\n\treturn watcher\n}\n<commit_msg>made a bunch of chnages to the indexer - i believe i quashed all bugs and got it to watch multiple directories<commit_after>package gnosis\n\nimport (\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/JackKnifed\/blackfriday\"\n\t\"github.com\/blevesearch\/bleve\"\n\t\"github.com\/mschoch\/blackfriday-text\"\n\t\"gopkg.in\/fsnotify.v1\"\n)\n\ntype gnosisIndex struct {\n\tTrueIndex bleve.Index\n\tConfig    IndexSection\n\topenWatchers fsnotify.Watcher[]\n}\n\ntype indexedPage struct {\n\tName     string    `json:\"name\"`\n\tFilepath string    `json:\"path\"`\n\tBody     string    `json:\"body\"`\n\tTopics   string    `json:\"topic\"`\n\tKeywords string    `json:\"keyword\"`\n\tModified time.Time `json:\"modified\"`\n}\n\nfunc openIndex(config IndexSection) (*gnosisIndex, err) {\n\tindex := new(gnosisIndex)\n\tindex.Config = config\n\tnewIndex, err := bleve.Open(path.Clean(index.Config.IndexPath))\n\tif err == nil {\n\t\tlog.Printf(\"Opening existing index %s\", index.Config.IndexName)\n\t\tindex.TrueIndex = newIndex\n\t} else if err == bleve.ErrorIndexPathDoesNotExist {\n\t\tlog.Printf(\"Creating new index %s\", index.Config.IndexName)\n\t\t\/\/ create a mapping\n\t\tindexMapping := index.buildIndexMapping()\n\t\tnewIndex, err := bleve.New(path.Clean(index.Config.IndexPath), indexMapping)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t} else {\n\t\t\tindex.TrueIndex = newIndex\n\t\t}\n\t} else {\n\t\tlog.Error(err)\n\t\treturn _, err\n\t}\n\t\/\/ You only got here if you opened an existing index, or a new index\n\tfor _, dir := range index.Config.WatchDir {\n\t\tlog.Printf(\"Watching and walking dir %s index %s\", dir, index.Config.IndexName)\n\t\twatcher := index.startWatching(dir)\n\t\tindex.openWatchers = append(index.openWatchers, watcher)\n\t\tindex.walkForIndexing(dir)\n\t}\n\treturn index\n}\n\nfunc (index *gnosisIndex) closeIndex() {\n\tfor _, watcher := range index.openWatchers {\n\t\twatcher.Close()\n\t}\n}\n\nfunc (index *gnosisIndex) buildIndexMapping() *bleve.IndexMapping {\n\n\t\/\/ create a text field type\n\tenTextFieldMapping := bleve.NewTextFieldMapping()\n\tenTextFieldMapping.Analyzer = index.Config.IndexType\n\n\t\/\/ create a date field type\n\tdateTimeMapping := bleve.NewDateTimeFieldMapping()\n\n\t\/\/ map out the wiki page\n\twikiMapping := bleve.NewDocumentMapping()\n\twikiMapping.AddFieldMappingsAt(\"path\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"body\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"topic\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"keyword\", enTextFieldMapping)\n\twikiMapping.AddFieldMappingsAt(\"modified\", dateTimeMapping)\n\n\t\/\/ add the wiki page mapping to a new index\n\tindexMapping := bleve.NewIndexMapping()\n\tindexMapping.AddDocumentMapping(index.Config.IndexName, wikiMapping)\n\tindexMapping.DefaultAnalyzer = index.Config.IndexType\n\n\treturn indexMapping\n}\n\nfunc (index *gnosisIndex) cleanupMarkdown(input []byte) []byte {\n\textensions := 0\n\trenderer := blackfridaytext.TextRenderer()\n\toutput := blackfriday.Markdown(input, renderer, extensions)\n\treturn output\n}\n\nfunc (index *gnosisIndex) relativePath(filePath string) string {\n\tfilePath = strings.TrimPrefix(filePath, index.Config.WatchDir)\n\tfilePath = path.Clean(filePath)\n\treturn filePath\n}\n\nfunc (index *gnosisIndex) generateWikiFromFile(filePath string) (*indexedPage, error) {\n\tpdata := new(PageMetadata)\n\terr := pdata.LoadPage(filePath)\n\t\/\/fileBytes, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif MatchedTag(index.Config.Restricted) == true {\n\t\treturn nil, sprintf(\"Hit a restricted page - %s\", filePath)\n\t} else {\n\tcleanedUpPage := index.cleanupMarkdown(pdata.Page)\n\ttopics, keywords := pdata.ListMeta()\n\trv := indexedPage{\n\t\tName: pdata.Title,\n\t\tBody: string(cleanedUpPage),\n\t\tFilepath: filePath,\n\t\tTopics: strings.Join(topics, \" \"),\n\t\tKeywords: strings.Join(keywords, \" \"),\n\t\tModified: pdata.FileStats.ModTime(),\n\t}\n\treturn &rv, nil\n\t}\n}\n\n\/\/ Update the entry in the index to the output from a given file\nfunc (index *gnosisIndex) processUpdate(path string) {\n\tlog.Printf(\"updated: %s\", path)\n\trp := index.relativePath(path)\n\twiki, err := index.generateWikiFromFile(path)\n\tif err != nil {\n\t\tlog.Print(err)\n\t} else {\n\t\tindex.TrueIndex.Index(rp, wiki)\n\t}\n}\n\n\/\/ Deletes a given path from the wiki entry\nfunc (index *gnosisIndex) processDelete(path string) {\n\tlog.Printf(\"delete: %s\", path)\n\trp := index.relativePath(path)\n\terr := index.TrueIndex.Delete(rp)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n}\n\n\/\/ walks a given path, and runs processUpdate on each File\nfunc (index *gnosisIndex) walkForIndexing(path string) {\n\tdirEntries, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, dirEntry := range dirEntries {\n\t\tdirEntryPath := path + string(os.PathSeparator) + dirEntry.Name()\n\t\tif dirEntry.IsDir() {\n\t\t\tindex.walkForIndexing(dirEntryPath)\n\t\t} else if strings.HasSuffix(dirEntry.Name(), index.Config.WatchExtension) {\n\t\t\tindex.processUpdate(dirEntryPath)\n\t\t}\n\t}\n}\n\n\/\/ watches a given filepath for an index for changes\nfunc (index *gnosisIndex) startWatching(filePath string) *fsnotify.Watcher {\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ maybe rework the index so the Watcher is inside the index? idk\n\n\t\/\/ start a go routine to process events\n\tgo func() {\n\t\tidleTimer := time.NewTimer(10 * time.Second)\n\t\tqueuedEvents := make([]fsnotify.Event, 0)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-watcher.Events:\n\t\t\t\tqueuedEvents = append(queuedEvents, ev)\n\t\t\t\tidleTimer.Reset(10 * time.Second)\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Fatal(err)\n\t\t\tcase <-idleTimer.C:\n\t\t\t\tfor _, ev := range queuedEvents {\n\t\t\t\t\tif strings.HasSuffix(ev.Name, index.Config.WatchExtension) {\n\t\t\t\t\t\tswitch ev.Op {\n\t\t\t\t\t\tcase fsnotify.Remove, fsnotify.Rename:\n\t\t\t\t\t\t\t\/\/ delete the filePath\n\t\t\t\t\t\t\tindex.processDelete(ev.Name)\n\t\t\t\t\t\tcase fsnotify.Create, fsnotify.Write:\n\t\t\t\t\t\t\t\/\/ update the filePath\n\t\t\t\t\t\t\tindex.processUpdate(ev.Name)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\/\/ ignore\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tqueuedEvents = make([]fsnotify.Event, 0)\n\t\t\t\tidleTimer.Reset(10 * time.Second)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ now actually watch the filePath requested\n\terr = watcher.Add(filePath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"watching '%s' for changes...\", filePath)\n\n\treturn watcher\n}\n<|endoftext|>"}
{"text":"<commit_before>package logutils\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype LogLevel string\n\n\/\/ LevelFilter is an io.Writer that can be used with a logger that\n\/\/ will filter out log messages that aren't at least a certain level.\n\/\/\n\/\/ Once the filter is in use somewhere, it is not safe to modify\n\/\/ the structure.\ntype LevelFilter struct {\n\t\/\/ Levels is the list of log levels, in increasing order of\n\t\/\/ severity. Example might be: {\"DEBUG\", \"WARN\", \"ERROR\"}.\n\tLevels []LogLevel\n\n\t\/\/ MinLevel is the minimum level allowed through\n\tMinLevel LogLevel\n\n\t\/\/ The underlying io.Writer where log messages that pass the filter\n\t\/\/ will be set.\n\tWriter io.Writer\n\n\tbadLevels map[LogLevel]struct{}\n\tonce      sync.Once\n}\n\n\/\/ Check will check a given line if it would be included in the level\n\/\/ filter.\nfunc (f *LevelFilter) Check(line []byte) bool {\n\tf.once.Do(f.init)\n\n\t\/\/ Check for a log level\n\tvar level LogLevel\n\tx := bytes.IndexByte(line, '[')\n\tif x >= 0 {\n\t\ty := bytes.IndexByte(line[x:], ']')\n\t\tif y >= 0 {\n\t\t\tlevel = LogLevel(line[x+1 : x+y])\n\t\t}\n\t}\n\n\t_, ok := f.badLevels[level]\n\treturn !ok\n}\n\nfunc (f *LevelFilter) Write(p []byte) (n int, err error) {\n\t\/\/ Note in general that io.Writer can receive any byte sequence\n\t\/\/ to write, but the \"log\" package always guarantees that we only\n\t\/\/ get a single line. We use that as a slight optimization within\n\t\/\/ this method, assuming we're dealing with a single, complete line\n\t\/\/ of log data.\n\n\tif !f.Check(p) {\n\t\treturn len(p), nil\n\t}\n\n\treturn f.Writer.Write(p)\n}\n\n\/\/ SetMinLevel is used to update the minimum log level\nfunc (f *LevelFilter) SetMinLevel(min LogLevel) {\n\tf.MinLevel = min\n\tf.init()\n}\n\nfunc (f *LevelFilter) init() {\n\tbadLevels := make(map[LogLevel]struct{})\n\tfor _, level := range f.Levels {\n\t\tif level == f.MinLevel {\n\t\t\tbreak\n\t\t}\n\t\tbadLevels[level] = struct{}{}\n\t}\n\tf.badLevels = badLevels\n}\n<commit_msg>Add package doc.<commit_after>\/\/ Package logutils augments the standard log package with levels.\npackage logutils\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype LogLevel string\n\n\/\/ LevelFilter is an io.Writer that can be used with a logger that\n\/\/ will filter out log messages that aren't at least a certain level.\n\/\/\n\/\/ Once the filter is in use somewhere, it is not safe to modify\n\/\/ the structure.\ntype LevelFilter struct {\n\t\/\/ Levels is the list of log levels, in increasing order of\n\t\/\/ severity. Example might be: {\"DEBUG\", \"WARN\", \"ERROR\"}.\n\tLevels []LogLevel\n\n\t\/\/ MinLevel is the minimum level allowed through\n\tMinLevel LogLevel\n\n\t\/\/ The underlying io.Writer where log messages that pass the filter\n\t\/\/ will be set.\n\tWriter io.Writer\n\n\tbadLevels map[LogLevel]struct{}\n\tonce      sync.Once\n}\n\n\/\/ Check will check a given line if it would be included in the level\n\/\/ filter.\nfunc (f *LevelFilter) Check(line []byte) bool {\n\tf.once.Do(f.init)\n\n\t\/\/ Check for a log level\n\tvar level LogLevel\n\tx := bytes.IndexByte(line, '[')\n\tif x >= 0 {\n\t\ty := bytes.IndexByte(line[x:], ']')\n\t\tif y >= 0 {\n\t\t\tlevel = LogLevel(line[x+1 : x+y])\n\t\t}\n\t}\n\n\t_, ok := f.badLevels[level]\n\treturn !ok\n}\n\nfunc (f *LevelFilter) Write(p []byte) (n int, err error) {\n\t\/\/ Note in general that io.Writer can receive any byte sequence\n\t\/\/ to write, but the \"log\" package always guarantees that we only\n\t\/\/ get a single line. We use that as a slight optimization within\n\t\/\/ this method, assuming we're dealing with a single, complete line\n\t\/\/ of log data.\n\n\tif !f.Check(p) {\n\t\treturn len(p), nil\n\t}\n\n\treturn f.Writer.Write(p)\n}\n\n\/\/ SetMinLevel is used to update the minimum log level\nfunc (f *LevelFilter) SetMinLevel(min LogLevel) {\n\tf.MinLevel = min\n\tf.init()\n}\n\nfunc (f *LevelFilter) init() {\n\tbadLevels := make(map[LogLevel]struct{})\n\tfor _, level := range f.Levels {\n\t\tif level == f.MinLevel {\n\t\t\tbreak\n\t\t}\n\t\tbadLevels[level] = struct{}{}\n\t}\n\tf.badLevels = badLevels\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n\tgamepkg is a package that helps locate, validate, and modify game package\n\timports.\n\n*\/\npackage gamepkg\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/path\"\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\ntype GamePkg struct {\n\t\/\/Every contstructo sets absolutePath to something that at least exists on\n\t\/\/disk.\n\tabsolutePath         string\n\timportPath           string\n\tcalculatedIsGamePkg  bool\n\tmemoizedIsGamePkg    bool\n\tmemoizedIsGamePkgErr error\n}\n\n\/\/New tries to interpret the input as an import. If that files, tries to\n\/\/interpret it as a path (rel or absolute), and if that fails, bails.\nfunc New(importOrPath string) (*GamePkg, error) {\n\tpkg, err := NewFromImport(importOrPath)\n\tif err == nil {\n\t\treturn pkg, nil\n\t}\n\treturn NewFromPath(importOrPath)\n}\n\n\/\/NewFromPath takes path (either relative or absolute path) and returns a new\n\/\/GamePkg. Will error if the given path does not appear to denote a valid game\n\/\/package for any reason.\nfunc NewFromPath(path string) (*GamePkg, error) {\n\n\tif !filepath.IsAbs(path) {\n\n\t\tcwd, err := os.Getwd()\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Couldn't get working directory: \" + err.Error())\n\t\t}\n\n\t\tpath = filepath.Join(cwd, path)\n\t}\n\n\treturn newGamePkg(path, \"\")\n\n}\n\n\/\/NewFromImport will return a new GamePkg pointing to that import. Will error\n\/\/if the given path does not appear to denote a valid game package for any\n\/\/reason.\nfunc NewFromImport(importPath string) (*GamePkg, error) {\n\n\tabsPath, err := path.AbsoluteGoPkgPath(importPath)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Absolute path couldn't be found: \" + err.Error())\n\t}\n\n\t\/\/If no error, then absPath must point to a valid thing\n\n\treturn newGamePkg(absPath, importPath)\n\n}\n\nfunc newGamePkg(absPath, importPath string) (*GamePkg, error) {\n\tresult := &GamePkg{\n\t\tabsolutePath: absPath,\n\t\timportPath:   importPath,\n\t}\n\n\tif info, err := os.Stat(absPath); err != nil {\n\t\treturn nil, errors.New(\"Path doesn't point to valid location on disk: \" + err.Error())\n\t} else if !info.IsDir() {\n\t\treturn nil, errors.New(\"Path points to an object but it's not a directory.\")\n\t}\n\n\tif !result.goPkg() {\n\t\treturn nil, errors.New(absPath + \" denotes a folder with no go source files\")\n\t}\n\n\tisGamePkg, err := result.isGamePkg()\n\n\tif !isGamePkg {\n\t\treturn nil, errors.New(absPath + \" was not a valid game package: \" + err.Error())\n\t}\n\n\treturn result, nil\n}\n\n\/\/AbsolutePath returns the absolute path where the package in question resides\n\/\/on disk. All constructors will have errored if AbsolutePath doesn't at the\n\/\/very least point to a valid location on disk.\nfunc (g *GamePkg) AbsolutePath() string {\n\treturn g.absolutePath\n}\n\n\/\/goPkg validates that the absolutePath denotes a package with at least one go\n\/\/file. If there's an error will default to false.\nfunc (g *GamePkg) goPkg() bool {\n\n\tinfos, _ := ioutil.ReadDir(g.AbsolutePath())\n\n\tfor _, info := range infos {\n\t\tif filepath.Ext(info.Name()) == \".go\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n\n}\n\n\/\/Import returns the string that could be used in your source to import this\n\/\/package.\nfunc (g *GamePkg) Import() (string, error) {\n\t\/\/Calculate it if not already calculated (for example via NewFromImport constructor)\n\tif g.importPath == \"\" {\n\n\t\tgoPkg, err := build.ImportDir(g.AbsolutePath(), 0)\n\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(\"Couldn't read package: \" + err.Error())\n\t\t}\n\n\t\t\/\/TODO: factor this into a helper that also sets the package name in\n\t\t\/\/case it's asked for later.\n\t\tg.importPath = goPkg.ImportPath\n\t}\n\n\treturn g.importPath, nil\n}\n\n\/\/isGamePkg verifies that the package appears to be a valid game package.\n\/\/Specifically it checks for\nfunc (g *GamePkg) isGamePkg() (bool, error) {\n\tif !g.calculatedIsGamePkg {\n\t\tg.memoizedIsGamePkg, g.memoizedIsGamePkgErr = g.calculateIsGamePkg()\n\t}\n\treturn g.memoizedIsGamePkg, g.memoizedIsGamePkgErr\n}\n\nfunc (g *GamePkg) calculateIsGamePkg() (bool, error) {\n\tpkgs, err := parser.ParseDir(token.NewFileSet(), g.AbsolutePath(), nil, 0)\n\n\tif err != nil {\n\t\treturn false, errors.New(\"Couldn't parse folder: \" + err.Error())\n\t}\n\n\tif len(pkgs) < 1 {\n\t\treturn false, errors.New(\"No packages in that directory\")\n\t}\n\n\tif len(pkgs) > 1 {\n\t\treturn false, errors.New(\"More than one package in that directory\")\n\t}\n\n\tvar pkg *ast.Package\n\n\tfor _, p := range pkgs {\n\t\tpkg = p\n\t}\n\n\tfoundNewDelegate := false\n\n\tfor _, file := range pkg.Files {\n\t\tfor _, decl := range file.Decls {\n\t\t\tfun, ok := decl.(*ast.FuncDecl)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fun.Name.String() != \"NewDelegate\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/OK, it might be the function. Does it have the right signature?\n\n\t\t\tif fun.Recv != nil {\n\t\t\t\treturn false, errors.New(\"NewDelegate had a receiver\")\n\t\t\t}\n\n\t\t\tif fun.Type.Params.NumFields() > 0 {\n\t\t\t\treturn false, errors.New(\"NewDelegate took more than 0 items\")\n\t\t\t}\n\n\t\t\tif fun.Type.Results.NumFields() != 1 {\n\t\t\t\treturn false, errors.New(\"NewDelegate didn't return exactly one item\")\n\t\t\t}\n\n\t\t\t\/\/TODO: check that the returned item implements\n\t\t\t\/\/boardgame.GameDelegate.\n\n\t\t\tfoundNewDelegate = true\n\t\t\tbreak\n\n\t\t}\n\n\t\tif foundNewDelegate {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !foundNewDelegate {\n\t\treturn false, errors.New(\"Couldn't find NewDelegate\")\n\t}\n\n\treturn true, nil\n}\n<commit_msg>Switch the top=level struct to be Pkg, not GamePkg. Part of #694.<commit_after>\/*\n\n\tgamepkg is a package that helps locate, validate, and modify game package\n\timports.\n\n*\/\npackage gamepkg\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/path\"\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\ntype Pkg struct {\n\t\/\/Every contstructo sets absolutePath to something that at least exists on\n\t\/\/disk.\n\tabsolutePath         string\n\timportPath           string\n\tcalculatedIsGamePkg  bool\n\tmemoizedIsGamePkg    bool\n\tmemoizedIsGamePkgErr error\n}\n\n\/\/New tries to interpret the input as an import. If that files, tries to\n\/\/interpret it as a path (rel or absolute), and if that fails, bails.\nfunc New(importOrPath string) (*Pkg, error) {\n\tpkg, err := NewFromImport(importOrPath)\n\tif err == nil {\n\t\treturn pkg, nil\n\t}\n\treturn NewFromPath(importOrPath)\n}\n\n\/\/NewFromPath takes path (either relative or absolute path) and returns a new\n\/\/Pkg. Will error if the given path does not appear to denote a valid game\n\/\/package for any reason.\nfunc NewFromPath(path string) (*Pkg, error) {\n\n\tif !filepath.IsAbs(path) {\n\n\t\tcwd, err := os.Getwd()\n\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Couldn't get working directory: \" + err.Error())\n\t\t}\n\n\t\tpath = filepath.Join(cwd, path)\n\t}\n\n\treturn newPkg(path, \"\")\n\n}\n\n\/\/NewFromImport will return a new Pkg pointing to that import. Will error\n\/\/if the given path does not appear to denote a valid game package for any\n\/\/reason.\nfunc NewFromImport(importPath string) (*Pkg, error) {\n\n\tabsPath, err := path.AbsoluteGoPkgPath(importPath)\n\n\tif err != nil {\n\t\treturn nil, errors.New(\"Absolute path couldn't be found: \" + err.Error())\n\t}\n\n\t\/\/If no error, then absPath must point to a valid thing\n\n\treturn newPkg(absPath, importPath)\n\n}\n\nfunc newPkg(absPath, importPath string) (*Pkg, error) {\n\tresult := &Pkg{\n\t\tabsolutePath: absPath,\n\t\timportPath:   importPath,\n\t}\n\n\tif info, err := os.Stat(absPath); err != nil {\n\t\treturn nil, errors.New(\"Path doesn't point to valid location on disk: \" + err.Error())\n\t} else if !info.IsDir() {\n\t\treturn nil, errors.New(\"Path points to an object but it's not a directory.\")\n\t}\n\n\tif !result.goPkg() {\n\t\treturn nil, errors.New(absPath + \" denotes a folder with no go source files\")\n\t}\n\n\tisGamePkg, err := result.isGamePkg()\n\n\tif !isGamePkg {\n\t\treturn nil, errors.New(absPath + \" was not a valid game package: \" + err.Error())\n\t}\n\n\treturn result, nil\n}\n\n\/\/AbsolutePath returns the absolute path where the package in question resides\n\/\/on disk. All constructors will have errored if AbsolutePath doesn't at the\n\/\/very least point to a valid location on disk.\nfunc (p *Pkg) AbsolutePath() string {\n\treturn p.absolutePath\n}\n\n\/\/goPkg validates that the absolutePath denotes a package with at least one go\n\/\/file. If there's an error will default to false.\nfunc (g *Pkg) goPkg() bool {\n\n\tinfos, _ := ioutil.ReadDir(g.AbsolutePath())\n\n\tfor _, info := range infos {\n\t\tif filepath.Ext(info.Name()) == \".go\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n\n}\n\n\/\/Import returns the string that could be used in your source to import this\n\/\/package.\nfunc (p *Pkg) Import() (string, error) {\n\t\/\/Calculate it if not already calculated (for example via NewFromImport constructor)\n\tif p.importPath == \"\" {\n\n\t\tgoPkg, err := build.ImportDir(p.AbsolutePath(), 0)\n\n\t\tif err != nil {\n\t\t\treturn \"\", errors.New(\"Couldn't read package: \" + err.Error())\n\t\t}\n\n\t\t\/\/TODO: factor this into a helper that also sets the package name in\n\t\t\/\/case it's asked for later.\n\t\tp.importPath = goPkg.ImportPath\n\t}\n\n\treturn p.importPath, nil\n}\n\n\/\/isPkg verifies that the package appears to be a valid game package.\n\/\/Specifically it checks for\nfunc (g *Pkg) isGamePkg() (bool, error) {\n\tif !g.calculatedIsGamePkg {\n\t\tg.memoizedIsGamePkg, g.memoizedIsGamePkgErr = g.calculateIsGamePkg()\n\t}\n\treturn g.memoizedIsGamePkg, g.memoizedIsGamePkgErr\n}\n\nfunc (g *Pkg) calculateIsGamePkg() (bool, error) {\n\tpkgs, err := parser.ParseDir(token.NewFileSet(), g.AbsolutePath(), nil, 0)\n\n\tif err != nil {\n\t\treturn false, errors.New(\"Couldn't parse folder: \" + err.Error())\n\t}\n\n\tif len(pkgs) < 1 {\n\t\treturn false, errors.New(\"No packages in that directory\")\n\t}\n\n\tif len(pkgs) > 1 {\n\t\treturn false, errors.New(\"More than one package in that directory\")\n\t}\n\n\tvar pkg *ast.Package\n\n\tfor _, p := range pkgs {\n\t\tpkg = p\n\t}\n\n\tfoundNewDelegate := false\n\n\tfor _, file := range pkg.Files {\n\t\tfor _, decl := range file.Decls {\n\t\t\tfun, ok := decl.(*ast.FuncDecl)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif fun.Name.String() != \"NewDelegate\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/OK, it might be the function. Does it have the right signature?\n\n\t\t\tif fun.Recv != nil {\n\t\t\t\treturn false, errors.New(\"NewDelegate had a receiver\")\n\t\t\t}\n\n\t\t\tif fun.Type.Params.NumFields() > 0 {\n\t\t\t\treturn false, errors.New(\"NewDelegate took more than 0 items\")\n\t\t\t}\n\n\t\t\tif fun.Type.Results.NumFields() != 1 {\n\t\t\t\treturn false, errors.New(\"NewDelegate didn't return exactly one item\")\n\t\t\t}\n\n\t\t\t\/\/TODO: check that the returned item implements\n\t\t\t\/\/boardgame.GameDelegate.\n\n\t\t\tfoundNewDelegate = true\n\t\t\tbreak\n\n\t\t}\n\n\t\tif foundNewDelegate {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !foundNewDelegate {\n\t\treturn false, errors.New(\"Couldn't find NewDelegate\")\n\t}\n\n\treturn true, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The present-tex 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\"image\"\n\t\"os\"\n\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\n\t_ \"golang.org\/x\/image\/bmp\"\n\t_ \"golang.org\/x\/image\/tiff\"\n\t_ \"golang.org\/x\/image\/vp8\"\n\t_ \"golang.org\/x\/image\/webp\"\n\n\t\"golang.org\/x\/tools\/present\"\n\t\"golang.org\/x\/xerrors\"\n)\n\ntype Image struct {\n\tpresent.Image\n\tHasCaption bool\n\tCaption    present.Caption\n}\n\nfunc parseImages(doc *present.Doc) error {\n\tvar err error\n\tfor i := range doc.Sections {\n\t\tsection := &doc.Sections[i]\n\t\tfor j := range section.Elem {\n\t\t\telem := section.Elem[j]\n\t\t\tswitch elem := elem.(type) {\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\tcase present.Image:\n\t\t\t\terr = parseImage(&elem)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn xerrors.Errorf(\"could not parse image %w: %w\", elem.URL, err)\n\t\t\t\t}\n\t\t\t\timg := Image{Image: elem}\n\t\t\t\tif j+1 < len(section.Elem) {\n\t\t\t\t\tif elem, ok := section.Elem[j+1].(present.Caption); ok {\n\t\t\t\t\t\terr = parseCaption(&elem)\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\timg.HasCaption = true\n\t\t\t\t\t\timg.Caption = elem\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsection.Elem[j] = img\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"could not parse images: %w\", err)\n\t}\n\n\treturn parseCaptions(doc)\n}\n\nfunc parseImage(elem *present.Image) error {\n\tvar err error\n\n\tif elem.Height == 0 || elem.Width == 0 {\n\t\tf, err := os.Open(elem.URL)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\n\t\t\t\t\"error opening file [%s]: %w\",\n\t\t\t\telem.URL,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\t\tdefer f.Close()\n\t\timg, _, err := image.Decode(f)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\n\t\t\t\t\"error decoding image file [%s]: %w\",\n\t\t\t\telem.URL,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\t\th := img.Bounds().Dy()\n\t\tw := img.Bounds().Dx()\n\n\t\tswitch {\n\t\tcase elem.Height == 0 && elem.Width == 0:\n\t\t\telem.Height = h\n\t\t\telem.Width = w\n\t\tcase elem.Height == 0 && elem.Width != 0:\n\t\t\t\/\/ rescale, keeping ratio\n\t\t\tratio := float64(elem.Width) \/ float64(w)\n\t\t\telem.Height = int(float64(h) * ratio)\n\t\tcase elem.Height != 0 && elem.Width == 0:\n\t\t\t\/\/ rescale, keeping ratio\n\t\t\tratio := float64(elem.Height) \/ float64(h)\n\t\t\telem.Width = int(float64(w) * ratio)\n\n\t\t}\n\n\t}\n\n\t\/\/ rescale height\/width to a (default=72) DPI resolution\n\t\/\/ height and width are now in inches.\n\telem.Height \/= *dpi\n\telem.Width \/= *dpi\n\n\treturn err\n}\n<commit_msg>image: add support for SVG<commit_after>\/\/ Copyright 2015 The present-tex 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\"image\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\n\t_ \"golang.org\/x\/image\/bmp\"\n\t_ \"golang.org\/x\/image\/tiff\"\n\t_ \"golang.org\/x\/image\/vp8\"\n\t_ \"golang.org\/x\/image\/webp\"\n\n\t\"golang.org\/x\/tools\/present\"\n\t\"golang.org\/x\/xerrors\"\n)\n\ntype Image struct {\n\tpresent.Image\n\tHasCaption bool\n\tCaption    present.Caption\n}\n\nfunc parseImages(doc *present.Doc) error {\n\tvar err error\n\tfor i := range doc.Sections {\n\t\tsection := &doc.Sections[i]\n\t\tfor j := range section.Elem {\n\t\t\telem := section.Elem[j]\n\t\t\tswitch elem := elem.(type) {\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\tcase present.Image:\n\t\t\t\terr = parseImage(&elem)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn xerrors.Errorf(\"could not parse image %w: %w\", elem.URL, err)\n\t\t\t\t}\n\t\t\t\timg := Image{Image: elem}\n\t\t\t\tif j+1 < len(section.Elem) {\n\t\t\t\t\tif elem, ok := section.Elem[j+1].(present.Caption); ok {\n\t\t\t\t\t\terr = parseCaption(&elem)\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\timg.HasCaption = true\n\t\t\t\t\t\timg.Caption = elem\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsection.Elem[j] = img\n\t\t\t}\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn xerrors.Errorf(\"could not parse images: %w\", err)\n\t}\n\n\treturn parseCaptions(doc)\n}\n\nfunc parseImage(elem *present.Image) error {\n\tvar err error\n\n\tif strings.HasSuffix(elem.URL, \".svg\") {\n\t\toname := elem.URL[:len(elem.URL)-len(\".svg\")] + \"_svg.png\"\n\t\terr := exec.Command(\"convert\", elem.URL, oname).Run()\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\n\t\t\t\t\"could not convert SVG image %q to PNG: %w\",\n\t\t\t\telem.URL, err,\n\t\t\t)\n\t\t}\n\t\telem.URL = oname\n\t}\n\n\tif elem.Height == 0 || elem.Width == 0 {\n\t\tf, err := os.Open(elem.URL)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\n\t\t\t\t\"error opening file [%s]: %w\",\n\t\t\t\telem.URL,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\t\tdefer f.Close()\n\t\timg, _, err := image.Decode(f)\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\n\t\t\t\t\"error decoding image file [%s]: %w\",\n\t\t\t\telem.URL,\n\t\t\t\terr,\n\t\t\t)\n\t\t}\n\t\th := img.Bounds().Dy()\n\t\tw := img.Bounds().Dx()\n\n\t\tswitch {\n\t\tcase elem.Height == 0 && elem.Width == 0:\n\t\t\telem.Height = h\n\t\t\telem.Width = w\n\t\tcase elem.Height == 0 && elem.Width != 0:\n\t\t\t\/\/ rescale, keeping ratio\n\t\t\tratio := float64(elem.Width) \/ float64(w)\n\t\t\telem.Height = int(float64(h) * ratio)\n\t\tcase elem.Height != 0 && elem.Width == 0:\n\t\t\t\/\/ rescale, keeping ratio\n\t\t\tratio := float64(elem.Height) \/ float64(h)\n\t\t\telem.Width = int(float64(w) * ratio)\n\n\t\t}\n\n\t}\n\n\t\/\/ rescale height\/width to a (default=72) DPI resolution\n\t\/\/ height and width are now in inches.\n\telem.Height \/= *dpi\n\telem.Width \/= *dpi\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The draw2d Authors. All rights reserved.\n\/\/ created: 21\/11\/2010 by Laurent Le Goff\n\npackage draw2d\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"log\"\n\t\"math\"\n\n\t\"code.google.com\/p\/freetype-go\/freetype\/raster\"\n\t\"code.google.com\/p\/freetype-go\/freetype\/truetype\"\n)\n\ntype Painter interface {\n\traster.Painter\n\tSetColor(color color.Color)\n}\n\nvar (\n\tdefaultFontData = FontData{\"luxi\", FontFamilySans, FontStyleNormal}\n)\n\ntype ImageGraphicContext struct {\n\t*StackGraphicContext\n\timg              draw.Image\n\tpainter          Painter\n\tfillRasterizer   *raster.Rasterizer\n\tstrokeRasterizer *raster.Rasterizer\n\tglyphBuf         *truetype.GlyphBuf\n\tDPI              int\n}\n\n\/**\n * Create a new Graphic context from an image\n *\/\nfunc NewGraphicContext(img draw.Image) *ImageGraphicContext {\n\tvar painter Painter\n\tswitch selectImage := img.(type) {\n\tcase *image.RGBA:\n\t\tpainter = raster.NewRGBAPainter(selectImage)\n\tdefault:\n\t\tpanic(\"Image type not supported\")\n\t}\n\treturn NewGraphicContextWithPainter(img, painter)\n}\n\n\/\/ Create a new Graphic context from an image and a Painter (see Freetype-go)\nfunc NewGraphicContextWithPainter(img draw.Image, painter Painter) *ImageGraphicContext {\n\twidth, height := img.Bounds().Dx(), img.Bounds().Dy()\n\tdpi := 92\n\tgc := &ImageGraphicContext{\n\t\tNewStackGraphicContext(),\n\t\timg,\n\t\tpainter,\n\t\traster.NewRasterizer(width, height),\n\t\traster.NewRasterizer(width, height),\n\t\ttruetype.NewGlyphBuf(),\n\t\tdpi,\n\t}\n\treturn gc\n}\n\nfunc (gc *ImageGraphicContext) GetDPI() int {\n\treturn gc.DPI\n}\n\nfunc (gc *ImageGraphicContext) Clear() {\n\twidth, height := gc.img.Bounds().Dx(), gc.img.Bounds().Dy()\n\tgc.ClearRect(0, 0, width, height)\n}\n\nfunc (gc *ImageGraphicContext) ClearRect(x1, y1, x2, y2 int) {\n\timageColor := image.NewUniform(gc.Current.FillColor)\n\tdraw.Draw(gc.img, image.Rect(x1, y1, x2, y2), imageColor, image.ZP, draw.Over)\n}\n\nfunc (gc *ImageGraphicContext) DrawImage(img image.Image) {\n\tDrawImage(img, gc.img, gc.Current.Tr, draw.Over, BilinearFilter)\n}\n\nfunc (gc *ImageGraphicContext) FillString(text string) (cursor float64) {\n\treturn gc.FillStringAt(text, 0, 0)\n}\n\nfunc (gc *ImageGraphicContext) FillStringAt(text string, x, y float64) (cursor float64) {\n\twidth := gc.CreateStringPath(text, x, y)\n\tgc.Fill()\n\treturn width\n}\n\nfunc (gc *ImageGraphicContext) StrokeString(text string) (cursor float64) {\n\treturn gc.StrokeStringAt(text, 0, 0)\n}\n\nfunc (gc *ImageGraphicContext) StrokeStringAt(text string, x, y float64) (cursor float64) {\n\twidth := gc.CreateStringPath(text, x, y)\n\tgc.Stroke()\n\treturn width\n}\n\nfunc (gc *ImageGraphicContext) loadCurrentFont() (*truetype.Font, error) {\n\tfont := GetFont(gc.Current.FontData)\n\tif font == nil {\n\t\tfont = GetFont(defaultFontData)\n\t}\n\tif font == nil {\n\t\treturn nil, errors.New(\"No font set, and no default font available.\")\n\t}\n\tgc.SetFont(font)\n\tgc.SetFontSize(gc.Current.FontSize)\n\treturn font, nil\n}\n\nfunc fUnitsToFloat64(x int32) float64 {\n\tscaled := x << 2\n\treturn float64(scaled\/256) + float64(scaled%256)\/256.0\n}\n\n\/\/ p is a truetype.Point measured in FUnits and positive Y going upwards.\n\/\/ The returned value is the same thing measured in floating point and positive Y\n\/\/ going downwards.\nfunc pointToF64Point(p truetype.Point) (x, y float64) {\n\treturn fUnitsToFloat64(p.X), -fUnitsToFloat64(p.Y)\n}\n\n\/\/ drawContour draws the given closed contour at the given sub-pixel offset.\nfunc (gc *ImageGraphicContext) drawContour(ps []truetype.Point, dx, dy float64) {\n\tif len(ps) == 0 {\n\t\treturn\n\t}\n\tstartX, startY := pointToF64Point(ps[0])\n\tgc.MoveTo(startX+dx, startY+dy)\n\tq0X, q0Y, on0 := startX, startY, true\n\tfor _, p := range ps[1:] {\n\t\tqX, qY := pointToF64Point(p)\n\t\ton := p.Flags&0x01 != 0\n\t\tif on {\n\t\t\tif on0 {\n\t\t\t\tgc.LineTo(qX+dx, qY+dy)\n\t\t\t} else {\n\t\t\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, qX+dx, qY+dy)\n\t\t\t}\n\t\t} else {\n\t\t\tif on0 {\n\t\t\t\t\/\/ No-op.\n\t\t\t} else {\n\t\t\t\tmidX := (q0X + qX) \/ 2\n\t\t\t\tmidY := (q0Y + qY) \/ 2\n\t\t\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, midX+dx, midY+dy)\n\t\t\t}\n\t\t}\n\t\tq0X, q0Y, on0 = qX, qY, on\n\t}\n\t\/\/ Close the curve.\n\tif on0 {\n\t\tgc.LineTo(startX+dx, startY+dy)\n\t} else {\n\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, startX+dx, startY+dy)\n\t}\n}\n\nfunc (gc *ImageGraphicContext) drawGlyph(glyph truetype.Index, dx, dy float64) error {\n\tif err := gc.glyphBuf.Load(gc.Current.Font, int32(gc.Current.Scale), glyph, truetype.NoHinting); err != nil {\n\t\treturn err\n\t}\n\te0 := 0\n\tfor _, e1 := range gc.glyphBuf.End {\n\t\tgc.drawContour(gc.glyphBuf.Point[e0:e1], dx, dy)\n\t\te0 = e1\n\t}\n\treturn nil\n}\n\n\/\/ CreateStringPath creates a path from the string s at x, y, and returns the string width.\n\/\/ The text is placed so that the left edge of the em square of the first character of s\n\/\/ and the baseline intersect at x, y. The majority of the affected pixels will be\n\/\/ above and to the right of the point, but some may be below or to the left.\n\/\/ For example, drawing a string that starts with a 'J' in an italic font may\n\/\/ affect pixels below and left of the point.\nfunc (gc *ImageGraphicContext) CreateStringPath(s string, x, y float64) float64 {\n\tfont, err := gc.loadCurrentFont()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0.0\n\t}\n\tstartx := x\n\tprev, hasPrev := truetype.Index(0), false\n\tfor _, rune := range s {\n\t\tindex := font.Index(rune)\n\t\tif hasPrev {\n\t\t\tx += fUnitsToFloat64(font.Kerning(int32(gc.Current.Scale), prev, index))\n\t\t}\n\t\terr := gc.drawGlyph(index, x, y)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn startx - x\n\t\t}\n\t\tx += fUnitsToFloat64(font.HMetric(int32(gc.Current.Scale), index).AdvanceWidth)\n\t\tprev, hasPrev = index, true\n\t}\n\treturn x - startx\n}\n\n\/\/ GetStringBounds returns the approximate pixel bounds of the string s at x, y.\n\/\/ The the left edge of the em square of the first character of s\n\/\/ and the baseline intersect at 0, 0 in the returned coordinates.\n\/\/ Therefore the top and left coordinates may well be negative.\nfunc (gc *ImageGraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {\n\tfont, err := gc.loadCurrentFont()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, 0, 0, 0\n\t}\n\ttop, left, bottom, right = 10e6, 10e6, -10e6, -10e6\n\tcursor := 0.0\n\tprev, hasPrev := truetype.Index(0), false\n\tfor _, rune := range s {\n\t\tindex := font.Index(rune)\n\t\tif hasPrev {\n\t\t\tcursor += fUnitsToFloat64(font.Kerning(int32(gc.Current.Scale), prev, index))\n\t\t}\n\t\tif err := gc.glyphBuf.Load(gc.Current.Font, int32(gc.Current.Scale), index, truetype.NoHinting); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn 0, 0, 0, 0\n\t\t}\n\t\te0 := 0\n\t\tfor _, e1 := range gc.glyphBuf.End {\n\t\t\tps := gc.glyphBuf.Point[e0:e1]\n\t\t\tfor _, p := range ps {\n\t\t\t\tx, y := pointToF64Point(p)\n\t\t\t\ttop = math.Min(top, y)\n\t\t\t\tbottom = math.Max(bottom, y)\n\t\t\t\tleft = math.Min(left, x+cursor)\n\t\t\t\tright = math.Max(right, x+cursor)\n\t\t\t}\n\t\t}\n\t\tcursor += fUnitsToFloat64(font.HMetric(int32(gc.Current.Scale), index).AdvanceWidth)\n\t\tprev, hasPrev = index, true\n\t}\n\treturn left, top, right, bottom\n}\n\n\/\/ recalc recalculates scale and bounds values from the font size, screen\n\/\/ resolution and font metrics, and invalidates the glyph cache.\nfunc (gc *ImageGraphicContext) recalc() {\n\tint32(gc.Current.Scale) = int32(gc.Current.FontSize * float64(gc.DPI) * (64.0 \/ 72.0))\n}\n\n\/\/ SetDPI sets the screen resolution in dots per inch.\nfunc (gc *ImageGraphicContext) SetDPI(dpi int) {\n\tgc.DPI = dpi\n\tgc.recalc()\n}\n\n\/\/ SetFont sets the font used to draw text.\nfunc (gc *ImageGraphicContext) SetFont(font *truetype.Font) {\n\tgc.Current.Font = font\n}\n\n\/\/ SetFontSize sets the font size in points (as in ``a 12 point font'').\nfunc (gc *ImageGraphicContext) SetFontSize(fontSize float64) {\n\tgc.Current.FontSize = fontSize\n\tgc.recalc()\n}\n\nfunc (gc *ImageGraphicContext) paint(rasterizer *raster.Rasterizer, color color.Color) {\n\tgc.painter.SetColor(color)\n\trasterizer.Rasterize(gc.painter)\n\trasterizer.Clear()\n\tgc.Current.Path.Clear()\n}\n\n\/**** second method ****\/\nfunc (gc *ImageGraphicContext) Stroke(paths ...*PathStorage) {\n\tpaths = append(paths, gc.Current.Path)\n\tgc.strokeRasterizer.UseNonZeroWinding = true\n\n\tstroker := NewLineStroker(gc.Current.Cap, gc.Current.Join, NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.strokeRasterizer)))\n\tstroker.HalfLineWidth = gc.Current.LineWidth \/ 2\n\tvar pathConverter *PathConverter\n\tif gc.Current.Dash != nil && len(gc.Current.Dash) > 0 {\n\t\tdasher := NewDashConverter(gc.Current.Dash, gc.Current.DashOffset, stroker)\n\t\tpathConverter = NewPathConverter(dasher)\n\t} else {\n\t\tpathConverter = NewPathConverter(stroker)\n\t}\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.strokeRasterizer, gc.Current.StrokeColor)\n}\n\n\/**** second method ****\/\nfunc (gc *ImageGraphicContext) Fill(paths ...*PathStorage) {\n\tpaths = append(paths, gc.Current.Path)\n\tgc.fillRasterizer.UseNonZeroWinding = gc.Current.FillRule.UseNonZeroWinding()\n\n\t\/**** first method ****\/\n\tpathConverter := NewPathConverter(NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.fillRasterizer)))\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.fillRasterizer, gc.Current.FillColor)\n}\n\n\/* second method *\/\nfunc (gc *ImageGraphicContext) FillStroke(paths ...*PathStorage) {\n\tgc.fillRasterizer.UseNonZeroWinding = gc.Current.FillRule.UseNonZeroWinding()\n\tgc.strokeRasterizer.UseNonZeroWinding = true\n\n\tfiller := NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.fillRasterizer))\n\n\tstroker := NewLineStroker(gc.Current.Cap, gc.Current.Join, NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.strokeRasterizer)))\n\tstroker.HalfLineWidth = gc.Current.LineWidth \/ 2\n\n\tdemux := NewDemuxConverter(filler, stroker)\n\tpaths = append(paths, gc.Current.Path)\n\tpathConverter := NewPathConverter(demux)\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.fillRasterizer, gc.Current.FillColor)\n\tgc.paint(gc.strokeRasterizer, gc.Current.StrokeColor)\n}\n\nfunc (f FillRule) UseNonZeroWinding() bool {\n\tswitch f {\n\tcase FillRuleEvenOdd:\n\t\treturn false\n\tcase FillRuleWinding:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c Cap) Convert() raster.Capper {\n\tswitch c {\n\tcase RoundCap:\n\t\treturn raster.RoundCapper\n\tcase ButtCap:\n\t\treturn raster.ButtCapper\n\tcase SquareCap:\n\t\treturn raster.SquareCapper\n\t}\n\treturn raster.RoundCapper\n}\n\nfunc (j Join) Convert() raster.Joiner {\n\tswitch j {\n\tcase RoundJoin:\n\t\treturn raster.RoundJoiner\n\tcase BevelJoin:\n\t\treturn raster.BevelJoiner\n\t}\n\treturn raster.RoundJoiner\n}\n<commit_msg>fix recalc<commit_after>\/\/ Copyright 2010 The draw2d Authors. All rights reserved.\n\/\/ created: 21\/11\/2010 by Laurent Le Goff\n\npackage draw2d\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"log\"\n\t\"math\"\n\n\t\"code.google.com\/p\/freetype-go\/freetype\/raster\"\n\t\"code.google.com\/p\/freetype-go\/freetype\/truetype\"\n)\n\ntype Painter interface {\n\traster.Painter\n\tSetColor(color color.Color)\n}\n\nvar (\n\tdefaultFontData = FontData{\"luxi\", FontFamilySans, FontStyleNormal}\n)\n\ntype ImageGraphicContext struct {\n\t*StackGraphicContext\n\timg              draw.Image\n\tpainter          Painter\n\tfillRasterizer   *raster.Rasterizer\n\tstrokeRasterizer *raster.Rasterizer\n\tglyphBuf         *truetype.GlyphBuf\n\tDPI              int\n}\n\n\/**\n * Create a new Graphic context from an image\n *\/\nfunc NewGraphicContext(img draw.Image) *ImageGraphicContext {\n\tvar painter Painter\n\tswitch selectImage := img.(type) {\n\tcase *image.RGBA:\n\t\tpainter = raster.NewRGBAPainter(selectImage)\n\tdefault:\n\t\tpanic(\"Image type not supported\")\n\t}\n\treturn NewGraphicContextWithPainter(img, painter)\n}\n\n\/\/ Create a new Graphic context from an image and a Painter (see Freetype-go)\nfunc NewGraphicContextWithPainter(img draw.Image, painter Painter) *ImageGraphicContext {\n\twidth, height := img.Bounds().Dx(), img.Bounds().Dy()\n\tdpi := 92\n\tgc := &ImageGraphicContext{\n\t\tNewStackGraphicContext(),\n\t\timg,\n\t\tpainter,\n\t\traster.NewRasterizer(width, height),\n\t\traster.NewRasterizer(width, height),\n\t\ttruetype.NewGlyphBuf(),\n\t\tdpi,\n\t}\n\treturn gc\n}\n\nfunc (gc *ImageGraphicContext) GetDPI() int {\n\treturn gc.DPI\n}\n\nfunc (gc *ImageGraphicContext) Clear() {\n\twidth, height := gc.img.Bounds().Dx(), gc.img.Bounds().Dy()\n\tgc.ClearRect(0, 0, width, height)\n}\n\nfunc (gc *ImageGraphicContext) ClearRect(x1, y1, x2, y2 int) {\n\timageColor := image.NewUniform(gc.Current.FillColor)\n\tdraw.Draw(gc.img, image.Rect(x1, y1, x2, y2), imageColor, image.ZP, draw.Over)\n}\n\nfunc (gc *ImageGraphicContext) DrawImage(img image.Image) {\n\tDrawImage(img, gc.img, gc.Current.Tr, draw.Over, BilinearFilter)\n}\n\nfunc (gc *ImageGraphicContext) FillString(text string) (cursor float64) {\n\treturn gc.FillStringAt(text, 0, 0)\n}\n\nfunc (gc *ImageGraphicContext) FillStringAt(text string, x, y float64) (cursor float64) {\n\twidth := gc.CreateStringPath(text, x, y)\n\tgc.Fill()\n\treturn width\n}\n\nfunc (gc *ImageGraphicContext) StrokeString(text string) (cursor float64) {\n\treturn gc.StrokeStringAt(text, 0, 0)\n}\n\nfunc (gc *ImageGraphicContext) StrokeStringAt(text string, x, y float64) (cursor float64) {\n\twidth := gc.CreateStringPath(text, x, y)\n\tgc.Stroke()\n\treturn width\n}\n\nfunc (gc *ImageGraphicContext) loadCurrentFont() (*truetype.Font, error) {\n\tfont := GetFont(gc.Current.FontData)\n\tif font == nil {\n\t\tfont = GetFont(defaultFontData)\n\t}\n\tif font == nil {\n\t\treturn nil, errors.New(\"No font set, and no default font available.\")\n\t}\n\tgc.SetFont(font)\n\tgc.SetFontSize(gc.Current.FontSize)\n\treturn font, nil\n}\n\nfunc fUnitsToFloat64(x int32) float64 {\n\tscaled := x << 2\n\treturn float64(scaled\/256) + float64(scaled%256)\/256.0\n}\n\n\/\/ p is a truetype.Point measured in FUnits and positive Y going upwards.\n\/\/ The returned value is the same thing measured in floating point and positive Y\n\/\/ going downwards.\nfunc pointToF64Point(p truetype.Point) (x, y float64) {\n\treturn fUnitsToFloat64(p.X), -fUnitsToFloat64(p.Y)\n}\n\n\/\/ drawContour draws the given closed contour at the given sub-pixel offset.\nfunc (gc *ImageGraphicContext) drawContour(ps []truetype.Point, dx, dy float64) {\n\tif len(ps) == 0 {\n\t\treturn\n\t}\n\tstartX, startY := pointToF64Point(ps[0])\n\tgc.MoveTo(startX+dx, startY+dy)\n\tq0X, q0Y, on0 := startX, startY, true\n\tfor _, p := range ps[1:] {\n\t\tqX, qY := pointToF64Point(p)\n\t\ton := p.Flags&0x01 != 0\n\t\tif on {\n\t\t\tif on0 {\n\t\t\t\tgc.LineTo(qX+dx, qY+dy)\n\t\t\t} else {\n\t\t\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, qX+dx, qY+dy)\n\t\t\t}\n\t\t} else {\n\t\t\tif on0 {\n\t\t\t\t\/\/ No-op.\n\t\t\t} else {\n\t\t\t\tmidX := (q0X + qX) \/ 2\n\t\t\t\tmidY := (q0Y + qY) \/ 2\n\t\t\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, midX+dx, midY+dy)\n\t\t\t}\n\t\t}\n\t\tq0X, q0Y, on0 = qX, qY, on\n\t}\n\t\/\/ Close the curve.\n\tif on0 {\n\t\tgc.LineTo(startX+dx, startY+dy)\n\t} else {\n\t\tgc.QuadCurveTo(q0X+dx, q0Y+dy, startX+dx, startY+dy)\n\t}\n}\n\nfunc (gc *ImageGraphicContext) drawGlyph(glyph truetype.Index, dx, dy float64) error {\n\tif err := gc.glyphBuf.Load(gc.Current.Font, int32(gc.Current.Scale), glyph, truetype.NoHinting); err != nil {\n\t\treturn err\n\t}\n\te0 := 0\n\tfor _, e1 := range gc.glyphBuf.End {\n\t\tgc.drawContour(gc.glyphBuf.Point[e0:e1], dx, dy)\n\t\te0 = e1\n\t}\n\treturn nil\n}\n\n\/\/ CreateStringPath creates a path from the string s at x, y, and returns the string width.\n\/\/ The text is placed so that the left edge of the em square of the first character of s\n\/\/ and the baseline intersect at x, y. The majority of the affected pixels will be\n\/\/ above and to the right of the point, but some may be below or to the left.\n\/\/ For example, drawing a string that starts with a 'J' in an italic font may\n\/\/ affect pixels below and left of the point.\nfunc (gc *ImageGraphicContext) CreateStringPath(s string, x, y float64) float64 {\n\tfont, err := gc.loadCurrentFont()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0.0\n\t}\n\tstartx := x\n\tprev, hasPrev := truetype.Index(0), false\n\tfor _, rune := range s {\n\t\tindex := font.Index(rune)\n\t\tif hasPrev {\n\t\t\tx += fUnitsToFloat64(font.Kerning(int32(gc.Current.Scale), prev, index))\n\t\t}\n\t\terr := gc.drawGlyph(index, x, y)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn startx - x\n\t\t}\n\t\tx += fUnitsToFloat64(font.HMetric(int32(gc.Current.Scale), index).AdvanceWidth)\n\t\tprev, hasPrev = index, true\n\t}\n\treturn x - startx\n}\n\n\/\/ GetStringBounds returns the approximate pixel bounds of the string s at x, y.\n\/\/ The the left edge of the em square of the first character of s\n\/\/ and the baseline intersect at 0, 0 in the returned coordinates.\n\/\/ Therefore the top and left coordinates may well be negative.\nfunc (gc *ImageGraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {\n\tfont, err := gc.loadCurrentFont()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn 0, 0, 0, 0\n\t}\n\ttop, left, bottom, right = 10e6, 10e6, -10e6, -10e6\n\tcursor := 0.0\n\tprev, hasPrev := truetype.Index(0), false\n\tfor _, rune := range s {\n\t\tindex := font.Index(rune)\n\t\tif hasPrev {\n\t\t\tcursor += fUnitsToFloat64(font.Kerning(int32(gc.Current.Scale), prev, index))\n\t\t}\n\t\tif err := gc.glyphBuf.Load(gc.Current.Font, int32(gc.Current.Scale), index, truetype.NoHinting); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn 0, 0, 0, 0\n\t\t}\n\t\te0 := 0\n\t\tfor _, e1 := range gc.glyphBuf.End {\n\t\t\tps := gc.glyphBuf.Point[e0:e1]\n\t\t\tfor _, p := range ps {\n\t\t\t\tx, y := pointToF64Point(p)\n\t\t\t\ttop = math.Min(top, y)\n\t\t\t\tbottom = math.Max(bottom, y)\n\t\t\t\tleft = math.Min(left, x+cursor)\n\t\t\t\tright = math.Max(right, x+cursor)\n\t\t\t}\n\t\t}\n\t\tcursor += fUnitsToFloat64(font.HMetric(int32(gc.Current.Scale), index).AdvanceWidth)\n\t\tprev, hasPrev = index, true\n\t}\n\treturn left, top, right, bottom\n}\n\n\/\/ recalc recalculates scale and bounds values from the font size, screen\n\/\/ resolution and font metrics, and invalidates the glyph cache.\nfunc (gc *ImageGraphicContext) recalc() {\n\tgc.Current.Scale = gc.Current.FontSize * float64(gc.DPI) * (64.0 \/ 72.0)\n}\n\n\/\/ SetDPI sets the screen resolution in dots per inch.\nfunc (gc *ImageGraphicContext) SetDPI(dpi int) {\n\tgc.DPI = dpi\n\tgc.recalc()\n}\n\n\/\/ SetFont sets the font used to draw text.\nfunc (gc *ImageGraphicContext) SetFont(font *truetype.Font) {\n\tgc.Current.Font = font\n}\n\n\/\/ SetFontSize sets the font size in points (as in ``a 12 point font'').\nfunc (gc *ImageGraphicContext) SetFontSize(fontSize float64) {\n\tgc.Current.FontSize = fontSize\n\tgc.recalc()\n}\n\nfunc (gc *ImageGraphicContext) paint(rasterizer *raster.Rasterizer, color color.Color) {\n\tgc.painter.SetColor(color)\n\trasterizer.Rasterize(gc.painter)\n\trasterizer.Clear()\n\tgc.Current.Path.Clear()\n}\n\n\/**** second method ****\/\nfunc (gc *ImageGraphicContext) Stroke(paths ...*PathStorage) {\n\tpaths = append(paths, gc.Current.Path)\n\tgc.strokeRasterizer.UseNonZeroWinding = true\n\n\tstroker := NewLineStroker(gc.Current.Cap, gc.Current.Join, NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.strokeRasterizer)))\n\tstroker.HalfLineWidth = gc.Current.LineWidth \/ 2\n\tvar pathConverter *PathConverter\n\tif gc.Current.Dash != nil && len(gc.Current.Dash) > 0 {\n\t\tdasher := NewDashConverter(gc.Current.Dash, gc.Current.DashOffset, stroker)\n\t\tpathConverter = NewPathConverter(dasher)\n\t} else {\n\t\tpathConverter = NewPathConverter(stroker)\n\t}\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.strokeRasterizer, gc.Current.StrokeColor)\n}\n\n\/**** second method ****\/\nfunc (gc *ImageGraphicContext) Fill(paths ...*PathStorage) {\n\tpaths = append(paths, gc.Current.Path)\n\tgc.fillRasterizer.UseNonZeroWinding = gc.Current.FillRule.UseNonZeroWinding()\n\n\t\/**** first method ****\/\n\tpathConverter := NewPathConverter(NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.fillRasterizer)))\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.fillRasterizer, gc.Current.FillColor)\n}\n\n\/* second method *\/\nfunc (gc *ImageGraphicContext) FillStroke(paths ...*PathStorage) {\n\tgc.fillRasterizer.UseNonZeroWinding = gc.Current.FillRule.UseNonZeroWinding()\n\tgc.strokeRasterizer.UseNonZeroWinding = true\n\n\tfiller := NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.fillRasterizer))\n\n\tstroker := NewLineStroker(gc.Current.Cap, gc.Current.Join, NewVertexMatrixTransform(gc.Current.Tr, NewVertexAdder(gc.strokeRasterizer)))\n\tstroker.HalfLineWidth = gc.Current.LineWidth \/ 2\n\n\tdemux := NewDemuxConverter(filler, stroker)\n\tpaths = append(paths, gc.Current.Path)\n\tpathConverter := NewPathConverter(demux)\n\tpathConverter.ApproximationScale = gc.Current.Tr.GetScale()\n\tpathConverter.Convert(paths...)\n\n\tgc.paint(gc.fillRasterizer, gc.Current.FillColor)\n\tgc.paint(gc.strokeRasterizer, gc.Current.StrokeColor)\n}\n\nfunc (f FillRule) UseNonZeroWinding() bool {\n\tswitch f {\n\tcase FillRuleEvenOdd:\n\t\treturn false\n\tcase FillRuleWinding:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c Cap) Convert() raster.Capper {\n\tswitch c {\n\tcase RoundCap:\n\t\treturn raster.RoundCapper\n\tcase ButtCap:\n\t\treturn raster.ButtCapper\n\tcase SquareCap:\n\t\treturn raster.SquareCapper\n\t}\n\treturn raster.RoundCapper\n}\n\nfunc (j Join) Convert() raster.Joiner {\n\tswitch j {\n\tcase RoundJoin:\n\t\treturn raster.RoundJoiner\n\tcase BevelJoin:\n\t\treturn raster.BevelJoiner\n\t}\n\treturn raster.RoundJoiner\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nfunc main() {\n\tvar port = flag.Int(\"p\", 0, \"port to listen on\")\n\tflag.Parse()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor range c {\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"localhost:%d\", *port))\n\tif err != nil {\n\t\tlog.Printf(\"failed to listen on port %d: %v\", port, err)\n\t\treturn\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to accept connection:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(conn)\n\t}\n}\n\nfunc handleConnection(c net.Conn) {\n\tf, err := c.(*net.TCPConn).File()\n\tc.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer f.Close()\n\n\tvar (\n\t\tchallenge uint32\n\t\tbuf       = make([]byte, 4)\n\t)\n\n\tfor {\n\t\tif _, err = f.Read(buf); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tfmt.Println(\"read error: \", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif challenge = binary.BigEndian.Uint32(buf); challenge == 0 {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tbinary.BigEndian.PutUint32(buf, challenge+1)\n\n\t\tif _, err = f.Write(buf); err != nil {\n\t\t\tlog.Println(\"write error: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>go-blocking: Increase threads for connections<commit_after>package main\n\nimport (\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"syscall\"\n)\n\nvar (\n\tnumConns   int32 = 0\n\tnumThreads int\n)\n\nfunc main() {\n\tvar port = flag.Int(\"p\", 0, \"port to listen on\")\n\tflag.Parse()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor range c {\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\n\tnumThreads = runtime.NumCPU()\n\truntime.GOMAXPROCS(numThreads)\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"localhost:%d\", *port))\n\tif err != nil {\n\t\tlog.Printf(\"failed to listen on port %d: %v\", port, err)\n\t\treturn\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to accept connection:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tnc := atomic.AddInt32(&numConns, 1)\n\t\tif int(nc) > numThreads {\n\t\t\tnumThreads *= 2\n\t\t\truntime.GOMAXPROCS(numThreads)\n\t\t}\n\t\tgo handleConnection(conn)\n\t}\n}\n\nfunc handleConnection(c net.Conn) {\n\truntime.LockOSThread()\n\n\tf, err := c.(*net.TCPConn).File()\n\tc.Close()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tf.Close()\n\t\tatomic.AddInt32(&numConns, -1)\n\t}()\n\n\tvar (\n\t\tchallenge uint32\n\t\tbuf       = make([]byte, 4)\n\t)\n\n\tfor {\n\t\tif _, err = f.Read(buf); err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tfmt.Println(\"read error: \", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tif challenge = binary.BigEndian.Uint32(buf); challenge == 0 {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tbinary.BigEndian.PutUint32(buf, challenge+1)\n\n\t\tif _, err = f.Write(buf); err != nil {\n\t\t\tlog.Println(\"write error: \", err)\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\ntype stateFn func(*CoffeeLex) stateFn\n\ntype CoffeeLex struct {\n\t\/\/ the line\n\tinput string\n\tline  int\n\tstart int\n\tpos   int\n\tstate stateFn\n\n\t\/\/ current space prefix length (used to calculate indentation level)\n\tspace     int\n\tlastSpace int\n\n\t\/\/ XXX\n\twidth int\n\titems chan *CoffeeSymType\n}\n\ntype TokenType int\n\nconst eof = -1\nconst lexError = -99\n\nfunc (self *CoffeeSymType) String() string {\n\tswitch self.typ {\n\tcase T_EOF:\n\t\treturn \"EOF\"\n\t}\n\treturn fmt.Sprintf(\"[%d] %q\", self.typ, self.val)\n}\n\nfunc (l *CoffeeLex) emit(t TokenType) {\n\tl.items <- &CoffeeSymType{\n\t\ttyp:  t,\n\t\tval:  l.input[l.start:l.pos],\n\t\tpos:  l.start,\n\t\tline: l.line,\n\t}\n\tl.start = l.pos\n}\n\n\/\/ peek returns but does not consume\n\/\/ the next rune in the input.\nfunc (l *CoffeeLex) peek() (r rune) {\n\tr = l.next()\n\tl.backup()\n\treturn r\n}\n\nfunc (l *CoffeeLex) peekMore(p int) (r rune) {\n\tvar w = 0\n\tfor i := p; i > 0; i-- {\n\t\tr = l.next()\n\t\tw += l.width\n\t}\n\tl.pos -= w\n\treturn r\n}\n\n\/\/ ignore skips over the pending input before this point.\nfunc (l *CoffeeLex) ignore() {\n\tl.start = l.pos\n}\n\n\/\/ accept consumes the next rune\n\/\/ if it's from the valid set.\nfunc (l *CoffeeLex) accept(valid string) bool {\n\tif strings.IndexRune(valid, l.next()) >= 0 {\n\t\treturn true\n\t}\n\tl.backup()\n\treturn false\n}\n\n\/\/ backup steps back one rune.\n\/\/ Can be called only once per call of next.\nfunc (l *CoffeeLex) backup() {\n\tl.pos -= l.width\n}\n\n\/\/ next returns the next rune in the input.\nfunc (l *CoffeeLex) next() (r rune) {\n\tif l.pos >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, l.width = utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += l.width\n\treturn r\n}\n\nfunc (l *CoffeeLex) run() {\n\tfor l.state = lexStart; l.state != nil; {\n\t\tfn := l.state(l)\n\t\tif fn != nil {\n\t\t\tl.state = fn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.emit(T_EOF)\n}\n\nfunc (l *CoffeeLex) close() {\n\tclose(l.items)\n}\n\nfunc lexStartLine(l *CoffeeLex) stateFn {\n\tvar c rune = l.peek()\n\tif c == ' ' || c == '\\t' {\n\t\treturn lexIndentSpaces\n\t}\n\t\/\/ default start state.\n\treturn lexStart\n}\n\nfunc lexStart(l *CoffeeLex) stateFn {\n\tvar c rune = l.peek()\n\tif unicode.IsDigit(c) {\n\t\treturn lexNumber\n\t} else if c == ' ' || c == '\\t' {\n\t\t\/\/ return lexSpaces\n\t\treturn lexIgnoreSpaces\n\t} else if c == '\\n' || c == '\\r' {\n\t\tl.line++\n\t\tl.next()\n\t\tl.emit(T_NEWLINE)\n\t\tl.lastSpace = l.space\n\t\tl.space = 0\n\t\treturn lexStartLine\n\t} else if c == '=' && l.peekMore(2) != '=' {\n\t\tl.next()\n\t\tl.emit(T_ASSIGN)\n\t\treturn lexStart\n\t} else if l.consumeIfMatch(\"\/\/\") {\n\t\treturn lexOnelineComment\n\t} else if l.consumeIfMatch(\"\/*\") {\n\t\treturn lexComment\n\t} else if l.emitIfMatch(\"if \", T_IF) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"if else \", T_ELSEIF) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"class \", T_CLASS) {\n\t\treturn lexStart\n\t} else if unicode.IsLetter(c) {\n\t\treturn lexIdentifier\n\t} else if c == eof {\n\t\tl.emit(T_EOF)\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc lexComment(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c == eof {\n\t\t\tbreak\n\t\t}\n\t\tif c == '*' && l.peek() == '\/' {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.next()\n\tl.emit(T_COMMENT)\n\treturn lexStart\n}\n\nfunc lexOnelineComment(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c == '\\n' || c == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_ONELINE_COMMENT)\n\treturn lexStartLine\n}\n\nfunc lexIdentifier(l *CoffeeLex) stateFn {\n\tfor {\n\t\tc := l.next()\n\t\tif unicode.IsLetter(c) || unicode.IsDigit(c) {\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_IDENTIFIER)\n\treturn lexStart\n}\n\nfunc lexIgnoreSpaces(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c != ' ' || c == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.ignore()\n\treturn lexStart\n}\n\nfunc lexIndentSpaces(l *CoffeeLex) stateFn {\n\tl.space = 0\n\tfor {\n\t\tc := l.next()\n\t\tif c == ' ' || c == '\\t' {\n\t\t\tl.space++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_SPACE)\n\treturn lexStart\n}\n\nfunc lexSpaces(l *CoffeeLex) stateFn {\n\tfor c := l.next(); c == ' ' || c == '\\t'; {\n\t}\n\tl.backup()\n\tl.emit(T_SPACE)\n\treturn lexStart\n}\n\nfunc lexFloating(l *CoffeeLex) stateFn {\n\tfor {\n\t\tc := l.next()\n\t\tif !unicode.IsDigit(c) {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_FLOATING)\n\treturn lexStart\n}\n\nfunc lexNumber(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor c = l.next(); true; c = l.next() {\n\t\tif unicode.IsDigit(c) {\n\t\t\tcontinue\n\t\t} else if c == '.' && unicode.IsDigit(l.peek()) {\n\t\t\treturn lexFloating\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_NUMBER)\n\treturn lexStart\n}\n\nfunc (l *CoffeeLex) emitIfMatch(str string, typ TokenType) bool {\n\tif l.consumeIfMatch(str) {\n\t\tl.emit(typ)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l *CoffeeLex) consumeIfMatch(str string) bool {\n\tvar c rune\n\tvar width = 0\n\tfor _, sc := range str {\n\t\tc = l.next()\n\t\twidth += l.width\n\t\tif sc != c {\n\t\t\t\/\/ rollback\n\t\t\tl.pos -= width\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/*\nlookahead match method\n*\/\nfunc (l *CoffeeLex) match(str string) bool {\n\tvar c rune\n\tvar width = 0\n\tfor _, sc := range str {\n\t\tc = l.next()\n\t\twidth += l.width\n\t\tif sc != c {\n\t\t\tl.pos -= width\n\t\t\treturn false\n\t\t}\n\t}\n\tl.pos -= width\n\treturn true\n}\n\n\/\/ set token in lval, return the token type id\nfunc (l *CoffeeLex) Lex(lval *CoffeeSymType) int {\n\tvar c rune = l.next()\n\tif unicode.IsDigit(c) {\n\t\tlval.val = string(c)\n\t\tlval.typ = T_DIGIT\n\t\treturn T_DIGIT\n\t} else if unicode.IsLower(c) {\n\t\tlval.val = string(c)\n\t\tlval.typ = T_LETTER\n\t\treturn T_LETTER\n\t}\n\treturn int(c)\n}\n\nfunc (l *CoffeeLex) Error(s string) {\n\tfmt.Printf(\"syntax error: %s\\n\", s)\n}\n<commit_msg>Lexer: add \"for\", \"foreach\" token<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\ntype stateFn func(*CoffeeLex) stateFn\n\ntype CoffeeLex struct {\n\t\/\/ the line\n\tinput string\n\tline  int\n\tstart int\n\tpos   int\n\tstate stateFn\n\n\t\/\/ current space prefix length (used to calculate indentation level)\n\tspace     int\n\tlastSpace int\n\n\t\/\/ XXX\n\twidth int\n\titems chan *CoffeeSymType\n}\n\ntype TokenType int\n\nconst eof = -1\nconst lexError = -99\n\nfunc (self *CoffeeSymType) String() string {\n\tswitch self.typ {\n\tcase T_EOF:\n\t\treturn \"EOF\"\n\t}\n\treturn fmt.Sprintf(\"[%d] %q\", self.typ, self.val)\n}\n\nfunc (l *CoffeeLex) emit(t TokenType) {\n\tl.items <- &CoffeeSymType{\n\t\ttyp:  t,\n\t\tval:  l.input[l.start:l.pos],\n\t\tpos:  l.start,\n\t\tline: l.line,\n\t}\n\tl.start = l.pos\n}\n\n\/\/ peek returns but does not consume\n\/\/ the next rune in the input.\nfunc (l *CoffeeLex) peek() (r rune) {\n\tr = l.next()\n\tl.backup()\n\treturn r\n}\n\nfunc (l *CoffeeLex) peekMore(p int) (r rune) {\n\tvar w = 0\n\tfor i := p; i > 0; i-- {\n\t\tr = l.next()\n\t\tw += l.width\n\t}\n\tl.pos -= w\n\treturn r\n}\n\n\/\/ ignore skips over the pending input before this point.\nfunc (l *CoffeeLex) ignore() {\n\tl.start = l.pos\n}\n\n\/\/ accept consumes the next rune\n\/\/ if it's from the valid set.\nfunc (l *CoffeeLex) accept(valid string) bool {\n\tif strings.IndexRune(valid, l.next()) >= 0 {\n\t\treturn true\n\t}\n\tl.backup()\n\treturn false\n}\n\n\/\/ backup steps back one rune.\n\/\/ Can be called only once per call of next.\nfunc (l *CoffeeLex) backup() {\n\tl.pos -= l.width\n}\n\n\/\/ next returns the next rune in the input.\nfunc (l *CoffeeLex) next() (r rune) {\n\tif l.pos >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, l.width = utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.pos += l.width\n\treturn r\n}\n\nfunc (l *CoffeeLex) run() {\n\tfor l.state = lexStart; l.state != nil; {\n\t\tfn := l.state(l)\n\t\tif fn != nil {\n\t\t\tl.state = fn\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.emit(T_EOF)\n}\n\nfunc (l *CoffeeLex) close() {\n\tclose(l.items)\n}\n\nfunc lexStartLine(l *CoffeeLex) stateFn {\n\tvar c rune = l.peek()\n\tif c == ' ' || c == '\\t' {\n\t\treturn lexIndentSpaces\n\t}\n\t\/\/ default start state.\n\treturn lexStart\n}\n\nfunc lexStart(l *CoffeeLex) stateFn {\n\tvar c rune = l.peek()\n\tif unicode.IsDigit(c) {\n\t\treturn lexNumber\n\t} else if c == ' ' || c == '\\t' {\n\t\t\/\/ return lexSpaces\n\t\treturn lexIgnoreSpaces\n\t} else if c == '\\n' || c == '\\r' {\n\t\tl.line++\n\t\tl.next()\n\t\tl.emit(T_NEWLINE)\n\t\tl.lastSpace = l.space\n\t\tl.space = 0\n\t\treturn lexStartLine\n\t} else if c == '=' && l.peekMore(2) != '=' {\n\t\tl.next()\n\t\tl.emit(T_ASSIGN)\n\t\treturn lexStart\n\t} else if l.consumeIfMatch(\"\/\/\") {\n\t\treturn lexOnelineComment\n\t} else if l.consumeIfMatch(\"\/*\") {\n\t\treturn lexComment\n\t} else if l.emitIfMatch(\"if \", T_IF) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"if else \", T_ELSEIF) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"class \", T_CLASS) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"for \", T_FOR) {\n\t\treturn lexStart\n\t} else if l.emitIfMatch(\"foreach \", T_FOREACH) {\n\t\treturn lexStart\n\t} else if unicode.IsLetter(c) {\n\t\treturn lexIdentifier\n\t} else if c == eof {\n\t\tl.emit(T_EOF)\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc lexComment(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c == eof {\n\t\t\tbreak\n\t\t}\n\t\tif c == '*' && l.peek() == '\/' {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.next()\n\tl.emit(T_COMMENT)\n\treturn lexStart\n}\n\nfunc lexOnelineComment(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c == '\\n' || c == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_ONELINE_COMMENT)\n\treturn lexStartLine\n}\n\nfunc lexIdentifier(l *CoffeeLex) stateFn {\n\tfor {\n\t\tc := l.next()\n\t\tif unicode.IsLetter(c) || unicode.IsDigit(c) {\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_IDENTIFIER)\n\treturn lexStart\n}\n\nfunc lexIgnoreSpaces(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor {\n\t\tc = l.next()\n\t\tif c != ' ' || c == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.ignore()\n\treturn lexStart\n}\n\nfunc lexIndentSpaces(l *CoffeeLex) stateFn {\n\tl.space = 0\n\tfor {\n\t\tc := l.next()\n\t\tif c == ' ' || c == '\\t' {\n\t\t\tl.space++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_SPACE)\n\treturn lexStart\n}\n\nfunc lexSpaces(l *CoffeeLex) stateFn {\n\tfor c := l.next(); c == ' ' || c == '\\t'; {\n\t}\n\tl.backup()\n\tl.emit(T_SPACE)\n\treturn lexStart\n}\n\nfunc lexFloating(l *CoffeeLex) stateFn {\n\tfor {\n\t\tc := l.next()\n\t\tif !unicode.IsDigit(c) {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_FLOATING)\n\treturn lexStart\n}\n\nfunc lexNumber(l *CoffeeLex) stateFn {\n\tvar c rune\n\tfor c = l.next(); true; c = l.next() {\n\t\tif unicode.IsDigit(c) {\n\t\t\tcontinue\n\t\t} else if c == '.' && unicode.IsDigit(l.peek()) {\n\t\t\treturn lexFloating\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.backup()\n\tl.emit(T_NUMBER)\n\treturn lexStart\n}\n\nfunc (l *CoffeeLex) emitIfMatch(str string, typ TokenType) bool {\n\tif l.consumeIfMatch(str) {\n\t\tl.emit(typ)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (l *CoffeeLex) consumeIfMatch(str string) bool {\n\tvar c rune\n\tvar width = 0\n\tfor _, sc := range str {\n\t\tc = l.next()\n\t\twidth += l.width\n\t\tif sc != c {\n\t\t\t\/\/ rollback\n\t\t\tl.pos -= width\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/*\nlookahead match method\n*\/\nfunc (l *CoffeeLex) match(str string) bool {\n\tvar c rune\n\tvar width = 0\n\tfor _, sc := range str {\n\t\tc = l.next()\n\t\twidth += l.width\n\t\tif sc != c {\n\t\t\tl.pos -= width\n\t\t\treturn false\n\t\t}\n\t}\n\tl.pos -= width\n\treturn true\n}\n\n\/\/ set token in lval, return the token type id\nfunc (l *CoffeeLex) Lex(lval *CoffeeSymType) int {\n\tvar c rune = l.next()\n\tif unicode.IsDigit(c) {\n\t\tlval.val = string(c)\n\t\tlval.typ = T_DIGIT\n\t\treturn T_DIGIT\n\t} else if unicode.IsLower(c) {\n\t\tlval.val = string(c)\n\t\tlval.typ = T_LETTER\n\t\treturn T_LETTER\n\t}\n\treturn int(c)\n}\n\nfunc (l *CoffeeLex) Error(s string) {\n\tfmt.Printf(\"syntax error: %s\\n\", s)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/user\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/atsaki\/golang-cloudstack-library\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/vaughan0\/go-ini\"\n)\n\nconst (\n\tsep = '\\t'\n)\n\nvar (\n\tclient *cloudstack.Client\n)\n\nfunc expandPath(path string) string {\n\tusr, _ := user.Current()\n\thome := usr.HomeDir\n\n\tif strings.HasPrefix(path, \"~\/\") {\n\t\tpath = strings.Replace(path, \"~\/\", home+\"\/\", 1)\n\t}\n\treturn path\n}\n\nfunc setup(c *cli.Context) {\n\tif !c.GlobalBool(\"debug\") {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\tconfigfile := expandPath(c.GlobalString(\"config-file\"))\n\tlog.Println(\"configfile:\", configfile)\n\tcfg, err := ini.LoadFile(configfile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar ok bool\n\n\tprofile, ok := cfg.Get(\"core\", \"profile\")\n\tif !ok {\n\t\tprofile = \"local\"\n\t}\n\tlog.Println(\"profile:\", profile)\n\n\tendpointUrl, ok := cfg.Get(profile, \"url\")\n\tif !ok {\n\t\tlog.Fatalf(\"URL is not specified\")\n\t}\n\tlog.Println(\"url:\", endpointUrl)\n\n\tapikey, ok := cfg.Get(profile, \"apikey\")\n\tif !ok {\n\t\tapikey = \"\"\n\t}\n\tlog.Println(\"apikey:\", apikey)\n\n\tsecretkey, ok := cfg.Get(profile, \"secretkey\")\n\tif !ok {\n\t\tsecretkey = \"\"\n\t}\n\tlog.Println(\"secretkey:\", secretkey)\n\n\tusername, ok := cfg.Get(profile, \"username\")\n\tif !ok {\n\t\tusername = \"\"\n\t}\n\tlog.Println(\"username:\", username)\n\n\tpassword, ok := cfg.Get(profile, \"password\")\n\tif !ok {\n\t\tpassword = \"\"\n\t}\n\tlog.Println(\"password:\", password)\n\n\tendpoint, err := url.Parse(endpointUrl)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"endpoint:\", endpoint)\n\n\tclient, err = cloudstack.NewClient(*endpoint, apikey, secretkey,\n\t\tusername, password)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\n\ttabw := new(tabwriter.Writer)\n\ttabw.Init(os.Stdout, 0, 8, 0, byte(sep), 0)\n\n\tapp := cli.NewApp()\n\tapp.Name = \"lg\"\n\tapp.Usage = \"lg comand\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"config-file, c\",\n\t\t\tValue: \"~\/.cloudmonkey\/config\",\n\t\t\tUsage: \"Config file path\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug\",\n\t\t\tUsage: \"Show debug messages\",\n\t\t},\n\t}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"virtualmachines\",\n\t\t\tShortName: \"vms\",\n\t\t\tUsage:     \"List virtualmachines\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListVirtualMachinesParameter{}\n\t\t\t\tvms, err := client.ListVirtualMachines(params)\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 _, vm := range vms {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"deploy\",\n\t\t\tUsage: \"Deploy virtualmachine\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"zone, z\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The zoneid or zonename of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"serviceoffering, s\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The serviceofferingid or serviceofferingname of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"template, t\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The templateid or templatename of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"displayname\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The displayname of the virtualmachine\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.DeployVirtualMachineParameter{}\n\t\t\t\tif c.String(\"zone\") != \"\" {\n\t\t\t\t\tparams.SetZoneid(c.String(\"zone\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"serviceoffering\") != \"\" {\n\t\t\t\t\tparams.SetServiceofferingid(c.String(\"serviceoffering\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"template\") != \"\" {\n\t\t\t\t\tparams.SetTemplateid(c.String(\"template\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"displayname\") != \"\" {\n\t\t\t\t\tparams.SetDisplayname(c.String(\"displayname\"))\n\t\t\t\t}\n\t\t\t\tvm, err := client.DeployVirtualMachine(params)\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.Fprintln(\n\t\t\t\t\ttabw,\n\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t}, string(sep)))\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"start\",\n\t\t\tUsage: \"Start virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.StartVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.StartVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"stop\",\n\t\t\tUsage: \"Stop virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.StopVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.StopVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"destroy\",\n\t\t\tUsage: \"Destroy virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.DestroyVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.DestroyVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"zones\",\n\t\t\tUsage: \"List zones\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListZonesParameter{}\n\t\t\t\tzones, err := client.ListZones(params)\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 _, zone := range zones {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tzone.Id.String,\n\t\t\t\t\t\t\t\tzone.Name.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"serviceofferings\",\n\t\t\tShortName: \"sizes\",\n\t\t\tUsage:     \"List serviceofferings\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListServiceOfferingsParameter{}\n\t\t\t\tserviceofferings, err := client.ListServiceOfferings(params)\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 _, serviceoffering := range serviceofferings {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tserviceoffering.Id.String,\n\t\t\t\t\t\t\t\tserviceoffering.Name.String,\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Cpunumber.Int64),\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Cpuspeed.Int64),\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Memory.Int64),\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"templates\",\n\t\t\tShortName: \"images\",\n\t\t\tUsage:     \"list templates\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListTemplatesParameter{}\n\t\t\t\tparams.SetTemplatefilter(\"featured\")\n\t\t\t\ttemplates, err := client.ListTemplates(params)\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 _, template := range templates {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\ttemplate.Id.String,\n\t\t\t\t\t\t\t\ttemplate.Name.String,\n\t\t\t\t\t\t\t\ttemplate.Displaytext.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"networks\",\n\t\t\tShortName: \"nws\",\n\t\t\tUsage:     \"list network\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListNetworksParameter{}\n\t\t\t\tnetworks, err := client.ListNetworks(params)\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 _, network := range networks {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tnetwork.Id.String,\n\t\t\t\t\t\t\t\tnetwork.Name.String,\n\t\t\t\t\t\t\t\tnetwork.Networkofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"publicipaddresses\",\n\t\t\tShortName: \"ips\",\n\t\t\tUsage:     \"list ipaddresses\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListPublicIpAddressesParameter{}\n\t\t\t\tips, err := client.ListPublicIpAddresses(params)\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 _, ip := range ips {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tip.Id.String,\n\t\t\t\t\t\t\t\tip.Zonename.String,\n\t\t\t\t\t\t\t\tip.Associatednetworkname.String,\n\t\t\t\t\t\t\t\tfmt.Sprint(ip.Issourcenat.Bool),\n\t\t\t\t\t\t\t\tip.Ipaddress.String,\n\t\t\t\t\t\t\t\tip.Virtualmachinedisplayname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n<commit_msg>add profile option<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/user\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/atsaki\/golang-cloudstack-library\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/vaughan0\/go-ini\"\n)\n\nconst (\n\tsep = '\\t'\n)\n\nvar (\n\tclient *cloudstack.Client\n)\n\nfunc expandPath(path string) string {\n\tusr, _ := user.Current()\n\thome := usr.HomeDir\n\n\tif strings.HasPrefix(path, \"~\/\") {\n\t\tpath = strings.Replace(path, \"~\/\", home+\"\/\", 1)\n\t}\n\treturn path\n}\n\nfunc setup(c *cli.Context) {\n\n\tif !c.GlobalBool(\"debug\") {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\n\tconfigfile := expandPath(c.GlobalString(\"config-file\"))\n\tlog.Println(\"configfile:\", configfile)\n\tcfg, err := ini.LoadFile(configfile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar ok bool\n\n\tprofile, ok := cfg.Get(\"core\", \"profile\")\n\tif !ok {\n\t\tprofile = \"local\"\n\t}\n\tif c.GlobalString(\"profile\") != \"\" {\n\t\tprofile = c.GlobalString(\"profile\")\n\t}\n\tlog.Println(\"profile:\", profile)\n\n\tendpointUrl, ok := cfg.Get(profile, \"url\")\n\tif !ok {\n\t\tlog.Fatalf(\"URL is not specified\")\n\t}\n\tlog.Println(\"url:\", endpointUrl)\n\n\tapikey, ok := cfg.Get(profile, \"apikey\")\n\tif !ok {\n\t\tapikey = \"\"\n\t}\n\tlog.Println(\"apikey:\", apikey)\n\n\tsecretkey, ok := cfg.Get(profile, \"secretkey\")\n\tif !ok {\n\t\tsecretkey = \"\"\n\t}\n\tlog.Println(\"secretkey:\", secretkey)\n\n\tusername, ok := cfg.Get(profile, \"username\")\n\tif !ok {\n\t\tusername = \"\"\n\t}\n\tlog.Println(\"username:\", username)\n\n\tpassword, ok := cfg.Get(profile, \"password\")\n\tif !ok {\n\t\tpassword = \"\"\n\t}\n\tlog.Println(\"password:\", password)\n\n\tendpoint, err := url.Parse(endpointUrl)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"endpoint:\", endpoint)\n\n\tclient, err = cloudstack.NewClient(*endpoint, apikey, secretkey,\n\t\tusername, password)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\n\ttabw := new(tabwriter.Writer)\n\ttabw.Init(os.Stdout, 0, 8, 0, byte(sep), 0)\n\n\tapp := cli.NewApp()\n\tapp.Name = \"lg\"\n\tapp.Usage = \"lg comand\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"config-file, c\",\n\t\t\tValue: \"~\/.cloudmonkey\/config\",\n\t\t\tUsage: \"Config file path\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"profile, P\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"Server profile\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug\",\n\t\t\tUsage: \"Show debug messages\",\n\t\t},\n\t}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"virtualmachines\",\n\t\t\tShortName: \"vms\",\n\t\t\tUsage:     \"List virtualmachines\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListVirtualMachinesParameter{}\n\t\t\t\tvms, err := client.ListVirtualMachines(params)\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 _, vm := range vms {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"deploy\",\n\t\t\tUsage: \"Deploy virtualmachine\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"zone, z\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The zoneid or zonename of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"serviceoffering, s\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The serviceofferingid or serviceofferingname of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"template, t\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The templateid or templatename of the virtualmachine\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"displayname\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"The displayname of the virtualmachine\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.DeployVirtualMachineParameter{}\n\t\t\t\tif c.String(\"zone\") != \"\" {\n\t\t\t\t\tparams.SetZoneid(c.String(\"zone\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"serviceoffering\") != \"\" {\n\t\t\t\t\tparams.SetServiceofferingid(c.String(\"serviceoffering\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"template\") != \"\" {\n\t\t\t\t\tparams.SetTemplateid(c.String(\"template\"))\n\t\t\t\t}\n\t\t\t\tif c.String(\"displayname\") != \"\" {\n\t\t\t\t\tparams.SetDisplayname(c.String(\"displayname\"))\n\t\t\t\t}\n\t\t\t\tvm, err := client.DeployVirtualMachine(params)\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.Fprintln(\n\t\t\t\t\ttabw,\n\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t}, string(sep)))\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"start\",\n\t\t\tUsage: \"Start virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.StartVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.StartVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"stop\",\n\t\t\tUsage: \"Stop virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.StopVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.StopVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"destroy\",\n\t\t\tUsage: \"Destroy virtualmachine\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.DestroyVirtualMachineParameter{}\n\t\t\t\tvar ids []string\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\t\tids = append(ids, strings.Split(scanner.Text(), string(sep))[0])\n\t\t\t\t\t}\n\t\t\t\t} else if len(c.Args()) == 1 {\n\t\t\t\t\tids = append(ids, c.Args()[0])\n\t\t\t\t}\n\t\t\t\tlog.Println(\"ids:\", ids)\n\t\t\t\tfor _, id := range ids {\n\t\t\t\t\tparams.SetId(id)\n\t\t\t\t\tvm, err := client.DestroyVirtualMachine(params)\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\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tvm.Id.String,\n\t\t\t\t\t\t\t\tvm.Name.String,\n\t\t\t\t\t\t\t\tvm.Displayname.String,\n\t\t\t\t\t\t\t\tvm.State.String,\n\t\t\t\t\t\t\t\tvm.Zonename.String,\n\t\t\t\t\t\t\t\tvm.Templatename.String,\n\t\t\t\t\t\t\t\tvm.Serviceofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"zones\",\n\t\t\tUsage: \"List zones\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListZonesParameter{}\n\t\t\t\tzones, err := client.ListZones(params)\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 _, zone := range zones {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tzone.Id.String,\n\t\t\t\t\t\t\t\tzone.Name.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"serviceofferings\",\n\t\t\tShortName: \"sizes\",\n\t\t\tUsage:     \"List serviceofferings\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListServiceOfferingsParameter{}\n\t\t\t\tserviceofferings, err := client.ListServiceOfferings(params)\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 _, serviceoffering := range serviceofferings {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tserviceoffering.Id.String,\n\t\t\t\t\t\t\t\tserviceoffering.Name.String,\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Cpunumber.Int64),\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Cpuspeed.Int64),\n\t\t\t\t\t\t\t\tfmt.Sprint(serviceoffering.Memory.Int64),\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"templates\",\n\t\t\tShortName: \"images\",\n\t\t\tUsage:     \"list templates\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListTemplatesParameter{}\n\t\t\t\tparams.SetTemplatefilter(\"featured\")\n\t\t\t\ttemplates, err := client.ListTemplates(params)\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 _, template := range templates {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\ttemplate.Id.String,\n\t\t\t\t\t\t\t\ttemplate.Name.String,\n\t\t\t\t\t\t\t\ttemplate.Displaytext.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"networks\",\n\t\t\tShortName: \"nws\",\n\t\t\tUsage:     \"list network\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListNetworksParameter{}\n\t\t\t\tnetworks, err := client.ListNetworks(params)\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 _, network := range networks {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tnetwork.Id.String,\n\t\t\t\t\t\t\t\tnetwork.Name.String,\n\t\t\t\t\t\t\t\tnetwork.Networkofferingname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"publicipaddresses\",\n\t\t\tShortName: \"ips\",\n\t\t\tUsage:     \"list ipaddresses\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup(c)\n\t\t\t\tparams := cloudstack.ListPublicIpAddressesParameter{}\n\t\t\t\tips, err := client.ListPublicIpAddresses(params)\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 _, ip := range ips {\n\t\t\t\t\tfmt.Fprintln(\n\t\t\t\t\t\ttabw,\n\t\t\t\t\t\tstrings.Join(\n\t\t\t\t\t\t\t[]string{\n\t\t\t\t\t\t\t\tip.Id.String,\n\t\t\t\t\t\t\t\tip.Zonename.String,\n\t\t\t\t\t\t\t\tip.Associatednetworkname.String,\n\t\t\t\t\t\t\t\tfmt.Sprint(ip.Issourcenat.Bool),\n\t\t\t\t\t\t\t\tip.Ipaddress.String,\n\t\t\t\t\t\t\t\tip.Virtualmachinedisplayname.String,\n\t\t\t\t\t\t\t}, string(sep)))\n\t\t\t\t}\n\t\t\t\ttabw.Flush()\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\"fmt\"\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximun keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, log_dir string, log_rotate int64) http.Server {\n\tapache_log, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif log_dir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stdout),\n\t\t}\n\t} else if log_dir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stderr),\n\t\t}\n\t} else if log_dir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlog_file := log_dir\n\tlink_name := log_dir\n\tif !strings.HasSuffix(log_dir, \"\/\") {\n\t\tlog_file += \"\/\"\n\t\tlink_name += \"\/\"\n\n\t}\n\tlog_file += \"access_log.%Y%m%d%H%M\"\n\tlink_name += \"current\"\n\n\trl := rotatelogs.New(\n\t\tlog_file,\n\t\trotatelogs.WithLinkName(link_name),\n\t\trotatelogs.WithMaxAge(time.Duration(log_rotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\n\treturn http.Server{\n\t\tHandler: apache_log.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy_handler.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\toriginalHost := r.Host\n\t\thostSplited := strings.Split(originalHost, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplited {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplited[0:lastPartIndex], \".\")\n\t\tif hostSplited[lastPartIndex] == \"ccnproxy-https\" || hostSplited[lastPartIndex] == \"ccnproxy-secure\" || hostSplited[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy_handler.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<commit_msg>bugfix. rewrite host header<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximun keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, log_dir string, log_rotate int64) http.Server {\n\tapache_log, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif log_dir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stdout),\n\t\t}\n\t} else if log_dir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apache_log.Wrap(h, os.Stderr),\n\t\t}\n\t} else if log_dir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlog_file := log_dir\n\tlink_name := log_dir\n\tif !strings.HasSuffix(log_dir, \"\/\") {\n\t\tlog_file += \"\/\"\n\t\tlink_name += \"\/\"\n\n\t}\n\tlog_file += \"access_log.%Y%m%d%H%M\"\n\tlink_name += \"current\"\n\n\trl := rotatelogs.New(\n\t\tlog_file,\n\t\trotatelogs.WithLinkName(link_name),\n\t\trotatelogs.WithMaxAge(time.Duration(log_rotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\n\treturn http.Server{\n\t\tHandler: apache_log.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy_handler.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\toriginalHost := r.Host\n\t\thostSplited := strings.Split(originalHost, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplited {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplited[0:lastPartIndex], \".\")\n\t\tpr.Host = pr.URL.Host\n\t\tif hostSplited[lastPartIndex] == \"ccnproxy-https\" || hostSplited[lastPartIndex] == \"ccnproxy-secure\" || hostSplited[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy_handler.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<|endoftext|>"}
{"text":"<commit_before>package haproxy\n\nimport (\n\t\"github.com\/QubitProducts\/bamboo\/Godeps\/_workspace\/src\/github.com\/samuel\/go-zookeeper\/zk\"\n\tconf \"github.com\/QubitProducts\/bamboo\/configuration\"\n\t\"github.com\/QubitProducts\/bamboo\/services\/marathon\"\n\t\"github.com\/QubitProducts\/bamboo\/services\/service\"\n)\n\ntype templateData struct {\n\tApps     marathon.AppList\n\tServices map[string]service.Service\n}\n\nfunc GetTemplateData(config *conf.Configuration, conn *zk.Conn) (*templateData, error) {\n\n\tapps, err := marathon.FetchApps(config.Marathon, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservices, err := service.All(conn, config.Bamboo.Zookeeper)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &templateData{apps, services}, nil\n}\n<commit_msg>Update services\/haproxy for service.Storage change<commit_after>package haproxy\n\nimport (\n\tconf \"github.com\/QubitProducts\/bamboo\/configuration\"\n\t\"github.com\/QubitProducts\/bamboo\/services\/marathon\"\n\t\"github.com\/QubitProducts\/bamboo\/services\/service\"\n)\n\ntype templateData struct {\n\tApps     marathon.AppList\n\tServices map[string]service.Service\n}\n\nfunc GetTemplateData(config *conf.Configuration, storage service.Storage) (*templateData, error) {\n\n\tapps, err := marathon.FetchApps(config.Marathon, config)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservices, err := storage.All()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbyName := make(map[string]service.Service)\n\tfor _, service := range services {\n\t\tbyName[service.Id] = service\n\t}\n\n\treturn &templateData{apps, byName}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package jwthelper\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\n\/\/ claims stores JWT claims.\n\/\/ it contains a jwt.MapClaims.\ntype claims struct {\n\tm      sync.Mutex\n\tclaims jwt.MapClaims\n}\n\n\/\/ Claim represents JWT claim.\n\/\/ Use claim helper functions to get a Claim:\n\/\/ StringClaim(), IntClaim(), UintClaim(), TimeClaim()...\ntype Claim struct {\n\tf func(ops *claims)\n}\n\n\/\/ newClaims news a Claims and intializes the internal mutext and map.\nfunc newClaims() claims {\n\treturn claims{\n\t\tsync.Mutex{},\n\t\tmap[string]interface{}{},\n\t}\n}\n\n\/\/ newClaim news a Claim and set the internal map with given name -> value pair.\nfunc newClaim(name string, value interface{}) Claim {\n\treturn Claim{func(c *claims) {\n\t\tc.m.Lock()\n\t\tdefer c.m.Unlock()\n\t\tc.claims[name] = value\n\t}}\n}\n\n\/\/ StringClaim returns a Claim with string value.\nfunc StringClaim(name, value string) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ IntClaim returns a Claim with int value.\nfunc IntClaim(name string, value int) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Int32Claim returns a Claim with int32 value.\nfunc Int32Claim(name string, value int32) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Int64Claim returns a Claim with int64 value.\nfunc Int64Claim(name string, value int64) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ UintClaim returns a Claim with uint value.\nfunc UintClaim(name string, value uint) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Uint32Claim returns a Claim with uint32 value.\nfunc Uint32Claim(name string, value uint32) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Uint64Claim returns a Claim with uint64 value.\nfunc Uint64Claim(name string, value uint64) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Float32Claim returns a Claim with float32 value.\nfunc Float32Claim(name string, value float32) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ Float64Claim returns a Claim with float64 value.\nfunc Float64Claim(name string, value float64) Claim {\n\treturn newClaim(name, value)\n}\n\n\/\/ TimeClaim returns a Claim with time.Time value.\n\/\/ It'll convert the time.Time to a Unix timestamp.\nfunc TimeClaim(name string, value time.Time) Claim {\n\treturn Int64Claim(name, value.Unix())\n}\n<commit_msg>Export NewClaim() and remove other type specific functions<commit_after>package jwthelper\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\n\/\/ claims stores JWT claims.\n\/\/ it contains a jwt.MapClaims.\ntype claims struct {\n\tm      sync.Mutex\n\tclaims jwt.MapClaims\n}\n\n\/\/ Claim represents JWT claim.\n\/\/ Use claim helper functions to get a Claim:\n\/\/ StringClaim(), IntClaim(), UintClaim(), TimeClaim()...\ntype Claim struct {\n\tf func(ops *claims)\n}\n\n\/\/ newClaims news a Claims and intializes the internal mutext and map.\nfunc newClaims() claims {\n\treturn claims{\n\t\tsync.Mutex{},\n\t\tmap[string]interface{}{},\n\t}\n}\n\n\/\/ NewClaim news a Claim with given name -> value pair.\nfunc NewClaim(name string, value interface{}) Claim {\n\treturn Claim{func(c *claims) {\n\t\tc.m.Lock()\n\t\tdefer c.m.Unlock()\n\t\tc.claims[name] = value\n\t}}\n}\n\n\/\/ TimeClaim returns a Claim with time.Time value.\n\/\/ It'll convert the time.Time to a Unix timestamp.\nfunc TimeClaim(name string, value time.Time) Claim {\n\treturn NewClaim(name, value.Unix())\n}\n<|endoftext|>"}
{"text":"<commit_before>package libp2pquic\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/minio\/sha256-simd\"\n\t\"golang.org\/x\/crypto\/hkdf\"\n\n\tlogging \"github.com\/ipfs\/go-log\"\n\t\"github.com\/libp2p\/go-libp2p-core\/connmgr\"\n\tic \"github.com\/libp2p\/go-libp2p-core\/crypto\"\n\tn \"github.com\/libp2p\/go-libp2p-core\/network\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n\t\"github.com\/libp2p\/go-libp2p-core\/pnet\"\n\ttpt \"github.com\/libp2p\/go-libp2p-core\/transport\"\n\tp2ptls \"github.com\/libp2p\/go-libp2p-tls\"\n\t\"github.com\/lucas-clemente\/quic-go\"\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\tmafmt \"github.com\/multiformats\/go-multiaddr-fmt\"\n\tmanet \"github.com\/multiformats\/go-multiaddr\/net\"\n)\n\nvar log = logging.Logger(\"quic-transport\")\n\nvar ErrHolePunching = errors.New(\"hole punching attempted; no active dial\")\n\nvar quicDialContext = quic.DialContext \/\/ so we can mock it in tests\n\nvar HolePunchTimeout = 5 * time.Second\n\nvar quicConfig = &quic.Config{\n\tMaxIncomingStreams:         1000,\n\tMaxIncomingUniStreams:      -1,             \/\/ disable unidirectional streams\n\tMaxStreamReceiveWindow:     10 * (1 << 20), \/\/ 10 MB\n\tMaxConnectionReceiveWindow: 15 * (1 << 20), \/\/ 15 MB\n\tAcceptToken: func(clientAddr net.Addr, _ *quic.Token) bool {\n\t\t\/\/ TODO(#6): require source address validation when under load\n\t\treturn true\n\t},\n\tKeepAlive: true,\n\tVersions:  []quic.VersionNumber{quic.VersionDraft29, quic.Version1},\n}\n\nconst statelessResetKeyInfo = \"libp2p quic stateless reset key\"\nconst errorCodeConnectionGating = 0x47415445 \/\/ GATE in ASCII\n\ntype connManager struct {\n\treuseUDP4 *reuse\n\treuseUDP6 *reuse\n}\n\nfunc newConnManager() (*connManager, error) {\n\treuseUDP4 := newReuse()\n\treuseUDP6 := newReuse()\n\n\treturn &connManager{\n\t\treuseUDP4: reuseUDP4,\n\t\treuseUDP6: reuseUDP6,\n\t}, nil\n}\n\nfunc (c *connManager) getReuse(network string) (*reuse, error) {\n\tswitch network {\n\tcase \"udp4\":\n\t\treturn c.reuseUDP4, nil\n\tcase \"udp6\":\n\t\treturn c.reuseUDP6, nil\n\tdefault:\n\t\treturn nil, errors.New(\"invalid network: must be either udp4 or udp6\")\n\t}\n}\n\nfunc (c *connManager) Listen(network string, laddr *net.UDPAddr) (*reuseConn, error) {\n\treuse, err := c.getReuse(network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reuse.Listen(network, laddr)\n}\n\nfunc (c *connManager) Dial(network string, raddr *net.UDPAddr) (*reuseConn, error) {\n\treuse, err := c.getReuse(network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reuse.Dial(network, raddr)\n}\n\nfunc (c *connManager) Close() error {\n\tif err := c.reuseUDP6.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn c.reuseUDP4.Close()\n}\n\n\/\/ The Transport implements the tpt.Transport interface for QUIC connections.\ntype transport struct {\n\tprivKey      ic.PrivKey\n\tlocalPeer    peer.ID\n\tidentity     *p2ptls.Identity\n\tconnManager  *connManager\n\tserverConfig *quic.Config\n\tclientConfig *quic.Config\n\tgater        connmgr.ConnectionGater\n\n\tholePunchingMx sync.Mutex\n\tholePunching   map[holePunchKey]*activeHolePunch\n}\n\nvar _ tpt.Transport = &transport{}\n\ntype holePunchKey struct {\n\taddr string\n\tpeer peer.ID\n}\n\ntype activeHolePunch struct {\n\tconnCh    chan tpt.CapableConn\n\tfulfilled bool\n}\n\n\/\/ NewTransport creates a new QUIC transport\nfunc NewTransport(key ic.PrivKey, psk pnet.PSK, gater connmgr.ConnectionGater) (tpt.Transport, error) {\n\tif len(psk) > 0 {\n\t\tlog.Error(\"QUIC doesn't support private networks yet.\")\n\t\treturn nil, errors.New(\"QUIC doesn't support private networks yet\")\n\t}\n\tlocalPeer, err := peer.IDFromPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tidentity, err := p2ptls.NewIdentity(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconnManager, err := newConnManager()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := quicConfig.Clone()\n\tkeyBytes, err := key.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyReader := hkdf.New(sha256.New, keyBytes, nil, []byte(statelessResetKeyInfo))\n\tconfig.StatelessResetKey = make([]byte, 32)\n\tif _, err := io.ReadFull(keyReader, config.StatelessResetKey); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.Tracer = tracer\n\n\treturn &transport{\n\t\tprivKey:      key,\n\t\tlocalPeer:    localPeer,\n\t\tidentity:     identity,\n\t\tconnManager:  connManager,\n\t\tserverConfig: config,\n\t\tclientConfig: config.Clone(),\n\t\tgater:        gater,\n\t\tholePunching: make(map[holePunchKey]*activeHolePunch),\n\t}, nil\n}\n\n\/\/ Dial dials a new QUIC connection\nfunc (t *transport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (tpt.CapableConn, error) {\n\tnetwork, host, err := manet.DialArgs(raddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddr, err := net.ResolveUDPAddr(network, host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tremoteMultiaddr, err := toQuicMultiaddr(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsConf, keyCh := t.identity.ConfigForPeer(p)\n\n\tif ok, isClient, _ := n.GetSimultaneousConnect(ctx); ok && !isClient {\n\t\treturn t.holePunch(ctx, network, addr, p)\n\t}\n\n\tpconn, err := t.connManager.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsess, err := quicDialContext(ctx, pconn, addr, host, tlsConf, t.clientConfig)\n\tif err != nil {\n\t\tpconn.DecreaseCount()\n\t\treturn nil, err\n\t}\n\t\/\/ Should be ready by this point, don't block.\n\tvar remotePubKey ic.PubKey\n\tselect {\n\tcase remotePubKey = <-keyCh:\n\tdefault:\n\t}\n\tif remotePubKey == nil {\n\t\tpconn.DecreaseCount()\n\t\treturn nil, errors.New(\"go-libp2p-quic-transport BUG: expected remote pub key to be set\")\n\t}\n\tgo func() {\n\t\t<-sess.Context().Done()\n\t\tpconn.DecreaseCount()\n\t}()\n\n\tlocalMultiaddr, err := toQuicMultiaddr(pconn.LocalAddr())\n\tif err != nil {\n\t\tsess.CloseWithError(0, \"\")\n\t\treturn nil, err\n\t}\n\tconn := &conn{\n\t\tsess:            sess,\n\t\ttransport:       t,\n\t\tprivKey:         t.privKey,\n\t\tlocalPeer:       t.localPeer,\n\t\tlocalMultiaddr:  localMultiaddr,\n\t\tremotePubKey:    remotePubKey,\n\t\tremotePeerID:    p,\n\t\tremoteMultiaddr: remoteMultiaddr,\n\t}\n\tif t.gater != nil && !t.gater.InterceptSecured(n.DirOutbound, p, conn) {\n\t\tsess.CloseWithError(errorCodeConnectionGating, \"connection gated\")\n\t\treturn nil, fmt.Errorf(\"secured connection gated\")\n\t}\n\treturn conn, nil\n}\n\nfunc (t *transport) holePunch(ctx context.Context, network string, addr *net.UDPAddr, p peer.ID) (tpt.CapableConn, error) {\n\tpconn, err := t.connManager.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer pconn.DecreaseCount()\n\n\tctx, cancel := context.WithTimeout(ctx, HolePunchTimeout)\n\tdefer cancel()\n\n\tkey := holePunchKey{addr: addr.String(), peer: p}\n\tt.holePunchingMx.Lock()\n\tif _, ok := t.holePunching[key]; ok {\n\t\tt.holePunchingMx.Unlock()\n\t\treturn nil, fmt.Errorf(\"already punching hole for %s\", addr)\n\t}\n\tconnCh := make(chan tpt.CapableConn, 1)\n\tt.holePunching[key] = &activeHolePunch{connCh: connCh}\n\tt.holePunchingMx.Unlock()\n\n\tvar timer *time.Timer\n\tdefer func() {\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t}()\n\n\tpayload := make([]byte, 64)\n\tvar punchErr error\nloop:\n\tfor i := 0; ; i++ {\n\t\tif _, err := rand.Read(payload); err != nil {\n\t\t\tpunchErr = err\n\t\t\tbreak\n\t\t}\n\t\tif _, err := pconn.UDPConn.WriteToUDP(payload, addr); err != nil {\n\t\t\tpunchErr = err\n\t\t\tbreak\n\t\t}\n\n\t\tmaxSleep := 10 * (i + 1) * (i + 1) \/\/ in ms\n\t\tif maxSleep > 200 {\n\t\t\tmaxSleep = 200\n\t\t}\n\t\td := 10*time.Millisecond + time.Duration(rand.Intn(maxSleep))*time.Millisecond\n\t\tif timer == nil {\n\t\t\ttimer = time.NewTimer(d)\n\t\t} else {\n\t\t\ttimer.Reset(d)\n\t\t}\n\t\tselect {\n\t\tcase c := <-connCh:\n\t\t\tt.holePunchingMx.Lock()\n\t\t\tdelete(t.holePunching, key)\n\t\t\tt.holePunchingMx.Unlock()\n\t\t\treturn c, nil\n\t\tcase <-timer.C:\n\t\tcase <-ctx.Done():\n\t\t\tpunchErr = ErrHolePunching\n\t\t\tbreak loop\n\t\t}\n\t}\n\t\/\/ we only arrive here if punchErr != nil\n\tt.holePunchingMx.Lock()\n\tdefer func() {\n\t\tdelete(t.holePunching, key)\n\t\tt.holePunchingMx.Unlock()\n\t}()\n\tselect {\n\tcase c := <-t.holePunching[key].connCh:\n\t\treturn c, nil\n\tdefault:\n\t\treturn nil, punchErr\n\t}\n}\n\n\/\/ Don't use mafmt.QUIC as we don't want to dial DNS addresses. Just \/ip{4,6}\/udp\/quic\nvar dialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_UDP), mafmt.Base(ma.P_QUIC))\n\n\/\/ CanDial determines if we can dial to an address\nfunc (t *transport) CanDial(addr ma.Multiaddr) bool {\n\treturn dialMatcher.Matches(addr)\n}\n\n\/\/ Listen listens for new QUIC connections on the passed multiaddr.\nfunc (t *transport) Listen(addr ma.Multiaddr) (tpt.Listener, error) {\n\tlnet, host, err := manet.DialArgs(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tladdr, err := net.ResolveUDPAddr(lnet, host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := t.connManager.Listen(lnet, laddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tln, err := newListener(conn, t, t.localPeer, t.privKey, t.identity)\n\tif err != nil {\n\t\tconn.DecreaseCount()\n\t\treturn nil, err\n\t}\n\treturn ln, nil\n}\n\n\/\/ Proxy returns true if this transport proxies.\nfunc (t *transport) Proxy() bool {\n\treturn false\n}\n\n\/\/ Protocols returns the set of protocols handled by this transport.\nfunc (t *transport) Protocols() []int {\n\treturn []int{ma.P_QUIC}\n}\n\nfunc (t *transport) String() string {\n\treturn \"QUIC\"\n}\n\nfunc (t *transport) Close() error {\n\treturn t.connManager.Close()\n}\n<commit_msg>chore: update go-log to v2 (#242)<commit_after>package libp2pquic\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/minio\/sha256-simd\"\n\t\"golang.org\/x\/crypto\/hkdf\"\n\n\tlogging \"github.com\/ipfs\/go-log\/v2\"\n\t\"github.com\/libp2p\/go-libp2p-core\/connmgr\"\n\tic \"github.com\/libp2p\/go-libp2p-core\/crypto\"\n\tn \"github.com\/libp2p\/go-libp2p-core\/network\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n\t\"github.com\/libp2p\/go-libp2p-core\/pnet\"\n\ttpt \"github.com\/libp2p\/go-libp2p-core\/transport\"\n\tp2ptls \"github.com\/libp2p\/go-libp2p-tls\"\n\t\"github.com\/lucas-clemente\/quic-go\"\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\tmafmt \"github.com\/multiformats\/go-multiaddr-fmt\"\n\tmanet \"github.com\/multiformats\/go-multiaddr\/net\"\n)\n\nvar log = logging.Logger(\"quic-transport\")\n\nvar ErrHolePunching = errors.New(\"hole punching attempted; no active dial\")\n\nvar quicDialContext = quic.DialContext \/\/ so we can mock it in tests\n\nvar HolePunchTimeout = 5 * time.Second\n\nvar quicConfig = &quic.Config{\n\tMaxIncomingStreams:         1000,\n\tMaxIncomingUniStreams:      -1,             \/\/ disable unidirectional streams\n\tMaxStreamReceiveWindow:     10 * (1 << 20), \/\/ 10 MB\n\tMaxConnectionReceiveWindow: 15 * (1 << 20), \/\/ 15 MB\n\tAcceptToken: func(clientAddr net.Addr, _ *quic.Token) bool {\n\t\t\/\/ TODO(#6): require source address validation when under load\n\t\treturn true\n\t},\n\tKeepAlive: true,\n\tVersions:  []quic.VersionNumber{quic.VersionDraft29, quic.Version1},\n}\n\nconst statelessResetKeyInfo = \"libp2p quic stateless reset key\"\nconst errorCodeConnectionGating = 0x47415445 \/\/ GATE in ASCII\n\ntype connManager struct {\n\treuseUDP4 *reuse\n\treuseUDP6 *reuse\n}\n\nfunc newConnManager() (*connManager, error) {\n\treuseUDP4 := newReuse()\n\treuseUDP6 := newReuse()\n\n\treturn &connManager{\n\t\treuseUDP4: reuseUDP4,\n\t\treuseUDP6: reuseUDP6,\n\t}, nil\n}\n\nfunc (c *connManager) getReuse(network string) (*reuse, error) {\n\tswitch network {\n\tcase \"udp4\":\n\t\treturn c.reuseUDP4, nil\n\tcase \"udp6\":\n\t\treturn c.reuseUDP6, nil\n\tdefault:\n\t\treturn nil, errors.New(\"invalid network: must be either udp4 or udp6\")\n\t}\n}\n\nfunc (c *connManager) Listen(network string, laddr *net.UDPAddr) (*reuseConn, error) {\n\treuse, err := c.getReuse(network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reuse.Listen(network, laddr)\n}\n\nfunc (c *connManager) Dial(network string, raddr *net.UDPAddr) (*reuseConn, error) {\n\treuse, err := c.getReuse(network)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn reuse.Dial(network, raddr)\n}\n\nfunc (c *connManager) Close() error {\n\tif err := c.reuseUDP6.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn c.reuseUDP4.Close()\n}\n\n\/\/ The Transport implements the tpt.Transport interface for QUIC connections.\ntype transport struct {\n\tprivKey      ic.PrivKey\n\tlocalPeer    peer.ID\n\tidentity     *p2ptls.Identity\n\tconnManager  *connManager\n\tserverConfig *quic.Config\n\tclientConfig *quic.Config\n\tgater        connmgr.ConnectionGater\n\n\tholePunchingMx sync.Mutex\n\tholePunching   map[holePunchKey]*activeHolePunch\n}\n\nvar _ tpt.Transport = &transport{}\n\ntype holePunchKey struct {\n\taddr string\n\tpeer peer.ID\n}\n\ntype activeHolePunch struct {\n\tconnCh    chan tpt.CapableConn\n\tfulfilled bool\n}\n\n\/\/ NewTransport creates a new QUIC transport\nfunc NewTransport(key ic.PrivKey, psk pnet.PSK, gater connmgr.ConnectionGater) (tpt.Transport, error) {\n\tif len(psk) > 0 {\n\t\tlog.Error(\"QUIC doesn't support private networks yet.\")\n\t\treturn nil, errors.New(\"QUIC doesn't support private networks yet\")\n\t}\n\tlocalPeer, err := peer.IDFromPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tidentity, err := p2ptls.NewIdentity(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconnManager, err := newConnManager()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := quicConfig.Clone()\n\tkeyBytes, err := key.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyReader := hkdf.New(sha256.New, keyBytes, nil, []byte(statelessResetKeyInfo))\n\tconfig.StatelessResetKey = make([]byte, 32)\n\tif _, err := io.ReadFull(keyReader, config.StatelessResetKey); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig.Tracer = tracer\n\n\treturn &transport{\n\t\tprivKey:      key,\n\t\tlocalPeer:    localPeer,\n\t\tidentity:     identity,\n\t\tconnManager:  connManager,\n\t\tserverConfig: config,\n\t\tclientConfig: config.Clone(),\n\t\tgater:        gater,\n\t\tholePunching: make(map[holePunchKey]*activeHolePunch),\n\t}, nil\n}\n\n\/\/ Dial dials a new QUIC connection\nfunc (t *transport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (tpt.CapableConn, error) {\n\tnetwork, host, err := manet.DialArgs(raddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddr, err := net.ResolveUDPAddr(network, host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tremoteMultiaddr, err := toQuicMultiaddr(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttlsConf, keyCh := t.identity.ConfigForPeer(p)\n\n\tif ok, isClient, _ := n.GetSimultaneousConnect(ctx); ok && !isClient {\n\t\treturn t.holePunch(ctx, network, addr, p)\n\t}\n\n\tpconn, err := t.connManager.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsess, err := quicDialContext(ctx, pconn, addr, host, tlsConf, t.clientConfig)\n\tif err != nil {\n\t\tpconn.DecreaseCount()\n\t\treturn nil, err\n\t}\n\t\/\/ Should be ready by this point, don't block.\n\tvar remotePubKey ic.PubKey\n\tselect {\n\tcase remotePubKey = <-keyCh:\n\tdefault:\n\t}\n\tif remotePubKey == nil {\n\t\tpconn.DecreaseCount()\n\t\treturn nil, errors.New(\"go-libp2p-quic-transport BUG: expected remote pub key to be set\")\n\t}\n\tgo func() {\n\t\t<-sess.Context().Done()\n\t\tpconn.DecreaseCount()\n\t}()\n\n\tlocalMultiaddr, err := toQuicMultiaddr(pconn.LocalAddr())\n\tif err != nil {\n\t\tsess.CloseWithError(0, \"\")\n\t\treturn nil, err\n\t}\n\tconn := &conn{\n\t\tsess:            sess,\n\t\ttransport:       t,\n\t\tprivKey:         t.privKey,\n\t\tlocalPeer:       t.localPeer,\n\t\tlocalMultiaddr:  localMultiaddr,\n\t\tremotePubKey:    remotePubKey,\n\t\tremotePeerID:    p,\n\t\tremoteMultiaddr: remoteMultiaddr,\n\t}\n\tif t.gater != nil && !t.gater.InterceptSecured(n.DirOutbound, p, conn) {\n\t\tsess.CloseWithError(errorCodeConnectionGating, \"connection gated\")\n\t\treturn nil, fmt.Errorf(\"secured connection gated\")\n\t}\n\treturn conn, nil\n}\n\nfunc (t *transport) holePunch(ctx context.Context, network string, addr *net.UDPAddr, p peer.ID) (tpt.CapableConn, error) {\n\tpconn, err := t.connManager.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer pconn.DecreaseCount()\n\n\tctx, cancel := context.WithTimeout(ctx, HolePunchTimeout)\n\tdefer cancel()\n\n\tkey := holePunchKey{addr: addr.String(), peer: p}\n\tt.holePunchingMx.Lock()\n\tif _, ok := t.holePunching[key]; ok {\n\t\tt.holePunchingMx.Unlock()\n\t\treturn nil, fmt.Errorf(\"already punching hole for %s\", addr)\n\t}\n\tconnCh := make(chan tpt.CapableConn, 1)\n\tt.holePunching[key] = &activeHolePunch{connCh: connCh}\n\tt.holePunchingMx.Unlock()\n\n\tvar timer *time.Timer\n\tdefer func() {\n\t\tif timer != nil {\n\t\t\ttimer.Stop()\n\t\t}\n\t}()\n\n\tpayload := make([]byte, 64)\n\tvar punchErr error\nloop:\n\tfor i := 0; ; i++ {\n\t\tif _, err := rand.Read(payload); err != nil {\n\t\t\tpunchErr = err\n\t\t\tbreak\n\t\t}\n\t\tif _, err := pconn.UDPConn.WriteToUDP(payload, addr); err != nil {\n\t\t\tpunchErr = err\n\t\t\tbreak\n\t\t}\n\n\t\tmaxSleep := 10 * (i + 1) * (i + 1) \/\/ in ms\n\t\tif maxSleep > 200 {\n\t\t\tmaxSleep = 200\n\t\t}\n\t\td := 10*time.Millisecond + time.Duration(rand.Intn(maxSleep))*time.Millisecond\n\t\tif timer == nil {\n\t\t\ttimer = time.NewTimer(d)\n\t\t} else {\n\t\t\ttimer.Reset(d)\n\t\t}\n\t\tselect {\n\t\tcase c := <-connCh:\n\t\t\tt.holePunchingMx.Lock()\n\t\t\tdelete(t.holePunching, key)\n\t\t\tt.holePunchingMx.Unlock()\n\t\t\treturn c, nil\n\t\tcase <-timer.C:\n\t\tcase <-ctx.Done():\n\t\t\tpunchErr = ErrHolePunching\n\t\t\tbreak loop\n\t\t}\n\t}\n\t\/\/ we only arrive here if punchErr != nil\n\tt.holePunchingMx.Lock()\n\tdefer func() {\n\t\tdelete(t.holePunching, key)\n\t\tt.holePunchingMx.Unlock()\n\t}()\n\tselect {\n\tcase c := <-t.holePunching[key].connCh:\n\t\treturn c, nil\n\tdefault:\n\t\treturn nil, punchErr\n\t}\n}\n\n\/\/ Don't use mafmt.QUIC as we don't want to dial DNS addresses. Just \/ip{4,6}\/udp\/quic\nvar dialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_UDP), mafmt.Base(ma.P_QUIC))\n\n\/\/ CanDial determines if we can dial to an address\nfunc (t *transport) CanDial(addr ma.Multiaddr) bool {\n\treturn dialMatcher.Matches(addr)\n}\n\n\/\/ Listen listens for new QUIC connections on the passed multiaddr.\nfunc (t *transport) Listen(addr ma.Multiaddr) (tpt.Listener, error) {\n\tlnet, host, err := manet.DialArgs(addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tladdr, err := net.ResolveUDPAddr(lnet, host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := t.connManager.Listen(lnet, laddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tln, err := newListener(conn, t, t.localPeer, t.privKey, t.identity)\n\tif err != nil {\n\t\tconn.DecreaseCount()\n\t\treturn nil, err\n\t}\n\treturn ln, nil\n}\n\n\/\/ Proxy returns true if this transport proxies.\nfunc (t *transport) Proxy() bool {\n\treturn false\n}\n\n\/\/ Protocols returns the set of protocols handled by this transport.\nfunc (t *transport) Protocols() []int {\n\treturn []int{ma.P_QUIC}\n}\n\nfunc (t *transport) String() string {\n\treturn \"QUIC\"\n}\n\nfunc (t *transport) Close() error {\n\treturn t.connManager.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package websocket\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\tws \"github.com\/gorilla\/websocket\"\n)\n\n\/\/ GracefulCloseTimeout is the time to wait trying to gracefully close a\n\/\/ connection before simply cutting it.\nvar GracefulCloseTimeout = 100 * time.Millisecond\n\nvar _ net.Conn = (*Conn)(nil)\n\n\/\/ Conn implements net.Conn interface for gorilla\/websocket.\ntype Conn struct {\n\t*ws.Conn\n\tDefaultMessageType int\n\tdone               func()\n\treader             io.Reader\n\tcloseOnce          sync.Once\n}\n\nfunc (c *Conn) Read(b []byte) (int, error) {\n\tif c.reader == nil {\n\t\tif err := c.prepNextReader(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tfor {\n\t\tn, err := c.reader.Read(b)\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\tc.reader = nil\n\n\t\t\tif n > 0 {\n\t\t\t\treturn n, nil\n\t\t\t}\n\n\t\t\tif err := c.prepNextReader(); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\t\/\/ explicitly looping\n\t\tdefault:\n\t\t\treturn n, err\n\t\t}\n\t}\n}\n\nfunc (c *Conn) prepNextReader() error {\n\tt, r, err := c.Conn.NextReader()\n\tif err != nil {\n\t\tif wserr, ok := err.(*ws.CloseError); ok {\n\t\t\tif wserr.Code == 1000 || wserr.Code == 1005 {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif t == ws.CloseMessage {\n\t\treturn io.EOF\n\t}\n\n\tc.reader = r\n\treturn nil\n}\n\nfunc (c *Conn) Write(b []byte) (n int, err error) {\n\tif err := c.Conn.WriteMessage(c.DefaultMessageType, b); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn len(b), nil\n}\n\n\/\/ Close closes the connection. Only the first call to Close will receive the\n\/\/ close error, subsequent and concurrent calls will return nil.\n\/\/ This method is thread-safe.\nfunc (c *Conn) Close() error {\n\tvar err error = nil\n\tc.closeOnce.Do(func() {\n\t\tif c.done != nil {\n\t\t\tc.done()\n\t\t\t\/\/ Be nice to GC\n\t\t\tc.done = nil\n\t\t}\n\n\t\tc.Conn.WriteControl(ws.CloseMessage, nil, time.Now().Add(GracefulCloseTimeout))\n\t\terr = c.Conn.Close()\n\t})\n\treturn err\n}\n\nfunc (c *Conn) LocalAddr() net.Addr {\n\treturn NewAddr(c.Conn.LocalAddr().String())\n}\n\nfunc (c *Conn) RemoteAddr() net.Addr {\n\treturn NewAddr(c.Conn.RemoteAddr().String())\n}\n\nfunc (c *Conn) SetDeadline(t time.Time) error {\n\tif err := c.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.SetWriteDeadline(t)\n}\n\nfunc (c *Conn) SetReadDeadline(t time.Time) error {\n\treturn c.Conn.SetReadDeadline(t)\n}\n\nfunc (c *Conn) SetWriteDeadline(t time.Time) error {\n\treturn c.Conn.SetWriteDeadline(t)\n}\n\n\/\/ NewConn creates a Conn given a regular gorilla\/websocket Conn.\nfunc NewConn(raw *ws.Conn, done func()) *Conn {\n\treturn &Conn{\n\t\tConn:               raw,\n\t\tDefaultMessageType: ws.BinaryMessage,\n\t\tdone:               done,\n\t}\n}\n<commit_msg>don't explicitly nil err<commit_after>package websocket\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\tws \"github.com\/gorilla\/websocket\"\n)\n\n\/\/ GracefulCloseTimeout is the time to wait trying to gracefully close a\n\/\/ connection before simply cutting it.\nvar GracefulCloseTimeout = 100 * time.Millisecond\n\nvar _ net.Conn = (*Conn)(nil)\n\n\/\/ Conn implements net.Conn interface for gorilla\/websocket.\ntype Conn struct {\n\t*ws.Conn\n\tDefaultMessageType int\n\tdone               func()\n\treader             io.Reader\n\tcloseOnce          sync.Once\n}\n\nfunc (c *Conn) Read(b []byte) (int, error) {\n\tif c.reader == nil {\n\t\tif err := c.prepNextReader(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tfor {\n\t\tn, err := c.reader.Read(b)\n\t\tswitch err {\n\t\tcase io.EOF:\n\t\t\tc.reader = nil\n\n\t\t\tif n > 0 {\n\t\t\t\treturn n, nil\n\t\t\t}\n\n\t\t\tif err := c.prepNextReader(); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\t\/\/ explicitly looping\n\t\tdefault:\n\t\t\treturn n, err\n\t\t}\n\t}\n}\n\nfunc (c *Conn) prepNextReader() error {\n\tt, r, err := c.Conn.NextReader()\n\tif err != nil {\n\t\tif wserr, ok := err.(*ws.CloseError); ok {\n\t\t\tif wserr.Code == 1000 || wserr.Code == 1005 {\n\t\t\t\treturn io.EOF\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tif t == ws.CloseMessage {\n\t\treturn io.EOF\n\t}\n\n\tc.reader = r\n\treturn nil\n}\n\nfunc (c *Conn) Write(b []byte) (n int, err error) {\n\tif err := c.Conn.WriteMessage(c.DefaultMessageType, b); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn len(b), nil\n}\n\n\/\/ Close closes the connection. Only the first call to Close will receive the\n\/\/ close error, subsequent and concurrent calls will return nil.\n\/\/ This method is thread-safe.\nfunc (c *Conn) Close() error {\n\tvar err error\n\tc.closeOnce.Do(func() {\n\t\tif c.done != nil {\n\t\t\tc.done()\n\t\t\t\/\/ Be nice to GC\n\t\t\tc.done = nil\n\t\t}\n\n\t\tc.Conn.WriteControl(ws.CloseMessage, nil, time.Now().Add(GracefulCloseTimeout))\n\t\terr = c.Conn.Close()\n\t})\n\treturn err\n}\n\nfunc (c *Conn) LocalAddr() net.Addr {\n\treturn NewAddr(c.Conn.LocalAddr().String())\n}\n\nfunc (c *Conn) RemoteAddr() net.Addr {\n\treturn NewAddr(c.Conn.RemoteAddr().String())\n}\n\nfunc (c *Conn) SetDeadline(t time.Time) error {\n\tif err := c.SetReadDeadline(t); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.SetWriteDeadline(t)\n}\n\nfunc (c *Conn) SetReadDeadline(t time.Time) error {\n\treturn c.Conn.SetReadDeadline(t)\n}\n\nfunc (c *Conn) SetWriteDeadline(t time.Time) error {\n\treturn c.Conn.SetWriteDeadline(t)\n}\n\n\/\/ NewConn creates a Conn given a regular gorilla\/websocket Conn.\nfunc NewConn(raw *ws.Conn, done func()) *Conn {\n\treturn &Conn{\n\t\tConn:               raw,\n\t\tDefaultMessageType: ws.BinaryMessage,\n\t\tdone:               done,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n)\n\ntype Client struct {\n\tdb      *sqlx.DB\n\thistory []string\n}\n\ntype Row []interface{}\n\ntype Result struct {\n\tColumns []string `json:\"columns\"`\n\tRows    []Row    `json:\"rows\"`\n}\n\nfunc NewClient() (*Client, error) {\n\tdb, err := sqlx.Open(\"postgres\", getConnectionString())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{db: db}, nil\n}\n\nfunc NewClientFromUrl(url string) (*Client, error) {\n\tdb, err := sqlx.Open(\"postgres\", url)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{db: db}, nil\n}\n\nfunc (client *Client) Test() error {\n\treturn client.db.Ping()\n}\n\nfunc (client *Client) recordQuery(query string) {\n\tclient.history = append(client.history, query)\n}\n\nfunc (client *Client) Info() (*Result, error) {\n\treturn client.query(PG_INFO)\n}\n\nfunc (client *Client) Databases() ([]string, error) {\n\tres, err := client.query(PG_DATABASES)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tables []string\n\n\tfor _, row := range res.Rows {\n\t\ttables = append(tables, row[0].(string))\n\t}\n\n\treturn tables, nil\n}\n\nfunc (client *Client) Tables() ([]string, error) {\n\tres, err := client.query(PG_TABLES)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tables []string\n\n\tfor _, row := range res.Rows {\n\t\ttables = append(tables, row[0].(string))\n\t}\n\n\treturn tables, nil\n}\n\nfunc (client *Client) Table(table string) (*Result, error) {\n\treturn client.query(PG_TABLE_SCHEMA, table)\n}\n\nfunc (client *Client) TableInfo(table string) (*Result, error) {\n\treturn client.query(PG_TABLE_INFO, table)\n}\n\nfunc (client *Client) TableIndexes(table string) (*Result, error) {\n\tres, err := client.query(PG_TABLE_INDEXES, table)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, err\n}\n\nfunc (client *Client) Query(query string) (*Result, error) {\n\tclient.recordQuery(query)\n\treturn client.query(query)\n}\n\nfunc (client *Client) query(query string, args ...interface{}) (*Result, error) {\n\trows, err := client.db.Queryx(query, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tcols, err := rows.Columns()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := Result{\n\t\tColumns: cols,\n\t}\n\n\tfor rows.Next() {\n\t\tobj, err := rows.SliceScan()\n\n\t\tfor i, item := range obj {\n\t\t\tif item == nil {\n\t\t\t\tobj[i] = nil\n\t\t\t} else {\n\t\t\t\tt := reflect.TypeOf(item).Kind().String()\n\n\t\t\t\tif t == \"slice\" {\n\t\t\t\t\tobj[i] = string(item.([]byte))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err == nil {\n\t\t\tresult.Rows = append(result.Rows, obj)\n\t\t}\n\t}\n\n\treturn &result, nil\n}\n\nfunc (res *Result) Format() []map[string]interface{} {\n\tvar items []map[string]interface{}\n\n\tfor _, row := range res.Rows {\n\t\titem := make(map[string]interface{})\n\n\t\tfor i, c := range res.Columns {\n\t\t\titem[c] = row[i]\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc (res *Result) CSV() []byte {\n\tbuff := &bytes.Buffer{}\n\twriter := csv.NewWriter(buff)\n\n\twriter.Write(res.Columns)\n\n\tfor _, row := range res.Rows {\n\t\trecord := make([]string, len(res.Columns))\n\n\t\tfor i, item := range row {\n\t\t\tif item != nil {\n\t\t\t\trecord[i] = fmt.Sprintf(\"%v\", item)\n\t\t\t} else {\n\t\t\t\trecord[i] = \"\"\n\t\t\t}\n\t\t}\n\n\t\terr := writer.Write(record)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\twriter.Flush()\n\treturn buff.Bytes()\n}\n<commit_msg>Propertly initialize string slice for Tables() method<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n)\n\ntype Client struct {\n\tdb      *sqlx.DB\n\thistory []string\n}\n\ntype Row []interface{}\n\ntype Result struct {\n\tColumns []string `json:\"columns\"`\n\tRows    []Row    `json:\"rows\"`\n}\n\nfunc NewClient() (*Client, error) {\n\tdb, err := sqlx.Open(\"postgres\", getConnectionString())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{db: db}, nil\n}\n\nfunc NewClientFromUrl(url string) (*Client, error) {\n\tdb, err := sqlx.Open(\"postgres\", url)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{db: db}, nil\n}\n\nfunc (client *Client) Test() error {\n\treturn client.db.Ping()\n}\n\nfunc (client *Client) recordQuery(query string) {\n\tclient.history = append(client.history, query)\n}\n\nfunc (client *Client) Info() (*Result, error) {\n\treturn client.query(PG_INFO)\n}\n\nfunc (client *Client) Databases() ([]string, error) {\n\tres, err := client.query(PG_DATABASES)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar tables []string\n\n\tfor _, row := range res.Rows {\n\t\ttables = append(tables, row[0].(string))\n\t}\n\n\treturn tables, nil\n}\n\nfunc (client *Client) Tables() ([]string, error) {\n\tres, err := client.query(PG_TABLES)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := make([]string, 0)\n\n\tfor _, row := range res.Rows {\n\t\tresults = append(results, row[0].(string))\n\t}\n\n\treturn results, nil\n}\n\nfunc (client *Client) Table(table string) (*Result, error) {\n\treturn client.query(PG_TABLE_SCHEMA, table)\n}\n\nfunc (client *Client) TableInfo(table string) (*Result, error) {\n\treturn client.query(PG_TABLE_INFO, table)\n}\n\nfunc (client *Client) TableIndexes(table string) (*Result, error) {\n\tres, err := client.query(PG_TABLE_INDEXES, table)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, err\n}\n\nfunc (client *Client) Query(query string) (*Result, error) {\n\tclient.recordQuery(query)\n\treturn client.query(query)\n}\n\nfunc (client *Client) query(query string, args ...interface{}) (*Result, error) {\n\trows, err := client.db.Queryx(query, args...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer rows.Close()\n\n\tcols, err := rows.Columns()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := Result{\n\t\tColumns: cols,\n\t}\n\n\tfor rows.Next() {\n\t\tobj, err := rows.SliceScan()\n\n\t\tfor i, item := range obj {\n\t\t\tif item == nil {\n\t\t\t\tobj[i] = nil\n\t\t\t} else {\n\t\t\t\tt := reflect.TypeOf(item).Kind().String()\n\n\t\t\t\tif t == \"slice\" {\n\t\t\t\t\tobj[i] = string(item.([]byte))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err == nil {\n\t\t\tresult.Rows = append(result.Rows, obj)\n\t\t}\n\t}\n\n\treturn &result, nil\n}\n\nfunc (res *Result) Format() []map[string]interface{} {\n\tvar items []map[string]interface{}\n\n\tfor _, row := range res.Rows {\n\t\titem := make(map[string]interface{})\n\n\t\tfor i, c := range res.Columns {\n\t\t\titem[c] = row[i]\n\t\t}\n\n\t\titems = append(items, item)\n\t}\n\n\treturn items\n}\n\nfunc (res *Result) CSV() []byte {\n\tbuff := &bytes.Buffer{}\n\twriter := csv.NewWriter(buff)\n\n\twriter.Write(res.Columns)\n\n\tfor _, row := range res.Rows {\n\t\trecord := make([]string, len(res.Columns))\n\n\t\tfor i, item := range row {\n\t\t\tif item != nil {\n\t\t\t\trecord[i] = fmt.Sprintf(\"%v\", item)\n\t\t\t} else {\n\t\t\t\trecord[i] = \"\"\n\t\t\t}\n\t\t}\n\n\t\terr := writer.Write(record)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\twriter.Flush()\n\treturn buff.Bytes()\n}\n<|endoftext|>"}
{"text":"<commit_before>package prisclient\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/priscillachat\/prislog\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype Client struct {\n\traw      net.Conn\n\tdecoder  *json.Decoder\n\tencoder  *json.Encoder\n\tSourceId string\n\tLogger   *prislog.PrisLogger\n}\n\ntype CommandBlock struct {\n\tId      string   `json:\"id,omitempty\"`\n\tAction  string   `json:\"action,omitempty\"`\n\tType    string   `json:\"type,omitempty\"`\n\tTime    int64    `json:\"time,omitempty\"`\n\tData    string   `json:\"data,omitempty\"`\n\tArray   []string `json:\"array,omitempty\"`\n\tOptions []string `json:\"options,omitempty\"`\n}\n\ntype MessageBlock struct {\n\tMessage   string `json:\"message,omitempty\"`\n\tFrom      string `json:\"from,omitempty\"`\n\tRoom      string `json:\"room,omitempty\"`\n\tMentioned bool   `json:\"mentioned,omitempty\"`\n}\n\ntype Query struct {\n\tType    string        `json:\"type,omitempty\"`\n\tSource  string        `json:\"source,omitempty\"`\n\tTo      string        `json:\"to,omitempty\"`\n\tCommand *CommandBlock `json:\"command,omitempty\"`\n\tMessage *MessageBlock `json:\"message,omitempty\"`\n}\n\nfunc RandomId() string {\n\tb := make([]byte, 8)\n\tio.ReadFull(rand.Reader, b)\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc NewClient(host, port string,\n\tlogger *prislog.PrisLog) (*Client, error) {\n\n\tpris := new(Client)\n\n\tpris.Logger = logger\n\n\tconn, err := net.Dial(\"tcp\", host+\":\"+port)\n\n\tif err != nil {\n\t\treturn pris, err\n\t}\n\n\tpris.raw = conn\n\tpris.decoder = json.NewDecoder(pris.raw)\n\tpris.encoder = json.NewEncoder(pris.raw)\n\n\treturn pris, nil\n}\n\nfunc (pris *Client) Engage(clienttype, sourceid string) error {\n\tif clienttype != \"adapter\" && clienttype != \"responder\" {\n\t\treturn errors.New(\"client type has to be adapter or responder\")\n\t}\n\n\tq := Query{\n\t\tType:   \"command\",\n\t\tSource: sourceid,\n\t\tCommand: &CommandBlock{\n\t\t\tId:     RandomId(),\n\t\t\tAction: \"engage\",\n\t\t\tType:   clienttype,\n\t\t\tTime:   time.Now().Unix(),\n\t\t},\n\t}\n\n\tpris.SourceId = sourceid\n\n\treturn pris.encoder.Encode(&q)\n}\n\nfunc (pris *Client) listen(out chan<- *Query) {\n\tvar q *Query\n\tfor {\n\t\tq = new(Query)\n\t\terr := pris.decoder.Decode(q)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tout <- &Query{\n\t\t\t\t\tType:   \"command\",\n\t\t\t\t\tSource: \"pris\",\n\t\t\t\t\tCommand: &CommandBlock{\n\t\t\t\t\t\tAction: \"disengage\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.Logger.Debug.Println(\"Query received:\", *q)\n\t\t\tif q.Type == \"message\" {\n\t\t\t\tpris.Logger.Debug.Println(\"Message:\", q.Message.Message)\n\t\t\t\tpris.Logger.Debug.Println(\"From:\", q.Message.From)\n\t\t\t\tpris.Logger.Debug.Println(\"Room:\", q.Message.Room)\n\t\t\t}\n\t\t\tout <- q\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query from server(?!!):\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) Run(toPris <-chan *Query, fromPris chan<- *Query) {\n\n\tgo pris.listen(fromPris)\n\tvar q *Query\n\tfor {\n\t\tq = <-toPris\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.encoder.Encode(q)\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query:\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) ValidateQuery(q *Query) bool {\n\tswitch {\n\tcase q.Type == \"command\" && q.Command != nil:\n\t\treturn true\n\tcase q.Type == \"message\" && q.Message != nil && q.Message.Room != \"\":\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>typo on the logger ref<commit_after>package prisclient\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/priscillachat\/prislog\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\ntype Client struct {\n\traw      net.Conn\n\tdecoder  *json.Decoder\n\tencoder  *json.Encoder\n\tSourceId string\n\tLogger   *prislog.PrisLog\n}\n\ntype CommandBlock struct {\n\tId      string   `json:\"id,omitempty\"`\n\tAction  string   `json:\"action,omitempty\"`\n\tType    string   `json:\"type,omitempty\"`\n\tTime    int64    `json:\"time,omitempty\"`\n\tData    string   `json:\"data,omitempty\"`\n\tArray   []string `json:\"array,omitempty\"`\n\tOptions []string `json:\"options,omitempty\"`\n}\n\ntype MessageBlock struct {\n\tMessage   string `json:\"message,omitempty\"`\n\tFrom      string `json:\"from,omitempty\"`\n\tRoom      string `json:\"room,omitempty\"`\n\tMentioned bool   `json:\"mentioned,omitempty\"`\n}\n\ntype Query struct {\n\tType    string        `json:\"type,omitempty\"`\n\tSource  string        `json:\"source,omitempty\"`\n\tTo      string        `json:\"to,omitempty\"`\n\tCommand *CommandBlock `json:\"command,omitempty\"`\n\tMessage *MessageBlock `json:\"message,omitempty\"`\n}\n\nfunc RandomId() string {\n\tb := make([]byte, 8)\n\tio.ReadFull(rand.Reader, b)\n\treturn fmt.Sprintf(\"%x\", b)\n}\n\nfunc NewClient(host, port string,\n\tlogger *prislog.PrisLog) (*Client, error) {\n\n\tpris := new(Client)\n\n\tpris.Logger = logger\n\n\tconn, err := net.Dial(\"tcp\", host+\":\"+port)\n\n\tif err != nil {\n\t\treturn pris, err\n\t}\n\n\tpris.raw = conn\n\tpris.decoder = json.NewDecoder(pris.raw)\n\tpris.encoder = json.NewEncoder(pris.raw)\n\n\treturn pris, nil\n}\n\nfunc (pris *Client) Engage(clienttype, sourceid string) error {\n\tif clienttype != \"adapter\" && clienttype != \"responder\" {\n\t\treturn errors.New(\"client type has to be adapter or responder\")\n\t}\n\n\tq := Query{\n\t\tType:   \"command\",\n\t\tSource: sourceid,\n\t\tCommand: &CommandBlock{\n\t\t\tId:     RandomId(),\n\t\t\tAction: \"engage\",\n\t\t\tType:   clienttype,\n\t\t\tTime:   time.Now().Unix(),\n\t\t},\n\t}\n\n\tpris.SourceId = sourceid\n\n\treturn pris.encoder.Encode(&q)\n}\n\nfunc (pris *Client) listen(out chan<- *Query) {\n\tvar q *Query\n\tfor {\n\t\tq = new(Query)\n\t\terr := pris.decoder.Decode(q)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tout <- &Query{\n\t\t\t\t\tType:   \"command\",\n\t\t\t\t\tSource: \"pris\",\n\t\t\t\t\tCommand: &CommandBlock{\n\t\t\t\t\t\tAction: \"disengage\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.Logger.Debug.Println(\"Query received:\", *q)\n\t\t\tif q.Type == \"message\" {\n\t\t\t\tpris.Logger.Debug.Println(\"Message:\", q.Message.Message)\n\t\t\t\tpris.Logger.Debug.Println(\"From:\", q.Message.From)\n\t\t\t\tpris.Logger.Debug.Println(\"Room:\", q.Message.Room)\n\t\t\t}\n\t\t\tout <- q\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query from server(?!!):\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) Run(toPris <-chan *Query, fromPris chan<- *Query) {\n\n\tgo pris.listen(fromPris)\n\tvar q *Query\n\tfor {\n\t\tq = <-toPris\n\t\tif pris.ValidateQuery(q) {\n\t\t\tpris.encoder.Encode(q)\n\t\t} else {\n\t\t\tpris.Logger.Error.Println(\"Invalid query:\", q)\n\t\t}\n\t}\n}\n\nfunc (pris *Client) ValidateQuery(q *Query) bool {\n\tswitch {\n\tcase q.Type == \"command\" && q.Command != nil:\n\t\treturn true\n\tcase q.Type == \"message\" && q.Message != nil && q.Message.Room != \"\":\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package pusher\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\n\/\/ ErrEvent error on event\nconst ErrEvent = \"ErrEvent\"\n\n\/\/ Client is a pusher client\ntype Client struct {\n\tws                 *websocket.Conn\n\tEvents             chan *Event\n\tStop               chan bool\n\tsubscribedChannels *subscribedChannels\n\tbinders            map[string]chan *Event\n\tm                  sync.Mutex\n}\n\n\/\/ heartbeat send a ping frame to server each - TODO reconnect on disconnect\nfunc (c *Client) heartbeat() {\n\tfor !c.Stopped() {\n\t\twebsocket.Message.Send(c.ws, `{\"event\":\"pusher:ping\",\"data\":\"{}\"}`)\n\t\ttime.Sleep(HEARTBEAT_RATE * time.Second)\n\t}\n}\n\n\/\/ listen to Pusher server and process\/dispatch recieved events\nfunc (c *Client) listen() {\n\tfor !c.Stopped() {\n\t\tvar event Event\n\t\terr := websocket.JSON.Receive(c.ws, &event)\n\t\tif err != nil {\n\t\t\tif c.Stopped() {\n\t\t\t\t\/\/ Normal termination (ws Receive returns error when ws is\n\t\t\t\t\/\/ closed by other goroutine)\n\t\t\t\tlog.Println(\"Listen error and c stopped :\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.m.Lock()\n\t\t\tch, ok := c.binders[ErrEvent]\n\t\t\tc.m.Unlock()\n\t\t\tif ok {\n\t\t\t\tch <- &Event{\n\t\t\t\t\tEvent: ErrEvent,\n\t\t\t\t\tData:  err.Error()}\n\t\t\t}\n\t\t\t\/\/ no matter what error happened, will log again and again\n\t\t\t\/\/ so return\n\t\t\t\/\/ err eg:\n\t\t\t\/\/ 1. use of closed network connection\n\t\t\t\/\/ 2. EOF (network error)\n\t\t\t\/\/ 3. ...\n\t\t\tlog.Println(\"Listen error : \", err)\n\t\t\treturn\n\t\t}\n\t\tswitch event.Event {\n\t\tcase \"pusher:ping\":\n\t\t\twebsocket.Message.Send(c.ws, `{\"event\":\"pusher:pong\",\"data\":\"{}\"}`)\n\t\tcase \"pusher:pong\":\n\t\tcase \"pusher:error\":\n\t\t\tlog.Println(\"Event error received: \", event.Data)\n\t\tdefault:\n\t\t\tc.m.Lock()\n\t\t\tch, ok := c.binders[event.Event]\n\t\t\tc.m.Unlock()\n\t\t\tif ok {\n\t\t\t\tch <- &event\n\t\t\t}\n\t\t}\n\n\t}\n}\n\n\/\/ Subscribe ..to a channel\nfunc (c *Client) Subscribe(channel string) (err error) {\n\t\/\/ Already subscribed ?\n\tif c.subscribedChannels.contains(channel) {\n\t\terr = fmt.Errorf(\"Channel %s already subscribed\", channel)\n\t\treturn\n\t}\n\terr = websocket.Message.Send(c.ws, fmt.Sprintf(`{\"event\":\"pusher:subscribe\",\"data\":{\"channel\":\"%s\"}}`, channel))\n\tif err != nil {\n\t\treturn\n\t}\n\terr = c.subscribedChannels.add(channel)\n\treturn\n}\n\n\/\/ Unsubscribe from a channel\nfunc (c *Client) Unsubscribe(channel string) (err error) {\n\t\/\/ subscribed ?\n\tif !c.subscribedChannels.contains(channel) {\n\t\terr = fmt.Errorf(\"Client isn't subscrived to %s\", channel)\n\t\treturn\n\t}\n\terr = websocket.Message.Send(c.ws, fmt.Sprintf(`{\"event\":\"pusher:unsubscribe\",\"data\":{\"channel\":\"%s\"}}`, channel))\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ Remove channel from subscribedChannels slice\n\tc.subscribedChannels.remove(channel)\n\treturn\n}\n\n\/\/ Bind an event\nfunc (c *Client) Bind(evt string) (dataChannel chan *Event, err error) {\n\t\/\/ Already binded\n\tc.m.Lock()\n\t_, ok := c.binders[evt]\n\tc.m.Unlock()\n\tif ok {\n\t\terr = fmt.Errorf(\"Event %s already binded\", evt)\n\t\treturn\n\t}\n\t\/\/ New data channel\n\tdataChannel = make(chan *Event, EVENT_CHANNEL_BUFF_SIZE)\n\tc.m.Lock()\n\tc.binders[evt] = dataChannel\n\tc.m.Unlock()\n\treturn\n}\n\n\/\/ Unbind a event\nfunc (c *Client) Unbind(evt string) {\n\tc.m.Lock()\n\tdelete(c.binders, evt)\n\tc.m.Unlock()\n}\n\n\/\/ Stopped checks, in a non-blocking way, if client has been closed.\nfunc (c *Client) Stopped() bool {\n\tselect {\n\tcase <-c.Stop:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ Close the underlying Pusher connection (websocket)\nfunc (c *Client) Close() error {\n\t\/\/ Closing the Stop channel \"broadcasts\" the stop signal.\n\tclose(c.Stop)\n\treturn c.ws.Close()\n}\n\n\/\/ NewCustomClient return a custom client\nfunc NewCustomClient(appKey, host, scheme string) (*Client, error) {\n\tws, err := NewWSS(appKey, host, scheme)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsChannels := new(subscribedChannels)\n\tsChannels.channels = make([]string, 0)\n\tpClient := Client{ws, make(chan *Event, EVENT_CHANNEL_BUFF_SIZE), make(chan bool), sChannels, make(map[string]chan *Event), sync.Mutex{}}\n\tgo pClient.heartbeat()\n\tgo pClient.listen()\n\treturn &pClient, nil\n}\n\n\/\/ NewWSS return a websocket connexion\nfunc NewWSS(appKey, host, scheme string) (ws *websocket.Conn, err error) {\n\torigin := \"http:\/\/localhost\/\"\n\turl := scheme + \":\/\/\" + host + \"\/app\/\" + appKey + \"?protocol=\" + PROTOCOL_VERSION\n\tws, err = websocket.Dial(url, \"\", origin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar resp = make([]byte, 11000) \/\/ Pusher max message size is 10KB\n\tn, err := ws.Read(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar eventStub EventStub\n\terr = json.Unmarshal(resp[0:n], &eventStub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch eventStub.Event {\n\tcase \"pusher:error\":\n\t\tvar ewe EventError\n\t\terr = json.Unmarshal(resp[0:n], &ewe)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, ewe\n\tcase \"pusher:connection_established\":\n\t\treturn ws, nil\n\t}\n\treturn nil, errors.New(\"Ooooops something wrong happen\")\n}\n\n\/\/ NewClient initialize & return a Pusher client\nfunc NewClient(appKey string) (*Client, error) {\n\treturn NewCustomClient(appKey, \"ws.pusherapp.com:443\", \"wss\")\n}\n<commit_msg>Adding error channel.<commit_after>package pusher\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\n\/\/ ErrEvent error on event\nconst ErrEvent = \"ErrEvent\"\n\n\/\/ Client is a pusher client\ntype Client struct {\n\tws                 *websocket.Conn\n\tEvents             chan *Event\n\tStop               chan bool\n\tErrors             chan error\n\tsubscribedChannels *subscribedChannels\n\tbinders            map[string]chan *Event\n\tm                  sync.Mutex\n}\n\nfunc (c *Client) sendError(err error) {\n\tselect {\n\tcase c.Errors <- err:\n\tdefault:\n\t\tlog.Println(err)\n\t}\n}\n\n\/\/ heartbeat send a ping frame to server each - TODO reconnect on disconnect\nfunc (c *Client) heartbeat() {\n\tfor !c.Stopped() {\n\t\tif err := websocket.Message.Send(c.ws, `{\"event\":\"pusher:ping\",\"data\":\"{}\"}`); err != nil {\n\t\t\tc.sendError(err)\n\t\t}\n\t\ttime.Sleep(HEARTBEAT_RATE * time.Second)\n\t}\n}\n\n\/\/ listen to Pusher server and process\/dispatch recieved events\nfunc (c *Client) listen() {\n\tfor !c.Stopped() {\n\t\tvar event Event\n\t\terr := websocket.JSON.Receive(c.ws, &event)\n\t\tif err != nil {\n\t\t\tif c.Stopped() {\n\t\t\t\t\/\/ Normal termination (ws Receive returns error when ws is\n\t\t\t\t\/\/ closed by other goroutine)\n\t\t\t\tc.sendError(fmt.Errorf(\"Listen error and c stopped : %s\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.m.Lock()\n\t\t\tch, ok := c.binders[ErrEvent]\n\t\t\tc.m.Unlock()\n\t\t\tif ok {\n\t\t\t\tch <- &Event{\n\t\t\t\t\tEvent: ErrEvent,\n\t\t\t\t\tData:  err.Error()}\n\t\t\t}\n\t\t\t\/\/ no matter what error happened, will log again and again\n\t\t\t\/\/ so return\n\t\t\t\/\/ err eg:\n\t\t\t\/\/ 1. use of closed network connection\n\t\t\t\/\/ 2. EOF (network error)\n\t\t\t\/\/ 3. ...\n\t\t\tc.sendError(fmt.Errorf(\"Listen error : %s\", err))\n\t\t\treturn\n\t\t}\n\t\tswitch event.Event {\n\t\tcase \"pusher:ping\":\n\t\t\twebsocket.Message.Send(c.ws, `{\"event\":\"pusher:pong\",\"data\":\"{}\"}`)\n\t\tcase \"pusher:pong\":\n\t\tcase \"pusher:error\":\n\t\t\tc.sendError(fmt.Errorf(\"Event error received : %s\", event.Data))\n\t\tdefault:\n\t\t\tc.m.Lock()\n\t\t\tch, ok := c.binders[event.Event]\n\t\t\tc.m.Unlock()\n\t\t\tif ok {\n\t\t\t\tch <- &event\n\t\t\t}\n\t\t}\n\n\t}\n}\n\n\/\/ Subscribe ..to a channel\nfunc (c *Client) Subscribe(channel string) (err error) {\n\t\/\/ Already subscribed ?\n\tif c.subscribedChannels.contains(channel) {\n\t\terr = fmt.Errorf(\"Channel %s already subscribed\", channel)\n\t\treturn\n\t}\n\terr = websocket.Message.Send(c.ws, fmt.Sprintf(`{\"event\":\"pusher:subscribe\",\"data\":{\"channel\":\"%s\"}}`, channel))\n\tif err != nil {\n\t\treturn\n\t}\n\terr = c.subscribedChannels.add(channel)\n\treturn\n}\n\n\/\/ Unsubscribe from a channel\nfunc (c *Client) Unsubscribe(channel string) (err error) {\n\t\/\/ subscribed ?\n\tif !c.subscribedChannels.contains(channel) {\n\t\terr = fmt.Errorf(\"Client isn't subscrived to %s\", channel)\n\t\treturn\n\t}\n\terr = websocket.Message.Send(c.ws, fmt.Sprintf(`{\"event\":\"pusher:unsubscribe\",\"data\":{\"channel\":\"%s\"}}`, channel))\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ Remove channel from subscribedChannels slice\n\tc.subscribedChannels.remove(channel)\n\treturn\n}\n\n\/\/ Bind an event\nfunc (c *Client) Bind(evt string) (dataChannel chan *Event, err error) {\n\t\/\/ Already binded\n\tc.m.Lock()\n\t_, ok := c.binders[evt]\n\tc.m.Unlock()\n\tif ok {\n\t\terr = fmt.Errorf(\"Event %s already binded\", evt)\n\t\treturn\n\t}\n\t\/\/ New data channel\n\tdataChannel = make(chan *Event, EVENT_CHANNEL_BUFF_SIZE)\n\tc.m.Lock()\n\tc.binders[evt] = dataChannel\n\tc.m.Unlock()\n\treturn\n}\n\n\/\/ Unbind a event\nfunc (c *Client) Unbind(evt string) {\n\tc.m.Lock()\n\tdelete(c.binders, evt)\n\tc.m.Unlock()\n}\n\n\/\/ Stopped checks, in a non-blocking way, if client has been closed.\nfunc (c *Client) Stopped() bool {\n\tselect {\n\tcase <-c.Stop:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ Close the underlying Pusher connection (websocket)\nfunc (c *Client) Close() error {\n\t\/\/ Closing the Stop channel \"broadcasts\" the stop signal.\n\tclose(c.Stop)\n\treturn c.ws.Close()\n}\n\n\/\/ NewCustomClient return a custom client\nfunc NewCustomClient(appKey, host, scheme string) (*Client, error) {\n\tws, err := NewWSS(appKey, host, scheme)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsChannels := new(subscribedChannels)\n\tsChannels.channels = make([]string, 0)\n\tpClient := Client{\n\t\tws:                 ws,\n\t\tEvents:             make(chan *Event, EVENT_CHANNEL_BUFF_SIZE),\n\t\tStop:               make(chan bool),\n\t\tErrors:             make(chan error),\n\t\tsubscribedChannels: sChannels,\n\t\tbinders:            make(map[string]chan *Event)}\n\tgo pClient.heartbeat()\n\tgo pClient.listen()\n\treturn &pClient, nil\n}\n\n\/\/ NewWSS return a websocket connexion\nfunc NewWSS(appKey, host, scheme string) (ws *websocket.Conn, err error) {\n\torigin := \"http:\/\/localhost\/\"\n\turl := scheme + \":\/\/\" + host + \"\/app\/\" + appKey + \"?protocol=\" + PROTOCOL_VERSION\n\tws, err = websocket.Dial(url, \"\", origin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar resp = make([]byte, 11000) \/\/ Pusher max message size is 10KB\n\tn, err := ws.Read(resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar eventStub EventStub\n\terr = json.Unmarshal(resp[0:n], &eventStub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch eventStub.Event {\n\tcase \"pusher:error\":\n\t\tvar ewe EventError\n\t\terr = json.Unmarshal(resp[0:n], &ewe)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, ewe\n\tcase \"pusher:connection_established\":\n\t\treturn ws, nil\n\t}\n\treturn nil, errors.New(\"Ooooops something wrong happen\")\n}\n\n\/\/ NewClient initialize & return a Pusher client\nfunc NewClient(appKey string) (*Client, error) {\n\treturn NewCustomClient(appKey, \"ws.pusherapp.com:443\", \"wss\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package flowdock\n\nimport (\n\t\"github.com\/njern\/httpstream\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tflowdockAPIURL = \"https:\/\/api.flowdock.com\"\n)\n\n\/\/ A Client is a Flowdock API client. It should be created\n\/\/ using NewClient() and provided with a valid API key.\ntype Client struct {\n\tapiKey         string\n\tstreamClient   *httpstream.Client\n\torganizations  []Organization\n\tAvailableFlows []Flow \/\/ TODO: Change to map[ID]Flow\n\tUsers          map[string]User\n}\n\n\/\/ NewClient creates a new Client and automatically fetches\n\/\/ information about joined flows, known users, etc.\nfunc NewClient(apiKey string) *Client {\n\tclient := &Client{apiKey: apiKey}\n\n\tvar wg sync.WaitGroup\n\twg.Add(3)\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.Users, err = getUsers(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get users: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.AvailableFlows, err = getFlows(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get flows: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.organizations, err = getOrganizations(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get organizations: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n\n\treturn client\n}\n\n\/\/ Connect connects the client to the streaming API. Flowdock events will\n\/\/ be sent back to the caller over the events channel, as will errors.\n\/\/ If flows is nil, the stream will contain events from all the\n\/\/ flows the user has joined.\n\/\/ TODO: pass online state (active \/ idle \/ offline)\n\/\/ TODO: Flag for whether to receive priv messages or not (now defaulting to not)\nfunc (c *Client) Connect(flows []Flow, events chan Event) error {\n\tstream := make(chan []byte, 1024) \/\/ Incoming (raw) data channel\n\tdone := make(chan error)          \/\/ Error channel\n\tflowURL := flowStreamURL(c, flows)\n\n\t\/\/ Set up the stream. Note we need to set a random password string (\"BATMAN\") or things will break.\n\tc.streamClient = httpstream.NewBasicAuthClient(c.apiKey, \"BATMAN\", func(line []byte) {\n\t\tstream <- line\n\t})\n\n\t\/\/ Initialize the connection\n\terr := c.streamClient.Connect(flowURL, done)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Fire up a goroutine that will listen to the stream\n\t\/\/ and pass events back to the client.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-stream:\n\t\t\t\tparsedEvent, err := unmarshalFlowdockJSONEvent(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tevents <- err\n\t\t\t\t} else {\n\t\t\t\t\tevents <- parsedEvent\n\t\t\t\t}\n\n\t\t\tcase err := <-done:\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ TODO: Actually handle errors instead of just closing the channel\n\t\t\t\t\tevents <- err\n\t\t\t\t\tclose(events)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ DetailsForUser returns a User object for the given user ID.\nfunc (c *Client) DetailsForUser(id string) User {\n\treturn c.Users[id]\n}\n\n\/\/ DetailsForFlow returns a Flow object for the given Flow ID\n\/\/ or nil if the client can't access details for that flow.\nfunc (c *Client) DetailsForFlow(id string) *Flow {\n\tfor _, flow := range c.AvailableFlows {\n\t\tif flow.ID == id {\n\t\t\treturn &flow\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SendMessage starts a new thread in the specified Flow\n\/\/ TODO: Implement this\nfunc SendMessage(flow Flow, message string) error {\n\treturn nil\n}\n\n\/\/ SendReply replies to an existing thread\n\/\/ TODO: Implement this\nfunc SendReply(flow Flow, reply string, threadID int64) error {\n\treturn nil\n}\n\n\/\/ flowStreamURL creates the complete URL used to connect\n\/\/ to the streaming API endpoint, including the flows filter.\nfunc flowStreamURL(c *Client, flows []Flow) string {\n\tif flows == nil {\n\t\t\/\/ Add all the flows!\n\t\tflows = c.AvailableFlows\n\t}\n\n\tflowURL := \"https:\/\/stream.flowdock.com\/flows?filter=\"\n\tfor i, flow := range flows {\n\t\tif i == len(flows)-1 {\n\t\t\t\/\/ Special case; Last item - no comma.\n\t\t\tflowURL = flowURL + flow.Organization.APIName + \"\/\" + flow.APIName\n\t\t} else {\n\t\t\tflowURL = flowURL + flow.Organization.APIName + \"\/\" + flow.APIName + \",\"\n\t\t}\n\t}\n\treturn flowURL\n}\n<commit_msg>Handle keep alive more nicely<commit_after>package flowdock\n\nimport (\n\t\"github.com\/njern\/httpstream\"\n\t\"log\"\n\t\"sync\"\n)\n\nconst (\n\tflowdockAPIURL = \"https:\/\/api.flowdock.com\"\n)\n\n\/\/ A Client is a Flowdock API client. It should be created\n\/\/ using NewClient() and provided with a valid API key.\ntype Client struct {\n\tapiKey         string\n\tstreamClient   *httpstream.Client\n\torganizations  []Organization\n\tAvailableFlows []Flow \/\/ TODO: Change to map[ID]Flow\n\tUsers          map[string]User\n}\n\n\/\/ NewClient creates a new Client and automatically fetches\n\/\/ information about joined flows, known users, etc.\nfunc NewClient(apiKey string) *Client {\n\tclient := &Client{apiKey: apiKey}\n\n\tvar wg sync.WaitGroup\n\twg.Add(3)\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.Users, err = getUsers(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get users: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.AvailableFlows, err = getFlows(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get flows: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\tgo func() {\n\t\tvar err error\n\t\tclient.organizations, err = getOrganizations(apiKey)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get organizations: %v\", err)\n\t\t}\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n\n\treturn client\n}\n\n\/\/ Connect connects the client to the streaming API. Flowdock events will\n\/\/ be sent back to the caller over the events channel, as will errors.\n\/\/ If flows is nil, the stream will contain events from all the\n\/\/ flows the user has joined.\n\/\/ TODO: pass online state (active \/ idle \/ offline)\n\/\/ TODO: Flag for whether to receive priv messages or not (now defaulting to not)\nfunc (c *Client) Connect(flows []Flow, events chan Event) error {\n\tstream := make(chan []byte, 1024) \/\/ Incoming (raw) data channel\n\tdone := make(chan error)          \/\/ Error channel\n\tflowURL := flowStreamURL(c, flows)\n\n\t\/\/ Set up the stream. Note we need to set a random password string (\"BATMAN\") or things will break.\n\tc.streamClient = httpstream.NewBasicAuthClient(c.apiKey, \"BATMAN\", func(line []byte) {\n\t\tstream <- line\n\t})\n\n\t\/\/ Initialize the connection\n\terr := c.streamClient.Connect(flowURL, done)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Fire up a goroutine that will listen to the stream\n\t\/\/ and pass events back to the client.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-stream:\n\t\t\t\tif bytes.Equal(event, []byte{10}) {\n\t\t\t\t\tlog.Printf(\"Keepalive, ignore...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tparsedEvent, err := unmarshalFlowdockJSONEvent(event)\n\t\t\t\tif err != nil {\n\t\t\t\t\tevents <- err\n\t\t\t\t} else {\n\t\t\t\t\tevents <- parsedEvent\n\t\t\t\t}\n\n\t\t\tcase err := <-done:\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ TODO: Actually handle errors instead of just closing the channel\n\t\t\t\t\tevents <- err\n\t\t\t\t\tclose(events)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ DetailsForUser returns a User object for the given user ID.\nfunc (c *Client) DetailsForUser(id string) User {\n\treturn c.Users[id]\n}\n\n\/\/ DetailsForFlow returns a Flow object for the given Flow ID\n\/\/ or nil if the client can't access details for that flow.\nfunc (c *Client) DetailsForFlow(id string) *Flow {\n\tfor _, flow := range c.AvailableFlows {\n\t\tif flow.ID == id {\n\t\t\treturn &flow\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SendMessage starts a new thread in the specified Flow\n\/\/ TODO: Implement this\nfunc SendMessage(flow Flow, message string) error {\n\treturn nil\n}\n\n\/\/ SendReply replies to an existing thread\n\/\/ TODO: Implement this\nfunc SendReply(flow Flow, reply string, threadID int64) error {\n\treturn nil\n}\n\n\/\/ flowStreamURL creates the complete URL used to connect\n\/\/ to the streaming API endpoint, including the flows filter.\nfunc flowStreamURL(c *Client, flows []Flow) string {\n\tif flows == nil {\n\t\t\/\/ Add all the flows!\n\t\tflows = c.AvailableFlows\n\t}\n\n\tflowURL := \"https:\/\/stream.flowdock.com\/flows?filter=\"\n\tfor i, flow := range flows {\n\t\tif i == len(flows)-1 {\n\t\t\t\/\/ Special case; Last item - no comma.\n\t\t\tflowURL = flowURL + flow.Organization.APIName + \"\/\" + flow.APIName\n\t\t} else {\n\t\t\tflowURL = flowURL + flow.Organization.APIName + \"\/\" + flow.APIName + \",\"\n\t\t}\n\t}\n\treturn flowURL\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package amplitude provides access to the Amplitude API\npackage amplitude\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nconst eventEndpoint = \"https:\/\/api.amplitude.com\/httpapi\"\nconst identifyEndpoint = \"https:\/\/api.amplitude.com\/identify\"\n\n\/\/ Client manages the communication to the Amplitude API\ntype Client struct {\n\teventEndpoint    string\n\tidentifyEndpoint string\n\tkey              string\n\tclient           *http.Client\n}\n\ntype Event struct {\n\tAdid               string                 `json:\"adid,omitempty\"`\n\tAppVersion         string                 `json:\"app_version,omitempty\"`\n\tCarrier            string                 `json:\"carrier,omitempty\"`\n\tCity               string                 `json:\"city,omitempty\"`\n\tCountry            string                 `json:\"country,omitempty\"`\n\tDeviceBrand        string                 `json:\"device_brand,omitempty\"`\n\tDeviceId           string                 `json:\"device_id,omitempty\"`\n\tDeviceManufacturer string                 `json:\"device_manufacturer,omitempty\"`\n\tDeviceModel        string                 `json:\"device_model,omitempty\"`\n\tDeviceType         string                 `json:\"device_type,omitempty\"`\n\tDma                string                 `json:\"dma,omitempty\"`\n\tEventId            int                    `json:\"event_id,omitempty\"`\n\tEventProperties    map[string]interface{} `json:\"event_properties,omitempty\"`\n\tEventType          string                 `json:\"event_type,omitempty\"`\n\tGroups             map[string]interface{} `json:\"groups,omitempty\"`\n\tIfda               string                 `json:\"ifda,omitempty\"`\n\tInsertId           string                 `json:\"insert_id,omitempty\"`\n\tIp                 string                 `json:\"ip,omitempty\"`\n\tLanguage           string                 `json:\"language,omitempty\"`\n\tLocationLat        string                 `json:\"location_lat,omitempty\"`\n\tLocationLng        string                 `json:\"location_lng,omitempty\"`\n\tOsName             string                 `json:\"os_name,omitempty\"`\n\tOsVersion          string                 `json:\"os_version,omitempty\"`\n\tPaying             string                 `json:\"paying,omitempty\"`\n\tPlatform           string                 `json:\"platform,omitempty\"`\n\tPrice              float64                `json:\"price,omitempty\"`\n\tProductId          string                 `json:\"productId,omitempty\"`\n\tQuantity           int                    `json:\"quantity,omitempty\"`\n\tRegion             string                 `json:\"region,omitempty\"`\n\tRevenue            float64                `json:\"revenue,omitempty\"`\n\tRevenueType        string                 `json:\"revenueType,omitempty\"`\n\tSessionId          int64                  `json:\"session_id,omitempty\"`\n\tStartVersion       string                 `json:\"start_version,omitempty\"`\n\tTime               int64                  `json:\"time,omitempty\"`\n\tUserId             string                 `json:\"user_id,omitempty\"`\n\tUserProperties     map[string]interface{} `json:\"user_properties,omitempty\"`\n}\n\ntype Identify struct {\n\tAppVersion         string                 `json:\"app_version,omitempty\"`\n\tCarrier            string                 `json:\"carrier,omitempty\"`\n\tCity               string                 `json:\"city,omitempty\"`\n\tCountry            string                 `json:\"country,omitempty\"`\n\tDeviceBrand        string                 `json:\"device_brand,omitempty\"`\n\tDeviceId           string                 `json:\"device_id,omitempty\"`\n\tDeviceManufacturer string                 `json:\"device_manufacturer,omitempty\"`\n\tDeviceModel        string                 `json:\"device_model,omitempty\"`\n\tDeviceType         string                 `json:\"device_type,omitempty\"`\n\tDma                string                 `json:\"dma,omitempty\"`\n\tGroups             map[string]interface{} `json:\"groups,omitempty\"`\n\tLanguage           string                 `json:\"language,omitempty\"`\n\tOsName             string                 `json:\"os_name,omitempty\"`\n\tOsVersion          string                 `json:\"os_version,omitempty\"`\n\tPaying             string                 `json:\"paying,omitempty\"`\n\tPlatform           string                 `json:\"platform,omitempty\"`\n\tRegion             string                 `json:\"region,omitempty\"`\n\tStartVersion       string                 `json:\"start_version,omitempty\"`\n\tUserId             string                 `json:\"user_id,omitempty\"`\n\tUserProperties     map[string]interface{} `json:\"user_properties,omitempty\"`\n}\n\n\/\/ New client with API key\nfunc New(key string) *Client {\n\treturn &Client{\n\t\teventEndpoint:    eventEndpoint,\n\t\tidentifyEndpoint: identifyEndpoint,\n\t\tkey:              key,\n\t\tclient:           new(http.Client),\n\t}\n}\n\nfunc (c *Client) SetClient(client *http.Client) {\n\tc.client = client\n}\n\nfunc (c *Client) Event(msg Event) error {\n\tmsgJson, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.send(c.eventEndpoint, \"event\", string(msgJson))\n}\n\nfunc (c *Client) Identify(msg Identify) error {\n\tmsgJson, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.send(c.identifyEndpoint, \"identification\", string(msgJson))\n}\n\nfunc (c *Client) send(endpoint string, key string, value string) error {\n\tvalues := url.Values{}\n\tvalues.Add(\"api_key\", c.key)\n\tvalues.Add(key, value)\n\n\t_, err := c.client.PostForm(endpoint, values)\n\treturn err\n}\n<commit_msg>close response body.<commit_after>\/\/ Package amplitude provides access to the Amplitude API\npackage amplitude\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nconst eventEndpoint = \"https:\/\/api.amplitude.com\/httpapi\"\nconst identifyEndpoint = \"https:\/\/api.amplitude.com\/identify\"\n\n\/\/ Client manages the communication to the Amplitude API\ntype Client struct {\n\teventEndpoint    string\n\tidentifyEndpoint string\n\tkey              string\n\tclient           *http.Client\n}\n\ntype Event struct {\n\tAdid               string                 `json:\"adid,omitempty\"`\n\tAppVersion         string                 `json:\"app_version,omitempty\"`\n\tCarrier            string                 `json:\"carrier,omitempty\"`\n\tCity               string                 `json:\"city,omitempty\"`\n\tCountry            string                 `json:\"country,omitempty\"`\n\tDeviceBrand        string                 `json:\"device_brand,omitempty\"`\n\tDeviceId           string                 `json:\"device_id,omitempty\"`\n\tDeviceManufacturer string                 `json:\"device_manufacturer,omitempty\"`\n\tDeviceModel        string                 `json:\"device_model,omitempty\"`\n\tDeviceType         string                 `json:\"device_type,omitempty\"`\n\tDma                string                 `json:\"dma,omitempty\"`\n\tEventId            int                    `json:\"event_id,omitempty\"`\n\tEventProperties    map[string]interface{} `json:\"event_properties,omitempty\"`\n\tEventType          string                 `json:\"event_type,omitempty\"`\n\tGroups             map[string]interface{} `json:\"groups,omitempty\"`\n\tIfda               string                 `json:\"ifda,omitempty\"`\n\tInsertId           string                 `json:\"insert_id,omitempty\"`\n\tIp                 string                 `json:\"ip,omitempty\"`\n\tLanguage           string                 `json:\"language,omitempty\"`\n\tLocationLat        string                 `json:\"location_lat,omitempty\"`\n\tLocationLng        string                 `json:\"location_lng,omitempty\"`\n\tOsName             string                 `json:\"os_name,omitempty\"`\n\tOsVersion          string                 `json:\"os_version,omitempty\"`\n\tPaying             string                 `json:\"paying,omitempty\"`\n\tPlatform           string                 `json:\"platform,omitempty\"`\n\tPrice              float64                `json:\"price,omitempty\"`\n\tProductId          string                 `json:\"productId,omitempty\"`\n\tQuantity           int                    `json:\"quantity,omitempty\"`\n\tRegion             string                 `json:\"region,omitempty\"`\n\tRevenue            float64                `json:\"revenue,omitempty\"`\n\tRevenueType        string                 `json:\"revenueType,omitempty\"`\n\tSessionId          int64                  `json:\"session_id,omitempty\"`\n\tStartVersion       string                 `json:\"start_version,omitempty\"`\n\tTime               int64                  `json:\"time,omitempty\"`\n\tUserId             string                 `json:\"user_id,omitempty\"`\n\tUserProperties     map[string]interface{} `json:\"user_properties,omitempty\"`\n}\n\ntype Identify struct {\n\tAppVersion         string                 `json:\"app_version,omitempty\"`\n\tCarrier            string                 `json:\"carrier,omitempty\"`\n\tCity               string                 `json:\"city,omitempty\"`\n\tCountry            string                 `json:\"country,omitempty\"`\n\tDeviceBrand        string                 `json:\"device_brand,omitempty\"`\n\tDeviceId           string                 `json:\"device_id,omitempty\"`\n\tDeviceManufacturer string                 `json:\"device_manufacturer,omitempty\"`\n\tDeviceModel        string                 `json:\"device_model,omitempty\"`\n\tDeviceType         string                 `json:\"device_type,omitempty\"`\n\tDma                string                 `json:\"dma,omitempty\"`\n\tGroups             map[string]interface{} `json:\"groups,omitempty\"`\n\tLanguage           string                 `json:\"language,omitempty\"`\n\tOsName             string                 `json:\"os_name,omitempty\"`\n\tOsVersion          string                 `json:\"os_version,omitempty\"`\n\tPaying             string                 `json:\"paying,omitempty\"`\n\tPlatform           string                 `json:\"platform,omitempty\"`\n\tRegion             string                 `json:\"region,omitempty\"`\n\tStartVersion       string                 `json:\"start_version,omitempty\"`\n\tUserId             string                 `json:\"user_id,omitempty\"`\n\tUserProperties     map[string]interface{} `json:\"user_properties,omitempty\"`\n}\n\n\/\/ New client with API key\nfunc New(key string) *Client {\n\treturn &Client{\n\t\teventEndpoint:    eventEndpoint,\n\t\tidentifyEndpoint: identifyEndpoint,\n\t\tkey:              key,\n\t\tclient:           new(http.Client),\n\t}\n}\n\nfunc (c *Client) SetClient(client *http.Client) {\n\tc.client = client\n}\n\nfunc (c *Client) Event(msg Event) error {\n\tmsgJson, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.send(c.eventEndpoint, \"event\", string(msgJson))\n}\n\nfunc (c *Client) Identify(msg Identify) error {\n\tmsgJson, err := json.Marshal(msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.send(c.identifyEndpoint, \"identification\", string(msgJson))\n}\n\nfunc (c *Client) send(endpoint string, key string, value string) error {\n\tvalues := url.Values{}\n\tvalues.Add(\"api_key\", c.key)\n\tvalues.Add(key, value)\n\n\tresp, err := c.client.PostForm(endpoint, values)\n\tif err == nil {\n\t\tresp.Body.Close()\n\t}\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2016-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 *\/\n\npackage gomatrixserverlib\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/gomatrix\"\n\t\"github.com\/matrix-org\/util\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ Default HTTPS request timeout\nconst requestTimeout time.Duration = time.Duration(30) * time.Second\n\n\/\/ A Client makes request to the federation listeners of matrix\n\/\/ homeservers\ntype Client struct {\n\tclient    http.Client\n\tuserAgent string\n}\n\n\/\/ UserInfo represents information about a user.\ntype UserInfo struct {\n\tSub string `json:\"sub\"`\n}\n\n\/\/ NewClient makes a new Client (with default timeout)\nfunc NewClient(skipVerify bool) *Client {\n\treturn NewClientWithTransportTimeout(requestTimeout, newFederationTripper(skipVerify))\n}\n\n\/\/ NewClientWithTieout makes a new Client (with specified timeout)\nfunc NewClientWithTimeout(timeout time.Duration, skipVerify bool) *Client {\n\treturn NewClientWithTransportTimeout(timeout, newFederationTripper(skipVerify))\n}\n\n\/\/ NewClientWithTransport makes a new Client with an existing transport\nfunc NewClientWithTransport(transport http.RoundTripper) *Client {\n\treturn NewClientWithTransportTimeout(requestTimeout, transport)\n}\n\n\/\/ NewClientWithTransportTimeout makes a new Client with a specified request timeout\nfunc NewClientWithTransportTimeout(timeout time.Duration, transport http.RoundTripper) *Client {\n\treturn &Client{\n\t\tclient: http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout:   timeout,\n\t\t},\n\t}\n}\n\ntype federationTripper struct {\n\t\/\/ transports maps an TLS server name with an HTTP transport.\n\ttransports      map[string]http.RoundTripper\n\ttransportsMutex sync.Mutex\n\tskipVerify      bool\n}\n\nfunc newFederationTripper(skipVerify bool) *federationTripper {\n\treturn &federationTripper{\n\t\ttransports: make(map[string]http.RoundTripper),\n\t\tskipVerify: skipVerify,\n\t}\n}\n\n\/\/ getTransport returns a http.Transport instance with a TLS configuration using\n\/\/ the given server name for SNI. It also creates the instance if there isn't\n\/\/ any for this server name.\n\/\/ We need to use one transport per TLS server name (instead of giving our round\n\/\/ tripper a single transport) because there is no way to specify the TLS\n\/\/ ServerName on a per-connection basis.\nfunc (f *federationTripper) getTransport(tlsServerName string) (transport http.RoundTripper) {\n\tvar ok bool\n\n\tf.transportsMutex.Lock()\n\n\t\/\/ Create the transport if we don't have any for this TLS server name.\n\tif transport, ok = f.transports[tlsServerName]; !ok {\n\t\ttransport = &http.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tServerName:         tlsServerName,\n\t\t\t\tInsecureSkipVerify: f.skipVerify,\n\t\t\t},\n\t\t}\n\n\t\tf.transports[tlsServerName] = transport\n\t}\n\n\tf.transportsMutex.Unlock()\n\n\treturn transport\n}\n\nfunc makeHTTPSURL(u *url.URL, addr string) (httpsURL url.URL) {\n\thttpsURL = *u\n\thttpsURL.Scheme = \"https\"\n\thttpsURL.Host = addr\n\treturn\n}\n\nfunc (f *federationTripper) RoundTrip(r *http.Request) (*http.Response, error) {\n\tserverName := ServerName(r.URL.Host)\n\tresolutionResults, err := ResolveServer(serverName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resolutionResults) == 0 {\n\t\treturn nil, fmt.Errorf(\"no address found for matrix host %v\", serverName)\n\t}\n\n\tvar resp *http.Response\n\t\/\/ TODO: respect the priority and weight fields from the SRV record\n\tfor _, result := range resolutionResults {\n\t\tu := makeHTTPSURL(r.URL, result.Destination)\n\t\tr.URL = &u\n\t\tr.Host = string(result.Host)\n\t\tresp, err = f.getTransport(result.TLSServerName).RoundTrip(r)\n\t\tif err == nil {\n\t\t\treturn resp, nil\n\t\t}\n\t\tutil.GetLogger(r.Context()).Warnf(\"Error sending request to %s: %v\",\n\t\t\tu.String(), err)\n\t}\n\n\t\/\/ just return the most recent error\n\treturn nil, err\n}\n\n\/\/ SetUserAgent sets the user agent string that is sent in the headers of\n\/\/ outbound HTTP requests.\nfunc (fc *Client) SetUserAgent(ua string) {\n\tfc.userAgent = ua\n}\n\n\/\/ LookupUserInfo gets information about a user from a given matrix homeserver\n\/\/ using a bearer access token.\nfunc (fc *Client) LookupUserInfo(\n\tctx context.Context, matrixServer ServerName, token string,\n) (u UserInfo, err error) {\n\turl := url.URL{\n\t\tScheme:   \"matrix\",\n\t\tHost:     string(matrixServer),\n\t\tPath:     \"\/_matrix\/federation\/v1\/openid\/userinfo\",\n\t\tRawQuery: url.Values{\"access_token\": []string{token}}.Encode(),\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar response *http.Response\n\tresponse, err = fc.DoHTTPRequest(ctx, req)\n\tif response != nil {\n\t\tdefer response.Body.Close() \/\/ nolint: errcheck\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tif response.StatusCode < 200 || response.StatusCode >= 300 {\n\t\tvar errorOutput []byte\n\t\terrorOutput, err = ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = fmt.Errorf(\"HTTP %d : %s\", response.StatusCode, errorOutput)\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(response.Body).Decode(&u)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tuserParts := strings.SplitN(u.Sub, \":\", 2)\n\tif len(userParts) != 2 || userParts[1] != string(matrixServer) {\n\t\terr = fmt.Errorf(\"userID doesn't match server name '%v' != '%v'\", u.Sub, matrixServer)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ GetServerKeys asks a matrix server for its signing keys and TLS cert\nfunc (fc *Client) GetServerKeys(\n\tctx context.Context, matrixServer ServerName,\n) (ServerKeys, error) {\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(matrixServer),\n\t\tPath:   \"\/_matrix\/key\/v2\/server\",\n\t}\n\n\tvar body ServerKeys\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn body, err\n\t}\n\n\terr = fc.DoRequestAndParseResponse(\n\t\tctx, req, &body,\n\t)\n\treturn body, err\n}\n\n\/\/ GetVersion gets the version information of a homeserver.\n\/\/ See https:\/\/matrix.org\/docs\/spec\/server_server\/r0.1.1.html#get-matrix-federation-v1-version\nfunc (fc *Client) GetVersion(\n\tctx context.Context, s ServerName,\n) (res Version, err error) {\n\t\/\/ Construct a request for version information\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(s),\n\t\tPath:   \"\/_matrix\/federation\/v1\/version\",\n\t}\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Make the request and parse the response\n\terr = fc.DoRequestAndParseResponse(ctx, req, &res)\n\treturn\n}\n\n\/\/ LookupServerKeys looks up the keys for a matrix server from a matrix server.\n\/\/ The first argument is the name of the matrix server to download the keys from.\n\/\/ The second argument is a map from (server name, key ID) pairs to timestamps.\n\/\/ The (server name, key ID) pair identifies the key to download.\n\/\/ The timestamps tell the server when the keys need to be valid until.\n\/\/ Perspective servers can use that timestamp to determine whether they can\n\/\/ return a cached copy of the keys or whether they will need to retrieve a fresh\n\/\/ copy of the keys.\n\/\/ Returns the keys returned by the server, or an error if there was a problem talking to the server.\nfunc (fc *Client) LookupServerKeys(\n\tctx context.Context, matrixServer ServerName, keyRequests map[PublicKeyLookupRequest]Timestamp,\n) ([]ServerKeys, error) {\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(matrixServer),\n\t\tPath:   \"\/_matrix\/key\/v2\/query\",\n\t}\n\n\t\/\/ The request format is:\n\t\/\/ { \"server_keys\": { \"<server_name>\": { \"<key_id>\": { \"minimum_valid_until_ts\": <ts> }}}\n\ttype keyreq struct {\n\t\tMinimumValidUntilTS Timestamp `json:\"minimum_valid_until_ts\"`\n\t}\n\trequest := struct {\n\t\tServerKeyMap map[ServerName]map[KeyID]keyreq `json:\"server_keys\"`\n\t}{map[ServerName]map[KeyID]keyreq{}}\n\tfor k, ts := range keyRequests {\n\t\tserver := request.ServerKeyMap[k.ServerName]\n\t\tif server == nil {\n\t\t\tserver = map[KeyID]keyreq{}\n\t\t\trequest.ServerKeyMap[k.ServerName] = server\n\t\t}\n\t\tif k.KeyID != \"\" {\n\t\t\tserver[k.KeyID] = keyreq{ts}\n\t\t}\n\t}\n\n\trequestBytes, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar body struct {\n\t\tServerKeyList []json.RawMessage `json:\"server_keys\"`\n\t}\n\n\tvar res struct {\n\t\tServerKeyList []ServerKeys\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url.String(), bytes.NewBuffer(requestBytes))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\n\terr = fc.DoRequestAndParseResponse(\n\t\tctx, req, &body,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, field := range body.ServerKeyList {\n\t\tvar keys ServerKeys\n\t\tif err := json.Unmarshal(field, &keys); err == nil {\n\t\t\tres.ServerKeyList = append(res.ServerKeyList, keys)\n\t\t}\n\t}\n\n\treturn res.ServerKeyList, nil\n}\n\n\/\/ CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error\nfunc (fc *Client) CreateMediaDownloadRequest(\n\tctx context.Context, matrixServer ServerName, mediaID string,\n) (*http.Response, error) {\n\t\/\/ Set allow_remote=false here so that we avoid loops:\n\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/pull\/1992\n\trequestURL := \"matrix:\/\/\" + string(matrixServer) + \"\/_matrix\/media\/v1\/download\/\" + string(matrixServer) + \"\/\" + mediaID + \"?allow_remote=false\"\n\treq, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fc.DoHTTPRequest(ctx, req)\n}\n\n\/\/ DoRequestAndParseResponse calls DoHTTPRequest and then decodes the response.\n\/\/\n\/\/ If the HTTP response is not a 200, an attempt is made to parse the response\n\/\/ body into a gomatrix.RespError. In any case, a non-200 response will result\n\/\/ in a gomatrix.HTTPError.\n\/\/\nfunc (fc *Client) DoRequestAndParseResponse(\n\tctx context.Context,\n\treq *http.Request,\n\tresult interface{},\n) error {\n\tresponse, err := fc.DoHTTPRequest(ctx, req)\n\tif response != nil {\n\t\tdefer response.Body.Close() \/\/ nolint: errcheck\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.StatusCode\/100 != 2 { \/\/ not 2xx\n\t\t\/\/ Adapted from https:\/\/github.com\/matrix-org\/gomatrix\/blob\/master\/client.go\n\t\tvar contents []byte\n\t\tcontents, err = ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar wrap error\n\t\tvar respErr gomatrix.RespError\n\t\tif _ = json.Unmarshal(contents, &respErr); respErr.ErrCode != \"\" {\n\t\t\twrap = respErr\n\t\t}\n\n\t\t\/\/ If we failed to decode as RespError, don't just drop the HTTP body, include it in the\n\t\t\/\/ HTTP error instead (e.g proxy errors which return HTML).\n\t\tmsg := fmt.Sprintf(\"Failed to %s JSON (hostname %q path %q)\", req.Method, req.Host, req.URL.Path)\n\t\tif wrap == nil {\n\t\t\tmsg += \": \" + string(contents)\n\t\t}\n\n\t\treturn gomatrix.HTTPError{\n\t\t\tCode:         response.StatusCode,\n\t\t\tMessage:      msg,\n\t\t\tWrappedError: wrap,\n\t\t\tContents:     contents,\n\t\t}\n\t}\n\n\tif err = json.NewDecoder(response.Body).Decode(result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ DoHTTPRequest creates an outgoing request ID and adds it to the context\n\/\/ before sending off the request and awaiting a response.\n\/\/\n\/\/ If the returned error is nil, the Response will contain a non-nil\n\/\/ Body which the caller is expected to close.\n\/\/\nfunc (fc *Client) DoHTTPRequest(ctx context.Context, req *http.Request) (*http.Response, error) {\n\treqID := util.RandomString(12)\n\tlogger := util.GetLogger(ctx).WithFields(logrus.Fields{\n\t\t\"out.req.ID\":     reqID,\n\t\t\"out.req.method\": req.Method,\n\t\t\"out.req.uri\":    req.URL,\n\t})\n\tlogger.Trace(\"Outgoing request\")\n\tnewCtx := util.ContextWithLogger(ctx, logger)\n\tif fc.userAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", fc.userAgent)\n\t}\n\n\tstart := time.Now()\n\tresp, err := fc.client.Do(req.WithContext(newCtx))\n\tif err != nil {\n\t\tlogger.WithField(\"error\", err).Warn(\"Outgoing request failed\")\n\t\treturn nil, err\n\t}\n\n\t\/\/ we haven't yet read the body, so this is slightly premature, but it's the easiest place.\n\tlogger.WithFields(logrus.Fields{\n\t\t\"out.req.code\":        resp.StatusCode,\n\t\t\"out.req.duration_ms\": int(time.Since(start) \/ time.Millisecond),\n\t}).Trace(\"Outgoing request returned\")\n\n\treturn resp, nil\n}\n<commit_msg>Resolver caching (#247)<commit_after>\/* Copyright 2016-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 *\/\n\npackage gomatrixserverlib\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/gomatrix\"\n\t\"github.com\/matrix-org\/util\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ Default HTTPS request timeout\nconst requestTimeout time.Duration = time.Duration(30) * time.Second\n\n\/\/ A Client makes request to the federation listeners of matrix\n\/\/ homeservers\ntype Client struct {\n\tclient    http.Client\n\tuserAgent string\n}\n\n\/\/ UserInfo represents information about a user.\ntype UserInfo struct {\n\tSub string `json:\"sub\"`\n}\n\n\/\/ NewClient makes a new Client (with default timeout)\nfunc NewClient(skipVerify bool) *Client {\n\treturn NewClientWithTransportTimeout(requestTimeout, newFederationTripper(skipVerify))\n}\n\n\/\/ NewClientWithTieout makes a new Client (with specified timeout)\nfunc NewClientWithTimeout(timeout time.Duration, skipVerify bool) *Client {\n\treturn NewClientWithTransportTimeout(timeout, newFederationTripper(skipVerify))\n}\n\n\/\/ NewClientWithTransport makes a new Client with an existing transport\nfunc NewClientWithTransport(transport http.RoundTripper) *Client {\n\treturn NewClientWithTransportTimeout(requestTimeout, transport)\n}\n\n\/\/ NewClientWithTransportTimeout makes a new Client with a specified request timeout\nfunc NewClientWithTransportTimeout(timeout time.Duration, transport http.RoundTripper) *Client {\n\treturn &Client{\n\t\tclient: http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout:   timeout,\n\t\t},\n\t}\n}\n\ntype federationTripper struct {\n\t\/\/ transports maps an TLS server name with an HTTP transport.\n\ttransports      map[string]http.RoundTripper\n\ttransportsMutex sync.Mutex\n\tskipVerify      bool\n\tresolutionCache sync.Map \/\/ serverName -> []ResolutionResult\n}\n\nfunc newFederationTripper(skipVerify bool) *federationTripper {\n\treturn &federationTripper{\n\t\ttransports: make(map[string]http.RoundTripper),\n\t\tskipVerify: skipVerify,\n\t}\n}\n\n\/\/ getTransport returns a http.Transport instance with a TLS configuration using\n\/\/ the given server name for SNI. It also creates the instance if there isn't\n\/\/ any for this server name.\n\/\/ We need to use one transport per TLS server name (instead of giving our round\n\/\/ tripper a single transport) because there is no way to specify the TLS\n\/\/ ServerName on a per-connection basis.\nfunc (f *federationTripper) getTransport(tlsServerName string) (transport http.RoundTripper) {\n\tvar ok bool\n\n\tf.transportsMutex.Lock()\n\n\t\/\/ Create the transport if we don't have any for this TLS server name.\n\tif transport, ok = f.transports[tlsServerName]; !ok {\n\t\ttransport = &http.Transport{\n\t\t\tDisableKeepAlives: true,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tServerName:         tlsServerName,\n\t\t\t\tInsecureSkipVerify: f.skipVerify,\n\t\t\t},\n\t\t}\n\n\t\tf.transports[tlsServerName] = transport\n\t}\n\n\tf.transportsMutex.Unlock()\n\n\treturn transport\n}\n\nfunc makeHTTPSURL(u *url.URL, addr string) (httpsURL url.URL) {\n\thttpsURL = *u\n\thttpsURL.Scheme = \"https\"\n\thttpsURL.Host = addr\n\treturn\n}\n\nfunc (f *federationTripper) RoundTrip(r *http.Request) (*http.Response, error) {\n\tvar err error\n\tserverName := ServerName(r.URL.Host)\n\tresolutionRetried := false\n\tresolutionResults := []ResolutionResult{}\n\nretryResolution:\n\tif cached, ok := f.resolutionCache.Load(serverName); ok {\n\t\tif results, ok := cached.([]ResolutionResult); ok {\n\t\t\tresolutionResults = results\n\t\t}\n\t}\n\n\t\/\/ If the cache returned nothing then we'll have no results here,\n\t\/\/ so go and hit the network.\n\tif len(resolutionResults) == 0 {\n\t\tresolutionResults, err = ResolveServer(serverName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.resolutionCache.Store(serverName, resolutionResults)\n\t}\n\n\t\/\/ If we still have no results at this point, even after possibly\n\t\/\/ hitting the network, then give up.\n\tif len(resolutionResults) == 0 {\n\t\treturn nil, fmt.Errorf(\"no address found for matrix host %v\", serverName)\n\t}\n\n\tvar resp *http.Response\n\t\/\/ TODO: respect the priority and weight fields from the SRV record\n\tfor _, result := range resolutionResults {\n\t\tu := makeHTTPSURL(r.URL, result.Destination)\n\t\tr.URL = &u\n\t\tr.Host = string(result.Host)\n\t\tresp, err = f.getTransport(result.TLSServerName).RoundTrip(r)\n\t\tif err == nil {\n\t\t\treturn resp, nil\n\t\t}\n\t\tutil.GetLogger(r.Context()).Warnf(\"Error sending request to %s: %v\",\n\t\t\tu.String(), err)\n\t}\n\n\t\/\/ We failed to reach any of the locations in the resolution results,\n\t\/\/ so clear the cache and mark that we're retrying, then give it a\n\t\/\/ try again.\n\tf.resolutionCache.Delete(serverName)\n\tif !resolutionRetried {\n\t\tresolutionRetried = true\n\t\tgoto retryResolution\n\t}\n\n\t\/\/ just return the most recent error\n\treturn nil, err\n}\n\n\/\/ SetUserAgent sets the user agent string that is sent in the headers of\n\/\/ outbound HTTP requests.\nfunc (fc *Client) SetUserAgent(ua string) {\n\tfc.userAgent = ua\n}\n\n\/\/ LookupUserInfo gets information about a user from a given matrix homeserver\n\/\/ using a bearer access token.\nfunc (fc *Client) LookupUserInfo(\n\tctx context.Context, matrixServer ServerName, token string,\n) (u UserInfo, err error) {\n\turl := url.URL{\n\t\tScheme:   \"matrix\",\n\t\tHost:     string(matrixServer),\n\t\tPath:     \"\/_matrix\/federation\/v1\/openid\/userinfo\",\n\t\tRawQuery: url.Values{\"access_token\": []string{token}}.Encode(),\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar response *http.Response\n\tresponse, err = fc.DoHTTPRequest(ctx, req)\n\tif response != nil {\n\t\tdefer response.Body.Close() \/\/ nolint: errcheck\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tif response.StatusCode < 200 || response.StatusCode >= 300 {\n\t\tvar errorOutput []byte\n\t\terrorOutput, err = ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = fmt.Errorf(\"HTTP %d : %s\", response.StatusCode, errorOutput)\n\t\treturn\n\t}\n\n\terr = json.NewDecoder(response.Body).Decode(&u)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tuserParts := strings.SplitN(u.Sub, \":\", 2)\n\tif len(userParts) != 2 || userParts[1] != string(matrixServer) {\n\t\terr = fmt.Errorf(\"userID doesn't match server name '%v' != '%v'\", u.Sub, matrixServer)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ GetServerKeys asks a matrix server for its signing keys and TLS cert\nfunc (fc *Client) GetServerKeys(\n\tctx context.Context, matrixServer ServerName,\n) (ServerKeys, error) {\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(matrixServer),\n\t\tPath:   \"\/_matrix\/key\/v2\/server\",\n\t}\n\n\tvar body ServerKeys\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn body, err\n\t}\n\n\terr = fc.DoRequestAndParseResponse(\n\t\tctx, req, &body,\n\t)\n\treturn body, err\n}\n\n\/\/ GetVersion gets the version information of a homeserver.\n\/\/ See https:\/\/matrix.org\/docs\/spec\/server_server\/r0.1.1.html#get-matrix-federation-v1-version\nfunc (fc *Client) GetVersion(\n\tctx context.Context, s ServerName,\n) (res Version, err error) {\n\t\/\/ Construct a request for version information\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(s),\n\t\tPath:   \"\/_matrix\/federation\/v1\/version\",\n\t}\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Make the request and parse the response\n\terr = fc.DoRequestAndParseResponse(ctx, req, &res)\n\treturn\n}\n\n\/\/ LookupServerKeys looks up the keys for a matrix server from a matrix server.\n\/\/ The first argument is the name of the matrix server to download the keys from.\n\/\/ The second argument is a map from (server name, key ID) pairs to timestamps.\n\/\/ The (server name, key ID) pair identifies the key to download.\n\/\/ The timestamps tell the server when the keys need to be valid until.\n\/\/ Perspective servers can use that timestamp to determine whether they can\n\/\/ return a cached copy of the keys or whether they will need to retrieve a fresh\n\/\/ copy of the keys.\n\/\/ Returns the keys returned by the server, or an error if there was a problem talking to the server.\nfunc (fc *Client) LookupServerKeys(\n\tctx context.Context, matrixServer ServerName, keyRequests map[PublicKeyLookupRequest]Timestamp,\n) ([]ServerKeys, error) {\n\turl := url.URL{\n\t\tScheme: \"matrix\",\n\t\tHost:   string(matrixServer),\n\t\tPath:   \"\/_matrix\/key\/v2\/query\",\n\t}\n\n\t\/\/ The request format is:\n\t\/\/ { \"server_keys\": { \"<server_name>\": { \"<key_id>\": { \"minimum_valid_until_ts\": <ts> }}}\n\ttype keyreq struct {\n\t\tMinimumValidUntilTS Timestamp `json:\"minimum_valid_until_ts\"`\n\t}\n\trequest := struct {\n\t\tServerKeyMap map[ServerName]map[KeyID]keyreq `json:\"server_keys\"`\n\t}{map[ServerName]map[KeyID]keyreq{}}\n\tfor k, ts := range keyRequests {\n\t\tserver := request.ServerKeyMap[k.ServerName]\n\t\tif server == nil {\n\t\t\tserver = map[KeyID]keyreq{}\n\t\t\trequest.ServerKeyMap[k.ServerName] = server\n\t\t}\n\t\tif k.KeyID != \"\" {\n\t\t\tserver[k.KeyID] = keyreq{ts}\n\t\t}\n\t}\n\n\trequestBytes, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar body struct {\n\t\tServerKeyList []json.RawMessage `json:\"server_keys\"`\n\t}\n\n\tvar res struct {\n\t\tServerKeyList []ServerKeys\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url.String(), bytes.NewBuffer(requestBytes))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\n\terr = fc.DoRequestAndParseResponse(\n\t\tctx, req, &body,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, field := range body.ServerKeyList {\n\t\tvar keys ServerKeys\n\t\tif err := json.Unmarshal(field, &keys); err == nil {\n\t\t\tres.ServerKeyList = append(res.ServerKeyList, keys)\n\t\t}\n\t}\n\n\treturn res.ServerKeyList, nil\n}\n\n\/\/ CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error\nfunc (fc *Client) CreateMediaDownloadRequest(\n\tctx context.Context, matrixServer ServerName, mediaID string,\n) (*http.Response, error) {\n\t\/\/ Set allow_remote=false here so that we avoid loops:\n\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/pull\/1992\n\trequestURL := \"matrix:\/\/\" + string(matrixServer) + \"\/_matrix\/media\/v1\/download\/\" + string(matrixServer) + \"\/\" + mediaID + \"?allow_remote=false\"\n\treq, err := http.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fc.DoHTTPRequest(ctx, req)\n}\n\n\/\/ DoRequestAndParseResponse calls DoHTTPRequest and then decodes the response.\n\/\/\n\/\/ If the HTTP response is not a 200, an attempt is made to parse the response\n\/\/ body into a gomatrix.RespError. In any case, a non-200 response will result\n\/\/ in a gomatrix.HTTPError.\n\/\/\nfunc (fc *Client) DoRequestAndParseResponse(\n\tctx context.Context,\n\treq *http.Request,\n\tresult interface{},\n) error {\n\tresponse, err := fc.DoHTTPRequest(ctx, req)\n\tif response != nil {\n\t\tdefer response.Body.Close() \/\/ nolint: errcheck\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif response.StatusCode\/100 != 2 { \/\/ not 2xx\n\t\t\/\/ Adapted from https:\/\/github.com\/matrix-org\/gomatrix\/blob\/master\/client.go\n\t\tvar contents []byte\n\t\tcontents, err = ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar wrap error\n\t\tvar respErr gomatrix.RespError\n\t\tif _ = json.Unmarshal(contents, &respErr); respErr.ErrCode != \"\" {\n\t\t\twrap = respErr\n\t\t}\n\n\t\t\/\/ If we failed to decode as RespError, don't just drop the HTTP body, include it in the\n\t\t\/\/ HTTP error instead (e.g proxy errors which return HTML).\n\t\tmsg := fmt.Sprintf(\"Failed to %s JSON (hostname %q path %q)\", req.Method, req.Host, req.URL.Path)\n\t\tif wrap == nil {\n\t\t\tmsg += \": \" + string(contents)\n\t\t}\n\n\t\treturn gomatrix.HTTPError{\n\t\t\tCode:         response.StatusCode,\n\t\t\tMessage:      msg,\n\t\t\tWrappedError: wrap,\n\t\t\tContents:     contents,\n\t\t}\n\t}\n\n\tif err = json.NewDecoder(response.Body).Decode(result); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ DoHTTPRequest creates an outgoing request ID and adds it to the context\n\/\/ before sending off the request and awaiting a response.\n\/\/\n\/\/ If the returned error is nil, the Response will contain a non-nil\n\/\/ Body which the caller is expected to close.\n\/\/\nfunc (fc *Client) DoHTTPRequest(ctx context.Context, req *http.Request) (*http.Response, error) {\n\treqID := util.RandomString(12)\n\tlogger := util.GetLogger(ctx).WithFields(logrus.Fields{\n\t\t\"out.req.ID\":     reqID,\n\t\t\"out.req.method\": req.Method,\n\t\t\"out.req.uri\":    req.URL,\n\t})\n\tlogger.Trace(\"Outgoing request\")\n\tnewCtx := util.ContextWithLogger(ctx, logger)\n\tif fc.userAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", fc.userAgent)\n\t}\n\n\tstart := time.Now()\n\tresp, err := fc.client.Do(req.WithContext(newCtx))\n\tif err != nil {\n\t\tlogger.WithField(\"error\", err).Warn(\"Outgoing request failed\")\n\t\treturn nil, err\n\t}\n\n\t\/\/ we haven't yet read the body, so this is slightly premature, but it's the easiest place.\n\tlogger.WithFields(logrus.Fields{\n\t\t\"out.req.code\":        resp.StatusCode,\n\t\t\"out.req.duration_ms\": int(time.Since(start) \/ time.Millisecond),\n\t}).Trace(\"Outgoing request returned\")\n\n\treturn resp, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package styx\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"aqwari.net\/net\/styx\/styxproto\"\n)\n\n\/\/ DefaultClient is the Client used by top-level functions such\n\/\/ as Open.\nvar DefaultClient = &Client{}\n\n\/\/ A Client is a 9P client, used to make remote requests to\n\/\/ a 9P server. The zero value of a Client is a usable 9P client\n\/\/ that uses default settings chosen by the styx package.\ntype Client struct {\n\t\/\/ The maximum size of a single 9P message. When working with\n\t\/\/ very large files, a larger MessageSize can reduce protocol\n\t\/\/ overhead. Because a remote server may choose to set a smaller\n\t\/\/ maximum size, increasing MessageSize may have no effect\n\t\/\/ with certain servers.\n\tMaxSize uint32\n\t\/\/ Timeout specifies the amount of time to wait for a response\n\t\/\/ from the server. Note that Timeout does not apply to Read\n\t\/\/ requests, to avoid interfering with long-poll or message\n\t\/\/ queue-like interfaces, where a client issues a Read request\n\t\/\/ for data that has not arrived yet. If zero, defaults to infinity.\n\tTimeout time.Duration\n}\n\n\/\/ Types that implement the Node interface can be returned by a Handler\n\/\/ when a client performs an operation on a file.\ntype Node interface {\n\tio.ReadWriteCloser\n\n\t\/\/ Stat returns metadata information about a file. The Sys() method\n\t\/\/ returns the styxproto.Stat structure sent by the 9P server. It\n\t\/\/ should not be modified or used after the file is closed. Calling\n\t\/\/ Stat on a file requires that the connected user has permissions to\n\t\/\/ read the directory.\n\tStat() (os.FileInfo, error)\n\n\t\/\/ Readdir reads the contents of the directory associated with node\n\t\/\/ and returns a slice of up to n (if n > 0) os.FileInfo values, in\n\t\/\/ the order returned by the remote server. If there are >n entries\n\t\/\/ in a directory, subsequent calls to Readdir will pick up where\n\t\/\/ previous call left off.\n\t\/\/\n\t\/\/ If n <= 0, Readdir will return an os.FileInfo value for all entries\n\t\/\/ in the directory. If an error is encountered before reading the\n\t\/\/ entire directory, it is returned, along with the entries read\n\t\/\/ so far. If n > 0 and there are no entries in the directory, the\n\t\/\/ error is io.EOF.\n\tReaddir(n int) ([]os.FileInfo, error)\n}\n\ntype FileSystem interface {\n\t\/\/ Open readies a file relative to the directory represented by\n\t\/\/ the Node for I\/O.\n\tOpen9P(req *Request, name string, flag int) (Node, error)\n\n\t\/\/ Create creates a new file relative to this node, with type\n\t\/\/ and permissions specified by mode, and opens it with the\n\t\/\/ mode specified by flag.\n\tCreate9P(req *Request, name string, flag int, mode Mode) (Node, error)\n}\n\n\/\/ A Request contains contextual information about a\n\/\/ 9P request.\ntype Request struct {\n\tcontext.Context\n}\n\n\/\/ A Mode contains permission and type information for a file.\ntype Mode uint32\n\n\/\/ IsDir returns true if m describes a directory.\nfunc (m Mode) IsDir() bool {\n\treturn m&styxproto.DMDIR != 0\n}\n\n\/\/ IsRegular reports whether m describes a regular file.\nfunc (m Mode) IsRegular() bool {\n\treturn m&styxproto.DMTYPE == 0\n}\n\ntype File struct {\n\tnode Node\n}\n\n\/\/ ReadFile reads all data from the file on the remote 9P server\n\/\/ specified by url. ReadFile is convenient if a single small file\n\/\/ needs to be accessed infrequently.\nfunc ReadFile(url string) ([]byte, error) {\n\treturn nil, errors.New(\"todo\")\n}\n\n\/\/ OpenFile opens a file on a remote 9P server with the specified\n\/\/ mode.\nfunc OpenFile(url string, flag int, mode uint32) (*File, error) {\n\treturn nil, errors.New(\"todo\")\n}\n<commit_msg>Put the client implementation on ice for now<commit_after>package styx\n\nimport \"time\"\n\n\/\/ DefaultClient is the Client used by top-level functions such\n\/\/ as Open.\nvar DefaultClient = &Client{}\n\n\/\/ A Client is a 9P client, used to make remote requests to\n\/\/ a 9P server. The zero value of a Client is a usable 9P client\n\/\/ that uses default settings chosen by the styx package.\ntype Client struct {\n\t\/\/ The maximum size of a single 9P message. When working with\n\t\/\/ very large files, a larger MessageSize can reduce protocol\n\t\/\/ overhead. Because a remote server may choose to set a smaller\n\t\/\/ maximum size, increasing MessageSize may have no effect\n\t\/\/ with certain servers.\n\tMaxSize uint32\n\t\/\/ Timeout specifies the amount of time to wait for a response\n\t\/\/ from the server. Note that Timeout does not apply to Read\n\t\/\/ requests, to avoid interfering with long-poll or message\n\t\/\/ queue-like interfaces, where a client issues a Read request\n\t\/\/ for data that has not arrived yet. If zero, defaults to infinity.\n\tTimeout time.Duration\n}\n<|endoftext|>"}
{"text":"<commit_before>package sensorsanalytics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ Client sensoranalytics client\ntype Client struct {\n\tconsumer        Consumer\n\tprojectName     *string\n\tenableTimeFree  bool\n\tappVersion      *string\n\tsuperProperties map[string]interface{}\n\tnamePattern     *regexp.Regexp\n}\n\n\/\/ NewClient create new client\nfunc NewClient(consumer Consumer, projectName string, timeFree bool) (*Client, error) {\n\tvar c Client\n\tc.consumer = consumer\n\tif projectName == \"\" {\n\t\treturn &c, errors.New(\"project_name must not be empty\")\n\t}\n\tc.projectName = &projectName\n\tc.enableTimeFree = timeFree\n\tnamePattern, err := regexp.Compile(\"^([a-zA-Z_$][a-zA-Z0-9_$]{0,99})\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.namePattern = namePattern\n\tc.ClearSuperProperties()\n\treturn &c, nil\n}\n\nfunc (c *Client) match(input string) bool {\n\tif c.namePattern.Match([]byte(input)) {\n\t\tfor _, keyword := range FieldKeywords {\n\t\t\tif keyword == input {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *Client) now() int64 {\n\treturn time.Now().Unix() * 1000\n}\n\n\/\/ RegisterSuperProperties 设置每个事件都带有的一些公共属性，当 track 的 properties 和 super properties 有相同的 key 时，将采用 track 的\n\/\/ :param superProperties 公共属性\nfunc (c *Client) RegisterSuperProperties(superProperties map[string]interface{}) {\n\tfor k, v := range superProperties {\n\t\tc.superProperties[k] = v\n\t}\n}\n\n\/\/ ClearSuperProperties 删除所有已设置的事件公共属性\nfunc (c *Client) ClearSuperProperties() {\n\tc.superProperties = map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t}\n}\n\n\/\/ Track 跟踪一个用户的行为。\n\/\/ :param distinctID: 用户的唯一标识\n\/\/ :param eventName: 事件名称\n\/\/ :param properties: 事件的属性\nfunc (c *Client) Track(distinctID string, eventName string, properties map[string]interface{}, isLoginID bool) error {\n\tallProperties := c.superProperties\n\tif properties != nil {\n\t\tfor k, v := range properties {\n\t\t\tallProperties[k] = v\n\t\t}\n\t}\n\treturn c.trackEvent(\"track\", eventName, distinctID, \"\", allProperties, isLoginID)\n}\n\n\/\/ TrackSignup 这个接口是一个较为复杂的功能，请在使用前先阅读相关说明:http:\/\/www.sensorsdata.cn\/manual\/track_signup.html，\n\/\/ 并在必要时联系我们的技术支持人员。\n\/\/ :param distinct_id: 用户注册之后的唯一标识\n\/\/ :param original_id: 用户注册前的唯一标识\n\/\/ :param properties: 事件的属性\nfunc (c *Client) TrackSignup(distinctID string, originalID string, properties map[string]interface{}) error {\n\tif len(originalID) == 0 {\n\t\treturn fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [original_id] must not be empty\")\n\t}\n\tif len(originalID) > 255 {\n\t\treturn fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"the max length of property [original_id] is 255\")\n\t}\n\tallProperties := c.superProperties\n\tif properties != nil {\n\t\tfor key, value := range properties {\n\t\t\tallProperties[key] = value\n\t\t}\n\t}\n\treturn c.trackEvent(\"track_signup\", \"$SignUp\", distinctID, originalID, allProperties, false)\n}\n\nfunc (c *Client) normalizeData(data map[string]interface{}) (map[string]interface{}, error) {\n\t\/\/ 检查 distinct_id\n\tdistinctIDI, ok := data[\"distinct_id\"]\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [distinct_id] must not be empty\")\n\t}\n\tdistinctID, ok := distinctIDI.(string)\n\tif !ok || len(distinctID) == 0 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [distinct_id] must not be empty\")\n\t}\n\tif len(distinctID) > 255 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"the max length of [distinct_id] is 255\")\n\t}\n\t\/\/ 检查 time\n\ttsI, ok := data[\"time\"]\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must not be empty\")\n\t}\n\tts, ok := tsI.(int64)\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must be int64\")\n\t}\n\ttsNum := len(strconv.FormatInt(ts, 10))\n\tif tsNum < 10 || tsNum > 13 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must be a timestamp in microseconds\")\n\t}\n\tif tsNum == 10 {\n\t\tts *= 1000\n\t}\n\tdata[\"time\"] = ts\n\n\t\/\/ 检查 event name\n\teventI, ok := data[\"event\"]\n\tif ok {\n\t\tevent, ok := eventI.(string)\n\t\tif !ok {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [event] must no be empty\")\n\t\t}\n\t\tif !c.match(event) {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"event name must be a valid variable name. [event=%s]\", event))\n\t\t}\n\t}\n\t\/\/ 检查 project name\n\tprojectI, ok := data[\"project\"]\n\tif ok {\n\t\tproject, ok := projectI.(string)\n\t\tif !ok {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [project] must no be empty\")\n\t\t}\n\t\tif !c.match(project) {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"project name must be a valid variable name. [project=%s]\", project))\n\t\t}\n\t}\n\t\/\/ 检查 properties\n\tvar eventType string\n\teventTypeI, ok := data[\"type\"]\n\tif ok {\n\t\teventType = eventTypeI.(string)\n\n\t}\n\tpropertiesi, ok := data[\"properties\"]\n\tif ok {\n\t\tproperties, ok := propertiesi.(map[string]interface{})\n\t\tif ok {\n\t\t\tfor key, value := range properties {\n\t\t\t\tif len(key) > 255 {\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the max length of property key is 256. [key=%s]\", key))\n\t\t\t\t}\n\t\t\t\tif !c.match(key) {\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the property key must be a valid variable name. [key=%s]\", key))\n\t\t\t\t}\n\t\t\t\tswitch value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tv, ok := value.(string)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tif len(v) > 8192 {\n\t\t\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the max length of property value is 8192. [value=%s]\", value))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase bool:\n\t\t\t\t\tif eventType != \"profile_unset\" && key != \"time_free\" && key != \"$is_login_id\" {\n\t\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"property value must be a str\/int\/float\/list. [key=%s, value=%s]\", key, reflect.TypeOf(value)))\n\t\t\t\t\t}\n\t\t\t\tcase int, int32, int64, float32, float64, []string:\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"default: property value must be a str\/int\/float\/list. [key=%s, value=%s]\", key, reflect.TypeOf(value)))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"properties must be a map[string]interface{}\")\n\t\t}\n\t}\n\treturn data, nil\n}\n\nfunc (c *Client) getLibProperties() map[string]interface{} {\n\tlibProperties := map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t\t\"$lib_method\":  \"code\",\n\t}\n\tif appVersion, ok := c.superProperties[\"$app_version\"]; ok {\n\t\tlibProperties[\"$app_version\"] = appVersion\n\t}\n\treturn libProperties\n}\n\n\/\/ getCommonProperties 构造所有 Event 通用的属性\nfunc (c *Client) getCommonProperties() map[string]interface{} {\n\tcommonProperties := map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t}\n\tif c.appVersion != nil {\n\t\tcommonProperties[\"$app_version\"] = c.appVersion\n\t}\n\treturn commonProperties\n}\n\n\/\/ extractUserTime 如果用户传入了 $time 字段，则不使用当前时间。\nfunc (c *Client) extractUserTime(properties map[string]interface{}) *int64 {\n\tif properties != nil {\n\t\tti, ok := properties[\"$time\"]\n\t\tif ok {\n\t\t\tt, ok := ti.(int64)\n\t\t\tif ok {\n\t\t\t\tdelete(properties, \"$time\")\n\t\t\t\treturn &t\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ProfileSet 直接设置一个用户的 Profile，如果已存在则覆盖\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileSet(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_set\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileSetOnce 直接设置一个用户的 Profile，如果某个 Profile 已存在则不设置。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileSetOnce(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_set_once\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileIncrement 增减\/减少一个用户的某一个或者多个数值类型的 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileIncrement(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_increment\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileAppend 追加一个用户的某一个或者多个集合类型的 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileAppend(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_append\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileUnset 删除一个用户的一个或者多个 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profile_keys: 用户属性键值列表\nfunc (c *Client) ProfileUnset(distinctID string, profileKeys []string, isLoginID bool) error {\n\tprofileMap := make(map[string]interface{}, len(profileKeys))\n\tfor _, v := range profileKeys {\n\t\tprofileMap[v] = true\n\t}\n\treturn c.trackEvent(\"profile_unset\", \"\", distinctID, \"\", profileMap, isLoginID)\n}\n\n\/\/ ProfileDelete 删除整个用户的信息。\n\/\/ :param distinct_id: 用户的唯一标识\nfunc (c *Client) ProfileDelete(distinctID string, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_delete\", \"\", distinctID, \"\", map[string]interface{}{}, isLoginID)\n}\n\nfunc (c *Client) trackEvent(eventType string, eventName string, distinctID string, originalID string, properties map[string]interface{}, isLoginID bool) error {\n\tvar eventTime int64\n\tt := c.extractUserTime(properties)\n\tif t != nil {\n\t\teventTime = *t\n\t} else {\n\t\teventTime = c.now()\n\t}\n\tif isLoginID {\n\t\tproperties[\"$is_login_id\"] = true\n\t}\n\tdata := map[string]interface{}{\n\t\t\"type\":        eventType,\n\t\t\"time\":        eventTime,\n\t\t\"distinct_id\": distinctID,\n\t\t\"properties\":  properties,\n\t\t\"lib\":         c.getLibProperties(),\n\t}\n\tif c.projectName != nil {\n\t\tdata[\"project\"] = *c.projectName\n\t}\n\tif eventType == \"track\" || eventType == \"track_signup\" {\n\t\tdata[\"event\"] = eventName\n\t}\n\tif eventType == \"track_signup\" {\n\t\tdata[\"original_id\"] = originalID\n\t}\n\tif c.enableTimeFree {\n\t\tdata[\"time_free\"] = true\n\t}\n\tdata, err := c.normalizeData(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.consumer.Send(data)\n}\n\n\/\/ Flush 对于不立即发送数据的 Consumer，调用此接口应当立即进行已有数据的发送。\nfunc (c *Client) Flush() error {\n\treturn c.consumer.Flush()\n}\n\n\/\/ Close 在进程结束或者数据发送完成时，应当调用此接口，以保证所有数据被发送完毕。如果发生意外，此方法将抛出异常。\nfunc (c *Client) Close() error {\n\treturn c.consumer.Close()\n}\n<commit_msg>Fix namePattern<commit_after>package sensorsanalytics\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ Client sensoranalytics client\ntype Client struct {\n\tconsumer        Consumer\n\tprojectName     *string\n\tenableTimeFree  bool\n\tappVersion      *string\n\tsuperProperties map[string]interface{}\n\tnamePattern     *regexp.Regexp\n}\n\n\/\/ NewClient create new client\nfunc NewClient(consumer Consumer, projectName string, timeFree bool) (*Client, error) {\n\tvar c Client\n\tc.consumer = consumer\n\tif projectName == \"\" {\n\t\treturn &c, errors.New(\"project_name must not be empty\")\n\t}\n\tc.projectName = &projectName\n\tc.enableTimeFree = timeFree\n\tnamePattern, err := regexp.Compile(\"^([a-zA-Z_$][a-zA-Z0-9_$]{0,99}$)\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.namePattern = namePattern\n\tc.ClearSuperProperties()\n\treturn &c, nil\n}\n\nfunc (c *Client) match(input string) bool {\n\tif c.namePattern.Match([]byte(input)) {\n\t\tfor _, keyword := range FieldKeywords {\n\t\t\tif keyword == input {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *Client) now() int64 {\n\treturn time.Now().Unix() * 1000\n}\n\n\/\/ RegisterSuperProperties 设置每个事件都带有的一些公共属性，当 track 的 properties 和 super properties 有相同的 key 时，将采用 track 的\n\/\/ :param superProperties 公共属性\nfunc (c *Client) RegisterSuperProperties(superProperties map[string]interface{}) {\n\tfor k, v := range superProperties {\n\t\tc.superProperties[k] = v\n\t}\n}\n\n\/\/ ClearSuperProperties 删除所有已设置的事件公共属性\nfunc (c *Client) ClearSuperProperties() {\n\tc.superProperties = map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t}\n}\n\n\/\/ Track 跟踪一个用户的行为。\n\/\/ :param distinctID: 用户的唯一标识\n\/\/ :param eventName: 事件名称\n\/\/ :param properties: 事件的属性\nfunc (c *Client) Track(distinctID string, eventName string, properties map[string]interface{}, isLoginID bool) error {\n\tallProperties := c.superProperties\n\tif properties != nil {\n\t\tfor k, v := range properties {\n\t\t\tallProperties[k] = v\n\t\t}\n\t}\n\treturn c.trackEvent(\"track\", eventName, distinctID, \"\", allProperties, isLoginID)\n}\n\n\/\/ TrackSignup 这个接口是一个较为复杂的功能，请在使用前先阅读相关说明:http:\/\/www.sensorsdata.cn\/manual\/track_signup.html，\n\/\/ 并在必要时联系我们的技术支持人员。\n\/\/ :param distinct_id: 用户注册之后的唯一标识\n\/\/ :param original_id: 用户注册前的唯一标识\n\/\/ :param properties: 事件的属性\nfunc (c *Client) TrackSignup(distinctID string, originalID string, properties map[string]interface{}) error {\n\tif len(originalID) == 0 {\n\t\treturn fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [original_id] must not be empty\")\n\t}\n\tif len(originalID) > 255 {\n\t\treturn fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"the max length of property [original_id] is 255\")\n\t}\n\tallProperties := c.superProperties\n\tif properties != nil {\n\t\tfor key, value := range properties {\n\t\t\tallProperties[key] = value\n\t\t}\n\t}\n\treturn c.trackEvent(\"track_signup\", \"$SignUp\", distinctID, originalID, allProperties, false)\n}\n\nfunc (c *Client) normalizeData(data map[string]interface{}) (map[string]interface{}, error) {\n\t\/\/ 检查 distinct_id\n\tdistinctIDI, ok := data[\"distinct_id\"]\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [distinct_id] must not be empty\")\n\t}\n\tdistinctID, ok := distinctIDI.(string)\n\tif !ok || len(distinctID) == 0 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [distinct_id] must not be empty\")\n\t}\n\tif len(distinctID) > 255 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"the max length of [distinct_id] is 255\")\n\t}\n\t\/\/ 检查 time\n\ttsI, ok := data[\"time\"]\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must not be empty\")\n\t}\n\tts, ok := tsI.(int64)\n\tif !ok {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must be int64\")\n\t}\n\ttsNum := len(strconv.FormatInt(ts, 10))\n\tif tsNum < 10 || tsNum > 13 {\n\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [time] must be a timestamp in microseconds\")\n\t}\n\tif tsNum == 10 {\n\t\tts *= 1000\n\t}\n\tdata[\"time\"] = ts\n\n\t\/\/ 检查 event name\n\teventI, ok := data[\"event\"]\n\tif ok {\n\t\tevent, ok := eventI.(string)\n\t\tif !ok {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [event] must no be empty\")\n\t\t}\n\t\tif !c.match(event) {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"event name must be a valid variable name. [event=%s]\", event))\n\t\t}\n\t}\n\t\/\/ 检查 project name\n\tprojectI, ok := data[\"project\"]\n\tif ok {\n\t\tproject, ok := projectI.(string)\n\t\tif !ok {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"property [project] must no be empty\")\n\t\t}\n\t\tif !c.match(project) {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"project name must be a valid variable name. [project=%s]\", project))\n\t\t}\n\t}\n\t\/\/ 检查 properties\n\tvar eventType string\n\teventTypeI, ok := data[\"type\"]\n\tif ok {\n\t\teventType = eventTypeI.(string)\n\n\t}\n\tpropertiesi, ok := data[\"properties\"]\n\tif ok {\n\t\tproperties, ok := propertiesi.(map[string]interface{})\n\t\tif ok {\n\t\t\tfor key, value := range properties {\n\t\t\t\tif len(key) > 255 {\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the max length of property key is 256. [key=%s]\", key))\n\t\t\t\t}\n\t\t\t\tif !c.match(key) {\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the property key must be a valid variable name. [key=%s]\", key))\n\t\t\t\t}\n\t\t\t\tswitch value.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tv, ok := value.(string)\n\t\t\t\t\tif ok {\n\t\t\t\t\t\tif len(v) > 8192 {\n\t\t\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"the max length of property value is 8192. [value=%s]\", value))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase bool:\n\t\t\t\t\tif eventType != \"profile_unset\" && key != \"time_free\" && key != \"$is_login_id\" {\n\t\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"property value must be a str\/int\/float\/list. [key=%s, value=%s]\", key, reflect.TypeOf(value)))\n\t\t\t\t\t}\n\t\t\t\tcase int, int32, int64, float32, float64, []string:\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, fmt.Sprintf(\"default: property value must be a str\/int\/float\/list. [key=%s, value=%s]\", key, reflect.TypeOf(value)))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn data, fmt.Errorf(\"%s: %s\", ErrIllegalDataException, \"properties must be a map[string]interface{}\")\n\t\t}\n\t}\n\treturn data, nil\n}\n\nfunc (c *Client) getLibProperties() map[string]interface{} {\n\tlibProperties := map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t\t\"$lib_method\":  \"code\",\n\t}\n\tif appVersion, ok := c.superProperties[\"$app_version\"]; ok {\n\t\tlibProperties[\"$app_version\"] = appVersion\n\t}\n\treturn libProperties\n}\n\n\/\/ getCommonProperties 构造所有 Event 通用的属性\nfunc (c *Client) getCommonProperties() map[string]interface{} {\n\tcommonProperties := map[string]interface{}{\n\t\t\"$lib\":         \"golang\",\n\t\t\"$lib_version\": SDKVersion,\n\t}\n\tif c.appVersion != nil {\n\t\tcommonProperties[\"$app_version\"] = c.appVersion\n\t}\n\treturn commonProperties\n}\n\n\/\/ extractUserTime 如果用户传入了 $time 字段，则不使用当前时间。\nfunc (c *Client) extractUserTime(properties map[string]interface{}) *int64 {\n\tif properties != nil {\n\t\tti, ok := properties[\"$time\"]\n\t\tif ok {\n\t\t\tt, ok := ti.(int64)\n\t\t\tif ok {\n\t\t\t\tdelete(properties, \"$time\")\n\t\t\t\treturn &t\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ProfileSet 直接设置一个用户的 Profile，如果已存在则覆盖\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileSet(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_set\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileSetOnce 直接设置一个用户的 Profile，如果某个 Profile 已存在则不设置。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileSetOnce(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_set_once\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileIncrement 增减\/减少一个用户的某一个或者多个数值类型的 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileIncrement(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_increment\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileAppend 追加一个用户的某一个或者多个集合类型的 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profiles: 用户属性\nfunc (c *Client) ProfileAppend(distinctID string, profiles map[string]interface{}, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_append\", \"\", distinctID, \"\", profiles, isLoginID)\n}\n\n\/\/ ProfileUnset 删除一个用户的一个或者多个 Profile。\n\/\/ :param distinct_id: 用户的唯一标识\n\/\/ :param profile_keys: 用户属性键值列表\nfunc (c *Client) ProfileUnset(distinctID string, profileKeys []string, isLoginID bool) error {\n\tprofileMap := make(map[string]interface{}, len(profileKeys))\n\tfor _, v := range profileKeys {\n\t\tprofileMap[v] = true\n\t}\n\treturn c.trackEvent(\"profile_unset\", \"\", distinctID, \"\", profileMap, isLoginID)\n}\n\n\/\/ ProfileDelete 删除整个用户的信息。\n\/\/ :param distinct_id: 用户的唯一标识\nfunc (c *Client) ProfileDelete(distinctID string, isLoginID bool) error {\n\treturn c.trackEvent(\"profile_delete\", \"\", distinctID, \"\", map[string]interface{}{}, isLoginID)\n}\n\nfunc (c *Client) trackEvent(eventType string, eventName string, distinctID string, originalID string, properties map[string]interface{}, isLoginID bool) error {\n\tvar eventTime int64\n\tt := c.extractUserTime(properties)\n\tif t != nil {\n\t\teventTime = *t\n\t} else {\n\t\teventTime = c.now()\n\t}\n\tif isLoginID {\n\t\tproperties[\"$is_login_id\"] = true\n\t}\n\tdata := map[string]interface{}{\n\t\t\"type\":        eventType,\n\t\t\"time\":        eventTime,\n\t\t\"distinct_id\": distinctID,\n\t\t\"properties\":  properties,\n\t\t\"lib\":         c.getLibProperties(),\n\t}\n\tif c.projectName != nil {\n\t\tdata[\"project\"] = *c.projectName\n\t}\n\tif eventType == \"track\" || eventType == \"track_signup\" {\n\t\tdata[\"event\"] = eventName\n\t}\n\tif eventType == \"track_signup\" {\n\t\tdata[\"original_id\"] = originalID\n\t}\n\tif c.enableTimeFree {\n\t\tdata[\"time_free\"] = true\n\t}\n\tdata, err := c.normalizeData(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.consumer.Send(data)\n}\n\n\/\/ Flush 对于不立即发送数据的 Consumer，调用此接口应当立即进行已有数据的发送。\nfunc (c *Client) Flush() error {\n\treturn c.consumer.Flush()\n}\n\n\/\/ Close 在进程结束或者数据发送完成时，应当调用此接口，以保证所有数据被发送完毕。如果发生意外，此方法将抛出异常。\nfunc (c *Client) Close() error {\n\treturn c.consumer.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package google\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n\t\"google.golang.org\/api\/iam\/v1\"\n)\n\nfunc resourceGoogleProjectIamCustomRole() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceGoogleProjectIamCustomRoleCreate,\n\t\tRead:   resourceGoogleProjectIamCustomRoleRead,\n\t\tUpdate: resourceGoogleProjectIamCustomRoleUpdate,\n\t\tDelete: resourceGoogleProjectIamCustomRoleDelete,\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\"role_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\"title\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"permissions\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tRequired: true,\n\t\t\t\tMinItems: 1,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\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\t\"stage\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tDefault:      \"GA\",\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\"ALPHA\", \"BETA\", \"GA\", \"DEPRECATED\", \"DISABLED\", \"EAP\"}, false),\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\"deleted\": {\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 resourceGoogleProjectIamCustomRoleCreate(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\tif d.Get(\"deleted\").(bool) {\n\t\treturn fmt.Errorf(\"Cannot create a custom project role with a deleted state. `deleted` field should be false.\")\n\t}\n\n\troleId := fmt.Sprintf(\"projects\/%s\/roles\/%s\", project, d.Get(\"role_id\").(string))\n\tr, err := config.clientIAM.Projects.Roles.Get(roleId).Do()\n\tif err == nil {\n\t\tif r.Deleted {\n\t\t\t\/\/ This role was soft-deleted; update to match new state.\n\t\t\td.SetId(r.Name)\n\t\t\tif err := resourceGoogleProjectIamCustomRoleUpdate(d, meta); err != nil {\n\t\t\t\t\/\/ If update failed, make sure it wasn't actually added to state.\n\t\t\t\td.SetId(\"\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ If a role with same name exists and is enabled, just return error\n\t\t\treturn fmt.Errorf(\"Custom project role %s already exists and must be imported\", roleId)\n\t\t}\n\t} else if err := handleNotFoundError(err, d, fmt.Sprintf(\"Custom Project Role %q\", roleId)); err == nil {\n\t\t\/\/ If no role is found, actually create a new role.\n\t\trole, err := config.clientIAM.Projects.Roles.Create(\"projects\/\"+project, &iam.CreateRoleRequest{\n\t\t\tRoleId: d.Get(\"role_id\").(string),\n\t\t\tRole: &iam.Role{\n\t\t\t\tTitle:               d.Get(\"title\").(string),\n\t\t\t\tDescription:         d.Get(\"description\").(string),\n\t\t\t\tStage:               d.Get(\"stage\").(string),\n\t\t\t\tIncludedPermissions: convertStringSet(d.Get(\"permissions\").(*schema.Set)),\n\t\t\t},\n\t\t}).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error creating the custom project role %s: %v\", roleId, err)\n\t\t}\n\n\t\td.SetId(role.Name)\n\t} else {\n\t\treturn fmt.Errorf(\"Unable to verify whether custom project role %s already exists and must be undeleted: %v\", roleId, err)\n\t}\n\n\treturn resourceGoogleProjectIamCustomRoleRead(d, meta)\n}\n\nfunc resourceGoogleProjectIamCustomRoleRead(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\trole, err := config.clientIAM.Projects.Roles.Get(d.Id()).Do()\n\tif err != nil {\n\t\treturn handleNotFoundError(err, d, d.Id())\n\t}\n\n\td.Set(\"role_id\", GetResourceNameFromSelfLink(role.Name))\n\td.Set(\"title\", role.Title)\n\td.Set(\"description\", role.Description)\n\td.Set(\"permissions\", role.IncludedPermissions)\n\td.Set(\"stage\", role.Stage)\n\td.Set(\"deleted\", role.Deleted)\n\td.Set(\"project\", project)\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\td.Partial(true)\n\n\tif d.Get(\"deleted\").(bool) {\n\t\tif d.HasChange(\"deleted\") {\n\t\t\t\/\/ If other fields were changed, we need to update those first and then delete.\n\t\t\t\/\/ If we don't update, we will get diffs from re-apply\n\t\t\t\/\/ If we delete and then try to update, we will get an error.\n\t\t\tif err := resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d, meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := resourceGoogleProjectIamCustomRoleDelete(d, meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\td.SetPartial(\"deleted\")\n\t\t\td.Partial(false)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"cannot make changes to deleted custom project role %s\", d.Id())\n\t\t}\n\t}\n\n\t\/\/ We want to update the role to some undeleted state.\n\t\/\/ Make sure the role with given ID exists and is un-deleted before patching.\n\tr, err := config.clientIAM.Projects.Roles.Get(d.Id()).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to find custom project role %s to update: %v\", d.Id(), err)\n\t}\n\tif r.Deleted {\n\t\t\/\/ Undelete if deleted previously\n\t\tif err := resourceGoogleProjectIamCustomRoleUndelete(d, meta); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.SetPartial(\"deleted\")\n\t}\n\n\tif err := resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d, meta); err != nil {\n\t\treturn err\n\t}\n\td.Partial(false)\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tif d.HasChange(\"title\") || d.HasChange(\"description\") || d.HasChange(\"stage\") || d.HasChange(\"permissions\") {\n\t\t_, err := config.clientIAM.Projects.Roles.Patch(d.Id(), &iam.Role{\n\t\t\tTitle:               d.Get(\"title\").(string),\n\t\t\tDescription:         d.Get(\"description\").(string),\n\t\t\tStage:               d.Get(\"stage\").(string),\n\t\t\tIncludedPermissions: convertStringSet(d.Get(\"permissions\").(*schema.Set)),\n\t\t}).Do()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t\t}\n\t\td.SetPartial(\"title\")\n\t\td.SetPartial(\"description\")\n\t\td.SetPartial(\"stage\")\n\t\td.SetPartial(\"permissions\")\n\t}\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\t_, err := config.clientIAM.Projects.Roles.Delete(d.Id()).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUndelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\t_, err := config.clientIAM.Projects.Roles.Undelete(d.Id(), &iam.UndeleteRoleRequest{}).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error undeleting the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Add deprecation message to resource_google_project_iam_custom_role.deleted.<commit_after>package google\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n\t\"google.golang.org\/api\/iam\/v1\"\n)\n\nfunc resourceGoogleProjectIamCustomRole() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceGoogleProjectIamCustomRoleCreate,\n\t\tRead:   resourceGoogleProjectIamCustomRoleRead,\n\t\tUpdate: resourceGoogleProjectIamCustomRoleUpdate,\n\t\tDelete: resourceGoogleProjectIamCustomRoleDelete,\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\"role_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\"title\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"permissions\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tRequired: true,\n\t\t\t\tMinItems: 1,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\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\t\"stage\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tDefault:      \"GA\",\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\"ALPHA\", \"BETA\", \"GA\", \"DEPRECATED\", \"DISABLED\", \"EAP\"}, false),\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\"deleted\": {\n\t\t\t\tType:       schema.TypeBool,\n\t\t\t\tOptional:   true,\n\t\t\t\tDefault:    false,\n\t\t\t\tDeprecated: `deleted will be converted to a computed-only field soon - if you want to delete this role, please use destroy`,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceGoogleProjectIamCustomRoleCreate(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\tif d.Get(\"deleted\").(bool) {\n\t\treturn fmt.Errorf(\"Cannot create a custom project role with a deleted state. `deleted` field should be false.\")\n\t}\n\n\troleId := fmt.Sprintf(\"projects\/%s\/roles\/%s\", project, d.Get(\"role_id\").(string))\n\tr, err := config.clientIAM.Projects.Roles.Get(roleId).Do()\n\tif err == nil {\n\t\tif r.Deleted {\n\t\t\t\/\/ This role was soft-deleted; update to match new state.\n\t\t\td.SetId(r.Name)\n\t\t\tif err := resourceGoogleProjectIamCustomRoleUpdate(d, meta); err != nil {\n\t\t\t\t\/\/ If update failed, make sure it wasn't actually added to state.\n\t\t\t\td.SetId(\"\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ If a role with same name exists and is enabled, just return error\n\t\t\treturn fmt.Errorf(\"Custom project role %s already exists and must be imported\", roleId)\n\t\t}\n\t} else if err := handleNotFoundError(err, d, fmt.Sprintf(\"Custom Project Role %q\", roleId)); err == nil {\n\t\t\/\/ If no role is found, actually create a new role.\n\t\trole, err := config.clientIAM.Projects.Roles.Create(\"projects\/\"+project, &iam.CreateRoleRequest{\n\t\t\tRoleId: d.Get(\"role_id\").(string),\n\t\t\tRole: &iam.Role{\n\t\t\t\tTitle:               d.Get(\"title\").(string),\n\t\t\t\tDescription:         d.Get(\"description\").(string),\n\t\t\t\tStage:               d.Get(\"stage\").(string),\n\t\t\t\tIncludedPermissions: convertStringSet(d.Get(\"permissions\").(*schema.Set)),\n\t\t\t},\n\t\t}).Do()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error creating the custom project role %s: %v\", roleId, err)\n\t\t}\n\n\t\td.SetId(role.Name)\n\t} else {\n\t\treturn fmt.Errorf(\"Unable to verify whether custom project role %s already exists and must be undeleted: %v\", roleId, err)\n\t}\n\n\treturn resourceGoogleProjectIamCustomRoleRead(d, meta)\n}\n\nfunc resourceGoogleProjectIamCustomRoleRead(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\trole, err := config.clientIAM.Projects.Roles.Get(d.Id()).Do()\n\tif err != nil {\n\t\treturn handleNotFoundError(err, d, d.Id())\n\t}\n\n\td.Set(\"role_id\", GetResourceNameFromSelfLink(role.Name))\n\td.Set(\"title\", role.Title)\n\td.Set(\"description\", role.Description)\n\td.Set(\"permissions\", role.IncludedPermissions)\n\td.Set(\"stage\", role.Stage)\n\td.Set(\"deleted\", role.Deleted)\n\td.Set(\"project\", project)\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\td.Partial(true)\n\n\tif d.Get(\"deleted\").(bool) {\n\t\tif d.HasChange(\"deleted\") {\n\t\t\t\/\/ If other fields were changed, we need to update those first and then delete.\n\t\t\t\/\/ If we don't update, we will get diffs from re-apply\n\t\t\t\/\/ If we delete and then try to update, we will get an error.\n\t\t\tif err := resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d, meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := resourceGoogleProjectIamCustomRoleDelete(d, meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\td.SetPartial(\"deleted\")\n\t\t\td.Partial(false)\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"cannot make changes to deleted custom project role %s\", d.Id())\n\t\t}\n\t}\n\n\t\/\/ We want to update the role to some undeleted state.\n\t\/\/ Make sure the role with given ID exists and is un-deleted before patching.\n\tr, err := config.clientIAM.Projects.Roles.Get(d.Id()).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to find custom project role %s to update: %v\", d.Id(), err)\n\t}\n\tif r.Deleted {\n\t\t\/\/ Undelete if deleted previously\n\t\tif err := resourceGoogleProjectIamCustomRoleUndelete(d, meta); err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.SetPartial(\"deleted\")\n\t}\n\n\tif err := resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d, meta); err != nil {\n\t\treturn err\n\t}\n\td.Partial(false)\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUpdateNonDeletedFields(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tif d.HasChange(\"title\") || d.HasChange(\"description\") || d.HasChange(\"stage\") || d.HasChange(\"permissions\") {\n\t\t_, err := config.clientIAM.Projects.Roles.Patch(d.Id(), &iam.Role{\n\t\t\tTitle:               d.Get(\"title\").(string),\n\t\t\tDescription:         d.Get(\"description\").(string),\n\t\t\tStage:               d.Get(\"stage\").(string),\n\t\t\tIncludedPermissions: convertStringSet(d.Get(\"permissions\").(*schema.Set)),\n\t\t}).Do()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t\t}\n\t\td.SetPartial(\"title\")\n\t\td.SetPartial(\"description\")\n\t\td.SetPartial(\"stage\")\n\t\td.SetPartial(\"permissions\")\n\t}\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\t_, err := config.clientIAM.Projects.Roles.Delete(d.Id()).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceGoogleProjectIamCustomRoleUndelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\t_, err := config.clientIAM.Projects.Roles.Undelete(d.Id(), &iam.UndeleteRoleRequest{}).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error undeleting the custom project role %s: %s\", d.Get(\"title\").(string), err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 ALTOROS\n\/\/ Licensed under the AGPLv3, see LICENSE file for details.\n\npackage gosigma\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/Altoros\/gosigma\/https\"\n)\n\ntype RequestSpec bool\n\nconst (\n\tRequestShort  RequestSpec = false\n\tRequestDetail RequestSpec = true\n)\n\ntype LibrarySpec bool\n\nconst (\n\tLibraryAccount LibrarySpec = false\n\tLibraryMedia   LibrarySpec = true\n)\n\n\/\/ A Client sends and receives requests to CloudSigma endpoint\ntype Client struct {\n\tendpoint         string\n\thttps            *https.Client\n\tlogger           https.Logger\n\toperationTimeout time.Duration\n}\n\nvar errEmptyUsername = errors.New(\"username is not allowed to be empty\")\nvar errEmptyPassword = errors.New(\"password is not allowed to be empty\")\nvar errEmptyUUID = errors.New(\"password is not allowed to be empty\")\n\n\/\/ NewClient returns new CloudSigma client object\nfunc NewClient(endpoint string, username, password string,\n\ttlsConfig *tls.Config) (*Client, error) {\n\n\tendpoint, err := ResolveEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(username) == 0 {\n\t\treturn nil, errEmptyUsername\n\t}\n\n\tif len(password) == 0 {\n\t\treturn nil, errEmptyPassword\n\t}\n\n\tclient := &Client{\n\t\tendpoint: endpoint,\n\t\thttps:    https.NewAuthClient(username, password, tlsConfig),\n\t}\n\n\treturn client, nil\n}\n\n\/\/ ConnectTimeout sets connection timeout\nfunc (c Client) ConnectTimeout(timeout time.Duration) {\n\tc.https.ConnectTimeout(timeout)\n}\n\n\/\/ GetConnectTimeout returns connection timeout for the object\nfunc (c Client) GetConnectTimeout() time.Duration {\n\treturn c.https.GetConnectTimeout()\n}\n\n\/\/ ReadWriteTimeout sets read-write timeout\nfunc (c Client) ReadWriteTimeout(timeout time.Duration) {\n\tc.https.ReadWriteTimeout(timeout)\n}\n\n\/\/ GetReadWriteTimeout returns connection timeout for the object\nfunc (c Client) GetReadWriteTimeout() time.Duration {\n\treturn c.https.GetReadWriteTimeout()\n}\n\n\/\/ OperationTimeout sets timeout for cloud operations (like cloning, starting, stopping etc)\nfunc (c *Client) OperationTimeout(timeout time.Duration) {\n\tc.operationTimeout = timeout\n}\n\n\/\/ GetOperationTimeout gets timeout for cloud operations (like cloning, starting, stopping etc)\nfunc (c Client) GetOperationTimeout() time.Duration {\n\treturn c.operationTimeout\n}\n\n\/\/ Logger sets logger for http traces\nfunc (c *Client) Logger(logger https.Logger) {\n\tc.logger = logger\n\tc.https.Logger(logger)\n}\n\n\/\/ Servers in current account\nfunc (c Client) Servers(rqspec RequestSpec) ([]Server, error) {\n\tobjs, err := c.getServers(rqspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservers := make([]Server, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\tservers[i] = &server{\n\t\t\tclient: &c,\n\t\t\tobj:    &objs[i],\n\t\t}\n\t}\n\n\treturn servers, nil\n}\n\n\/\/ ServersFiltered in current account with filter applied\nfunc (c Client) ServersFiltered(rqspec RequestSpec, filter func(s Server) bool) ([]Server, error) {\n\tobjs, err := c.getServers(rqspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservers := make([]Server, 0, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\ts := &server{\n\t\t\tclient: &c,\n\t\t\tobj:    &objs[i],\n\t\t}\n\t\tif filter(s) {\n\t\t\tservers = append(servers, s)\n\t\t}\n\t}\n\n\treturn servers, nil\n}\n\n\/\/ Server returns given server by uuid\nfunc (c Client) Server(uuid string) (Server, error) {\n\tobj, err := c.getServer(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := &server{\n\t\tclient: &c,\n\t\tobj:    obj,\n\t}\n\n\treturn srv, nil\n}\n\n\/\/ CreateServer in CloudSigma user account\nfunc (c Client) CreateServer(components Components) (Server, error) {\n\tobjs, err := c.createServer(components)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(objs) == 0 {\n\t\treturn nil, errors.New(\"no servers in response from endpoint\")\n\t}\n\n\ts := &server{\n\t\tclient: &c,\n\t\tobj:    &objs[0],\n\t}\n\n\treturn s, nil\n}\n\n\/\/ StartServer by uuid of server instance.\nfunc (c Client) StartServer(uuid string, avoid []string) error {\n\treturn c.startServer(uuid, avoid)\n}\n\n\/\/ StopServer by uuid of server instance\nfunc (c Client) StopServer(uuid string) error {\n\treturn c.stopServer(uuid)\n}\n\n\/\/ RemoveServer by uuid of server instance with an option recursively removing attached drives.\n\/\/ See RecurseXXX constants in server.go file.\nfunc (c Client) RemoveServer(uuid, recurse string) error {\n\treturn c.removeServer(uuid, recurse)\n}\n\n\/\/ Drives returns list of drives\nfunc (c Client) Drives(rqspec RequestSpec, libspec LibrarySpec) ([]Drive, error) {\n\tobjs, err := c.getDrives(rqspec, libspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdrives := make([]Drive, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\tdrives[i] = &drive{\n\t\t\tclient:  &c,\n\t\t\tobj:     &objs[i],\n\t\t\tlibrary: libspec,\n\t\t}\n\t}\n\n\treturn drives, nil\n}\n\n\/\/ Drive returns given drive by uuid\nfunc (c Client) Drive(uuid string, libspec LibrarySpec) (Drive, error) {\n\tobj, err := c.getDrive(uuid, libspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdrv := &drive{\n\t\tclient:  &c,\n\t\tobj:     obj,\n\t\tlibrary: libspec,\n\t}\n\n\treturn drv, nil\n}\n\n\/\/ CloneDrive clones given drive by uuid\nfunc (c Client) CloneDrive(uuid string, libspec LibrarySpec, params CloneParams, avoid []string) (Drive, error) {\n\tobjs, err := c.cloneDrive(uuid, libspec, params, avoid)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(objs) == 0 {\n\t\treturn nil, errors.New(\"No object was returned from server\")\n\t}\n\n\tdrv := &drive{\n\t\tclient:  &c,\n\t\tobj:     &objs[0],\n\t\tlibrary: libspec,\n\t}\n\n\treturn drv, nil\n}\n\n\/\/ Job returns job object by uuid\nfunc (c Client) Job(uuid string) (Job, error) {\n\tobj, err := c.getJob(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tj := &job{\n\t\tclient: &c,\n\t\tobj:    obj,\n\t}\n\n\treturn j, nil\n}\n\n\/\/ ReadContext reads and returns context of current server\nfunc (c Client) ReadContext() (Context, error) {\n\tobj, err := c.readContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := context{obj: obj}\n\n\treturn ctx, nil\n}\n<commit_msg>fix error message<commit_after>\/\/ Copyright 2014 ALTOROS\n\/\/ Licensed under the AGPLv3, see LICENSE file for details.\n\npackage gosigma\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/Altoros\/gosigma\/https\"\n)\n\ntype RequestSpec bool\n\nconst (\n\tRequestShort  RequestSpec = false\n\tRequestDetail RequestSpec = true\n)\n\ntype LibrarySpec bool\n\nconst (\n\tLibraryAccount LibrarySpec = false\n\tLibraryMedia   LibrarySpec = true\n)\n\n\/\/ A Client sends and receives requests to CloudSigma endpoint\ntype Client struct {\n\tendpoint         string\n\thttps            *https.Client\n\tlogger           https.Logger\n\toperationTimeout time.Duration\n}\n\nvar errEmptyUsername = errors.New(\"username is not allowed to be empty\")\nvar errEmptyPassword = errors.New(\"password is not allowed to be empty\")\nvar errEmptyUUID = errors.New(\"password is not allowed to be empty\")\n\n\/\/ NewClient returns new CloudSigma client object\nfunc NewClient(endpoint string, username, password string,\n\ttlsConfig *tls.Config) (*Client, error) {\n\n\tendpoint, err := ResolveEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(username) == 0 {\n\t\treturn nil, errEmptyUsername\n\t}\n\n\tif len(password) == 0 {\n\t\treturn nil, errEmptyPassword\n\t}\n\n\tclient := &Client{\n\t\tendpoint: endpoint,\n\t\thttps:    https.NewAuthClient(username, password, tlsConfig),\n\t}\n\n\treturn client, nil\n}\n\n\/\/ ConnectTimeout sets connection timeout\nfunc (c Client) ConnectTimeout(timeout time.Duration) {\n\tc.https.ConnectTimeout(timeout)\n}\n\n\/\/ GetConnectTimeout returns connection timeout for the object\nfunc (c Client) GetConnectTimeout() time.Duration {\n\treturn c.https.GetConnectTimeout()\n}\n\n\/\/ ReadWriteTimeout sets read-write timeout\nfunc (c Client) ReadWriteTimeout(timeout time.Duration) {\n\tc.https.ReadWriteTimeout(timeout)\n}\n\n\/\/ GetReadWriteTimeout returns connection timeout for the object\nfunc (c Client) GetReadWriteTimeout() time.Duration {\n\treturn c.https.GetReadWriteTimeout()\n}\n\n\/\/ OperationTimeout sets timeout for cloud operations (like cloning, starting, stopping etc)\nfunc (c *Client) OperationTimeout(timeout time.Duration) {\n\tc.operationTimeout = timeout\n}\n\n\/\/ GetOperationTimeout gets timeout for cloud operations (like cloning, starting, stopping etc)\nfunc (c Client) GetOperationTimeout() time.Duration {\n\treturn c.operationTimeout\n}\n\n\/\/ Logger sets logger for http traces\nfunc (c *Client) Logger(logger https.Logger) {\n\tc.logger = logger\n\tc.https.Logger(logger)\n}\n\n\/\/ Servers in current account\nfunc (c Client) Servers(rqspec RequestSpec) ([]Server, error) {\n\tobjs, err := c.getServers(rqspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservers := make([]Server, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\tservers[i] = &server{\n\t\t\tclient: &c,\n\t\t\tobj:    &objs[i],\n\t\t}\n\t}\n\n\treturn servers, nil\n}\n\n\/\/ ServersFiltered in current account with filter applied\nfunc (c Client) ServersFiltered(rqspec RequestSpec, filter func(s Server) bool) ([]Server, error) {\n\tobjs, err := c.getServers(rqspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tservers := make([]Server, 0, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\ts := &server{\n\t\t\tclient: &c,\n\t\t\tobj:    &objs[i],\n\t\t}\n\t\tif filter(s) {\n\t\t\tservers = append(servers, s)\n\t\t}\n\t}\n\n\treturn servers, nil\n}\n\n\/\/ Server returns given server by uuid\nfunc (c Client) Server(uuid string) (Server, error) {\n\tobj, err := c.getServer(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsrv := &server{\n\t\tclient: &c,\n\t\tobj:    obj,\n\t}\n\n\treturn srv, nil\n}\n\n\/\/ CreateServer in CloudSigma user account\nfunc (c Client) CreateServer(components Components) (Server, error) {\n\tobjs, err := c.createServer(components)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(objs) == 0 {\n\t\treturn nil, errors.New(\"no servers in response from endpoint\")\n\t}\n\n\ts := &server{\n\t\tclient: &c,\n\t\tobj:    &objs[0],\n\t}\n\n\treturn s, nil\n}\n\n\/\/ StartServer by uuid of server instance.\nfunc (c Client) StartServer(uuid string, avoid []string) error {\n\treturn c.startServer(uuid, avoid)\n}\n\n\/\/ StopServer by uuid of server instance\nfunc (c Client) StopServer(uuid string) error {\n\treturn c.stopServer(uuid)\n}\n\n\/\/ RemoveServer by uuid of server instance with an option recursively removing attached drives.\n\/\/ See RecurseXXX constants in server.go file.\nfunc (c Client) RemoveServer(uuid, recurse string) error {\n\treturn c.removeServer(uuid, recurse)\n}\n\n\/\/ Drives returns list of drives\nfunc (c Client) Drives(rqspec RequestSpec, libspec LibrarySpec) ([]Drive, error) {\n\tobjs, err := c.getDrives(rqspec, libspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdrives := make([]Drive, len(objs))\n\tfor i := 0; i < len(objs); i++ {\n\t\tdrives[i] = &drive{\n\t\t\tclient:  &c,\n\t\t\tobj:     &objs[i],\n\t\t\tlibrary: libspec,\n\t\t}\n\t}\n\n\treturn drives, nil\n}\n\n\/\/ Drive returns given drive by uuid\nfunc (c Client) Drive(uuid string, libspec LibrarySpec) (Drive, error) {\n\tobj, err := c.getDrive(uuid, libspec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdrv := &drive{\n\t\tclient:  &c,\n\t\tobj:     obj,\n\t\tlibrary: libspec,\n\t}\n\n\treturn drv, nil\n}\n\n\/\/ CloneDrive clones given drive by uuid\nfunc (c Client) CloneDrive(uuid string, libspec LibrarySpec, params CloneParams, avoid []string) (Drive, error) {\n\tobjs, err := c.cloneDrive(uuid, libspec, params, avoid)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(objs) == 0 {\n\t\treturn nil, errors.New(\"no object was returned from server\")\n\t}\n\n\tdrv := &drive{\n\t\tclient:  &c,\n\t\tobj:     &objs[0],\n\t\tlibrary: libspec,\n\t}\n\n\treturn drv, nil\n}\n\n\/\/ Job returns job object by uuid\nfunc (c Client) Job(uuid string) (Job, error) {\n\tobj, err := c.getJob(uuid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tj := &job{\n\t\tclient: &c,\n\t\tobj:    obj,\n\t}\n\n\treturn j, nil\n}\n\n\/\/ ReadContext reads and returns context of current server\nfunc (c Client) ReadContext() (Context, error) {\n\tobj, err := c.readContext()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx := context{obj: obj}\n\n\treturn ctx, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package quic\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"errors\"\n\t\"hash\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\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)\n\n\/\/ The packetHandlerMap stores packetHandlers, identified by connection ID.\n\/\/ It is used:\n\/\/ * by the server to store sessions\n\/\/ * when multiplexing outgoing connections to store clients\ntype packetHandlerMap struct {\n\tmutex sync.RWMutex\n\n\tconn      net.PacketConn\n\tconnIDLen int\n\n\thandlers    map[string] \/* string(ConnectionID)*\/ packetHandler\n\tresetTokens map[[16]byte] \/* stateless reset token *\/ packetHandler\n\tserver      unknownPacketHandler\n\n\tlistening chan struct{} \/\/ is closed when listen returns\n\tclosed    bool\n\n\tdeleteRetiredSessionsAfter time.Duration\n\n\tstatelessResetEnabled bool\n\tstatelessResetMutex   sync.Mutex\n\tstatelessResetHasher  hash.Hash\n\n\tlogger utils.Logger\n}\n\nvar _ packetHandlerManager = &packetHandlerMap{}\n\nfunc newPacketHandlerMap(\n\tconn net.PacketConn,\n\tconnIDLen int,\n\tstatelessResetKey []byte,\n\tlogger utils.Logger,\n) packetHandlerManager {\n\tm := &packetHandlerMap{\n\t\tconn:                       conn,\n\t\tconnIDLen:                  connIDLen,\n\t\tlistening:                  make(chan struct{}),\n\t\thandlers:                   make(map[string]packetHandler),\n\t\tresetTokens:                make(map[[16]byte]packetHandler),\n\t\tdeleteRetiredSessionsAfter: protocol.RetiredConnectionIDDeleteTimeout,\n\t\tstatelessResetEnabled:      len(statelessResetKey) > 0,\n\t\tstatelessResetHasher:       hmac.New(sha256.New, statelessResetKey),\n\t\tlogger:                     logger,\n\t}\n\tgo m.listen()\n\treturn m\n}\n\nfunc (h *packetHandlerMap) Add(id protocol.ConnectionID, handler packetHandler) {\n\th.mutex.Lock()\n\th.handlers[string(id)] = handler\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) Remove(id protocol.ConnectionID) {\n\th.mutex.Lock()\n\tdelete(h.handlers, string(id))\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) Retire(id protocol.ConnectionID) {\n\ttime.AfterFunc(h.deleteRetiredSessionsAfter, func() {\n\t\th.mutex.Lock()\n\t\tdelete(h.handlers, string(id))\n\t\th.mutex.Unlock()\n\t})\n}\n\nfunc (h *packetHandlerMap) ReplaceWithClosed(id protocol.ConnectionID, handler packetHandler) {\n\th.mutex.Lock()\n\th.handlers[string(id)] = handler\n\th.mutex.Unlock()\n\n\ttime.AfterFunc(h.deleteRetiredSessionsAfter, func() {\n\t\th.mutex.Lock()\n\t\thandler.Close()\n\t\tdelete(h.handlers, string(id))\n\t\th.mutex.Unlock()\n\t})\n}\n\nfunc (h *packetHandlerMap) AddResetToken(token [16]byte, handler packetHandler) {\n\th.mutex.Lock()\n\th.resetTokens[token] = handler\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) RemoveResetToken(token [16]byte) {\n\th.mutex.Lock()\n\tdelete(h.resetTokens, token)\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) SetServer(s unknownPacketHandler) {\n\th.mutex.Lock()\n\th.server = s\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) CloseServer() {\n\th.mutex.Lock()\n\th.server = nil\n\tvar wg sync.WaitGroup\n\tfor _, handler := range h.handlers {\n\t\tif handler.getPerspective() == protocol.PerspectiveServer {\n\t\t\twg.Add(1)\n\t\t\tgo func(handler packetHandler) {\n\t\t\t\t\/\/ session.Close() blocks until the CONNECTION_CLOSE has been sent and the run-loop has stopped\n\t\t\t\t_ = handler.Close()\n\t\t\t\twg.Done()\n\t\t\t}(handler)\n\t\t}\n\t}\n\th.mutex.Unlock()\n\twg.Wait()\n}\n\n\/\/ Close the underlying connection and wait until listen() has returned.\nfunc (h *packetHandlerMap) Close() error {\n\tif err := h.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\t<-h.listening \/\/ wait until listening returns\n\treturn nil\n}\n\nfunc (h *packetHandlerMap) close(e error) error {\n\th.mutex.Lock()\n\tif h.closed {\n\t\th.mutex.Unlock()\n\t\treturn nil\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor _, handler := range h.handlers {\n\t\twg.Add(1)\n\t\tgo func(handler packetHandler) {\n\t\t\thandler.destroy(e)\n\t\t\twg.Done()\n\t\t}(handler)\n\t}\n\n\tif h.server != nil {\n\t\th.server.setCloseError(e)\n\t}\n\th.closed = true\n\th.mutex.Unlock()\n\twg.Wait()\n\treturn getMultiplexer().RemoveConn(h.conn)\n}\n\nfunc (h *packetHandlerMap) listen() {\n\tdefer close(h.listening)\n\tfor {\n\t\tbuffer := getPacketBuffer()\n\t\tdata := buffer.Slice\n\t\t\/\/ The packet size should not exceed protocol.MaxReceivePacketSize bytes\n\t\t\/\/ If it does, we only read a truncated packet, which will then end up undecryptable\n\t\tn, addr, err := h.conn.ReadFrom(data)\n\t\tif err != nil {\n\t\t\th.close(err)\n\t\t\treturn\n\t\t}\n\t\th.handlePacket(addr, buffer, data[:n])\n\t}\n}\n\nfunc (h *packetHandlerMap) handlePacket(\n\taddr net.Addr,\n\tbuffer *packetBuffer,\n\tdata []byte,\n) {\n\tconnID, err := wire.ParseConnectionID(data, h.connIDLen)\n\tif err != nil {\n\t\th.logger.Debugf(\"error parsing connection ID on packet from %s: %s\", addr, err)\n\t\treturn\n\t}\n\trcvTime := time.Now()\n\n\th.mutex.RLock()\n\tdefer h.mutex.RUnlock()\n\n\tif isStatelessReset := h.maybeHandleStatelessReset(data); isStatelessReset {\n\t\treturn\n\t}\n\n\thandler, handlerFound := h.handlers[string(connID)]\n\n\tp := &receivedPacket{\n\t\tremoteAddr: addr,\n\t\trcvTime:    rcvTime,\n\t\tbuffer:     buffer,\n\t\tdata:       data,\n\t}\n\tif handlerFound { \/\/ existing session\n\t\thandler.handlePacket(p)\n\t\treturn\n\t}\n\tif data[0]&0x80 == 0 {\n\t\tgo h.maybeSendStatelessReset(p, connID)\n\t\treturn\n\t}\n\tif h.server == nil { \/\/ no server set\n\t\th.logger.Debugf(\"received a packet with an unexpected connection ID %s\", connID)\n\t\treturn\n\t}\n\th.server.handlePacket(p)\n}\n\nfunc (h *packetHandlerMap) maybeHandleStatelessReset(data []byte) bool {\n\t\/\/ stateless resets are always short header packets\n\tif data[0]&0x80 != 0 {\n\t\treturn false\n\t}\n\tif len(data) < 17 \/* type byte + 16 bytes for the reset token *\/ {\n\t\treturn false\n\t}\n\n\tvar token [16]byte\n\tcopy(token[:], data[len(data)-16:])\n\tif sess, ok := h.resetTokens[token]; ok {\n\t\th.logger.Debugf(\"Received a stateless retry with token %#x. Closing session.\", token)\n\t\tgo sess.destroy(errors.New(\"received a stateless reset\"))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (h *packetHandlerMap) GetStatelessResetToken(connID protocol.ConnectionID) [16]byte {\n\tvar token [16]byte\n\tif !h.statelessResetEnabled {\n\t\t\/\/ Return a random stateless reset token.\n\t\t\/\/ This token will be sent in the server's transport parameters.\n\t\t\/\/ By using a random token, an off-path attacker won't be able to disrupt the connection.\n\t\trand.Read(token[:])\n\t\treturn token\n\t}\n\th.statelessResetMutex.Lock()\n\th.statelessResetHasher.Write(connID.Bytes())\n\tcopy(token[:], h.statelessResetHasher.Sum(nil))\n\th.statelessResetHasher.Reset()\n\th.statelessResetMutex.Unlock()\n\treturn token\n}\n\nfunc (h *packetHandlerMap) maybeSendStatelessReset(p *receivedPacket, connID protocol.ConnectionID) {\n\tdefer p.buffer.Release()\n\tif !h.statelessResetEnabled {\n\t\treturn\n\t}\n\t\/\/ Don't send a stateless reset in response to very small packets.\n\t\/\/ This includes packets that could be stateless resets.\n\tif len(p.data) <= protocol.MinStatelessResetSize {\n\t\treturn\n\t}\n\ttoken := h.GetStatelessResetToken(connID)\n\th.logger.Debugf(\"Sending stateless reset to %s (connection ID: %s). Token: %#x\", p.remoteAddr, connID, token)\n\tdata := make([]byte, protocol.MinStatelessResetSize-16, protocol.MinStatelessResetSize)\n\trand.Read(data)\n\tdata[0] = (data[0] & 0x7f) | 0x40\n\tdata = append(data, token[:]...)\n\tif _, err := h.conn.WriteTo(data, p.remoteAddr); err != nil {\n\t\th.logger.Debugf(\"Error sending Stateless Reset: %s\", err)\n\t}\n}\n<commit_msg>periodically log the number of tracked items in the packet handler map<commit_after>package quic\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"errors\"\n\t\"hash\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\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)\n\n\/\/ The packetHandlerMap stores packetHandlers, identified by connection ID.\n\/\/ It is used:\n\/\/ * by the server to store sessions\n\/\/ * when multiplexing outgoing connections to store clients\ntype packetHandlerMap struct {\n\tmutex sync.RWMutex\n\n\tconn      net.PacketConn\n\tconnIDLen int\n\n\thandlers    map[string] \/* string(ConnectionID)*\/ packetHandler\n\tresetTokens map[[16]byte] \/* stateless reset token *\/ packetHandler\n\tserver      unknownPacketHandler\n\n\tlistening chan struct{} \/\/ is closed when listen returns\n\tclosed    bool\n\n\tdeleteRetiredSessionsAfter time.Duration\n\n\tstatelessResetEnabled bool\n\tstatelessResetMutex   sync.Mutex\n\tstatelessResetHasher  hash.Hash\n\n\tlogger utils.Logger\n}\n\nvar _ packetHandlerManager = &packetHandlerMap{}\n\nfunc newPacketHandlerMap(\n\tconn net.PacketConn,\n\tconnIDLen int,\n\tstatelessResetKey []byte,\n\tlogger utils.Logger,\n) packetHandlerManager {\n\tm := &packetHandlerMap{\n\t\tconn:                       conn,\n\t\tconnIDLen:                  connIDLen,\n\t\tlistening:                  make(chan struct{}),\n\t\thandlers:                   make(map[string]packetHandler),\n\t\tresetTokens:                make(map[[16]byte]packetHandler),\n\t\tdeleteRetiredSessionsAfter: protocol.RetiredConnectionIDDeleteTimeout,\n\t\tstatelessResetEnabled:      len(statelessResetKey) > 0,\n\t\tstatelessResetHasher:       hmac.New(sha256.New, statelessResetKey),\n\t\tlogger:                     logger,\n\t}\n\tgo m.listen()\n\n\tif logger.Debug() {\n\t\tgo m.logUsage()\n\t}\n\n\treturn m\n}\n\nfunc (h *packetHandlerMap) logUsage() {\n\tticker := time.NewTicker(2 * time.Second)\n\tvar printedZero bool\n\tfor {\n\t\tselect {\n\t\tcase <-h.listening:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\th.mutex.Lock()\n\t\tnumHandlers := len(h.handlers)\n\t\tnumTokens := len(h.resetTokens)\n\t\th.mutex.Unlock()\n\t\t\/\/ If the number tracked handlers and tokens is zero, only print it a single time.\n\t\thasZero := numHandlers == 0 && numTokens == 0\n\t\tif !hasZero || (hasZero && !printedZero) {\n\t\t\th.logger.Debugf(\"Tracking %d connection IDs and %d reset tokens.\\n\", numHandlers, numTokens)\n\t\t\tprintedZero = false\n\t\t\tif hasZero {\n\t\t\t\tprintedZero = true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *packetHandlerMap) Add(id protocol.ConnectionID, handler packetHandler) {\n\th.mutex.Lock()\n\th.handlers[string(id)] = handler\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) Remove(id protocol.ConnectionID) {\n\th.mutex.Lock()\n\tdelete(h.handlers, string(id))\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) Retire(id protocol.ConnectionID) {\n\ttime.AfterFunc(h.deleteRetiredSessionsAfter, func() {\n\t\th.mutex.Lock()\n\t\tdelete(h.handlers, string(id))\n\t\th.mutex.Unlock()\n\t})\n}\n\nfunc (h *packetHandlerMap) ReplaceWithClosed(id protocol.ConnectionID, handler packetHandler) {\n\th.mutex.Lock()\n\th.handlers[string(id)] = handler\n\th.mutex.Unlock()\n\n\ttime.AfterFunc(h.deleteRetiredSessionsAfter, func() {\n\t\th.mutex.Lock()\n\t\thandler.Close()\n\t\tdelete(h.handlers, string(id))\n\t\th.mutex.Unlock()\n\t})\n}\n\nfunc (h *packetHandlerMap) AddResetToken(token [16]byte, handler packetHandler) {\n\th.mutex.Lock()\n\th.resetTokens[token] = handler\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) RemoveResetToken(token [16]byte) {\n\th.mutex.Lock()\n\tdelete(h.resetTokens, token)\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) SetServer(s unknownPacketHandler) {\n\th.mutex.Lock()\n\th.server = s\n\th.mutex.Unlock()\n}\n\nfunc (h *packetHandlerMap) CloseServer() {\n\th.mutex.Lock()\n\th.server = nil\n\tvar wg sync.WaitGroup\n\tfor _, handler := range h.handlers {\n\t\tif handler.getPerspective() == protocol.PerspectiveServer {\n\t\t\twg.Add(1)\n\t\t\tgo func(handler packetHandler) {\n\t\t\t\t\/\/ session.Close() blocks until the CONNECTION_CLOSE has been sent and the run-loop has stopped\n\t\t\t\t_ = handler.Close()\n\t\t\t\twg.Done()\n\t\t\t}(handler)\n\t\t}\n\t}\n\th.mutex.Unlock()\n\twg.Wait()\n}\n\n\/\/ Close the underlying connection and wait until listen() has returned.\nfunc (h *packetHandlerMap) Close() error {\n\tif err := h.conn.Close(); err != nil {\n\t\treturn err\n\t}\n\t<-h.listening \/\/ wait until listening returns\n\treturn nil\n}\n\nfunc (h *packetHandlerMap) close(e error) error {\n\th.mutex.Lock()\n\tif h.closed {\n\t\th.mutex.Unlock()\n\t\treturn nil\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor _, handler := range h.handlers {\n\t\twg.Add(1)\n\t\tgo func(handler packetHandler) {\n\t\t\thandler.destroy(e)\n\t\t\twg.Done()\n\t\t}(handler)\n\t}\n\n\tif h.server != nil {\n\t\th.server.setCloseError(e)\n\t}\n\th.closed = true\n\th.mutex.Unlock()\n\twg.Wait()\n\treturn getMultiplexer().RemoveConn(h.conn)\n}\n\nfunc (h *packetHandlerMap) listen() {\n\tdefer close(h.listening)\n\tfor {\n\t\tbuffer := getPacketBuffer()\n\t\tdata := buffer.Slice\n\t\t\/\/ The packet size should not exceed protocol.MaxReceivePacketSize bytes\n\t\t\/\/ If it does, we only read a truncated packet, which will then end up undecryptable\n\t\tn, addr, err := h.conn.ReadFrom(data)\n\t\tif err != nil {\n\t\t\th.close(err)\n\t\t\treturn\n\t\t}\n\t\th.handlePacket(addr, buffer, data[:n])\n\t}\n}\n\nfunc (h *packetHandlerMap) handlePacket(\n\taddr net.Addr,\n\tbuffer *packetBuffer,\n\tdata []byte,\n) {\n\tconnID, err := wire.ParseConnectionID(data, h.connIDLen)\n\tif err != nil {\n\t\th.logger.Debugf(\"error parsing connection ID on packet from %s: %s\", addr, err)\n\t\treturn\n\t}\n\trcvTime := time.Now()\n\n\th.mutex.RLock()\n\tdefer h.mutex.RUnlock()\n\n\tif isStatelessReset := h.maybeHandleStatelessReset(data); isStatelessReset {\n\t\treturn\n\t}\n\n\thandler, handlerFound := h.handlers[string(connID)]\n\n\tp := &receivedPacket{\n\t\tremoteAddr: addr,\n\t\trcvTime:    rcvTime,\n\t\tbuffer:     buffer,\n\t\tdata:       data,\n\t}\n\tif handlerFound { \/\/ existing session\n\t\thandler.handlePacket(p)\n\t\treturn\n\t}\n\tif data[0]&0x80 == 0 {\n\t\tgo h.maybeSendStatelessReset(p, connID)\n\t\treturn\n\t}\n\tif h.server == nil { \/\/ no server set\n\t\th.logger.Debugf(\"received a packet with an unexpected connection ID %s\", connID)\n\t\treturn\n\t}\n\th.server.handlePacket(p)\n}\n\nfunc (h *packetHandlerMap) maybeHandleStatelessReset(data []byte) bool {\n\t\/\/ stateless resets are always short header packets\n\tif data[0]&0x80 != 0 {\n\t\treturn false\n\t}\n\tif len(data) < 17 \/* type byte + 16 bytes for the reset token *\/ {\n\t\treturn false\n\t}\n\n\tvar token [16]byte\n\tcopy(token[:], data[len(data)-16:])\n\tif sess, ok := h.resetTokens[token]; ok {\n\t\th.logger.Debugf(\"Received a stateless retry with token %#x. Closing session.\", token)\n\t\tgo sess.destroy(errors.New(\"received a stateless reset\"))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (h *packetHandlerMap) GetStatelessResetToken(connID protocol.ConnectionID) [16]byte {\n\tvar token [16]byte\n\tif !h.statelessResetEnabled {\n\t\t\/\/ Return a random stateless reset token.\n\t\t\/\/ This token will be sent in the server's transport parameters.\n\t\t\/\/ By using a random token, an off-path attacker won't be able to disrupt the connection.\n\t\trand.Read(token[:])\n\t\treturn token\n\t}\n\th.statelessResetMutex.Lock()\n\th.statelessResetHasher.Write(connID.Bytes())\n\tcopy(token[:], h.statelessResetHasher.Sum(nil))\n\th.statelessResetHasher.Reset()\n\th.statelessResetMutex.Unlock()\n\treturn token\n}\n\nfunc (h *packetHandlerMap) maybeSendStatelessReset(p *receivedPacket, connID protocol.ConnectionID) {\n\tdefer p.buffer.Release()\n\tif !h.statelessResetEnabled {\n\t\treturn\n\t}\n\t\/\/ Don't send a stateless reset in response to very small packets.\n\t\/\/ This includes packets that could be stateless resets.\n\tif len(p.data) <= protocol.MinStatelessResetSize {\n\t\treturn\n\t}\n\ttoken := h.GetStatelessResetToken(connID)\n\th.logger.Debugf(\"Sending stateless reset to %s (connection ID: %s). Token: %#x\", p.remoteAddr, connID, token)\n\tdata := make([]byte, protocol.MinStatelessResetSize-16, protocol.MinStatelessResetSize)\n\trand.Read(data)\n\tdata[0] = (data[0] & 0x7f) | 0x40\n\tdata = append(data, token[:]...)\n\tif _, err := h.conn.WriteTo(data, p.remoteAddr); err != nil {\n\t\th.logger.Debugf(\"Error sending Stateless Reset: %s\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package pkcs7\n\nimport (\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"github.com\/st3fan\/gocrypto\/pkcs7\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\/\/\n\/\/ Test key and certificate are in testdata\/ and were generated with OpenSSL as follows:\n\/\/\n\/\/   openssl genrsa -out test.key 2048\n\/\/   openssl req -nodes -new -key test.key -out test.csr -subj \"\/C=CA\/ST=Ontario\/L=Toronto\/O=Stefan Arentz\/OU=Golang Hacks\/CN=example.com\"\n\/\/   openssl x509 -req -days 1825 -in test.csr -signkey test.key -out test.crt\n\/\/\n\nfunc loadPKCS1PrivateKey(path string) (*rsa.PrivateKey, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, _ := pem.Decode(bytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Invalid key; no PEM data found\")\n\t}\n\tif block.Type != \"RSA PRIVATE KEY\" {\n\t\treturn nil, errors.New(\"Invalid key; no RSA PRIVATE KEY block\")\n\t}\n\treturn x509.ParsePKCS1PrivateKey(block.Bytes)\n}\n\nfunc loadCertificate(path string) (*x509.Certificate, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, _ := pem.Decode(bytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Invalid certificate; no PEM data found\")\n\t}\n\tif block.Type != \"CERTIFICATE\" {\n\t\treturn nil, errors.New(\"Invalid certificate; no CERTIFICATE block\")\n\t}\n\treturn x509.ParseCertificate(block.Bytes)\n}\n\nfunc Test_Sign(t *testing.T) {\n\tkey, err := loadPKCS1PrivateKey(\"testdata\/test.key\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcert, err := loadCertificate(\"testdata\/test.crt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tf, err := os.Open(\"testdata\/test.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tsignature, err := pkcs7.Sign(f, cert, key)\n\tif err != nil {\n\t\tt.Error(\"Cannot Sign:\", err)\n\t}\n\n\tif len(signature) == 0 {\n\t\tt.Error(\"Signature is zero length\")\n\t}\n}\n<commit_msg>Remove dependency cycle. Oops.<commit_after>package pkcs7\n\nimport (\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\n\/\/\n\/\/ Test key and certificate are in testdata\/ and were generated with OpenSSL as follows:\n\/\/\n\/\/   openssl genrsa -out test.key 2048\n\/\/   openssl req -nodes -new -key test.key -out test.csr -subj \"\/C=CA\/ST=Ontario\/L=Toronto\/O=Stefan Arentz\/OU=Golang Hacks\/CN=example.com\"\n\/\/   openssl x509 -req -days 1825 -in test.csr -signkey test.key -out test.crt\n\/\/\n\nfunc loadPKCS1PrivateKey(path string) (*rsa.PrivateKey, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, _ := pem.Decode(bytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Invalid key; no PEM data found\")\n\t}\n\tif block.Type != \"RSA PRIVATE KEY\" {\n\t\treturn nil, errors.New(\"Invalid key; no RSA PRIVATE KEY block\")\n\t}\n\treturn x509.ParsePKCS1PrivateKey(block.Bytes)\n}\n\nfunc loadCertificate(path string) (*x509.Certificate, error) {\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, _ := pem.Decode(bytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Invalid certificate; no PEM data found\")\n\t}\n\tif block.Type != \"CERTIFICATE\" {\n\t\treturn nil, errors.New(\"Invalid certificate; no CERTIFICATE block\")\n\t}\n\treturn x509.ParseCertificate(block.Bytes)\n}\n\nfunc Test_Sign(t *testing.T) {\n\tkey, err := loadPKCS1PrivateKey(\"testdata\/test.key\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tcert, err := loadCertificate(\"testdata\/test.crt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tf, err := os.Open(\"testdata\/test.txt\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\n\tsignature, err := pkcs7.Sign(f, cert, key)\n\tif err != nil {\n\t\tt.Error(\"Cannot Sign:\", err)\n\t}\n\n\tif len(signature) == 0 {\n\t\tt.Error(\"Signature is zero length\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package goref\n\nimport \"time\"\n\n\/\/ Snapshot -- point-in-time copy of a GoRef instance\ntype Snapshot struct {\n\t\/\/ Child GoRef instance data\n\tChildren map[string]Snapshot\n\n\t\/\/ Snapshot data\n\tData map[string]Data\n\n\t\/\/ Creation timestamp\n\tTs time.Time\n}\n\n\/\/ Keys -- List all keys of this read-only instance\nfunc (s *Snapshot) Keys() []string {\n\trc := make([]string, 0, len(s.Data))\n\n\tfor k := range s.Data {\n\t\trc = append(rc, k)\n\t}\n\n\treturn rc\n}\n<commit_msg>snapshot: added json field declarations<commit_after>package goref\n\nimport \"time\"\n\n\/\/ Snapshot -- point-in-time copy of a GoRef instance\ntype Snapshot struct {\n\t\/\/ Child GoRef instance data\n\tChildren map[string]Snapshot `json:\"_children,omitempty\"`\n\n\t\/\/ Snapshot data\n\tData map[string]Data `json:\"data,omitempty\"`\n\n\t\/\/ Creation timestamp\n\tTs time.Time `json:\"ts\"`\n}\n\n\/\/ Keys -- List all keys of this read-only instance\nfunc (s *Snapshot) Keys() []string {\n\trc := make([]string, 0, len(s.Data))\n\n\tfor k := range s.Data {\n\t\trc = append(rc, k)\n\t}\n\n\treturn rc\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 main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"time\"\n\n\t\"github.com\/thinkofdeath\/steven\/render\"\n\t\"github.com\/thinkofdeath\/steven\/type\/vmath\"\n)\n\nconst (\n\tplayerHeight = 1.62\n)\n\nvar Client = ClientState{\n\tBounds: vmath.AABB{\n\t\tMin: vmath.Vector3{-0.3, 0, -0.3},\n\t\tMax: vmath.Vector3{0.3, 1.8, 0.3},\n\t},\n}\n\ntype ClientState struct {\n\tX, Y, Z    float64\n\tYaw, Pitch float64\n\n\tJumping  bool\n\tVSpeed   float64\n\tOnGround bool\n\n\tGameMode gameMode\n\tHardCore bool\n\n\tBounds vmath.AABB\n\n\tpositionText *render.UIText\n\n\tfps       int\n\tframes    int\n\tlastCount time.Time\n\tfpsText   *render.UIText\n\n\tchat ChatUI\n}\n\n\/\/ The render tick needs to remain pretty light so it\n\/\/ doesn't hold the lock for too long.\nfunc (c *ClientState) renderTick(delta float64) {\n\tc.frames++\n\tif c.GameMode.Fly() {\n\t\tc.X += mf * math.Cos(c.Yaw-math.Pi\/2) * -math.Cos(c.Pitch) * delta * 0.2\n\t\tc.Z -= mf * math.Sin(c.Yaw-math.Pi\/2) * -math.Cos(c.Pitch) * delta * 0.2\n\t\tc.Y -= mf * math.Sin(c.Pitch) * delta * 0.2\n\t} else {\n\t\tc.X += mf * math.Cos(c.Yaw-math.Pi\/2) * delta * 0.1\n\t\tc.Z -= mf * math.Sin(c.Yaw-math.Pi\/2) * delta * 0.1\n\t\tif !c.OnGround {\n\t\t\tc.VSpeed -= 0.01 * delta\n\t\t\tif c.VSpeed < -0.3 {\n\t\t\t\tc.VSpeed = -0.3\n\t\t\t}\n\t\t} else if c.Jumping {\n\t\t\tc.VSpeed = 0.15\n\t\t} else {\n\t\t\tc.VSpeed = 0\n\t\t}\n\t\tc.Y += c.VSpeed * delta\n\t}\n\n\tif !c.GameMode.NoClip() && chunkMap[chunkPosition{int(c.X) >> 4, int(c.Z) >> 4}] != nil {\n\t\tcy := c.Y\n\t\tcz := c.Z\n\t\tc.Y = render.Camera.Y - playerHeight\n\t\tc.Z = render.Camera.Z\n\n\t\t\/\/ We handle each axis separately to allow for a sliding\n\t\t\/\/ effect when pushing up against walls.\n\n\t\tbounds, _ := c.checkCollisions(c.Bounds)\n\t\tc.X = bounds.Min.X + 0.3\n\n\t\tc.Z = cz\n\t\tbounds, _ = c.checkCollisions(c.Bounds)\n\t\tc.Z = bounds.Min.Z + 0.3\n\n\t\tc.Y = cy\n\t\tbounds, _ = c.checkCollisions(c.Bounds)\n\t\tc.Y = bounds.Min.Y\n\n\t\tground := vmath.AABB{\n\t\t\tMin: vmath.Vector3{-0.3, -0.05, -0.3},\n\t\t\tMax: vmath.Vector3{0.3, 0, 0.3},\n\t\t}\n\t\t_, c.OnGround = c.checkCollisions(ground)\n\t}\n\n\t\/\/ Copy to the camera\n\trender.Camera.X = c.X\n\trender.Camera.Y = c.Y + playerHeight\n\trender.Camera.Z = c.Z\n\trender.Camera.Yaw = c.Yaw\n\trender.Camera.Pitch = c.Pitch\n\n\tif c.positionText != nil {\n\t\tc.positionText.Free()\n\t}\n\tc.positionText = render.AddUIText(\n\t\tfmt.Sprintf(\"X: %.2f, Y: %.2f, Z: %.2f\", c.X, c.Y, c.Z),\n\t\t5, 5, 255, 255, 255,\n\t)\n\n\tnow := time.Now()\n\tif now.Sub(c.lastCount) > time.Second {\n\t\tc.lastCount = now\n\t\tc.fps = c.frames\n\t\tc.frames = 0\n\t}\n\tif c.fpsText != nil {\n\t\tc.fpsText.Free()\n\t}\n\ttext := fmt.Sprintf(\"FPS: %d\", c.fps)\n\tc.fpsText = render.AddUIText(\n\t\ttext,\n\t\t800-5-float64(render.SizeOfString(text)), 5, 255, 255, 255,\n\t)\n\n\tc.chat.render(delta)\n}\n\nfunc (c *ClientState) checkCollisions(bounds vmath.AABB) (vmath.AABB, bool) {\n\tbounds.Shift(c.X, c.Y, c.Z)\n\n\tdir := &vmath.Vector3{\n\t\tX: -(render.Camera.X - c.X),\n\t\tY: -(render.Camera.Y - playerHeight - c.Y),\n\t\tZ: -(render.Camera.Z - c.Z),\n\t}\n\n\tminX, minY, minZ := int(bounds.Min.X-1), int(bounds.Min.Y-1), int(bounds.Min.Z-1)\n\tmaxX, maxY, maxZ := int(bounds.Max.X+1), int(bounds.Max.Y+1), int(bounds.Max.Z+1)\n\n\thit := false\n\tfor y := minY; y < maxY; y++ {\n\t\tfor z := minZ; z < maxZ; z++ {\n\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\tb := chunkMap.Block(x, y, z)\n\n\t\t\t\tif b.Collidable() {\n\t\t\t\t\tfor _, bb := range b.CollisionBounds() {\n\t\t\t\t\t\tbb.Shift(float64(x), float64(y), float64(z))\n\t\t\t\t\t\tif bb.Intersects(&bounds) {\n\t\t\t\t\t\t\tbounds.MoveOutOf(&bb, dir)\n\t\t\t\t\t\t\thit = 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\treturn bounds, hit\n}\n\nfunc (c *ClientState) tick() {\n}\n\ntype gameMode int\n\nconst (\n\tgmSurvival gameMode = iota\n\tgmCreative\n\tgmAdventure\n\tgmSpecator\n)\n\nfunc (g gameMode) Fly() bool {\n\tswitch g {\n\tcase gmCreative, gmSpecator:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g gameMode) NoClip() bool {\n\tswitch g {\n\tcase gmSpecator:\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype teleportFlag byte\n\nconst (\n\tteleportRelX teleportFlag = 1 << iota\n\tteleportRelY\n\tteleportRelZ\n\tteleportRelYaw\n\tteleportRelPitch\n)\n\nfunc calculateTeleport(flag teleportFlag, flags byte, base, val float64) float64 {\n\tif flags&byte(flag) != 0 {\n\t\treturn base + val\n\t}\n\treturn val\n}\n<commit_msg>steven: display memory usage<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 main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/thinkofdeath\/steven\/render\"\n\t\"github.com\/thinkofdeath\/steven\/type\/vmath\"\n)\n\nconst (\n\tplayerHeight = 1.62\n)\n\nvar Client = ClientState{\n\tBounds: vmath.AABB{\n\t\tMin: vmath.Vector3{-0.3, 0, -0.3},\n\t\tMax: vmath.Vector3{0.3, 1.8, 0.3},\n\t},\n}\n\ntype ClientState struct {\n\tX, Y, Z    float64\n\tYaw, Pitch float64\n\n\tJumping  bool\n\tVSpeed   float64\n\tOnGround bool\n\n\tGameMode gameMode\n\tHardCore bool\n\n\tBounds vmath.AABB\n\n\tpositionText *render.UIText\n\tmemoryText   *render.UIText\n\n\tfps       int\n\tframes    int\n\tlastCount time.Time\n\tfpsText   *render.UIText\n\n\tchat ChatUI\n}\n\nvar memoryStats runtime.MemStats\n\n\/\/ The render tick needs to remain pretty light so it\n\/\/ doesn't hold the lock for too long.\nfunc (c *ClientState) renderTick(delta float64) {\n\tc.frames++\n\tif c.GameMode.Fly() {\n\t\tc.X += mf * math.Cos(c.Yaw-math.Pi\/2) * -math.Cos(c.Pitch) * delta * 0.2\n\t\tc.Z -= mf * math.Sin(c.Yaw-math.Pi\/2) * -math.Cos(c.Pitch) * delta * 0.2\n\t\tc.Y -= mf * math.Sin(c.Pitch) * delta * 0.2\n\t} else {\n\t\tc.X += mf * math.Cos(c.Yaw-math.Pi\/2) * delta * 0.1\n\t\tc.Z -= mf * math.Sin(c.Yaw-math.Pi\/2) * delta * 0.1\n\t\tif !c.OnGround {\n\t\t\tc.VSpeed -= 0.01 * delta\n\t\t\tif c.VSpeed < -0.3 {\n\t\t\t\tc.VSpeed = -0.3\n\t\t\t}\n\t\t} else if c.Jumping {\n\t\t\tc.VSpeed = 0.15\n\t\t} else {\n\t\t\tc.VSpeed = 0\n\t\t}\n\t\tc.Y += c.VSpeed * delta\n\t}\n\n\tif !c.GameMode.NoClip() && chunkMap[chunkPosition{int(c.X) >> 4, int(c.Z) >> 4}] != nil {\n\t\tcy := c.Y\n\t\tcz := c.Z\n\t\tc.Y = render.Camera.Y - playerHeight\n\t\tc.Z = render.Camera.Z\n\n\t\t\/\/ We handle each axis separately to allow for a sliding\n\t\t\/\/ effect when pushing up against walls.\n\n\t\tbounds, _ := c.checkCollisions(c.Bounds)\n\t\tc.X = bounds.Min.X + 0.3\n\n\t\tc.Z = cz\n\t\tbounds, _ = c.checkCollisions(c.Bounds)\n\t\tc.Z = bounds.Min.Z + 0.3\n\n\t\tc.Y = cy\n\t\tbounds, _ = c.checkCollisions(c.Bounds)\n\t\tc.Y = bounds.Min.Y\n\n\t\tground := vmath.AABB{\n\t\t\tMin: vmath.Vector3{-0.3, -0.05, -0.3},\n\t\t\tMax: vmath.Vector3{0.3, 0, 0.3},\n\t\t}\n\t\t_, c.OnGround = c.checkCollisions(ground)\n\t}\n\n\t\/\/ Copy to the camera\n\trender.Camera.X = c.X\n\trender.Camera.Y = c.Y + playerHeight\n\trender.Camera.Z = c.Z\n\trender.Camera.Yaw = c.Yaw\n\trender.Camera.Pitch = c.Pitch\n\n\t\/\/ Temp displays\n\n\tif c.positionText != nil {\n\t\tc.positionText.Free()\n\t}\n\tc.positionText = render.AddUIText(\n\t\tfmt.Sprintf(\"X: %.2f, Y: %.2f, Z: %.2f\", c.X, c.Y, c.Z),\n\t\t5, 5, 255, 255, 255,\n\t)\n\n\truntime.ReadMemStats(&memoryStats)\n\tif c.memoryText != nil {\n\t\tc.memoryText.Free()\n\t}\n\ttext := fmt.Sprintf(\"%s\", formatMemory(memoryStats.Alloc))\n\tc.memoryText = render.AddUIText(\n\t\ttext,\n\t\t800-5-float64(render.SizeOfString(text)), 23, 255, 255, 255,\n\t)\n\n\tnow := time.Now()\n\tif now.Sub(c.lastCount) > time.Second {\n\t\tc.lastCount = now\n\t\tc.fps = c.frames\n\t\tc.frames = 0\n\t}\n\tif c.fpsText != nil {\n\t\tc.fpsText.Free()\n\t}\n\ttext = fmt.Sprintf(\"FPS: %d\", c.fps)\n\tc.fpsText = render.AddUIText(\n\t\ttext,\n\t\t800-5-float64(render.SizeOfString(text)), 5, 255, 255, 255,\n\t)\n\n\tc.chat.render(delta)\n}\n\nfunc formatMemory(alloc uint64) string {\n\tconst letters = \"BKMG\"\n\ti := 0\n\tfor {\n\t\tcheck := alloc\n\t\tcheck >>= 10\n\t\tif check == 0 {\n\t\t\tbreak\n\t\t}\n\t\talloc = check\n\t\ti++\n\t}\n\tl := string(letters[i])\n\tif l != \"B\" {\n\t\tl += \"B\"\n\t}\n\treturn fmt.Sprintf(\"%d%s\", alloc, l)\n}\n\nfunc (c *ClientState) checkCollisions(bounds vmath.AABB) (vmath.AABB, bool) {\n\tbounds.Shift(c.X, c.Y, c.Z)\n\n\tdir := &vmath.Vector3{\n\t\tX: -(render.Camera.X - c.X),\n\t\tY: -(render.Camera.Y - playerHeight - c.Y),\n\t\tZ: -(render.Camera.Z - c.Z),\n\t}\n\n\tminX, minY, minZ := int(bounds.Min.X-1), int(bounds.Min.Y-1), int(bounds.Min.Z-1)\n\tmaxX, maxY, maxZ := int(bounds.Max.X+1), int(bounds.Max.Y+1), int(bounds.Max.Z+1)\n\n\thit := false\n\tfor y := minY; y < maxY; y++ {\n\t\tfor z := minZ; z < maxZ; z++ {\n\t\t\tfor x := minX; x < maxX; x++ {\n\t\t\t\tb := chunkMap.Block(x, y, z)\n\n\t\t\t\tif b.Collidable() {\n\t\t\t\t\tfor _, bb := range b.CollisionBounds() {\n\t\t\t\t\t\tbb.Shift(float64(x), float64(y), float64(z))\n\t\t\t\t\t\tif bb.Intersects(&bounds) {\n\t\t\t\t\t\t\tbounds.MoveOutOf(&bb, dir)\n\t\t\t\t\t\t\thit = 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\treturn bounds, hit\n}\n\nfunc (c *ClientState) tick() {\n}\n\ntype gameMode int\n\nconst (\n\tgmSurvival gameMode = iota\n\tgmCreative\n\tgmAdventure\n\tgmSpecator\n)\n\nfunc (g gameMode) Fly() bool {\n\tswitch g {\n\tcase gmCreative, gmSpecator:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g gameMode) NoClip() bool {\n\tswitch g {\n\tcase gmSpecator:\n\t\treturn true\n\t}\n\treturn false\n}\n\ntype teleportFlag byte\n\nconst (\n\tteleportRelX teleportFlag = 1 << iota\n\tteleportRelY\n\tteleportRelZ\n\tteleportRelYaw\n\tteleportRelPitch\n)\n\nfunc calculateTeleport(flag teleportFlag, flags byte, base, val float64) float64 {\n\tif flags&byte(flag) != 0 {\n\t\treturn base + val\n\t}\n\treturn val\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 server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/auth\"\n\t\"camlistore.org\/pkg\/blobserver\"\n\t\"camlistore.org\/pkg\/buildinfo\"\n\t\"camlistore.org\/pkg\/images\"\n\t\"camlistore.org\/pkg\/jsonconfig\"\n\t\"camlistore.org\/pkg\/osutil\"\n\t\"camlistore.org\/pkg\/search\"\n)\n\n\/\/ RootHandler handles serving the about\/splash page.\ntype RootHandler struct {\n\t\/\/ Stealth determines whether we hide from non-authenticated\n\t\/\/ clients.\n\tStealth bool\n\n\tOwnerName string \/\/ for display purposes only.\n\tUsername  string \/\/ default user for mobile setup.\n\n\t\/\/ URL prefixes (path or full URL) to the primary blob and\n\t\/\/ search root.\n\tBlobRoot   string\n\tSearchRoot string\n\tstatusRoot string\n\tPrefix     string \/\/ root handler's prefix\n\n\tStorage blobserver.Storage \/\/ of BlobRoot, or nil\n\n\tsearchInitOnce sync.Once \/\/ runs searchInit, which populates searchHandler\n\tsearchInit     func()\n\tsearchHandler  *search.Handler \/\/ of SearchRoot, or nil\n\n\tui   *UIHandler     \/\/ or nil, if none configured\n\tsync []*SyncHandler \/\/ list of configured sync handlers, for discovery.\n}\n\nfunc (rh *RootHandler) SearchHandler() (h *search.Handler, ok bool) {\n\trh.searchInitOnce.Do(rh.searchInit)\n\treturn rh.searchHandler, rh.searchHandler != nil\n}\n\nfunc init() {\n\tblobserver.RegisterHandlerConstructor(\"root\", newRootFromConfig)\n}\n\nfunc newRootFromConfig(ld blobserver.Loader, conf jsonconfig.Obj) (h http.Handler, err error) {\n\tusername, err := getUserName()\n\tif err != nil {\n\t\treturn\n\t}\n\troot := &RootHandler{\n\t\tBlobRoot:   conf.OptionalString(\"blobRoot\", \"\"),\n\t\tSearchRoot: conf.OptionalString(\"searchRoot\", \"\"),\n\t\tOwnerName:  conf.OptionalString(\"ownerName\", username),\n\t\tUsername:   osutil.Username(),\n\t\tPrefix:     ld.MyPrefix(),\n\t}\n\troot.Stealth = conf.OptionalBool(\"stealth\", false)\n\troot.statusRoot = conf.OptionalString(\"statusRoot\", \"\")\n\tif err = conf.Validate(); err != nil {\n\t\treturn\n\t}\n\n\tif root.BlobRoot != \"\" {\n\t\tbs, err := ld.GetStorage(root.BlobRoot)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Root handler's blobRoot of %q error: %v\", root.BlobRoot, err)\n\t\t}\n\t\troot.Storage = bs\n\t}\n\n\troot.searchInit = func() {}\n\tif root.SearchRoot != \"\" {\n\t\tprefix := root.SearchRoot\n\t\tif t := ld.GetHandlerType(prefix); t != \"search\" {\n\t\t\tif t == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"root handler's searchRoot of %q is invalid and doesn't refer to a declared handler\", prefix)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"root handler's searchRoot of %q is of type %q, not %q\", prefix, t, \"search\")\n\t\t}\n\t\troot.searchInit = func() {\n\t\t\th, err := ld.GetHandler(prefix)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error fetching SearchRoot at %q: %v\", prefix, err)\n\t\t\t}\n\t\t\troot.searchHandler = h.(*search.Handler)\n\t\t\troot.searchInit = nil\n\t\t}\n\t}\n\n\treturn root, nil\n}\n\nfunc (rh *RootHandler) registerUIHandler(h *UIHandler) {\n\trh.ui = h\n}\n\nfunc (rh *RootHandler) registerSyncHandler(h *SyncHandler) {\n\trh.sync = append(rh.sync, h)\n\tsort.Sort(byFromTo(rh.sync))\n}\n\nfunc (rh *RootHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif wantsDiscovery(req) {\n\t\tif auth.Allowed(req, auth.OpDiscovery) {\n\t\t\trh.serveDiscovery(rw, req)\n\t\t\treturn\n\t\t}\n\t\tif !rh.Stealth {\n\t\t\thttp.Error(rw, \"Unauthorized\", http.StatusUnauthorized)\n\t\t}\n\t\treturn\n\t}\n\n\tif rh.Stealth {\n\t\treturn\n\t}\n\tif req.URL.Path == \"\/favicon.ico\" {\n\t\tServeStaticFile(rw, req, Files, \"favicon.ico\")\n\t\treturn\n\t}\n\tf := func(p string, a ...interface{}) {\n\t\tfmt.Fprintf(rw, p, a...)\n\t}\n\tf(\"<html><body><p>This is camlistored (%s), a \"+\n\t\t\"<a href='http:\/\/camlistore.org'>Camlistore<\/a> server.<\/p>\", buildinfo.Version())\n\tif auth.IsLocalhost(req) && !isDevServer() {\n\t\tf(\"<p>If you're coming from localhost, configure your Camlistore server at <a href='\/setup'>\/setup<\/a>.<\/p>\")\n\t}\n\tif rh.ui != nil {\n\t\tf(\"<p>To manage your content, access the <a href='%s'>%s<\/a>.<\/p>\", rh.ui.prefix, rh.ui.prefix)\n\t}\n\tif rh.statusRoot != \"\" {\n\t\tf(\"<p>To view status, see <a href='%s'>%s<\/a>\", rh.statusRoot, rh.statusRoot)\n\t}\n\tfmt.Fprintf(rw, \"<\/body><\/html>\")\n}\n\nfunc isDevServer() bool {\n\treturn os.Getenv(\"CAMLI_DEV_CAMLI_ROOT\") != \"\"\n}\n\ntype byFromTo []*SyncHandler\n\nfunc (b byFromTo) Len() int      { return len(b) }\nfunc (b byFromTo) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byFromTo) Less(i, j int) bool {\n\tif b[i].fromName < b[j].fromName {\n\t\treturn true\n\t}\n\treturn b[i].fromName == b[j].fromName && b[i].toName < b[j].toName\n}\n\nfunc (rh *RootHandler) serveDiscovery(rw http.ResponseWriter, req *http.Request) {\n\tm := map[string]interface{}{\n\t\t\"blobRoot\":     rh.BlobRoot,\n\t\t\"searchRoot\":   rh.SearchRoot,\n\t\t\"ownerName\":    rh.OwnerName,\n\t\t\"username\":     rh.Username,\n\t\t\"statusRoot\":   rh.statusRoot,\n\t\t\"wsAuthToken\":  auth.ProcessRandom(),\n\t\t\"thumbVersion\": images.ThumbnailVersion(),\n\t}\n\tif gener, ok := rh.Storage.(blobserver.Generationer); ok {\n\t\tinitTime, gen, err := gener.StorageGeneration()\n\t\tif err != nil {\n\t\t\tm[\"storageGenerationError\"] = err.Error()\n\t\t} else {\n\t\t\tm[\"storageInitTime\"] = initTime.UTC().Format(time.RFC3339)\n\t\t\tm[\"storageGeneration\"] = gen\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Storage type %T is not a blobserver.Generationer; not sending storageGeneration\", rh.Storage)\n\t}\n\tif rh.ui != nil {\n\t\trh.ui.populateDiscoveryMap(m)\n\t}\n\tif len(rh.sync) > 0 {\n\t\tvar syncHandlers []map[string]interface{}\n\t\tfor _, sh := range rh.sync {\n\t\t\tsyncHandlers = append(syncHandlers, sh.discoveryMap())\n\t\t}\n\t\tm[\"syncHandlers\"] = syncHandlers\n\t}\n\tdiscoveryHelper(rw, req, m)\n}\n\nfunc discoveryHelper(rw http.ResponseWriter, req *http.Request, m map[string]interface{}) {\n\trw.Header().Set(\"Content-Type\", \"text\/javascript\")\n\tif cb := req.FormValue(\"cb\"); identOrDotPattern.MatchString(cb) {\n\t\tfmt.Fprintf(rw, \"%s(\", cb)\n\t\tdefer rw.Write([]byte(\");\\n\"))\n\t} else if v := req.FormValue(\"var\"); identOrDotPattern.MatchString(v) {\n\t\tfmt.Fprintf(rw, \"%s = \", v)\n\t\tdefer rw.Write([]byte(\";\\n\"))\n\t}\n\tbytes, _ := json.MarshalIndent(m, \"\", \"  \")\n\trw.Write(bytes)\n}\n<commit_msg>server: ignore errors looking up optional username.<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 server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/auth\"\n\t\"camlistore.org\/pkg\/blobserver\"\n\t\"camlistore.org\/pkg\/buildinfo\"\n\t\"camlistore.org\/pkg\/images\"\n\t\"camlistore.org\/pkg\/jsonconfig\"\n\t\"camlistore.org\/pkg\/osutil\"\n\t\"camlistore.org\/pkg\/search\"\n)\n\n\/\/ RootHandler handles serving the about\/splash page.\ntype RootHandler struct {\n\t\/\/ Stealth determines whether we hide from non-authenticated\n\t\/\/ clients.\n\tStealth bool\n\n\tOwnerName string \/\/ for display purposes only.\n\tUsername  string \/\/ default user for mobile setup.\n\n\t\/\/ URL prefixes (path or full URL) to the primary blob and\n\t\/\/ search root.\n\tBlobRoot   string\n\tSearchRoot string\n\tstatusRoot string\n\tPrefix     string \/\/ root handler's prefix\n\n\tStorage blobserver.Storage \/\/ of BlobRoot, or nil\n\n\tsearchInitOnce sync.Once \/\/ runs searchInit, which populates searchHandler\n\tsearchInit     func()\n\tsearchHandler  *search.Handler \/\/ of SearchRoot, or nil\n\n\tui   *UIHandler     \/\/ or nil, if none configured\n\tsync []*SyncHandler \/\/ list of configured sync handlers, for discovery.\n}\n\nfunc (rh *RootHandler) SearchHandler() (h *search.Handler, ok bool) {\n\trh.searchInitOnce.Do(rh.searchInit)\n\treturn rh.searchHandler, rh.searchHandler != nil\n}\n\nfunc init() {\n\tblobserver.RegisterHandlerConstructor(\"root\", newRootFromConfig)\n}\n\nfunc newRootFromConfig(ld blobserver.Loader, conf jsonconfig.Obj) (h http.Handler, err error) {\n\tusername, _ := getUserName()\n\troot := &RootHandler{\n\t\tBlobRoot:   conf.OptionalString(\"blobRoot\", \"\"),\n\t\tSearchRoot: conf.OptionalString(\"searchRoot\", \"\"),\n\t\tOwnerName:  conf.OptionalString(\"ownerName\", username),\n\t\tUsername:   osutil.Username(),\n\t\tPrefix:     ld.MyPrefix(),\n\t}\n\troot.Stealth = conf.OptionalBool(\"stealth\", false)\n\troot.statusRoot = conf.OptionalString(\"statusRoot\", \"\")\n\tif err = conf.Validate(); err != nil {\n\t\treturn\n\t}\n\n\tif root.BlobRoot != \"\" {\n\t\tbs, err := ld.GetStorage(root.BlobRoot)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Root handler's blobRoot of %q error: %v\", root.BlobRoot, err)\n\t\t}\n\t\troot.Storage = bs\n\t}\n\n\troot.searchInit = func() {}\n\tif root.SearchRoot != \"\" {\n\t\tprefix := root.SearchRoot\n\t\tif t := ld.GetHandlerType(prefix); t != \"search\" {\n\t\t\tif t == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"root handler's searchRoot of %q is invalid and doesn't refer to a declared handler\", prefix)\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"root handler's searchRoot of %q is of type %q, not %q\", prefix, t, \"search\")\n\t\t}\n\t\troot.searchInit = func() {\n\t\t\th, err := ld.GetHandler(prefix)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error fetching SearchRoot at %q: %v\", prefix, err)\n\t\t\t}\n\t\t\troot.searchHandler = h.(*search.Handler)\n\t\t\troot.searchInit = nil\n\t\t}\n\t}\n\n\treturn root, nil\n}\n\nfunc (rh *RootHandler) registerUIHandler(h *UIHandler) {\n\trh.ui = h\n}\n\nfunc (rh *RootHandler) registerSyncHandler(h *SyncHandler) {\n\trh.sync = append(rh.sync, h)\n\tsort.Sort(byFromTo(rh.sync))\n}\n\nfunc (rh *RootHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif wantsDiscovery(req) {\n\t\tif auth.Allowed(req, auth.OpDiscovery) {\n\t\t\trh.serveDiscovery(rw, req)\n\t\t\treturn\n\t\t}\n\t\tif !rh.Stealth {\n\t\t\thttp.Error(rw, \"Unauthorized\", http.StatusUnauthorized)\n\t\t}\n\t\treturn\n\t}\n\n\tif rh.Stealth {\n\t\treturn\n\t}\n\tif req.URL.Path == \"\/favicon.ico\" {\n\t\tServeStaticFile(rw, req, Files, \"favicon.ico\")\n\t\treturn\n\t}\n\tf := func(p string, a ...interface{}) {\n\t\tfmt.Fprintf(rw, p, a...)\n\t}\n\tf(\"<html><body><p>This is camlistored (%s), a \"+\n\t\t\"<a href='http:\/\/camlistore.org'>Camlistore<\/a> server.<\/p>\", buildinfo.Version())\n\tif auth.IsLocalhost(req) && !isDevServer() {\n\t\tf(\"<p>If you're coming from localhost, configure your Camlistore server at <a href='\/setup'>\/setup<\/a>.<\/p>\")\n\t}\n\tif rh.ui != nil {\n\t\tf(\"<p>To manage your content, access the <a href='%s'>%s<\/a>.<\/p>\", rh.ui.prefix, rh.ui.prefix)\n\t}\n\tif rh.statusRoot != \"\" {\n\t\tf(\"<p>To view status, see <a href='%s'>%s<\/a>\", rh.statusRoot, rh.statusRoot)\n\t}\n\tfmt.Fprintf(rw, \"<\/body><\/html>\")\n}\n\nfunc isDevServer() bool {\n\treturn os.Getenv(\"CAMLI_DEV_CAMLI_ROOT\") != \"\"\n}\n\ntype byFromTo []*SyncHandler\n\nfunc (b byFromTo) Len() int      { return len(b) }\nfunc (b byFromTo) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byFromTo) Less(i, j int) bool {\n\tif b[i].fromName < b[j].fromName {\n\t\treturn true\n\t}\n\treturn b[i].fromName == b[j].fromName && b[i].toName < b[j].toName\n}\n\nfunc (rh *RootHandler) serveDiscovery(rw http.ResponseWriter, req *http.Request) {\n\tm := map[string]interface{}{\n\t\t\"blobRoot\":     rh.BlobRoot,\n\t\t\"searchRoot\":   rh.SearchRoot,\n\t\t\"ownerName\":    rh.OwnerName,\n\t\t\"username\":     rh.Username,\n\t\t\"statusRoot\":   rh.statusRoot,\n\t\t\"wsAuthToken\":  auth.ProcessRandom(),\n\t\t\"thumbVersion\": images.ThumbnailVersion(),\n\t}\n\tif gener, ok := rh.Storage.(blobserver.Generationer); ok {\n\t\tinitTime, gen, err := gener.StorageGeneration()\n\t\tif err != nil {\n\t\t\tm[\"storageGenerationError\"] = err.Error()\n\t\t} else {\n\t\t\tm[\"storageInitTime\"] = initTime.UTC().Format(time.RFC3339)\n\t\t\tm[\"storageGeneration\"] = gen\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Storage type %T is not a blobserver.Generationer; not sending storageGeneration\", rh.Storage)\n\t}\n\tif rh.ui != nil {\n\t\trh.ui.populateDiscoveryMap(m)\n\t}\n\tif len(rh.sync) > 0 {\n\t\tvar syncHandlers []map[string]interface{}\n\t\tfor _, sh := range rh.sync {\n\t\t\tsyncHandlers = append(syncHandlers, sh.discoveryMap())\n\t\t}\n\t\tm[\"syncHandlers\"] = syncHandlers\n\t}\n\tdiscoveryHelper(rw, req, m)\n}\n\nfunc discoveryHelper(rw http.ResponseWriter, req *http.Request, m map[string]interface{}) {\n\trw.Header().Set(\"Content-Type\", \"text\/javascript\")\n\tif cb := req.FormValue(\"cb\"); identOrDotPattern.MatchString(cb) {\n\t\tfmt.Fprintf(rw, \"%s(\", cb)\n\t\tdefer rw.Write([]byte(\");\\n\"))\n\t} else if v := req.FormValue(\"var\"); identOrDotPattern.MatchString(v) {\n\t\tfmt.Fprintf(rw, \"%s = \", v)\n\t\tdefer rw.Write([]byte(\";\\n\"))\n\t}\n\tbytes, _ := json.MarshalIndent(m, \"\", \"  \")\n\trw.Write(bytes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package astilectron\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n)\n\n\/\/ Target IDs\nconst (\n\ttargetIDApp  = \"app\"\n\ttargetIDDock = \"dock\"\n)\n\n\/\/ Event represents an event\ntype Event struct {\n\t\/\/ This is the base of the event\n\tName     string `json:\"name\"`\n\tTargetID string `json:\"targetID,omitempty\"`\n\n\t\/\/ This is a list of all possible payloads.\n\t\/\/ A choice was made not to use interfaces since it's a pain in the ass asserting each an every payload afterwards\n\t\/\/ We use pointers so that omitempty works\n\tAuthInfo            *EventAuthInfo       `json:\"authInfo,omitempty\"`\n\tBadge               string               `json:\"badge,omitempty\"`\n\tBounceType          string               `json:\"bounceType,omitempty\"`\n\tBounds              *RectangleOptions    `json:\"bounds,omitempty\"`\n\tCallbackID          string               `json:\"callbackId,omitempty\"`\n\tCode                string               `json:\"code,omitempty\"`\n\tDisplays            *EventDisplays       `json:\"displays,omitempty\"`\n\tFilePath            string               `json:\"filePath,omitempty\"`\n\tID                  *int                 `json:\"id,omitempty\"`\n\tImage               string               `json:\"image,omitempty\"`\n\tIndex               *int                 `json:\"index,omitempty\"`\n\tMenu                *EventMenu           `json:\"menu,omitempty\"`\n\tMenuItem            *EventMenuItem       `json:\"menuItem,omitempty\"`\n\tMenuItemOptions     *MenuItemOptions     `json:\"menuItemOptions,omitempty\"`\n\tMenuItemPosition    *int                 `json:\"menuItemPosition,omitempty\"`\n\tMenuPopupOptions    *MenuPopupOptions    `json:\"menuPopupOptions,omitempty\"`\n\tMessage             *EventMessage        `json:\"message,omitempty\"`\n\tNotificationOptions *NotificationOptions `json:\"notificationOptions,omitempty\"`\n\tPassword            string               `json:\"password,omitempty\"`\n\tPath                string               `json:\"path\"`\n\tReply               string               `json:\"reply,omitempty\"`\n\tRequest             *EventRequest        `json:\"request,omitempty\"`\n\tSecondInstance      *EventSecondInstance `json:\"secondInstance,omitempty\"`\n\tSessionID           string               `json:\"sessionId,omitempty\"`\n\tSupported           *Supported           `json:\"supported,omitempty\"`\n\tTrayOptions         *TrayOptions         `json:\"trayOptions,omitempty\"`\n\tURL                 string               `json:\"url,omitempty\"`\n\tURLNew              string               `json:\"newUrl,omitempty\"`\n\tURLOld              string               `json:\"oldUrl,omitempty\"`\n\tUsername            string               `json:\"username,omitempty\"`\n\tWindowID            string               `json:\"windowId,omitempty\"`\n\tWindowOptions       *WindowOptions       `json:\"windowOptions,omitempty\"`\n}\n\n\/\/ EventAuthInfo represents an event auth info\ntype EventAuthInfo struct {\n\tHost    string `json:\"host,omitempty\"`\n\tIsProxy *bool  `json:\"isProxy,omitempty\"`\n\tPort    *int   `json:\"port,omitempty\"`\n\tRealm   string `json:\"realm,omitempty\"`\n\tScheme  string `json:\"scheme,omitempty\"`\n}\n\n\/\/ EventDisplays represents events displays\ntype EventDisplays struct {\n\tAll     []*DisplayOptions `json:\"all,omitempty\"`\n\tPrimary *DisplayOptions   `json:\"primary,omitempty\"`\n}\n\n\/\/ EventMessage represents an event message\ntype EventMessage struct {\n\ti interface{}\n}\n\n\/\/ newEventMessage creates a new event message\nfunc newEventMessage(i interface{}) *EventMessage {\n\treturn &EventMessage{i: i}\n}\n\n\/\/ MarshalJSON implements the JSONMarshaler interface\nfunc (p *EventMessage) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(p.i)\n}\n\n\/\/ Unmarshal unmarshals the payload into the given interface\nfunc (p *EventMessage) Unmarshal(i interface{}) error {\n\tif b, ok := p.i.([]byte); ok {\n\t\treturn json.Unmarshal(b, i)\n\t}\n\treturn errors.New(\"event message should []byte\")\n}\n\n\/\/ UnmarshalJSON implements the JSONUnmarshaler interface\nfunc (p *EventMessage) UnmarshalJSON(i []byte) error {\n\tp.i = i\n\treturn nil\n}\n\n\/\/ EventMenu represents an event menu\ntype EventMenu struct {\n\t*EventSubMenu\n}\n\n\/\/ EventMenuItem represents an event menu item\ntype EventMenuItem struct {\n\tID      string           `json:\"id\"`\n\tOptions *MenuItemOptions `json:\"options,omitempty\"`\n\tRootID  string           `json:\"rootId\"`\n\tSubMenu *EventSubMenu    `json:\"submenu,omitempty\"`\n}\n\n\/\/ EventRequest represents an event request\ntype EventRequest struct {\n\tMethod   string `json:\"method,omitempty\"`\n\tReferrer string `json:\"referrer,omitempty\"`\n\tURL      string `json:\"url,omitempty\"`\n}\n\n\/\/ EventSecondInstance represents data related to a second instance of the app being started\ntype EventSecondInstance struct {\n\tCommandLine      []string `json:\"commandLine,omitempty\"`\n\tWorkingDirectory string   `json:\"workingDirectory,omitempty\"`\n}\n\n\/\/ EventSubMenu represents a sub menu event\ntype EventSubMenu struct {\n\tID     string           `json:\"id\"`\n\tItems  []*EventMenuItem `json:\"items,omitempty\"`\n\tRootID string           `json:\"rootId\"`\n}\n<commit_msg>Fixed tests<commit_after>package astilectron\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n)\n\n\/\/ Target IDs\nconst (\n\ttargetIDApp  = \"app\"\n\ttargetIDDock = \"dock\"\n)\n\n\/\/ Event represents an event\ntype Event struct {\n\t\/\/ This is the base of the event\n\tName     string `json:\"name\"`\n\tTargetID string `json:\"targetID,omitempty\"`\n\n\t\/\/ This is a list of all possible payloads.\n\t\/\/ A choice was made not to use interfaces since it's a pain in the ass asserting each an every payload afterwards\n\t\/\/ We use pointers so that omitempty works\n\tAuthInfo            *EventAuthInfo       `json:\"authInfo,omitempty\"`\n\tBadge               string               `json:\"badge,omitempty\"`\n\tBounceType          string               `json:\"bounceType,omitempty\"`\n\tBounds              *RectangleOptions    `json:\"bounds,omitempty\"`\n\tCallbackID          string               `json:\"callbackId,omitempty\"`\n\tCode                string               `json:\"code,omitempty\"`\n\tDisplays            *EventDisplays       `json:\"displays,omitempty\"`\n\tFilePath            string               `json:\"filePath,omitempty\"`\n\tID                  *int                 `json:\"id,omitempty\"`\n\tImage               string               `json:\"image,omitempty\"`\n\tIndex               *int                 `json:\"index,omitempty\"`\n\tMenu                *EventMenu           `json:\"menu,omitempty\"`\n\tMenuItem            *EventMenuItem       `json:\"menuItem,omitempty\"`\n\tMenuItemOptions     *MenuItemOptions     `json:\"menuItemOptions,omitempty\"`\n\tMenuItemPosition    *int                 `json:\"menuItemPosition,omitempty\"`\n\tMenuPopupOptions    *MenuPopupOptions    `json:\"menuPopupOptions,omitempty\"`\n\tMessage             *EventMessage        `json:\"message,omitempty\"`\n\tNotificationOptions *NotificationOptions `json:\"notificationOptions,omitempty\"`\n\tPassword            string               `json:\"password,omitempty\"`\n\tPath                string               `json:\"path,omitempty\"`\n\tReply               string               `json:\"reply,omitempty\"`\n\tRequest             *EventRequest        `json:\"request,omitempty\"`\n\tSecondInstance      *EventSecondInstance `json:\"secondInstance,omitempty\"`\n\tSessionID           string               `json:\"sessionId,omitempty\"`\n\tSupported           *Supported           `json:\"supported,omitempty\"`\n\tTrayOptions         *TrayOptions         `json:\"trayOptions,omitempty\"`\n\tURL                 string               `json:\"url,omitempty\"`\n\tURLNew              string               `json:\"newUrl,omitempty\"`\n\tURLOld              string               `json:\"oldUrl,omitempty\"`\n\tUsername            string               `json:\"username,omitempty\"`\n\tWindowID            string               `json:\"windowId,omitempty\"`\n\tWindowOptions       *WindowOptions       `json:\"windowOptions,omitempty\"`\n}\n\n\/\/ EventAuthInfo represents an event auth info\ntype EventAuthInfo struct {\n\tHost    string `json:\"host,omitempty\"`\n\tIsProxy *bool  `json:\"isProxy,omitempty\"`\n\tPort    *int   `json:\"port,omitempty\"`\n\tRealm   string `json:\"realm,omitempty\"`\n\tScheme  string `json:\"scheme,omitempty\"`\n}\n\n\/\/ EventDisplays represents events displays\ntype EventDisplays struct {\n\tAll     []*DisplayOptions `json:\"all,omitempty\"`\n\tPrimary *DisplayOptions   `json:\"primary,omitempty\"`\n}\n\n\/\/ EventMessage represents an event message\ntype EventMessage struct {\n\ti interface{}\n}\n\n\/\/ newEventMessage creates a new event message\nfunc newEventMessage(i interface{}) *EventMessage {\n\treturn &EventMessage{i: i}\n}\n\n\/\/ MarshalJSON implements the JSONMarshaler interface\nfunc (p *EventMessage) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(p.i)\n}\n\n\/\/ Unmarshal unmarshals the payload into the given interface\nfunc (p *EventMessage) Unmarshal(i interface{}) error {\n\tif b, ok := p.i.([]byte); ok {\n\t\treturn json.Unmarshal(b, i)\n\t}\n\treturn errors.New(\"event message should []byte\")\n}\n\n\/\/ UnmarshalJSON implements the JSONUnmarshaler interface\nfunc (p *EventMessage) UnmarshalJSON(i []byte) error {\n\tp.i = i\n\treturn nil\n}\n\n\/\/ EventMenu represents an event menu\ntype EventMenu struct {\n\t*EventSubMenu\n}\n\n\/\/ EventMenuItem represents an event menu item\ntype EventMenuItem struct {\n\tID      string           `json:\"id\"`\n\tOptions *MenuItemOptions `json:\"options,omitempty\"`\n\tRootID  string           `json:\"rootId\"`\n\tSubMenu *EventSubMenu    `json:\"submenu,omitempty\"`\n}\n\n\/\/ EventRequest represents an event request\ntype EventRequest struct {\n\tMethod   string `json:\"method,omitempty\"`\n\tReferrer string `json:\"referrer,omitempty\"`\n\tURL      string `json:\"url,omitempty\"`\n}\n\n\/\/ EventSecondInstance represents data related to a second instance of the app being started\ntype EventSecondInstance struct {\n\tCommandLine      []string `json:\"commandLine,omitempty\"`\n\tWorkingDirectory string   `json:\"workingDirectory,omitempty\"`\n}\n\n\/\/ EventSubMenu represents a sub menu event\ntype EventSubMenu struct {\n\tID     string           `json:\"id\"`\n\tItems  []*EventMenuItem `json:\"items,omitempty\"`\n\tRootID string           `json:\"rootId\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package octokit\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n)\n\nconst (\n\tGitHubApiUrl  string = \"https:\/\/\" + GitHubApiHost\n\tGitHubApiHost string = \"api.github.com\"\n)\n\ntype Client struct {\n\thttpClient *http.Client\n\tLogin      string\n\tPassword   string\n\tToken      string\n}\n\nfunc (c *Client) WithLogin(login string, password string) *Client {\n\tc.Login = login\n\tc.Password = password\n\treturn c\n}\n\nfunc (c *Client) WithToken(token string) *Client {\n\tc.Token = token\n\treturn c\n}\n\nfunc (c *Client) get(path string, extraHeaders map[string]string) ([]byte, error) {\n\treturn c.request(\"GET\", path, extraHeaders, nil)\n}\n\nfunc (c *Client) post(path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {\n\treturn c.request(\"POST\", path, extraHeaders, content)\n}\n\nfunc (c *Client) jsonGet(path string, extraHeaders map[string]string, v interface{}) error {\n\tbody, err := c.get(path, extraHeaders)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jsonUnmarshal(body, v)\n}\n\nfunc (c *Client) jsonPost(path string, extraHeaders map[string]string, params interface{}, v interface{}) error {\n\tb, err := jsonMarshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuffer := bytes.NewBuffer(b)\n\tbody, err := c.post(path, extraHeaders, buffer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jsonUnmarshal(body, v)\n}\n\nfunc (c *Client) request(method, path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {\n\turl := concatPath(GitHubApiUrl, path)\n\trequest, err := http.NewRequest(method, url, content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.setDefaultHeaders(request)\n\n\tif extraHeaders != nil {\n\t\tfor h, v := range extraHeaders {\n\t\t\trequest.Header.Set(h, v)\n\t\t}\n\t}\n\n\tresponse, err := c.httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.StatusCode >= 400 && response.StatusCode < 600 {\n\t\treturn nil, handleErrors(body)\n\t}\n\n\treturn body, nil\n}\n\nfunc (c *Client) setDefaultHeaders(request *http.Request) {\n\trequest.Header.Set(\"Accept\", \"application\/vnd.github.beta+json\")\n\tif c.Token != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"token %s\", c.Token))\n\t}\n\tif c.Login != \"\" && c.Password != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"Basic %s\", hashAuth(c.Login, c.Password)))\n\t}\n}\n<commit_msg>Make argument concise<commit_after>package octokit\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n)\n\nconst (\n\tGitHubApiUrl  string = \"https:\/\/\" + GitHubApiHost\n\tGitHubApiHost string = \"api.github.com\"\n)\n\ntype Client struct {\n\thttpClient *http.Client\n\tLogin      string\n\tPassword   string\n\tToken      string\n}\n\nfunc (c *Client) WithLogin(login, password string) *Client {\n\tc.Login = login\n\tc.Password = password\n\treturn c\n}\n\nfunc (c *Client) WithToken(token string) *Client {\n\tc.Token = token\n\treturn c\n}\n\nfunc (c *Client) get(path string, extraHeaders map[string]string) ([]byte, error) {\n\treturn c.request(\"GET\", path, extraHeaders, nil)\n}\n\nfunc (c *Client) post(path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {\n\treturn c.request(\"POST\", path, extraHeaders, content)\n}\n\nfunc (c *Client) jsonGet(path string, extraHeaders map[string]string, v interface{}) error {\n\tbody, err := c.get(path, extraHeaders)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jsonUnmarshal(body, v)\n}\n\nfunc (c *Client) jsonPost(path string, extraHeaders map[string]string, params interface{}, v interface{}) error {\n\tb, err := jsonMarshal(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbuffer := bytes.NewBuffer(b)\n\tbody, err := c.post(path, extraHeaders, buffer)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn jsonUnmarshal(body, v)\n}\n\nfunc (c *Client) request(method, path string, extraHeaders map[string]string, content io.Reader) ([]byte, error) {\n\turl := concatPath(GitHubApiUrl, path)\n\trequest, err := http.NewRequest(method, url, content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.setDefaultHeaders(request)\n\n\tif extraHeaders != nil {\n\t\tfor h, v := range extraHeaders {\n\t\t\trequest.Header.Set(h, v)\n\t\t}\n\t}\n\n\tresponse, err := c.httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif response.StatusCode >= 400 && response.StatusCode < 600 {\n\t\treturn nil, handleErrors(body)\n\t}\n\n\treturn body, nil\n}\n\nfunc (c *Client) setDefaultHeaders(request *http.Request) {\n\trequest.Header.Set(\"Accept\", \"application\/vnd.github.beta+json\")\n\tif c.Token != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"token %s\", c.Token))\n\t}\n\tif c.Login != \"\" && c.Password != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"Basic %s\", hashAuth(c.Login, c.Password)))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"net\/url\"\n\t\"os\"\n)\n\ntype Client struct {\n\tUsername   string\n\tPassword   string\n\tFeedUrl    string\n\tHttpClient *http.Client\n}\n\nfunc NewClient() *Client {\n\tcookieJar, _ := cookiejar.New(nil)\n\tclient := &Client{\n\t\tFeedUrl:    FeedUrl,\n\t\tHttpClient: &http.Client{Jar: cookieJar},\n\t}\n\treturn client\n}\n\nfunc (c *Client) Get(url string) (*http.Response, error) {\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.SetBasicAuth(c.Username, c.Password)\n\n\tresp, err := c.HttpClient.Do(req)\n\n\treturn resp, err\n}\n\nfunc (c *Client) Login(username, password string) {\n\tc.HttpClient.PostForm(LoginUrl,\n\t\turl.Values{\n\t\t\t\"username\": {username},\n\t\t\t\"password\": {password},\n\t\t},\n\t)\n\tc.Username = username\n\tc.Password = password\n}\n\nfunc (c *Client) FetchFeed() []byte {\n\tresp, err := c.Get(c.FeedUrl)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tlogger.Fatal(\"Error: failed to fetch feed: \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\trss, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlogger.Fatal(\"Error while reading feed: \" + err.Error())\n\t}\n\n\treturn rss\n}\n\nfunc (c *Client) DownloadFile(url, target string) {\n\ttmpFile := target + \".part\"\n\tout, err := os.Create(tmpFile)\n\tdefer out.Close()\n\n\tif err != nil {\n\t\tlogger.Error(\"Error creating file \" + target + \": \" + err.Error())\n\t\treturn\n\t}\n\n\tresp, err := c.Get(url)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tlogger.Error(\"Error fetching file\" + url + \": \" + err.Error())\n\t\treturn\n\t}\n\n\t_, err = io.Copy(out, resp.Body)\n\n\tif err != nil {\n\t\tlogger.Error(\"Error copying file: \" + err.Error())\n\t\treturn\n\t}\n\n\tos.Rename(tmpFile, target)\n\n\tlogger.Debug(\"Download Complete: \" + target + \" from \" + url)\n}\n<commit_msg>check for login success\/failure<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"net\/url\"\n\t\"os\"\n)\n\ntype Client struct {\n\tUsername   string\n\tPassword   string\n\tFeedUrl    string\n\tHttpClient *http.Client\n}\n\nfunc NewClient() *Client {\n\tcookieJar, _ := cookiejar.New(nil)\n\tclient := &Client{\n\t\tFeedUrl:    FeedUrl,\n\t\tHttpClient: &http.Client{Jar: cookieJar},\n\t}\n\treturn client\n}\n\nfunc (c *Client) Get(url string) (*http.Response, error) {\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.SetBasicAuth(c.Username, c.Password)\n\n\tresp, err := c.HttpClient.Do(req)\n\n\treturn resp, err\n}\n\nfunc (c *Client) Login(username, password string) {\n\tresp, err := c.HttpClient.PostForm(LoginUrl,\n\t\turl.Values{\n\t\t\t\"username\": {username},\n\t\t\t\"password\": {password},\n\t\t},\n\t)\n\n\tif err != nil {\n\t\tlogger.Fatal(\"Error while logging in: \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\treader := bytes.NewReader(body)\n\tdoc, err := goquery.NewDocumentFromReader(reader)\n\tselection := doc.Find(\"form#login-form\")\n\tif selection.Length() > 0 {\n\t\tlogger.Fatal(\"Login failed\")\n\t\tos.Exit(1)\n\t}\n\n\tc.Username = username\n\tc.Password = password\n}\n\nfunc (c *Client) FetchFeed() []byte {\n\tresp, err := c.Get(c.FeedUrl)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tlogger.Fatal(\"Error: failed to fetch feed: \" + err.Error())\n\t\tos.Exit(1)\n\t}\n\n\trss, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\tlogger.Fatal(\"Error while reading feed: \" + err.Error())\n\t}\n\n\treturn rss\n}\n\nfunc (c *Client) DownloadFile(url, target string) {\n\ttmpFile := target + \".part\"\n\tout, err := os.Create(tmpFile)\n\tdefer out.Close()\n\n\tif err != nil {\n\t\tlogger.Error(\"Error creating file \" + target + \": \" + err.Error())\n\t\treturn\n\t}\n\n\tresp, err := c.Get(url)\n\tdefer resp.Body.Close()\n\n\tif err != nil {\n\t\tlogger.Error(\"Error fetching file\" + url + \": \" + err.Error())\n\t\treturn\n\t}\n\n\t_, err = io.Copy(out, resp.Body)\n\n\tif err != nil {\n\t\tlogger.Error(\"Error copying file: \" + err.Error())\n\t\treturn\n\t}\n\n\tos.Rename(tmpFile, target)\n\n\tlogger.Debug(\"Download Complete: \" + target + \" from \" + url)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Francisco Souza. All rights 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 docker provides a client for the Docker remote API.\n\/\/\n\/\/ See http:\/\/goo.gl\/mxyql for more details on the remote API.\npackage docker\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\/url\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tapiVersion = 1.1\n\tuserAgent  = \"go-dockerclient\"\n)\n\nvar (\n\t\/\/ Error returned when the endpoint is not a valid HTTP URL.\n\tErrInvalidEndpoint = errors.New(\"Invalid endpoint\")\n\n\t\/\/ Error returned when the client cannot connect to the given endpoint.\n\tErrConnectionRefused = errors.New(\"Cannot connect to Docker endpoint\")\n)\n\n\/\/ Client is the basic type of this package. It provides methods for\n\/\/ interaction with the API.\ntype Client struct {\n\tendpoint    string\n\tendpointURL *url.URL\n\tclient      *http.Client\n}\n\n\/\/ NewClient returns a Client instance ready for communication with the\n\/\/ given server endpoint.\nfunc NewClient(endpoint string) (*Client, error) {\n\tu, err := parseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{endpoint: endpoint, endpointURL: u, client: http.DefaultClient}, nil\n}\n\nfunc (c *Client) do(method, path string, data interface{}) ([]byte, int, error) {\n\tvar params io.Reader\n\tif data != nil {\n\t\tbuf, err := json.Marshal(data)\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t\tparams = bytes.NewBuffer(buf)\n\t}\n\treq, err := http.NewRequest(method, c.getURL(path), params)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif data != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t} else if method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\treturn nil, -1, ErrConnectionRefused\n\t\t}\n\t\treturn nil, -1, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\tif resp.StatusCode < 200 || resp.StatusCode >= 400 {\n\t\treturn nil, resp.StatusCode, newAPIClientError(resp.StatusCode, body)\n\t}\n\treturn body, resp.StatusCode, nil\n}\n\nfunc (c *Client) stream(method, path string, in io.Reader, out io.Writer) error {\n\tif (method == \"POST\" || method == \"PUT\") && in == nil {\n\t\tin = bytes.NewReader(nil)\n\t}\n\treq, err := http.NewRequest(method, c.getURL(path), in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\treturn ErrConnectionRefused\n\t\t}\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 400 {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn newAPIClientError(resp.StatusCode, body)\n\t}\n\tif resp.Header.Get(\"Content-Type\") == \"application\/json\" {\n\t\tdec := json.NewDecoder(resp.Body)\n\t\tfor {\n\t\t\tvar m jsonMessage\n\t\t\tif err := dec.Decode(&m); 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\t\t\tif m.Progress != \"\" {\n\t\t\t\tfmt.Fprintf(out, \"%s %s\\r\", m.Status, m.Progress)\n\t\t\t} else if m.Error != \"\" {\n\t\t\t\treturn errors.New(m.Error)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(out, \"%s\\n\", m.Status)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif _, err := io.Copy(out, resp.Body); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *Client) getURL(path string) string {\n\treturn fmt.Sprintf(\"%s\/v%f%s\", strings.TrimRight(c.endpoint, \"\/\"), apiVersion, path)\n}\n\ntype jsonMessage struct {\n\tStatus   string `json:\"status,omitempty\"`\n\tProgress string `json:\"progress,omitempty\"`\n\tError    string `json:\"error,omitempty\"`\n}\n\nfunc queryString(opts interface{}) string {\n\tif opts == nil {\n\t\treturn \"\"\n\t}\n\tvalue := reflect.ValueOf(opts)\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\tif value.Kind() != reflect.Struct {\n\t\treturn \"\"\n\t}\n\titems := url.Values(map[string][]string{})\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tfield := value.Type().Field(i)\n\t\tif field.PkgPath != \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tkey := field.Tag.Get(\"qs\")\n\t\tif key == \"\" {\n\t\t\tkey = strings.ToLower(field.Name)\n\t\t}\n\t\tv := value.Field(i)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tif v.Bool() {\n\t\t\t\titems.Add(key, \"1\")\n\t\t\t}\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tif v.Int() > 0 {\n\t\t\t\titems.Add(key, strconv.FormatInt(v.Int(), 10))\n\t\t\t}\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tif v.Float() > 0 {\n\t\t\t\titems.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64))\n\t\t\t}\n\t\tcase reflect.String:\n\t\t\tif v.String() != \"\" {\n\t\t\t\titems.Add(key, v.String())\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif !v.IsNil() {\n\t\t\t\tif b, err := json.Marshal(v.Interface()); err == nil {\n\t\t\t\t\titems.Add(key, string(b))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn items.Encode()\n}\n\ntype apiClientError struct {\n\tstatus  int\n\tmessage string\n}\n\nfunc newAPIClientError(status int, body []byte) *apiClientError {\n\treturn &apiClientError{status: status, message: string(body)}\n}\n\nfunc (e *apiClientError) Error() string {\n\treturn fmt.Sprintf(\"API error (%d): %s\", e.status, e.message)\n}\n\nfunc parseEndpoint(endpoint string) (*url.URL, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\tif u.Scheme != \"http\" && u.Scheme != \"https\" {\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\t_, port, err := net.SplitHostPort(u.Host)\n\tif err != nil {\n\t\tif e, ok := err.(*net.AddrError); ok {\n\t\t\tif e.Err == \"missing port in address\" {\n\t\t\t\treturn u, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\tnumber, err := strconv.ParseInt(port, 10, 64)\n\tif err == nil && number > 0 && number < 65536 {\n\t\treturn u, nil\n\t}\n\treturn nil, ErrInvalidEndpoint\n}\n<commit_msg>client: import hijack from dotcloud\/docker<commit_after>\/\/ Copyright 2013 Francisco Souza. All rights 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 docker provides a client for the Docker remote API.\n\/\/\n\/\/ See http:\/\/goo.gl\/mxyql for more details on the remote API.\npackage docker\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/dotcloud\/docker\/term\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tapiVersion = 1.1\n\tuserAgent  = \"go-dockerclient\"\n)\n\nvar (\n\t\/\/ Error returned when the endpoint is not a valid HTTP URL.\n\tErrInvalidEndpoint = errors.New(\"Invalid endpoint\")\n\n\t\/\/ Error returned when the client cannot connect to the given endpoint.\n\tErrConnectionRefused = errors.New(\"Cannot connect to Docker endpoint\")\n)\n\n\/\/ Client is the basic type of this package. It provides methods for\n\/\/ interaction with the API.\ntype Client struct {\n\tendpoint    string\n\tendpointURL *url.URL\n\tclient      *http.Client\n}\n\n\/\/ NewClient returns a Client instance ready for communication with the\n\/\/ given server endpoint.\nfunc NewClient(endpoint string) (*Client, error) {\n\tu, err := parseEndpoint(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{endpoint: endpoint, endpointURL: u, client: http.DefaultClient}, nil\n}\n\nfunc (c *Client) do(method, path string, data interface{}) ([]byte, int, error) {\n\tvar params io.Reader\n\tif data != nil {\n\t\tbuf, err := json.Marshal(data)\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t\tparams = bytes.NewBuffer(buf)\n\t}\n\treq, err := http.NewRequest(method, c.getURL(path), params)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif data != nil {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t} else if method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\treturn nil, -1, ErrConnectionRefused\n\t\t}\n\t\treturn nil, -1, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, -1, err\n\t}\n\tif resp.StatusCode < 200 || resp.StatusCode >= 400 {\n\t\treturn nil, resp.StatusCode, newAPIClientError(resp.StatusCode, body)\n\t}\n\treturn body, resp.StatusCode, nil\n}\n\nfunc (c *Client) stream(method, path string, in io.Reader, out io.Writer) error {\n\tif (method == \"POST\" || method == \"PUT\") && in == nil {\n\t\tin = bytes.NewReader(nil)\n\t}\n\treq, err := http.NewRequest(method, c.getURL(path), in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\tif method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\t}\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"connection refused\") {\n\t\t\treturn ErrConnectionRefused\n\t\t}\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 400 {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn newAPIClientError(resp.StatusCode, body)\n\t}\n\tif resp.Header.Get(\"Content-Type\") == \"application\/json\" {\n\t\tdec := json.NewDecoder(resp.Body)\n\t\tfor {\n\t\t\tvar m jsonMessage\n\t\t\tif err := dec.Decode(&m); 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\t\t\tif m.Progress != \"\" {\n\t\t\t\tfmt.Fprintf(out, \"%s %s\\r\", m.Status, m.Progress)\n\t\t\t} else if m.Error != \"\" {\n\t\t\t\treturn errors.New(m.Error)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(out, \"%s\\n\", m.Status)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif _, err := io.Copy(out, resp.Body); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *Client) hijack(method, path string, setRawTerminal bool, in *os.File, errStream io.Writer, out io.Writer) error {\n\treq, err := http.NewRequest(method, c.getURL(path), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\tdial, err := net.Dial(\"tcp\", c.endpointURL.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientconn := httputil.NewClientConn(dial, nil)\n\tclientconn.Do(req)\n\tdefer clientconn.Close()\n\trwc, br := clientconn.Hijack()\n\tdefer rwc.Close()\n\terrStdout := make(chan error, 1)\n\tgo func() {\n\t\t_, err := io.Copy(out, br)\n\t\terrStdout <- err\n\t}()\n\tif in != nil && setRawTerminal && term.IsTerminal(in.Fd()) && os.Getenv(\"NORAW\") == \"\" {\n\t\toldState, err := term.SetRawTerminal()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer term.RestoreTerminal(oldState)\n\t}\n\terrStdin := make(chan error, 1)\n\tgo func() {\n\t\t_, err := io.Copy(rwc, in)\n\t\tif err := rwc.(*net.TCPConn).CloseWrite(); err != nil {\n\t\t\tfmt.Fprintf(errStream, \"Couldn't send EOF: %s\\n\", err)\n\t\t}\n\t\terrStdin <- err\n\t}()\n\tif err := <-errStdout; err != nil {\n\t\treturn err\n\t}\n\tif !term.IsTerminal(in.Fd()) {\n\t\tif err := <-errStdin; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *Client) getURL(path string) string {\n\treturn fmt.Sprintf(\"%s\/v%f%s\", strings.TrimRight(c.endpoint, \"\/\"), apiVersion, path)\n}\n\ntype jsonMessage struct {\n\tStatus   string `json:\"status,omitempty\"`\n\tProgress string `json:\"progress,omitempty\"`\n\tError    string `json:\"error,omitempty\"`\n}\n\nfunc queryString(opts interface{}) string {\n\tif opts == nil {\n\t\treturn \"\"\n\t}\n\tvalue := reflect.ValueOf(opts)\n\tif value.Kind() == reflect.Ptr {\n\t\tvalue = value.Elem()\n\t}\n\tif value.Kind() != reflect.Struct {\n\t\treturn \"\"\n\t}\n\titems := url.Values(map[string][]string{})\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tfield := value.Type().Field(i)\n\t\tif field.PkgPath != \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tkey := field.Tag.Get(\"qs\")\n\t\tif key == \"\" {\n\t\t\tkey = strings.ToLower(field.Name)\n\t\t}\n\t\tv := value.Field(i)\n\t\tswitch v.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tif v.Bool() {\n\t\t\t\titems.Add(key, \"1\")\n\t\t\t}\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tif v.Int() > 0 {\n\t\t\t\titems.Add(key, strconv.FormatInt(v.Int(), 10))\n\t\t\t}\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tif v.Float() > 0 {\n\t\t\t\titems.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64))\n\t\t\t}\n\t\tcase reflect.String:\n\t\t\tif v.String() != \"\" {\n\t\t\t\titems.Add(key, v.String())\n\t\t\t}\n\t\tcase reflect.Ptr:\n\t\t\tif !v.IsNil() {\n\t\t\t\tif b, err := json.Marshal(v.Interface()); err == nil {\n\t\t\t\t\titems.Add(key, string(b))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn items.Encode()\n}\n\ntype apiClientError struct {\n\tstatus  int\n\tmessage string\n}\n\nfunc newAPIClientError(status int, body []byte) *apiClientError {\n\treturn &apiClientError{status: status, message: string(body)}\n}\n\nfunc (e *apiClientError) Error() string {\n\treturn fmt.Sprintf(\"API error (%d): %s\", e.status, e.message)\n}\n\nfunc parseEndpoint(endpoint string) (*url.URL, error) {\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\tif u.Scheme != \"http\" && u.Scheme != \"https\" {\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\t_, port, err := net.SplitHostPort(u.Host)\n\tif err != nil {\n\t\tif e, ok := err.(*net.AddrError); ok {\n\t\t\tif e.Err == \"missing port in address\" {\n\t\t\t\treturn u, nil\n\t\t\t}\n\t\t}\n\t\treturn nil, ErrInvalidEndpoint\n\t}\n\tnumber, err := strconv.ParseInt(port, 10, 64)\n\tif err == nil && number > 0 && number < 65536 {\n\t\treturn u, nil\n\t}\n\treturn nil, ErrInvalidEndpoint\n}\n<|endoftext|>"}
{"text":"<commit_before>package support\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\tneturl \"net\/url\"\n)\n\ntype HijackHttpOptions struct {\n\tMethod             string\n\tUrl                string\n\tSuccess            chan struct{}\n\tDockerTermProtocol bool\n\tInputStream        io.Reader\n\tErrorStream        io.Writer\n\tOutputStream       io.Writer\n\tData               interface{}\n\tHeader             http.Header\n\tLog                Logger\n}\n\n\/\/ HijackHttpRequest performs an HTTP  request with given method, url and data and hijacks the request (after a successful connection) to stream\n\/\/ data from\/to the given input, output and error streams.\nfunc HijackHttpRequest(options HijackHttpOptions) error {\n\treq, err := createHijackHttpRequest(options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Parse URL for endpoint data\n\tep, err := neturl.Parse(options.Url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotocol := ep.Scheme\n\taddress := ep.Path\n\tif protocol != \"unix\" {\n\t\tprotocol = \"tcp\"\n\t\taddress = ep.Host\n\t}\n\n\t\/\/ Dial the server\n\tvar dial net.Conn\n\tdial, err = net.Dial(protocol, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start initial HTTP connection\n\tclientconn := httputil.NewClientConn(dial, nil)\n\tdefer clientconn.Close()\n\n\tclientconn.Do(req)\n\n\t\/\/ Hijack HTTP connection\n\tsuccess := options.Success\n\tif success != nil {\n\t\tsuccess <- struct{}{}\n\t\t<-success\n\t}\n\n\trwc, br := clientconn.Hijack()\n\tdefer rwc.Close()\n\n\t\/\/ Stream data\n\treturn streamData(rwc, br, options)\n}\n\n\/\/ createHijackHttpRequest creates an upgradable HTTP request according to the given options\nfunc createHijackHttpRequest(options HijackHttpOptions) (*http.Request, error) {\n\tvar params io.Reader\n\tif options.Data != nil {\n\t\tbuf, err := json.Marshal(options.Data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparams = bytes.NewBuffer(buf)\n\t}\n\n\treq, err := http.NewRequest(options.Method, options.Url, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif options.Header != nil {\n\t\tfor k, values := range options.Header {\n\t\t\treq.Header.Del(k)\n\t\t\tfor _, v := range values {\n\t\t\t\treq.Header.Set(k, v)\n\t\t\t}\n\t\t}\n\t}\n\treq.Header.Set(\"Content-Type\", \"text\/plain\")\n\treq.Header.Set(\"Connection\", \"Upgrade\")\n\treq.Header.Set(\"Upgrade\", \"tcp\")\n\treturn req, nil\n}\n\n\/\/ streamData copies both input\/output\/error streams to\/from the hijacked streams\nfunc streamData(rwc io.Writer, br io.Reader, options HijackHttpOptions) error {\n\terrs := make(chan error, 2)\n\texit := make(chan bool)\n\n\tgo func() {\n\t\tdefer close(exit)\n\t\tvar err error\n\t\tstdout := options.OutputStream\n\t\tif stdout == nil {\n\t\t\tstdout = ioutil.Discard\n\t\t}\n\t\tstderr := options.ErrorStream\n\t\tif stderr == nil {\n\t\t\tstderr = ioutil.Discard\n\t\t}\n\t\tif !options.DockerTermProtocol {\n\t\t\t\/\/ When TTY is ON, use regular copy\n\t\t\t_, err = io.Copy(stdout, br)\n\t\t} else {\n\t\t\t_, err = StdCopy(stdout, stderr, br, options.Log)\n\t\t}\n\t\terrs <- err\n\t}()\n\tgo func() {\n\t\tvar err error\n\t\tin := options.InputStream\n\t\tif in != nil {\n\t\t\t_, err = io.Copy(rwc, in)\n\t\t}\n\t\trwc.(interface {\n\t\t\tCloseWrite() error\n\t\t}).CloseWrite()\n\t\terrs <- err\n\t}()\n\t<-exit\n\treturn <-errs\n}\n<commit_msg>Ensure a logger<commit_after>package support\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\tneturl \"net\/url\"\n)\n\ntype HijackHttpOptions struct {\n\tMethod             string\n\tUrl                string\n\tSuccess            chan struct{}\n\tDockerTermProtocol bool\n\tInputStream        io.Reader\n\tErrorStream        io.Writer\n\tOutputStream       io.Writer\n\tData               interface{}\n\tHeader             http.Header\n\tLog                Logger\n}\n\n\/\/ HijackHttpRequest performs an HTTP  request with given method, url and data and hijacks the request (after a successful connection) to stream\n\/\/ data from\/to the given input, output and error streams.\nfunc HijackHttpRequest(options HijackHttpOptions) error {\n\tif options.Log == nil {\n\t\t\/\/ Make sure there is always a logger\n\t\toptions.Log = &logIgnore{}\n\t}\n\n\treq, err := createHijackHttpRequest(options)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Parse URL for endpoint data\n\tep, err := neturl.Parse(options.Url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprotocol := ep.Scheme\n\taddress := ep.Path\n\tif protocol != \"unix\" {\n\t\tprotocol = \"tcp\"\n\t\taddress = ep.Host\n\t}\n\n\t\/\/ Dial the server\n\tvar dial net.Conn\n\tdial, err = net.Dial(protocol, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start initial HTTP connection\n\tclientconn := httputil.NewClientConn(dial, nil)\n\tdefer clientconn.Close()\n\n\tclientconn.Do(req)\n\n\t\/\/ Hijack HTTP connection\n\tsuccess := options.Success\n\tif success != nil {\n\t\tsuccess <- struct{}{}\n\t\t<-success\n\t}\n\n\trwc, br := clientconn.Hijack()\n\tdefer rwc.Close()\n\n\t\/\/ Stream data\n\treturn streamData(rwc, br, options)\n}\n\n\/\/ createHijackHttpRequest creates an upgradable HTTP request according to the given options\nfunc createHijackHttpRequest(options HijackHttpOptions) (*http.Request, error) {\n\tvar params io.Reader\n\tif options.Data != nil {\n\t\tbuf, err := json.Marshal(options.Data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tparams = bytes.NewBuffer(buf)\n\t}\n\n\treq, err := http.NewRequest(options.Method, options.Url, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif options.Header != nil {\n\t\tfor k, values := range options.Header {\n\t\t\treq.Header.Del(k)\n\t\t\tfor _, v := range values {\n\t\t\t\treq.Header.Set(k, v)\n\t\t\t}\n\t\t}\n\t}\n\treq.Header.Set(\"Content-Type\", \"text\/plain\")\n\treq.Header.Set(\"Connection\", \"Upgrade\")\n\treq.Header.Set(\"Upgrade\", \"tcp\")\n\treturn req, nil\n}\n\n\/\/ streamData copies both input\/output\/error streams to\/from the hijacked streams\nfunc streamData(rwc io.Writer, br io.Reader, options HijackHttpOptions) error {\n\terrs := make(chan error, 2)\n\texit := make(chan bool)\n\n\tgo func() {\n\t\tdefer close(exit)\n\t\tvar err error\n\t\tstdout := options.OutputStream\n\t\tif stdout == nil {\n\t\t\tstdout = ioutil.Discard\n\t\t}\n\t\tstderr := options.ErrorStream\n\t\tif stderr == nil {\n\t\t\tstderr = ioutil.Discard\n\t\t}\n\t\tif !options.DockerTermProtocol {\n\t\t\t\/\/ When TTY is ON, use regular copy\n\t\t\t_, err = io.Copy(stdout, br)\n\t\t} else {\n\t\t\t_, err = StdCopy(stdout, stderr, br, options.Log)\n\t\t}\n\t\terrs <- err\n\t}()\n\tgo func() {\n\t\tvar err error\n\t\tin := options.InputStream\n\t\tif in != nil {\n\t\t\t_, err = io.Copy(rwc, in)\n\t\t}\n\t\trwc.(interface {\n\t\t\tCloseWrite() error\n\t\t}).CloseWrite()\n\t\terrs <- err\n\t}()\n\t<-exit\n\treturn <-errs\n}\n\ntype logIgnore struct {\n}\n\nfunc (this *logIgnore) Debugf(msg string, args ...interface{}) {\n\t\/\/ Ignore the log message\n}\n<|endoftext|>"}
{"text":"<commit_before>package cortexbot\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/ilyaglow\/go-cortex\"\n\t\"gopkg.in\/telegram-bot-api.v4\"\n)\n\nvar boltFileName string = \"bolt.db\"\nvar bucket string = \"users\"\n\n\/\/ Client defines bot's abilities to interact with services\ntype Client struct {\n\tBot              *tgbotapi.BotAPI\n\tCortex           *gocortex.Client\n\tPassword         string\n\tAllowedUsernames map[string]bool\n\tDB               *bolt.DB\n\tUsersBucket      string\n}\n\n\/\/ NewClient bootstraps the Client struct from env variables\nfunc NewClient() *Client {\n\tbot, err := tgbotapi.NewBotAPI(os.Getenv(\"TGBOT_API_TOKEN\"))\n\tif err != nil {\n\t\tlog.Println(\"TGBOT_API_TOKEN env variable is empty\")\n\t\tlog.Panic(err)\n\t}\n\n\tcortex := gocortex.NewClient(os.Getenv(\"CORTEX_LOCATION\"))\n\n\tdb, err := bolt.Open(\"bolt.db\", 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Create a bucket\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucket([]byte(bucket))\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Create users bucket failed\")\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn &Client{\n\t\tBot:              bot,\n\t\tCortex:           cortex,\n\t\tPassword:         os.Getenv(\"CORTEX_BOT_PASSWORD\"),\n\t\tAllowedUsernames: make(map[string]bool),\n\t\tDB:               db,\n\t\tUsersBucket:      bucket,\n\t}\n}\n<commit_msg>Remove map from client struct<commit_after>package cortexbot\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/ilyaglow\/go-cortex\"\n\t\"gopkg.in\/telegram-bot-api.v4\"\n)\n\nvar boltFileName string = \"bolt.db\"\nvar bucket string = \"users\"\n\n\/\/ Client defines bot's abilities to interact with services\ntype Client struct {\n\tBot         *tgbotapi.BotAPI\n\tCortex      *gocortex.Client\n\tPassword    string\n\tDB          *bolt.DB\n\tUsersBucket string\n}\n\n\/\/ NewClient bootstraps the Client struct from env variables\nfunc NewClient() *Client {\n\tbot, err := tgbotapi.NewBotAPI(os.Getenv(\"TGBOT_API_TOKEN\"))\n\tif err != nil {\n\t\tlog.Println(\"TGBOT_API_TOKEN env variable is empty\")\n\t\tlog.Panic(err)\n\t}\n\n\tcortex := gocortex.NewClient(os.Getenv(\"CORTEX_LOCATION\"))\n\n\tdb, err := bolt.Open(\"bolt.db\", 0644, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Create a bucket\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucket([]byte(bucket))\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Create users bucket failed\")\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn &Client{\n\t\tBot:         bot,\n\t\tCortex:      cortex,\n\t\tPassword:    os.Getenv(\"CORTEX_BOT_PASSWORD\"),\n\t\tDB:          db,\n\t\tUsersBucket: bucket,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitcoind\n\nimport (\n\t\"fmt\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc getNewTestServer(handler http.Handler) (testServer *httptest.Server, host string, port int, err error) {\n\ttestServer = httptest.NewServer(handler)\n\tp := strings.Split(testServer.URL, \":\")\n\thost = p[1][2:]\n\tpport, err := strconv.ParseInt(p[2], 10, 64)\n\tport = int(pport)\n\treturn\n}\n\nvar _ = Describe(\"Bitcoind\", func() {\n\tDescribe(\"get difficulty\", func() {\n\n\t\tContext(\"when success\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":8853416309.12779999,\"error\":null,\"id\":1400425780999713481}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\tdifficulty, err := bitcoindClient.GetDifficulty()\n\t\t\tIt(\"should not error\", func() {\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"should return float64 8853416309.12779999\", func() {\n\t\t\t\tExpect(difficulty).To(BeEquivalentTo(8853416309.12779999))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when error from server\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":null,\"error\":{\"code\":6,\"message\":\"fake error\"},\"id\":1400425780999713481}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\t_, err = bitcoindClient.GetDifficulty()\n\t\t\tIt(\"error should occured\", func() {\n\t\t\t\tExpect(err).To(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"error should be 'fake error'\", func() {\n\t\t\t\tExpect(err).Should(MatchError(\"(6) fake error\"))\n\t\t\t})\n\t\t})\n\n\t})\n})\n<commit_msg>backupwallet, dumpprivkey, wallerpassphrase<commit_after>package bitcoind\n\nimport (\n\t\"fmt\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc getNewTestServer(handler http.Handler) (testServer *httptest.Server, host string, port int, err error) {\n\ttestServer = httptest.NewServer(handler)\n\tp := strings.Split(testServer.URL, \":\")\n\thost = p[1][2:]\n\tpport, err := strconv.ParseInt(p[2], 10, 64)\n\tport = int(pport)\n\treturn\n}\n\nvar _ = Describe(\"Bitcoind\", func() {\n\n\tDescribe(\"backupwallet\", func() {\n\t\tContext(\"when success\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":null,\"error\":null,\"id\":1400432805294160077}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\terr = bitcoindClient.BackupWallet(\"\/tmp\/wallet.dat\")\n\t\t\tIt(\"should not error\", func() {\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"dumpprivkey\", func() {\n\t\tContext(\"when success\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":\"K7boEpon3igLpbVv6xebaR4bHALHPeLQSHhUJGiZ9S1U85ERWWi9\",\"error\":null,\"id\":1400433741655216321}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\tprivKey, err := bitcoindClient.DumpPrivKey(\"1KU5DX7jKECLxh1nYhmQ7CahY7GMNMVLP3\")\n\t\t\tIt(\"should not error\", func() {\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\t\t\tIt(\"should be a the pk\", func() {\n\t\t\t\tExpect(privKey).To(Equal(\"K7boEpon3igLpbVv6xebaR4bHALHPeLQSHhUJGiZ9S1U85ERWWi9\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"get difficulty\", func() {\n\t\tContext(\"when success\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":8853416309.12779999,\"error\":null,\"id\":1400425780999713481}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\tdifficulty, err := bitcoindClient.GetDifficulty()\n\t\t\tIt(\"should not error\", func() {\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"should return float64 8853416309.12779999\", func() {\n\t\t\t\tExpect(difficulty).To(BeEquivalentTo(8853416309.12779999))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when error from server\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":null,\"error\":{\"code\":6,\"message\":\"fake error\"},\"id\":1400425780999713481}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\t_, err = bitcoindClient.GetDifficulty()\n\t\t\tIt(\"error should occured\", func() {\n\t\t\t\tExpect(err).To(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"error should be 'fake error'\", func() {\n\t\t\t\tExpect(err).Should(MatchError(\"(6) fake error\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"walletpassphrase\", func() {\n\t\tContext(\"when success\", func() {\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfmt.Fprintln(w, `{\"result\":null,\"error\":null,\"id\":1400433627531460562}`)\n\t\t\t})\n\t\t\tts, host, port, err := getNewTestServer(handler)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t}\n\t\t\tdefer ts.Close()\n\t\t\tbitcoindClient, _ := New(host, port, \"x\", \"fake\", false)\n\t\t\terr = bitcoindClient.WalletPassphrase(\"fakePassPhrase\", 60)\n\t\t\tIt(\"should not error\", func() {\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\t\t})\n\t})\n\n\t\/\/{\"result\":null,\"error\":null,\"id\":1400433627531460562}\n})\n<|endoftext|>"}
{"text":"<commit_before>package oci\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/opencontainers\/specs\/specs-go\"\n)\n\nfunc sPtr(s string) *string      { return &s }\nfunc iPtr(i int64) *int64        { return &i }\nfunc u32Ptr(i int64) *uint32     { u := uint32(i); return &u }\nfunc fmPtr(i int64) *os.FileMode { fm := os.FileMode(i); return &fm }\n\n\/\/ DefaultSpec returns default oci spec used by docker.\nfunc DefaultSpec() specs.Spec {\n\ts := specs.Spec{\n\t\tVersion: specs.Version,\n\t\tPlatform: specs.Platform{\n\t\t\tOS:   runtime.GOOS,\n\t\t\tArch: runtime.GOARCH,\n\t\t},\n\t}\n\ts.Mounts = []specs.Mount{\n\t\t{\n\t\t\tDestination: \"\/proc\",\n\t\t\tType:        \"proc\",\n\t\t\tSource:      \"proc\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"nodev\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\",\n\t\t\tType:        \"tmpfs\",\n\t\t\tSource:      \"tmpfs\",\n\t\t\tOptions:     []string{\"nosuid\", \"strictatime\", \"mode=755\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/pts\",\n\t\t\tType:        \"devpts\",\n\t\t\tSource:      \"devpts\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\", \"gid=5\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/sys\",\n\t\t\tType:        \"sysfs\",\n\t\t\tSource:      \"sysfs\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"nodev\", \"ro\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/sys\/fs\/cgroup\",\n\t\t\tType:        \"cgroup\",\n\t\t\tSource:      \"cgroup\",\n\t\t\tOptions:     []string{\"ro\", \"nosuid\", \"noexec\", \"nodev\"},\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\", \"nodev\"},\n\t\t},\n\t}\n\n\ts.Process.Capabilities = []string{\n\t\t\"CAP_CHOWN\",\n\t\t\"CAP_DAC_OVERRIDE\",\n\t\t\"CAP_FSETID\",\n\t\t\"CAP_FOWNER\",\n\t\t\"CAP_MKNOD\",\n\t\t\"CAP_NET_RAW\",\n\t\t\"CAP_SETGID\",\n\t\t\"CAP_SETUID\",\n\t\t\"CAP_SETFCAP\",\n\t\t\"CAP_SETPCAP\",\n\t\t\"CAP_NET_BIND_SERVICE\",\n\t\t\"CAP_SYS_CHROOT\",\n\t\t\"CAP_KILL\",\n\t\t\"CAP_AUDIT_WRITE\",\n\t}\n\n\ts.Linux = specs.Linux{\n\t\tMaskedPaths: []string{\n\t\t\t\"\/proc\/kcore\",\n\t\t\t\"\/proc\/latency_stats\",\n\t\t\t\"\/proc\/timer_stats\",\n\t\t\t\"\/proc\/sched_debug\",\n\t\t},\n\t\tReadonlyPaths: []string{\n\t\t\t\"\/proc\/asound\",\n\t\t\t\"\/proc\/bus\",\n\t\t\t\"\/proc\/fs\",\n\t\t\t\"\/proc\/irq\",\n\t\t\t\"\/proc\/sys\",\n\t\t\t\"\/proc\/sysrq-trigger\",\n\t\t},\n\t\tNamespaces: []specs.Namespace{\n\t\t\t{Type: \"mount\"},\n\t\t\t{Type: \"network\"},\n\t\t\t{Type: \"uts\"},\n\t\t\t{Type: \"pid\"},\n\t\t\t{Type: \"ipc\"},\n\t\t},\n\t\tDevices: []specs.Device{\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/zero\",\n\t\t\t\tMajor:    1,\n\t\t\t\tMinor:    5,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/null\",\n\t\t\t\tMajor:    1,\n\t\t\t\tMinor:    3,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/urandom\",\n\t\t\t\tMajor:    1,\n\t\t\t\tMinor:    9,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/random\",\n\t\t\t\tMajor:    1,\n\t\t\t\tMinor:    8,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/fuse\",\n\t\t\t\tMajor:    10,\n\t\t\t\tMinor:    229,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t},\n\t\tResources: &specs.Resources{\n\t\t\tDevices: []specs.DeviceCgroup{\n\t\t\t\t{\n\t\t\t\t\tAllow:  false,\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(5),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(3),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(9),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(8),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(5),\n\t\t\t\t\tMinor:  iPtr(0),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(5),\n\t\t\t\t\tMinor:  iPtr(1),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  false,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(10),\n\t\t\t\t\tMinor:  iPtr(229),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s\n}\n<commit_msg>oci: default devices don't need to be listed explicitly<commit_after>package oci\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/opencontainers\/specs\/specs-go\"\n)\n\nfunc sPtr(s string) *string      { return &s }\nfunc iPtr(i int64) *int64        { return &i }\nfunc u32Ptr(i int64) *uint32     { u := uint32(i); return &u }\nfunc fmPtr(i int64) *os.FileMode { fm := os.FileMode(i); return &fm }\n\n\/\/ DefaultSpec returns default oci spec used by docker.\nfunc DefaultSpec() specs.Spec {\n\ts := specs.Spec{\n\t\tVersion: specs.Version,\n\t\tPlatform: specs.Platform{\n\t\t\tOS:   runtime.GOOS,\n\t\t\tArch: runtime.GOARCH,\n\t\t},\n\t}\n\ts.Mounts = []specs.Mount{\n\t\t{\n\t\t\tDestination: \"\/proc\",\n\t\t\tType:        \"proc\",\n\t\t\tSource:      \"proc\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"nodev\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\",\n\t\t\tType:        \"tmpfs\",\n\t\t\tSource:      \"tmpfs\",\n\t\t\tOptions:     []string{\"nosuid\", \"strictatime\", \"mode=755\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/pts\",\n\t\t\tType:        \"devpts\",\n\t\t\tSource:      \"devpts\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\", \"gid=5\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/sys\",\n\t\t\tType:        \"sysfs\",\n\t\t\tSource:      \"sysfs\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"nodev\", \"ro\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/sys\/fs\/cgroup\",\n\t\t\tType:        \"cgroup\",\n\t\t\tSource:      \"cgroup\",\n\t\t\tOptions:     []string{\"ro\", \"nosuid\", \"noexec\", \"nodev\"},\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\", \"nodev\"},\n\t\t},\n\t}\n\n\ts.Process.Capabilities = []string{\n\t\t\"CAP_CHOWN\",\n\t\t\"CAP_DAC_OVERRIDE\",\n\t\t\"CAP_FSETID\",\n\t\t\"CAP_FOWNER\",\n\t\t\"CAP_MKNOD\",\n\t\t\"CAP_NET_RAW\",\n\t\t\"CAP_SETGID\",\n\t\t\"CAP_SETUID\",\n\t\t\"CAP_SETFCAP\",\n\t\t\"CAP_SETPCAP\",\n\t\t\"CAP_NET_BIND_SERVICE\",\n\t\t\"CAP_SYS_CHROOT\",\n\t\t\"CAP_KILL\",\n\t\t\"CAP_AUDIT_WRITE\",\n\t}\n\n\ts.Linux = specs.Linux{\n\t\tMaskedPaths: []string{\n\t\t\t\"\/proc\/kcore\",\n\t\t\t\"\/proc\/latency_stats\",\n\t\t\t\"\/proc\/timer_stats\",\n\t\t\t\"\/proc\/sched_debug\",\n\t\t},\n\t\tReadonlyPaths: []string{\n\t\t\t\"\/proc\/asound\",\n\t\t\t\"\/proc\/bus\",\n\t\t\t\"\/proc\/fs\",\n\t\t\t\"\/proc\/irq\",\n\t\t\t\"\/proc\/sys\",\n\t\t\t\"\/proc\/sysrq-trigger\",\n\t\t},\n\t\tNamespaces: []specs.Namespace{\n\t\t\t{Type: \"mount\"},\n\t\t\t{Type: \"network\"},\n\t\t\t{Type: \"uts\"},\n\t\t\t{Type: \"pid\"},\n\t\t\t{Type: \"ipc\"},\n\t\t},\n\t\t\/\/ Devices implicitly contains the following devices:\n\t\t\/\/ null, zero, full, random, urandom, tty, console, and ptmx.\n\t\t\/\/ ptmx is a bind-mount or symlink of the container's ptmx.\n\t\t\/\/ See also: https:\/\/github.com\/opencontainers\/runtime-spec\/blob\/master\/config-linux.md#default-devices\n\t\tDevices: []specs.Device{\n\t\t\t{\n\t\t\t\tType:     \"c\",\n\t\t\t\tPath:     \"\/dev\/fuse\",\n\t\t\t\tMajor:    10,\n\t\t\t\tMinor:    229,\n\t\t\t\tFileMode: fmPtr(0666),\n\t\t\t\tUID:      u32Ptr(0),\n\t\t\t\tGID:      u32Ptr(0),\n\t\t\t},\n\t\t},\n\t\tResources: &specs.Resources{\n\t\t\tDevices: []specs.DeviceCgroup{\n\t\t\t\t{\n\t\t\t\t\tAllow:  false,\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(5),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(3),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(9),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(1),\n\t\t\t\t\tMinor:  iPtr(8),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(5),\n\t\t\t\t\tMinor:  iPtr(0),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  true,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(5),\n\t\t\t\t\tMinor:  iPtr(1),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tAllow:  false,\n\t\t\t\t\tType:   sPtr(\"c\"),\n\t\t\t\t\tMajor:  iPtr(10),\n\t\t\t\t\tMinor:  iPtr(229),\n\t\t\t\t\tAccess: sPtr(\"rwm\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s\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\n\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"gosl\/chk\"\n\t\"gosl\/io\"\n\t\"gosl\/la\"\n\t\"gosl\/mpi\"\n\t\"gosl\/ode\"\n)\n\nfunc main() {\n\n\t\/\/ start mpi\n\tmpi.Start()\n\tdefer mpi.Stop()\n\n\t\/\/ check number of processors\n\tif mpi.WorldRank() == 0 {\n\t\tchk.Verbose = true\n\t\tchk.PrintTitle(\"Hairer-Wanner VII-p376 Transistor Amplifier\")\n\t}\n\tif mpi.WorldSize() != 3 {\n\t\tif mpi.WorldRank() == 0 {\n\t\t\tio.Pf(\"ERROR: this test needs 3 processors (run with mpi -np 3)\\n\")\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ communicator\n\tcomm := mpi.NewCommunicator(nil)\n\n\t\/\/ constants\n\tue, ub, uf, α, β := 0.1, 6.0, 0.026, 0.99, 1.0e-6\n\tr0, r1, r2, r3, r4, r5 := 1000.0, 9000.0, 9000.0, 9000.0, 9000.0, 9000.0\n\tr6, r7, r8, r9 := 9000.0, 9000.0, 9000.0, 9000.0\n\tw := 2.0 * 3.141592654 * 100.0\n\txf := 0.05\n\n\t\/\/ initial values\n\ty := la.NewVectorSlice([]float64{0.0,\n\t\tub,\n\t\tub \/ (r6\/r5 + 1.0),\n\t\tub \/ (r6\/r5 + 1.0),\n\t\tub,\n\t\tub \/ (r2\/r1 + 1.0),\n\t\tub \/ (r2\/r1 + 1.0),\n\t\t0.0,\n\t})\n\tndim := len(y)\n\n\t\/\/ right-hand side of the amplifier problem\n\tfcn := func(f la.Vector, dx, x float64, y la.Vector) {\n\t\tuet := ue * math.Sin(w*x)\n\t\tfac1 := β * (math.Exp((y[3]-y[2])\/uf) - 1.0)\n\t\tfac2 := β * (math.Exp((y[6]-y[5])\/uf) - 1.0)\n\t\tf[0] = y[0] \/ r9\n\t\tf[1] = (y[1]-ub)\/r8 + α*fac1\n\t\tf[2] = y[2]\/r7 - fac1\n\t\tf[3] = y[3]\/r5 + (y[3]-ub)\/r6 + (1.0-α)*fac1\n\t\tf[4] = (y[4]-ub)\/r4 + α*fac2\n\t\tf[5] = y[5]\/r3 - fac2\n\t\tf[6] = y[6]\/r1 + (y[6]-ub)\/r2 + (1.0-α)*fac2\n\t\tf[7] = (y[7] - uet) \/ r0\n\t}\n\n\t\/\/ Jacobian of the amplifier problem\n\tjac := func(dfdy *la.Triplet, dx, x float64, y la.Vector) {\n\t\tfac14 := β * math.Exp((y[3]-y[2])\/uf) \/ uf\n\t\tfac27 := β * math.Exp((y[6]-y[5])\/uf) \/ uf\n\t\tif dfdy.Max() == 0 {\n\t\t\tdfdy.Init(8, 8, 16)\n\t\t}\n\t\tnu := 2\n\t\tdfdy.Start()\n\t\tswitch comm.Rank() {\n\t\tcase 0:\n\t\t\tdfdy.Put(2+0-nu, 0, 1.0\/r9)\n\t\t\tdfdy.Put(2+1-nu, 1, 1.0\/r8)\n\t\t\tdfdy.Put(1+2-nu, 2, -α*fac14)\n\t\t\tdfdy.Put(0+3-nu, 3, α*fac14)\n\t\t\tdfdy.Put(2+2-nu, 2, 1.0\/r7+fac14)\n\t\tcase 1:\n\t\t\tdfdy.Put(1+3-nu, 3, -fac14)\n\t\t\tdfdy.Put(2+3-nu, 3, 1.0\/r5+1.0\/r6+(1.0-α)*fac14)\n\t\t\tdfdy.Put(3+2-nu, 2, -(1.0-α)*fac14)\n\t\t\tdfdy.Put(2+4-nu, 4, 1.0\/r4)\n\t\t\tdfdy.Put(1+5-nu, 5, -α*fac27)\n\t\tcase 2:\n\t\t\tdfdy.Put(0+6-nu, 6, α*fac27)\n\t\t\tdfdy.Put(2+5-nu, 5, 1.0\/r3+fac27)\n\t\t\tdfdy.Put(1+6-nu, 6, -fac27)\n\t\t\tdfdy.Put(2+6-nu, 6, 1.0\/r1+1.0\/r2+(1.0-α)*fac27)\n\t\t\tdfdy.Put(3+5-nu, 5, -(1.0-α)*fac27)\n\t\t\tdfdy.Put(2+7-nu, 7, 1.0\/r0)\n\t\t}\n\t}\n\n\t\/\/ \"mass\" matrix\n\tc1, c2, c3, c4, c5 := 1.0e-6, 2.0e-6, 3.0e-6, 4.0e-6, 5.0e-6\n\tM := new(la.Triplet)\n\tM.Init(8, 8, 14)\n\tM.Start()\n\tnu := 1\n\tswitch comm.Rank() {\n\tcase 0:\n\t\tM.Put(1+0-nu, 0, -c5)\n\t\tM.Put(0+1-nu, 1, c5)\n\t\tM.Put(2+0-nu, 0, c5)\n\t\tM.Put(1+1-nu, 1, -c5)\n\t\tM.Put(1+2-nu, 2, -c4)\n\t\tM.Put(1+3-nu, 3, -c3)\n\tcase 1:\n\t\tM.Put(0+4-nu, 4, c3)\n\t\tM.Put(2+3-nu, 3, c3)\n\t\tM.Put(1+4-nu, 4, -c3)\n\tcase 2:\n\t\tM.Put(1+5-nu, 5, -c2)\n\t\tM.Put(1+6-nu, 6, -c1)\n\t\tM.Put(0+7-nu, 7, c1)\n\t\tM.Put(2+6-nu, 6, c1)\n\t\tM.Put(1+7-nu, 7, -c1)\n\t}\n\n\t\/\/ configurations\n\tconf := ode.NewConfig(\"radau5\", \"mumps\", comm)\n\tconf.SetStepOut(true, nil)\n\tconf.IniH = 1.0e-6 \/\/ initial step size\n\n\t\/\/ set tolerances\n\tatol, rtol := 1e-11, 1e-5\n\tconf.SetTols(atol, rtol)\n\n\t\/\/ ODE solver\n\tsol := ode.NewSolver(ndim, conf, fcn, jac, M)\n\tdefer sol.Free()\n\n\t\/\/ run\n\tsol.Solve(y, 0.0, xf)\n\n\t\/\/ only root\n\tif mpi.WorldRank() == 0 {\n\n\t\t\/\/ check\n\t\ttst := new(testing.T)\n\t\tchk.Int(tst, \"number of F evaluations \", sol.Stat.Nfeval, 2655)\n\t\tchk.Int(tst, \"number of J evaluations \", sol.Stat.Njeval, 217)\n\t\tchk.Int(tst, \"total number of steps   \", sol.Stat.Nsteps, 282)\n\t\tchk.Int(tst, \"number of accepted steps\", sol.Stat.Naccepted, 221)\n\t\tchk.Int(tst, \"number of rejected steps\", sol.Stat.Nrejected, 23)\n\t\tchk.Int(tst, \"number of decompositions\", sol.Stat.Ndecomp, 281)\n\t\tchk.Int(tst, \"number of lin solutions \", sol.Stat.Nlinsol, 809)\n\t\tchk.Int(tst, \"max number of iterations\", sol.Stat.Nitmax, 6)\n\t}\n}\n<commit_msg>Update stats for ODE amplifier tests (they are better)<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\n\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"gosl\/chk\"\n\t\"gosl\/io\"\n\t\"gosl\/la\"\n\t\"gosl\/mpi\"\n\t\"gosl\/ode\"\n)\n\nfunc main() {\n\n\t\/\/ start mpi\n\tmpi.Start()\n\tdefer mpi.Stop()\n\n\t\/\/ check number of processors\n\tif mpi.WorldRank() == 0 {\n\t\tchk.Verbose = true\n\t\tchk.PrintTitle(\"Hairer-Wanner VII-p376 Transistor Amplifier\")\n\t}\n\tif mpi.WorldSize() != 3 {\n\t\tif mpi.WorldRank() == 0 {\n\t\t\tio.Pf(\"ERROR: this test needs 3 processors (run with mpi -np 3)\\n\")\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ communicator\n\tcomm := mpi.NewCommunicator(nil)\n\n\t\/\/ constants\n\tue, ub, uf, α, β := 0.1, 6.0, 0.026, 0.99, 1.0e-6\n\tr0, r1, r2, r3, r4, r5 := 1000.0, 9000.0, 9000.0, 9000.0, 9000.0, 9000.0\n\tr6, r7, r8, r9 := 9000.0, 9000.0, 9000.0, 9000.0\n\tw := 2.0 * 3.141592654 * 100.0\n\txf := 0.05\n\n\t\/\/ initial values\n\ty := la.NewVectorSlice([]float64{0.0,\n\t\tub,\n\t\tub \/ (r6\/r5 + 1.0),\n\t\tub \/ (r6\/r5 + 1.0),\n\t\tub,\n\t\tub \/ (r2\/r1 + 1.0),\n\t\tub \/ (r2\/r1 + 1.0),\n\t\t0.0,\n\t})\n\tndim := len(y)\n\n\t\/\/ right-hand side of the amplifier problem\n\tfcn := func(f la.Vector, dx, x float64, y la.Vector) {\n\t\tuet := ue * math.Sin(w*x)\n\t\tfac1 := β * (math.Exp((y[3]-y[2])\/uf) - 1.0)\n\t\tfac2 := β * (math.Exp((y[6]-y[5])\/uf) - 1.0)\n\t\tf[0] = y[0] \/ r9\n\t\tf[1] = (y[1]-ub)\/r8 + α*fac1\n\t\tf[2] = y[2]\/r7 - fac1\n\t\tf[3] = y[3]\/r5 + (y[3]-ub)\/r6 + (1.0-α)*fac1\n\t\tf[4] = (y[4]-ub)\/r4 + α*fac2\n\t\tf[5] = y[5]\/r3 - fac2\n\t\tf[6] = y[6]\/r1 + (y[6]-ub)\/r2 + (1.0-α)*fac2\n\t\tf[7] = (y[7] - uet) \/ r0\n\t}\n\n\t\/\/ Jacobian of the amplifier problem\n\tjac := func(dfdy *la.Triplet, dx, x float64, y la.Vector) {\n\t\tfac14 := β * math.Exp((y[3]-y[2])\/uf) \/ uf\n\t\tfac27 := β * math.Exp((y[6]-y[5])\/uf) \/ uf\n\t\tif dfdy.Max() == 0 {\n\t\t\tdfdy.Init(8, 8, 16)\n\t\t}\n\t\tnu := 2\n\t\tdfdy.Start()\n\t\tswitch comm.Rank() {\n\t\tcase 0:\n\t\t\tdfdy.Put(2+0-nu, 0, 1.0\/r9)\n\t\t\tdfdy.Put(2+1-nu, 1, 1.0\/r8)\n\t\t\tdfdy.Put(1+2-nu, 2, -α*fac14)\n\t\t\tdfdy.Put(0+3-nu, 3, α*fac14)\n\t\t\tdfdy.Put(2+2-nu, 2, 1.0\/r7+fac14)\n\t\tcase 1:\n\t\t\tdfdy.Put(1+3-nu, 3, -fac14)\n\t\t\tdfdy.Put(2+3-nu, 3, 1.0\/r5+1.0\/r6+(1.0-α)*fac14)\n\t\t\tdfdy.Put(3+2-nu, 2, -(1.0-α)*fac14)\n\t\t\tdfdy.Put(2+4-nu, 4, 1.0\/r4)\n\t\t\tdfdy.Put(1+5-nu, 5, -α*fac27)\n\t\tcase 2:\n\t\t\tdfdy.Put(0+6-nu, 6, α*fac27)\n\t\t\tdfdy.Put(2+5-nu, 5, 1.0\/r3+fac27)\n\t\t\tdfdy.Put(1+6-nu, 6, -fac27)\n\t\t\tdfdy.Put(2+6-nu, 6, 1.0\/r1+1.0\/r2+(1.0-α)*fac27)\n\t\t\tdfdy.Put(3+5-nu, 5, -(1.0-α)*fac27)\n\t\t\tdfdy.Put(2+7-nu, 7, 1.0\/r0)\n\t\t}\n\t}\n\n\t\/\/ \"mass\" matrix\n\tc1, c2, c3, c4, c5 := 1.0e-6, 2.0e-6, 3.0e-6, 4.0e-6, 5.0e-6\n\tM := new(la.Triplet)\n\tM.Init(8, 8, 14)\n\tM.Start()\n\tnu := 1\n\tswitch comm.Rank() {\n\tcase 0:\n\t\tM.Put(1+0-nu, 0, -c5)\n\t\tM.Put(0+1-nu, 1, c5)\n\t\tM.Put(2+0-nu, 0, c5)\n\t\tM.Put(1+1-nu, 1, -c5)\n\t\tM.Put(1+2-nu, 2, -c4)\n\t\tM.Put(1+3-nu, 3, -c3)\n\tcase 1:\n\t\tM.Put(0+4-nu, 4, c3)\n\t\tM.Put(2+3-nu, 3, c3)\n\t\tM.Put(1+4-nu, 4, -c3)\n\tcase 2:\n\t\tM.Put(1+5-nu, 5, -c2)\n\t\tM.Put(1+6-nu, 6, -c1)\n\t\tM.Put(0+7-nu, 7, c1)\n\t\tM.Put(2+6-nu, 6, c1)\n\t\tM.Put(1+7-nu, 7, -c1)\n\t}\n\n\t\/\/ configurations\n\tconf := ode.NewConfig(\"radau5\", \"mumps\", comm)\n\tconf.SetStepOut(true, nil)\n\tconf.IniH = 1.0e-6 \/\/ initial step size\n\n\t\/\/ set tolerances\n\tatol, rtol := 1e-11, 1e-5\n\tconf.SetTols(atol, rtol)\n\n\t\/\/ ODE solver\n\tsol := ode.NewSolver(ndim, conf, fcn, jac, M)\n\tdefer sol.Free()\n\n\t\/\/ run\n\tsol.Solve(y, 0.0, xf)\n\n\t\/\/ only root\n\tif mpi.WorldRank() == 0 {\n\n\t\t\/\/ check\n\t\ttst := new(testing.T)\n\t\tchk.Int(tst, \"number of F evaluations \", sol.Stat.Nfeval, 2559)\n\t\tchk.Int(tst, \"number of J evaluations \", sol.Stat.Njeval, 212)\n\t\tchk.Int(tst, \"total number of steps   \", sol.Stat.Nsteps, 266)\n\t\tchk.Int(tst, \"number of accepted steps\", sol.Stat.Naccepted, 217)\n\t\tchk.Int(tst, \"number of rejected steps\", sol.Stat.Nrejected, 23)\n\t\tchk.Int(tst, \"number of decompositions\", sol.Stat.Ndecomp, 265)\n\t\tchk.Int(tst, \"number of lin solutions \", sol.Stat.Nlinsol, 780)\n\t\tchk.Int(tst, \"max number of iterations\", sol.Stat.Nitmax, 6)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"log\"\n)\n\ntype Config struct {\n\tPort int `default:\"3000\"`\n}\n\nvar config Config\n\nfunc init() {\n\terr := envconfig.Process(\"slack_exact\", &config)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\n<commit_msg>Defined some more settings<commit_after>package main\n\nimport (\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"log\"\n)\n\ntype configSpecification struct {\n\t\/\/ Port\n\tPort int `default:\"3000\"`\n\t\/\/ URL of the Slack Webhook\n\tWebhookURL string `envconfig:\"webhook_url\"`\n\t\/\/ Token for incoming Slack requests\n\tIncomingToken string `envconfig:\"incoming_token\"`\n\t\/\/ Username for bot replies\n\tBotUsername string `envconfig:\"bot_username\" default:\"Exact Online\"`\n\t\/\/ Base URL of Slack Exact\n\tBaseURL string `envconfig:\"base_url\" default:\"http:\/\/slackexact.greymug.io\/\"`\n\t\/\/ Exact app key\n\tAppKey string `envconfig:\"app_key\"`\n\t\/\/ Exact client ID\n\tClientID string `envconfig:\"client_id\"`\n\t\/\/ Exact client secret\n\tClientSecret string `envconfig:\"client_secret\"`\n}\n\nvar config configSpecification\n\nfunc init() {\n\terr := envconfig.Process(\"slack_exact\", &config)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dulbecco\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/BurntSushi\/toml\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar defaultReplies []string\n\ntype Configuration struct {\n\tServers []ServerConfiguration\n\tPlugins []PluginConfiguration\n\tReplies []string\n\tHipchat HipchatConfiguration\n}\n\ntype ServerConfiguration struct {\n\tName           string\n\tAddress        string\n\tSsl            bool\n\tSslInsecure    bool   `json:\"ssl_insecure\" toml:\"ssl_insecure\"`\n\tSslCertificate string `json:\"ssl_certificate\" toml:\"ssl_certificate\"`\n\tChannels       []string\n\tNickname       string\n\tAltnicknames   []string\n\tUsername       string\n\tRealname       string\n\tPassword       string\n\tNickserv       string\n\tDebug          bool\n}\n\nfunc (sc *ServerConfiguration) GetHostname() string {\n\tif colon := strings.Index(sc.Address, \":\"); colon > 0 {\n\t\treturn sc.Address[0:colon]\n\t}\n\treturn sc.Address\n}\n\ntype PluginConfiguration struct {\n\tName    string\n\tCommand string\n\tTrigger string\n}\n\ntype HipchatConfiguration struct {\n\tAddress string\n}\n\nfunc ReadConfig(filename string) (*Configuration, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config *Configuration\n\tif filepath.Ext(filename) == \".json\" {\n\t\tconfig, err = readJsonConfig(data)\n\t} else {\n\t\tconfig, err = readTomlConfig(data)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(config.Servers) < 1 {\n\t\treturn nil, errors.New(\"no servers defined\")\n\t}\n\n\tdefaultReplies = append(defaultReplies, config.Replies...)\n\n\treturn config, nil\n}\n\nfunc readJsonConfig(data []byte) (*Configuration, error) {\n\tvar config Configuration\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}\n\nfunc readTomlConfig(data []byte) (*Configuration, error) {\n\tvar config Configuration\n\tif _, err := toml.Decode(string(data), &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}\n\nfunc GetRandomReply() string {\n\tif len(defaultReplies) > 0 {\n\t\treturn defaultReplies[rand.Intn(len(defaultReplies))]\n\t}\n\treturn \"DEMENZA MI COLSE\"\n}\n<commit_msg>fix toml configuration<commit_after>package dulbecco\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/BurntSushi\/toml\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar defaultReplies []string\n\ntype Configuration struct {\n\tServers []ServerConfiguration `toml:\"server\"`\n\tPlugins []PluginConfiguration\n\tReplies []string\n\tHipchat HipchatConfiguration\n}\n\ntype ServerConfiguration struct {\n\tName           string\n\tAddress        string\n\tSsl            bool\n\tSslInsecure    bool   `json:\"ssl_insecure\" toml:\"ssl_insecure\"`\n\tSslCertificate string `json:\"ssl_certificate\" toml:\"ssl_certificate\"`\n\tChannels       []string\n\tNickname       string\n\tAltnicknames   []string\n\tUsername       string\n\tRealname       string\n\tPassword       string\n\tNickserv       string\n\tDebug          bool\n}\n\nfunc (sc *ServerConfiguration) GetHostname() string {\n\tif colon := strings.Index(sc.Address, \":\"); colon > 0 {\n\t\treturn sc.Address[0:colon]\n\t}\n\treturn sc.Address\n}\n\ntype PluginConfiguration struct {\n\tName    string\n\tCommand string\n\tTrigger string\n}\n\ntype HipchatConfiguration struct {\n\tAddress string\n}\n\nfunc ReadConfig(filename string) (*Configuration, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config *Configuration\n\tif filepath.Ext(filename) == \".json\" {\n\t\tconfig, err = readJsonConfig(data)\n\t} else {\n\t\tconfig, err = readTomlConfig(data)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(config.Servers) < 1 {\n\t\treturn nil, errors.New(\"no servers defined\")\n\t}\n\n\tdefaultReplies = append(defaultReplies, config.Replies...)\n\n\treturn config, nil\n}\n\nfunc readJsonConfig(data []byte) (*Configuration, error) {\n\tvar config Configuration\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}\n\nfunc readTomlConfig(data []byte) (*Configuration, error) {\n\tvar config Configuration\n\tif _, err := toml.Decode(string(data), &config); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &config, nil\n}\n\nfunc GetRandomReply() string {\n\tif len(defaultReplies) > 0 {\n\t\treturn defaultReplies[rand.Intn(len(defaultReplies))]\n\t}\n\treturn \"DEMENZA MI COLSE\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Provider interface {\n\tSetRawString(raw string)\n\tSetRawBytes(raw []byte)\n\tGet(data interface{}) error\n\tSet(data interface{}) (int, error)\n}\n\nvar (\n\tPrefix   string\n\tfilepath string\n\tprovider Provider\n)\n\nfunc New(file, format string) (provider Provider, err error) {\n\n\t\/\/ set config file full path\n\tfilepath = Prefix + file\n\tfp, fperr := os.Open(filepath)\n\tif os.IsNotExist(fperr) {\n\t\tfperr = nil\n\t\tfilepath = Prefix + \"\/etc\/\" + file\n\t\tfp, fperr = os.Open(filepath)\n\t}\n\n\tif fperr != nil {\n\t\treturn nil, fperr\n\t}\n\n\t\/\/ read config file raw data.\n\tfstat, _ := fp.Stat()\n\traw := make([]byte, fstat.Size())\n\tfp.Read(raw)\n\n\tswitch format {\n\tcase \"json\":\n\t\tprovider = &JSON{}\n\t\tprovider.SetRawBytes(raw)\n\n\tcase \"xml\":\n\t\tprovider = &XML{}\n\t\tprovider.SetRawBytes(raw)\n\n\tdefault:\n\t\treturn nil, errors.New(\"Not support this format config file.\")\n\t}\n\treturn\n}\n\n\/\/ init default provider\nfunc defaultProvider() {\n\tvar derr error\n\tPrefix = \".\/\"\n\tprovider, derr = New(\"main.json\", \"json\")\n\tif derr != nil {\n\t\tfmt.Printf(\"[config package]get default config error,details: %v\\n\", derr)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc Get(data interface{}) error {\n\tdefaultProvider()\n\treturn provider.Get(data)\n}\n\nfunc Set(data interface{}) (int, error) {\n\tdefaultProvider()\n\treturn provider.Set(data)\n}\n<commit_msg>if not exist create config file when create new provider.<commit_after>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Provider interface {\n\tSetRawString(raw string)\n\tSetRawBytes(raw []byte)\n\tGet(data interface{}) error\n\tSet(data interface{}) (int, error)\n}\n\nvar (\n\tPrefix   string\n\tfilepath string\n\tprovider Provider\n)\n\nfunc New(file, format string) (provider Provider, err error) {\n\n\t\/\/ set config file full path\n\tfilepath = Prefix + file\n\tfp, fperr := os.OpenFile(filepath, os.O_RDONLY|os.O_CREATE, os.ModePerm)\n\tif os.IsNotExist(fperr) {\n\t\tfperr = nil\n\t\tfilepath = Prefix + \"\/etc\/\" + file\n\t\tfp, fperr = os.Open(filepath)\n\t}\n\n\tif fperr != nil {\n\t\treturn nil, fperr\n\t}\n\n\t\/\/ read config file raw data.\n\tfstat, _ := fp.Stat()\n\traw := make([]byte, fstat.Size())\n\tfp.Read(raw)\n\n\tswitch format {\n\tcase \"json\":\n\t\tprovider = &JSON{}\n\t\tprovider.SetRawBytes(raw)\n\n\tcase \"xml\":\n\t\tprovider = &XML{}\n\t\tprovider.SetRawBytes(raw)\n\n\tdefault:\n\t\treturn nil, errors.New(\"Not support this format config file.\")\n\t}\n\treturn\n}\n\n\/\/ init default provider\nfunc defaultProvider() {\n\tvar derr error\n\tPrefix = \".\/\"\n\tprovider, derr = New(\"main.json\", \"json\")\n\tif derr != nil {\n\t\tfmt.Printf(\"[config package]get default config error,details: %v\\n\", derr)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc Get(data interface{}) error {\n\tdefaultProvider()\n\treturn provider.Get(data)\n}\n\nfunc Set(data interface{}) (int, error) {\n\tdefaultProvider()\n\treturn provider.Set(data)\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitutils\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar r *rand.Rand\nvar w Word\nvar ws string\n\nfunc reverse(s string) string {\n\trunes := []rune(s)\n\tfor i, j := 0, len(runes)-1; i < len(runes)\/2; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\treturn string(runes)\n}\n\nfunc testCase() (w Word, ws string) {\n\tr = rand.New(rand.NewSource(time.Now().UnixNano()))\n\tw = Word(r.Uint32()) | Word(r.Uint32())<<32\n\tws = fmt.Sprintf(\"%064b\", w)\n\treturn\n}\n\nfunc TestMain(m *testing.M) {\n\tw, ws = testCase()\n\tos.Exit(m.Run())\n}\n\nfunc TestCount1(t *testing.T) {\n\tgot := w.Count1()\n\twant := strings.Count(ws, \"1\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d for %s\", got, want, ws)\n\t}\n}\n\nfunc TestCount0(t *testing.T) {\n\twant := w.Count0()\n\tgot := strings.Count(ws, \"0\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d for %s\", got, want, ws)\n\t}\n}\n\nfunc TestCount(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\twant := w.Count(i)\n\t\tgot := strings.Count(ws, strconv.Itoa(i))\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d for %s\", got, want, ws)\n\t\t}\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tj := W - i - 1 \/\/ corresponding index in ws.\n\n\t\tn, err := strconv.ParseUint(ws[j:j+1], 10, 0)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ParseUint failed\")\n\t\t}\n\n\t\tgot := w.Get(i)\n\t\twant := Word(n)\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d for %s\", got, want, ws)\n\t\t}\n\t}\n}\n\nfunc TestSet1(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Set1(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot := v.Get(j)\n\t\t\twant := w.Get(j)\n\t\t\tif i == j {\n\t\t\t\twant = 1\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSet0(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Set0(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot := v.Get(j)\n\t\t\twant := w.Get(j)\n\t\t\tif i == j {\n\t\t\t\twant = 0\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestFlip(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Flip(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot := v.Get(j)\n\t\t\twant := w.Get(j)\n\t\t\tif i == j {\n\t\t\t\tif want == 1 {\n\t\t\t\t\twant = 0\n\t\t\t\t} else {\n\t\t\t\t\twant = 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestLsb(t *testing.T) {\n\tgot := w.Lsb()\n\twant := strings.Index(reverse(ws), \"1\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d for %s\", got, want, ws)\n\t}\n}\n\nfunc TestRank1(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tgot := w.Rank1(i)\n\t\twant := strings.Count(ws[len(ws)-i-1:len(ws)], \"1\")\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestRank0(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tgot := w.Rank0(i)\n\t\twant := strings.Count(ws[len(ws)-i-1:len(ws)], \"0\")\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc BenchmarkCount1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count1()\n\t}\n}\n\nfunc BenchmarkCount0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count0()\n\t}\n}\n\nfunc BenchmarkCount(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count(1)\n\t}\n}\n\nfunc BenchmarkGet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Get(i % W)\n\t}\n}\n\nfunc BenchmarkSet1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Set1(i % W)\n\t}\n}\n\nfunc BenchmarkSet0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Set0(i % W)\n\t}\n}\n\nfunc BenchmarkFlip(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Flip(i % W)\n\t}\n}\n\n\nfunc BenchmarkLsb(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Lsb()\n\t}\n}\n\nfunc BenchmarkRank1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Rank1(i % W)\n\t}\n}\n\nfunc BenchmarkRank0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Rank0(i % W)\n\t}\n}\n<commit_msg>Refactor test code<commit_after>package bitutils\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar r *rand.Rand\nvar w Word\nvar ws, wsR string\n\nfunc reverse(s string) string {\n\trunes := []rune(s)\n\tfor i, j := 0, len(runes)-1; i < len(runes)\/2; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\treturn string(runes)\n}\n\nfunc testCase() (w Word, ws string) {\n\tr = rand.New(rand.NewSource(time.Now().UnixNano()))\n\tw = Word(r.Uint32()) | Word(r.Uint32())<<32\n\tws = fmt.Sprintf(\"%064b\", w)\n\twsR = reverse(ws)\n\treturn\n}\n\nfunc TestMain(m *testing.M) {\n\tw, ws = testCase()\n\tos.Exit(m.Run())\n}\n\nfunc TestCount1(t *testing.T) {\n\tgot, want := w.Count1(), strings.Count(ws, \"1\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t}\n}\n\nfunc TestCount0(t *testing.T) {\n\tgot, want := w.Count0(), strings.Count(ws, \"0\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t}\n}\n\nfunc TestCount(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\tgot, want := w.Count(i), strings.Count(ws, strconv.Itoa(i))\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tn, err := strconv.ParseUint(wsR[i:i+1], 10, 0)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"ParseUint failed\")\n\t\t}\n\t\tgot, want := w.Get(i), Word(n)\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestSet1(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Set1(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot, want := v.Get(j), w.Get(j)\n\t\t\tif i == j {\n\t\t\t\twant = 1\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSet0(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Set0(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot, want := v.Get(j), w.Get(j)\n\t\t\tif i == j {\n\t\t\t\twant = 0\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestFlip(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tv := w.Flip(i)\n\t\tfor j := 0; j < W; j++ {\n\t\t\tgot, want := v.Get(j), w.Get(j)\n\t\t\tif i == j {\n\t\t\t\tif want == 1 {\n\t\t\t\t\twant = 0\n\t\t\t\t} else {\n\t\t\t\t\twant = 1\n\t\t\t\t}\n\t\t\t}\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestLsb(t *testing.T) {\n\tgot, want := w.Lsb(), strings.Index(wsR, \"1\")\n\tif got != want {\n\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t}\n}\n\nfunc TestRank1(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tgot, want := w.Rank1(i), strings.Count(wsR[0:i+1], \"1\")\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc TestRank0(t *testing.T) {\n\tfor i := 0; i < W; i++ {\n\t\tgot, want := w.Rank0(i), strings.Count(wsR[0:i+1], \"0\")\n\t\tif got != want {\n\t\t\tt.Errorf(\"got %d, want %d\", got, want)\n\t\t}\n\t}\n}\n\nfunc BenchmarkCount1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count1()\n\t}\n}\n\nfunc BenchmarkCount0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count0()\n\t}\n}\n\nfunc BenchmarkCount(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Count(1)\n\t}\n}\n\nfunc BenchmarkGet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Get(i % W)\n\t}\n}\n\nfunc BenchmarkSet1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Set1(i % W)\n\t}\n}\n\nfunc BenchmarkSet0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Set0(i % W)\n\t}\n}\n\nfunc BenchmarkFlip(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Flip(i % W)\n\t}\n}\n\nfunc BenchmarkLsb(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Lsb()\n\t}\n}\n\nfunc BenchmarkRank1(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Rank1(i % W)\n\t}\n}\n\nfunc BenchmarkRank0(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tw := Word(i)\n\t\t_ = w.Rank0(i % W)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package config version v1.0.0\npackage 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\n\/\/ Namespace holds the pieces joined together to form the\n\/\/ directory namespacing for config.\ntype Namespace struct {\n\tOrganization string \/\/ optional additional namespace for orgs.\n\tSystem       string \/\/ Name of the system associated with this config.\n}\n\n\/\/ The Config interface implements config.\ntype Config interface {\n\tLoad(src string, dst interface{}) error\n}\n\n\/\/ UserBase and SystemBase are the prefixes for the user and system config\n\/\/ paths, respectively.\nconst (\n\tUserBase   string = \"~\/.config\/\"\n\tSystemBase string = \"\/etc\/\"\n)\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}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpath := ExpandUser(src)\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\n\/\/ ExpandUser acts kind of like os.path.expanduser in Python, except only\n\/\/ supports expanding \"~\/\" or \"$HOME\"\nfunc ExpandUser(path string) (exPath string) {\n\tusr, _ := user.Current()\n\n\tdir := fmt.Sprintf(\"%s\/\", usr.HomeDir)\n\n\texPath = path\n\tif len(path) > 2 && path[:2] == \"~\/\" {\n\t\texPath = strings.Replace(exPath, \"~\/\", dir, 1)\n\t} else if len(path) > 5 && path[:5] == \"$HOME\" {\n\t\texPath = strings.Replace(exPath, \"$HOME\", dir, 1)\n\t}\n\n\texPath, _ = filepath.Abs(filepath.Clean(exPath))\n\treturn\n}\n\n\/\/ Path returns path to config, chosen by hierarchy and checked for\n\/\/ existence:\n\/\/\n\/\/ 1. User config (~\/.config\/podhub\/canary\/config.yaml)\n\/\/\n\/\/ 2. System config (\/etc\/podhub\/canary\/config.yaml)\nfunc (c Namespace) Path() (path string) {\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 Namespace) systemPath() (path string, err error) {\n\tpath = filepath.Join(SystemBase, c.Organization, c.System, \"config.yaml\")\n\treturn\n}\n\nfunc (c Namespace) userPath() (path string, err error) {\n\tuserBase := ExpandUser(UserBase)\n\n\tpath = filepath.Join(userBase, c.Organization, c.System, \"config.yaml\")\n\treturn\n}\n\n\/\/ EnvVar returns the name of the environment variable containing the URI\n\/\/ of the config.\n\/\/ Example: PODHUB_UUIDD_CONFIG_URI\nfunc (c Namespace) EnvVar() (envvar string) {\n\ts := []string{c.Organization, c.System, \"CONFIG\", \"URI\"}\n\tenvvar = strings.ToUpper(strings.Join(s, \"_\"))\n\treturn\n}\n\n\/\/ Load is a convenience function registered to config.Namespace to\n\/\/ implement Config.Load().\nfunc (c Namespace) Load(dst interface{}) (err error) {\n\tcfgPath := c.Path()\n\n\terr = Load(cfgPath, dst)\n\treturn\n}\n<commit_msg>add basic support for uri<commit_after>\/\/ Package config version v1.0.0\npackage config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\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\n\/\/ Namespace holds the pieces joined together to form the\n\/\/ directory namespacing for config.\ntype Namespace struct {\n\tOrganization string \/\/ optional additional namespace for orgs.\n\tSystem       string \/\/ Name of the system associated with this config.\n}\n\n\/\/ The Config interface implements config.\ntype Config interface {\n\tLoad(src string, dst interface{}) error\n}\n\n\/\/ UserBase and SystemBase are the prefixes for the user and system config\n\/\/ paths, respectively.\nconst (\n\tUserBase   string = \"~\/.config\/\"\n\tSystemBase string = \"\/etc\/\"\n)\n\n\/\/ Load reads the contents of the src URI and unmarshals into dst using\n\/\/ go-yaml.\nfunc Load(src string, dst interface{}) (err error) {\n\tvar data []byte\n\tdstv := reflect.ValueOf(dst)\n\n\tif dstv.Kind() != reflect.Ptr {\n\t\terr = errors.New(\"config: not a pointer\")\n\t\treturn\n\t}\n\n\turi, err := url.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch {\n\tcase uri.Scheme == \"file\":\n\t\tpath := ExpandUser(uri.Path)\n\t\tdata, err = ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase uri.Scheme == \"http\" || uri.Scheme == \"https\":\n\t\tresp, err := http.Get(uri.String())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdata, err = ioutil.ReadAll(resp.Body)\n\n\t\tresp.Body.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = yaml.Unmarshal(data, dst)\n\treturn\n}\n\n\/\/ ExpandUser acts kind of like os.path.expanduser in Python, except only\n\/\/ supports expanding \"~\/\" or \"$HOME\"\nfunc ExpandUser(path string) (exPath string) {\n\tusr, _ := user.Current()\n\n\tdir := fmt.Sprintf(\"%s\/\", usr.HomeDir)\n\n\texPath = path\n\tif len(path) > 2 && path[:2] == \"~\/\" {\n\t\texPath = strings.Replace(exPath, \"~\/\", dir, 1)\n\t} else if len(path) > 5 && path[:5] == \"$HOME\" {\n\t\texPath = strings.Replace(exPath, \"$HOME\", dir, 1)\n\t}\n\n\texPath, _ = filepath.Abs(filepath.Clean(exPath))\n\treturn\n}\n\n\/\/ Path returns path to config, chosen by hierarchy and checked for\n\/\/ existence:\n\/\/\n\/\/ 1. User config (~\/.config\/podhub\/canary\/config.yaml)\n\/\/\n\/\/ 2. System config (\/etc\/podhub\/canary\/config.yaml)\nfunc (c Namespace) Path() (path string) {\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 Namespace) systemPath() (path string, err error) {\n\tpath = filepath.Join(SystemBase, c.Organization, c.System, \"config.yaml\")\n\treturn\n}\n\nfunc (c Namespace) userPath() (path string, err error) {\n\tuserBase := ExpandUser(UserBase)\n\n\tpath = filepath.Join(userBase, c.Organization, c.System, \"config.yaml\")\n\treturn\n}\n\n\/\/ EnvVar returns the name of the environment variable containing the URI\n\/\/ of the config.\n\/\/ Example: PODHUB_UUIDD_CONFIG_URI\nfunc (c Namespace) EnvVar() (envvar string) {\n\ts := []string{c.Organization, c.System, \"CONFIG\", \"URI\"}\n\tenvvar = strings.ToUpper(strings.Join(s, \"_\"))\n\treturn\n}\n\n\/\/ Load is a convenience function registered to config.Namespace to\n\/\/ implement Config.Load().\nfunc (c Namespace) Load(dst interface{}) (err error) {\n\tcfgPath := c.Path()\n\n\terr = Load(cfgPath, dst)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n)\n\ntype SLHConfig struct {\n\tSerialPort SerialPortConfig `toml:\"serialport\"`\n\tBluetooth  BluetoothConfig  `toml:\"bluetooth\"`\n\tTwitter    TwitterConfig    `toml:\"twitter\"`\n}\ntype SerialPortConfig struct {\n\tSerial string `toml:\"serial\"`\n}\ntype BluetoothConfig struct {\n\tUuid  string `toml:\"uuid\"`\n\tMajor string `toml:\"major\"`\n\tMinor string `toml:\"minor\"`\n}\ntype TwitterConfig struct {\n\tConsumerKey       string `toml:\"consumer_key\"`\n\tConsumerSecret    string `toml:\"consumer_secret\"`\n\tAccessToken       string `toml:\"access_token\"`\n\tAccessTokenSecret string `toml:\"access_token_secret\"`\n}\n\nfunc uuid() string {\n\tuuidgen, err := exec.Command(\"uuidgen\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(uuidgen[:len(uuidgen)-1])\n}\n\nfunc randomNum(i int64) string {\n\t\/\/ 0 - 65535\n\trand.Seed(time.Now().Unix() * i)\n\treturn strconv.Itoa(rand.Intn(math.MaxUint16))\n}\n\nfunc scan() string {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Scan()\n\tinput := sc.Text()\n\treturn input\n}\n\n\/\/ get config file path\nfunc getConfigPath() (string, error) {\n\t\/\/ check the home directory\n\thomeDir := \"\"\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"linux\":\n\t\thomeDir = os.Getenv(\"HOME\")\n\tdefault:\n\t\treturn \"\", errors.New(\"don't support this platform\")\n\t}\n\n\t\/\/ create the config directory\n\t\/\/ $HOME\/.config\/surelock-homes\n\tconfigDir := filepath.Join(homeDir, \".config\", \"surelock-homes\")\n\tif _, err := os.Stat(configDir); err != nil {\n\t\tif err := os.MkdirAll(configDir, 0755); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t\/\/ create the config filepath\n\tfile := filepath.Join(configDir, \"config.tml\")\n\treturn file, nil\n}\n\n\/\/ set config data\nfunc setConfig() error {\n\tvar config SLHConfig\n\n\tvar serialportConfig SerialPortConfig\n\tfmt.Printf(\"Input the serial port: \")\n\tserialportConfig.Serial = scan()\n\n\tvar bluetoothConfig BluetoothConfig\n\tbluetoothConfig.Uuid = uuid()\n\tbluetoothConfig.Major = randomNum(1)\n\tbluetoothConfig.Minor = randomNum(2)\n\n\tvar twitterConfig TwitterConfig\n\tfmt.Printf(\"Input the twitter consumer-key: \")\n\ttwitterConfig.ConsumerKey = scan()\n\tfmt.Printf(\"Input the twitter consumer-secret: \")\n\ttwitterConfig.ConsumerSecret = scan()\n\tfmt.Printf(\"Input the twitter access-token: \")\n\ttwitterConfig.AccessToken = scan()\n\tfmt.Printf(\"Input the twitter access-token-secret: \")\n\ttwitterConfig.AccessTokenSecret = scan()\n\n\tconfig.SerialPort = serialportConfig\n\tconfig.Bluetooth = bluetoothConfig\n\tconfig.Twitter = twitterConfig\n\n\tvar buffer bytes.Buffer\n\tencoder := toml.NewEncoder(&buffer)\n\tif err := encoder.Encode(config); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create the config file\n\tif file, err := getConfigPath(); err != nil {\n\t\treturn err\n\t} else {\n\t\tioutil.WriteFile(file, []byte(buffer.String()), 0755)\n\t\tfmt.Printf(\"Created: \\\"\" + file + \"\\\"\\n\\n\")\n\t\tfmt.Println(buffer.String())\n\t}\n\n\treturn nil\n}\n\n\/\/ get config data\nfunc getConfig() (SLHConfig, error) {\n\tvar config SLHConfig\n\n\tif file, err := getConfigPath(); err != nil {\n\t\treturn config, err\n\t} else {\n\t\tif _, err := toml.DecodeFile(file, &config); err != nil {\n\t\t\treturn config, err\n\t\t} else {\n\t\t\treturn config, nil\n\t\t}\n\t}\n}\n<commit_msg>add: twitter account<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n)\n\ntype SLHConfig struct {\n\tSerialPort SerialPortConfig `toml:\"serialport\"`\n\tBluetooth  BluetoothConfig  `toml:\"bluetooth\"`\n\tTwitter    TwitterConfig    `toml:\"twitter\"`\n}\ntype SerialPortConfig struct {\n\tSerial string `toml:\"serial\"`\n}\ntype BluetoothConfig struct {\n\tUuid  string `toml:\"uuid\"`\n\tMajor string `toml:\"major\"`\n\tMinor string `toml:\"minor\"`\n}\ntype TwitterConfig struct {\n\tAccount           string `toml:\"account\"`\n\tConsumerKey       string `toml:\"consumer_key\"`\n\tConsumerSecret    string `toml:\"consumer_secret\"`\n\tAccessToken       string `toml:\"access_token\"`\n\tAccessTokenSecret string `toml:\"access_token_secret\"`\n}\n\nfunc uuid() string {\n\tuuidgen, err := exec.Command(\"uuidgen\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(uuidgen[:len(uuidgen)-1])\n}\n\nfunc randomNum(i int64) string {\n\t\/\/ 0 - 65535\n\trand.Seed(time.Now().Unix() * i)\n\treturn strconv.Itoa(rand.Intn(math.MaxUint16))\n}\n\nfunc scan() string {\n\tsc := bufio.NewScanner(os.Stdin)\n\tsc.Scan()\n\tinput := sc.Text()\n\treturn input\n}\n\n\/\/ get config file path\nfunc getConfigPath() (string, error) {\n\t\/\/ check the home directory\n\thomeDir := \"\"\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"linux\":\n\t\thomeDir = os.Getenv(\"HOME\")\n\tdefault:\n\t\treturn \"\", errors.New(\"don't support this platform\")\n\t}\n\n\t\/\/ create the config directory\n\t\/\/ $HOME\/.config\/surelock-homes\n\tconfigDir := filepath.Join(homeDir, \".config\", \"surelock-homes\")\n\tif _, err := os.Stat(configDir); err != nil {\n\t\tif err := os.MkdirAll(configDir, 0755); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\t\/\/ create the config filepath\n\tfile := filepath.Join(configDir, \"config.tml\")\n\treturn file, nil\n}\n\n\/\/ set config data\nfunc setConfig() error {\n\tvar config SLHConfig\n\n\tvar serialportConfig SerialPortConfig\n\tfmt.Printf(\"Input the serial port: \")\n\tserialportConfig.Serial = scan()\n\n\tvar bluetoothConfig BluetoothConfig\n\tbluetoothConfig.Uuid = uuid()\n\tbluetoothConfig.Major = randomNum(1)\n\tbluetoothConfig.Minor = randomNum(2)\n\n\tvar twitterConfig TwitterConfig\n\tfmt.Printf(\"Input the twitter account: \")\n\ttwitterConfig.Account = scan()\n\tfmt.Printf(\"Input the twitter consumer-key: \")\n\ttwitterConfig.ConsumerKey = scan()\n\tfmt.Printf(\"Input the twitter consumer-secret: \")\n\ttwitterConfig.ConsumerSecret = scan()\n\tfmt.Printf(\"Input the twitter access-token: \")\n\ttwitterConfig.AccessToken = scan()\n\tfmt.Printf(\"Input the twitter access-token-secret: \")\n\ttwitterConfig.AccessTokenSecret = scan()\n\n\tconfig.SerialPort = serialportConfig\n\tconfig.Bluetooth = bluetoothConfig\n\tconfig.Twitter = twitterConfig\n\n\tvar buffer bytes.Buffer\n\tencoder := toml.NewEncoder(&buffer)\n\tif err := encoder.Encode(config); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create the config file\n\tif file, err := getConfigPath(); err != nil {\n\t\treturn err\n\t} else {\n\t\tioutil.WriteFile(file, []byte(buffer.String()), 0755)\n\t\tfmt.Printf(\"Created: \\\"\" + file + \"\\\"\\n\\n\")\n\t\tfmt.Println(buffer.String())\n\t}\n\n\treturn nil\n}\n\n\/\/ get config data\nfunc getConfig() (SLHConfig, error) {\n\tvar config SLHConfig\n\n\tif file, err := getConfigPath(); err != nil {\n\t\treturn config, err\n\t} else {\n\t\tif _, err := toml.DecodeFile(file, &config); err != nil {\n\t\t\treturn config, err\n\t\t} else {\n\t\t\treturn config, nil\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mitchellh\/mapstructure\"\n\t\"github.com\/papertrail\/remote_syslog2\/syslog\"\n\t\"github.com\/papertrail\/remote_syslog2\/utils\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar (\n\tconfig *viper.Viper\n\tflags  *pflag.FlagSet\n\n\tVersion string\n\n\tErrUsage = errors.New(\"usage\")\n)\n\nconst (\n\tenvPrefix         = \"remote_syslog\"\n\tdefaultConfigFile = \"\/etc\/log_files.yml\"\n)\n\n\/\/ The global Config object for remote_syslog2 server. \"mapstructure\" tags\n\/\/ signify the config file key names.\ntype Config struct {\n\tConnectTimeout       time.Duration    `mapstructure:\"connect_timeout\"`\n\tWriteTimeout         time.Duration    `mapstructure:\"write_timeout\"`\n\tNewFileCheckInterval time.Duration    `mapstructure:\"new_file_check_interval\"`\n\tExcludeFiles         []*regexp.Regexp `mapstructure:\"exclude_files\"`\n\tExcludePatterns      []*regexp.Regexp `mapstructure:\"exclude_patterns\"`\n\tLogLevels            string           `mapstructure:\"log_levels\"`\n\tDebugLogFile         string           `mapstructure:\"debug_log_file\"`\n\tPidFile              string           `mapstructure:\"pid_file\"`\n\tTcpMaxLineLength     int              `mapstructure:\"tcp_max_line_length\"`\n\tNoDetach             bool             `mapstructure:\"no_detach\"`\n\tTCP                  bool             `mapstructure:\"tcp\"`\n\tTLS                  bool             `mapstructure:\"tls\"`\n\tFiles                []LogFile\n\tHostname             string\n\tSeverity             syslog.Priority\n\tFacility             syslog.Priority\n\tPoll                 bool\n\tDestination          struct {\n\t\tHost     string\n\t\tPort     int\n\t\tProtocol string\n\t\tToken    string\n\t}\n\tRootCAs *x509.CertPool\n}\n\ntype LogFile struct {\n\tPath string\n\tTag  string\n}\n\nfunc init() {\n\tinitConfigAndFlags()\n}\n\nfunc initConfigAndFlags() {\n\tflags = pflag.NewFlagSet(envPrefix, pflag.ExitOnError)\n\n\tconfig = viper.New()\n\tconfig.SetEnvPrefix(envPrefix)\n\n\t\/\/ set defaults for configuration values that aren't provided by flags here:\n\tconfig.SetDefault(\"destination.protocol\", \"udp\")\n\tconfig.SetDefault(\"tcp_max_line_length\", 99990)\n\tconfig.SetDefault(\"debug_log_file\", \"\/dev\/null\")\n\tconfig.SetDefault(\"connect_timeout\", 30*time.Second)\n\tconfig.SetDefault(\"write_timeout\", 30*time.Second)\n\n\t\/\/ flag-only \"configuration\" values (help and version)\n\tflags.BoolP(\"help\", \"h\", false, \"Display this help message\")\n\tflags.BoolP(\"version\", \"V\", false, \"Display version and exit\")\n\n\t\/\/ set available commandline flags here:\n\tflags.StringP(\"configfile\", \"c\", defaultConfigFile, \"Path to config\")\n\tconfig.BindPFlag(\"config_file\", flags.Lookup(\"configfile\"))\n\n\tflags.StringP(\"dest-host\", \"d\", \"\", \"Destination syslog hostname or IP\")\n\tconfig.BindPFlag(\"destination.host\", flags.Lookup(\"dest-host\"))\n\n\tflags.IntP(\"dest-port\", \"p\", 514, \"Destination syslog port\")\n\tconfig.BindPFlag(\"destination.port\", flags.Lookup(\"dest-port\"))\n\n\tflags.StringP(\"dest-token\", \"t\", \"\", \"Destination ingestion token\")\n\tconfig.BindPFlag(\"destination.token\", flags.Lookup(\"dest-token\"))\n\n\tflags.StringP(\"facility\", \"f\", \"user\", \"Facility\")\n\tconfig.BindPFlag(\"facility\", flags.Lookup(\"facility\"))\n\n\thostname, _ := os.Hostname()\n\tflags.String(\"hostname\", hostname, \"Local hostname to send from\")\n\tconfig.BindPFlag(\"hostname\", flags.Lookup(\"hostname\"))\n\n\tflags.String(\"pid-file\", \"\", \"Location of the PID file\")\n\tconfig.BindPFlag(\"pid_file\", flags.Lookup(\"pid-file\"))\n\n\tflags.StringP(\"severity\", \"s\", \"notice\", \"Severity\")\n\tconfig.BindPFlag(\"severity\", flags.Lookup(\"severity\"))\n\n\tflags.Bool(\"tcp\", false, \"Connect via TCP (no TLS)\")\n\tconfig.BindPFlag(\"tcp\", flags.Lookup(\"tcp\"))\n\n\tflags.Bool(\"tls\", false, \"Connect via TCP with TLS\")\n\tconfig.BindPFlag(\"tls\", flags.Lookup(\"tls\"))\n\n\tflags.Bool(\"poll\", false, \"Detect changes by polling instead of inotify\")\n\tconfig.BindPFlag(\"poll\", flags.Lookup(\"poll\"))\n\n\tflags.Int(\"new-file-check-interval\", 10, \"How often to check for new files (seconds)\")\n\tconfig.BindPFlag(\"new_file_check_interval\", flags.Lookup(\"new-file-check-interval\"))\n\n\tflags.String(\"debug-log-cfg\", \"\", \"The debug log file; overridden by -D\/--no-detach\")\n\tconfig.BindPFlag(\"debug_log_file\", flags.Lookup(\"debug-log-cfg\"))\n\n\tflags.String(\"log\", \"<root>=INFO\", \"Set loggo config, like: --log=\\\"<root>=DEBUG\\\"\")\n\tconfig.BindPFlag(\"log_levels\", flags.Lookup(\"log\"))\n\n\t\/\/ only present this flag to systems that can daemonize\n\tif utils.CanDaemonize {\n\t\tflags.BoolP(\"no-detach\", \"D\", false, \"Don't daemonize and detach from the terminal; overrides --debug-log-cfg\")\n\t\tconfig.BindPFlag(\"no_detach\", flags.Lookup(\"no-detach\"))\n\t}\n\n\t\/\/ deprecated flags\n\tflags.Bool(\"no-eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\tflags.Bool(\"eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\n\t\/\/ bind env vars to config automatically\n\tconfig.AutomaticEnv()\n}\n\n\/\/ Read in configuration from environment, flags, and specified or default config file.\nfunc NewConfigFromEnv() (*Config, error) {\n\tif err := flags.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif h, _ := flags.GetBool(\"help\"); h {\n\t\tusage()\n\t\treturn nil, ErrUsage\n\t}\n\n\tif v, _ := flags.GetBool(\"version\"); v {\n\t\tversion()\n\t\treturn nil, ErrUsage\n\t}\n\n\tc := &Config{}\n\n\t\/\/ read in config file if it's there\n\tconfigFile := config.GetString(\"config_file\")\n\tconfig.SetConfigFile(configFile)\n\tif err := config.ReadInConfig(); err != nil && configFile != defaultConfigFile {\n\t\treturn nil, err\n\t}\n\n\t\/\/ override daemonize setting for platforms that don't support it\n\tif !utils.CanDaemonize {\n\t\tconfig.Set(\"no_daemonize\", true)\n\t}\n\n\t\/\/ unmarshal environment config into our Config object here\n\tdecoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{\n\t\tResult:           c,\n\t\tWeaklyTypedInput: true,\n\t\tDecodeHook:       decodeHook,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = decoder.Decode(config.AllSettings()); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ explicitly set destination fields since they are nested\n\tc.Destination.Host = config.GetString(\"destination.host\")\n\tc.Destination.Port = config.GetInt(\"destination.port\")\n\tc.Destination.Protocol = config.GetString(\"destination.protocol\")\n\tc.Destination.Token = config.GetString(\"destination.token\")\n\n\t\/\/ explicitly set destination protocol if we've asked for tcp or tls\n\tif c.TLS {\n\t\tc.Destination.Protocol = \"tls\"\n\t}\n\tif c.TCP {\n\t\tc.Destination.Protocol = \"tcp\"\n\t}\n\n\t\/\/ figure out where to create a pidfile if none was configured\n\tif c.PidFile == \"\" {\n\t\tc.PidFile = getPidFile()\n\t}\n\n\t\/\/ collect any extra args passed on the command line and add them to our file list\n\tfor _, file := range flags.Args() {\n\t\tfiles, err := decodeLogFiles([]interface{}{file})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc.Files = append(c.Files, files...)\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *Config) Validate() error {\n\tif c.Destination.Host == \"\" {\n\t\treturn fmt.Errorf(\"No destination hostname specified\")\n\t}\n\n\tif c.NewFileCheckInterval < 1*time.Second {\n\t\treturn fmt.Errorf(\"new_file_check_interval is too small, try setting >= 1\")\n\t}\n\n\treturn nil\n}\n\nfunc decodeDuration(f interface{}) (time.Duration, error) {\n\tvar (\n\t\ti   int\n\t\terr error\n\t)\n\n\tswitch val := f.(type) {\n\tcase string:\n\t\ti, err = strconv.Atoi(val)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\tcase int:\n\t\ti = val\n\n\tcase time.Duration:\n\t\treturn val, nil\n\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Invalid duration: %#v\", val)\n\t}\n\n\treturn time.Duration(i) * time.Second, nil\n}\n\nfunc decodeRegexps(f interface{}) ([]*regexp.Regexp, error) {\n\trs, ok := f.([]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid input type for regular expression %#v\", f)\n\t}\n\n\texps := make([]*regexp.Regexp, len(rs))\n\tfor i, r := range rs {\n\t\tstr, ok := r.(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Invalid input type for regular expression %#v\", r)\n\t\t}\n\n\t\texp, err := regexp.Compile(str)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texps[i] = exp\n\t}\n\n\treturn exps, nil\n}\n\nfunc decodeLogFiles(f interface{}) ([]LogFile, error) {\n\tvar (\n\t\tfiles []LogFile\n\t)\n\n\tvals, ok := f.([]interface{})\n\tif !ok {\n\t\treturn files, fmt.Errorf(\"Invalid input type for files: %#v\", f)\n\t}\n\n\tfor _, v := range vals {\n\t\tswitch val := v.(type) {\n\t\tcase string:\n\t\t\tlf := strings.Split(val, \"=\")\n\t\t\tswitch len(lf) {\n\t\t\tcase 2:\n\t\t\t\tfiles = append(files, LogFile{Tag: lf[0], Path: lf[1]})\n\t\t\tcase 1:\n\t\t\t\tfiles = append(files, LogFile{Path: val})\n\t\t\tdefault:\n\t\t\t\treturn files, fmt.Errorf(\"Invalid log file name %s\", val)\n\t\t\t}\n\n\t\tcase map[interface{}]interface{}:\n\t\t\tvar (\n\t\t\t\ttag  string\n\t\t\t\tpath string\n\t\t\t)\n\n\t\t\ttag, _ = val[\"tag\"].(string)\n\t\t\tpath, _ = val[\"path\"].(string)\n\n\t\t\tif path == \"\" {\n\t\t\t\treturn files, fmt.Errorf(\"Invalid log file %#v\", val)\n\t\t\t}\n\n\t\t\tfiles = append(files, LogFile{Tag: tag, Path: path})\n\n\t\tdefault:\n\t\t\tpanic(vals)\n\t\t}\n\t}\n\n\treturn files, nil\n}\n\nfunc decodePriority(p interface{}) (interface{}, error) {\n\tps, ok := p.(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid priority: %#v\", p)\n\t}\n\n\tpri, err := syslog.Severity(ps)\n\tif err == nil {\n\t\treturn pri, nil\n\t}\n\n\t\/\/ if it's not a severity, try facility\n\tpri, err = syslog.Facility(ps)\n\tif err == nil {\n\t\treturn pri, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"%s: %s\", err.Error(), ps)\n}\n\nfunc decodeHook(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {\n\tswitch to {\n\tcase reflect.TypeOf([]LogFile{}):\n\t\treturn decodeLogFiles(data)\n\tcase reflect.TypeOf([]*regexp.Regexp{}):\n\t\treturn decodeRegexps(data)\n\tcase reflect.TypeOf(syslog.Priority(0)):\n\t\treturn decodePriority(data)\n\tcase reflect.TypeOf(time.Duration(0)):\n\t\treturn decodeDuration(data)\n\t}\n\n\treturn data, nil\n}\n\nfunc getPidFile() 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\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\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\n\t\treturn f\n\t}\n\n\treturn \"\/tmp\/remote_syslog.pid\"\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of %s %s:\\n\", envPrefix, Version)\n\tflags.PrintDefaults()\n}\n\nfunc version() {\n\tfmt.Fprintf(os.Stderr, \"%s %s\\n\", envPrefix, Version)\n}\n<commit_msg>Fix panic: cannot daemonize on windows<commit_after>package main\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mitchellh\/mapstructure\"\n\t\"github.com\/papertrail\/remote_syslog2\/syslog\"\n\t\"github.com\/papertrail\/remote_syslog2\/utils\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar (\n\tconfig *viper.Viper\n\tflags  *pflag.FlagSet\n\n\tVersion string\n\n\tErrUsage = errors.New(\"usage\")\n)\n\nconst (\n\tenvPrefix         = \"remote_syslog\"\n\tdefaultConfigFile = \"\/etc\/log_files.yml\"\n)\n\n\/\/ The global Config object for remote_syslog2 server. \"mapstructure\" tags\n\/\/ signify the config file key names.\ntype Config struct {\n\tConnectTimeout       time.Duration    `mapstructure:\"connect_timeout\"`\n\tWriteTimeout         time.Duration    `mapstructure:\"write_timeout\"`\n\tNewFileCheckInterval time.Duration    `mapstructure:\"new_file_check_interval\"`\n\tExcludeFiles         []*regexp.Regexp `mapstructure:\"exclude_files\"`\n\tExcludePatterns      []*regexp.Regexp `mapstructure:\"exclude_patterns\"`\n\tLogLevels            string           `mapstructure:\"log_levels\"`\n\tDebugLogFile         string           `mapstructure:\"debug_log_file\"`\n\tPidFile              string           `mapstructure:\"pid_file\"`\n\tTcpMaxLineLength     int              `mapstructure:\"tcp_max_line_length\"`\n\tNoDetach             bool             `mapstructure:\"no_detach\"`\n\tTCP                  bool             `mapstructure:\"tcp\"`\n\tTLS                  bool             `mapstructure:\"tls\"`\n\tFiles                []LogFile\n\tHostname             string\n\tSeverity             syslog.Priority\n\tFacility             syslog.Priority\n\tPoll                 bool\n\tDestination          struct {\n\t\tHost     string\n\t\tPort     int\n\t\tProtocol string\n\t\tToken    string\n\t}\n\tRootCAs *x509.CertPool\n}\n\ntype LogFile struct {\n\tPath string\n\tTag  string\n}\n\nfunc init() {\n\tinitConfigAndFlags()\n}\n\nfunc initConfigAndFlags() {\n\tflags = pflag.NewFlagSet(envPrefix, pflag.ExitOnError)\n\n\tconfig = viper.New()\n\tconfig.SetEnvPrefix(envPrefix)\n\n\t\/\/ set defaults for configuration values that aren't provided by flags here:\n\tconfig.SetDefault(\"destination.protocol\", \"udp\")\n\tconfig.SetDefault(\"tcp_max_line_length\", 99990)\n\tconfig.SetDefault(\"debug_log_file\", \"\/dev\/null\")\n\tconfig.SetDefault(\"connect_timeout\", 30*time.Second)\n\tconfig.SetDefault(\"write_timeout\", 30*time.Second)\n\n\t\/\/ flag-only \"configuration\" values (help and version)\n\tflags.BoolP(\"help\", \"h\", false, \"Display this help message\")\n\tflags.BoolP(\"version\", \"V\", false, \"Display version and exit\")\n\n\t\/\/ set available commandline flags here:\n\tflags.StringP(\"configfile\", \"c\", defaultConfigFile, \"Path to config\")\n\tconfig.BindPFlag(\"config_file\", flags.Lookup(\"configfile\"))\n\n\tflags.StringP(\"dest-host\", \"d\", \"\", \"Destination syslog hostname or IP\")\n\tconfig.BindPFlag(\"destination.host\", flags.Lookup(\"dest-host\"))\n\n\tflags.IntP(\"dest-port\", \"p\", 514, \"Destination syslog port\")\n\tconfig.BindPFlag(\"destination.port\", flags.Lookup(\"dest-port\"))\n\n\tflags.StringP(\"dest-token\", \"t\", \"\", \"Destination ingestion token\")\n\tconfig.BindPFlag(\"destination.token\", flags.Lookup(\"dest-token\"))\n\n\tflags.StringP(\"facility\", \"f\", \"user\", \"Facility\")\n\tconfig.BindPFlag(\"facility\", flags.Lookup(\"facility\"))\n\n\thostname, _ := os.Hostname()\n\tflags.String(\"hostname\", hostname, \"Local hostname to send from\")\n\tconfig.BindPFlag(\"hostname\", flags.Lookup(\"hostname\"))\n\n\tflags.String(\"pid-file\", \"\", \"Location of the PID file\")\n\tconfig.BindPFlag(\"pid_file\", flags.Lookup(\"pid-file\"))\n\n\tflags.StringP(\"severity\", \"s\", \"notice\", \"Severity\")\n\tconfig.BindPFlag(\"severity\", flags.Lookup(\"severity\"))\n\n\tflags.Bool(\"tcp\", false, \"Connect via TCP (no TLS)\")\n\tconfig.BindPFlag(\"tcp\", flags.Lookup(\"tcp\"))\n\n\tflags.Bool(\"tls\", false, \"Connect via TCP with TLS\")\n\tconfig.BindPFlag(\"tls\", flags.Lookup(\"tls\"))\n\n\tflags.Bool(\"poll\", false, \"Detect changes by polling instead of inotify\")\n\tconfig.BindPFlag(\"poll\", flags.Lookup(\"poll\"))\n\n\tflags.Int(\"new-file-check-interval\", 10, \"How often to check for new files (seconds)\")\n\tconfig.BindPFlag(\"new_file_check_interval\", flags.Lookup(\"new-file-check-interval\"))\n\n\tflags.String(\"debug-log-cfg\", \"\", \"The debug log file; overridden by -D\/--no-detach\")\n\tconfig.BindPFlag(\"debug_log_file\", flags.Lookup(\"debug-log-cfg\"))\n\n\tflags.String(\"log\", \"<root>=INFO\", \"Set loggo config, like: --log=\\\"<root>=DEBUG\\\"\")\n\tconfig.BindPFlag(\"log_levels\", flags.Lookup(\"log\"))\n\n\t\/\/ only present this flag to systems that can daemonize\n\tif utils.CanDaemonize {\n\t\tflags.BoolP(\"no-detach\", \"D\", false, \"Don't daemonize and detach from the terminal; overrides --debug-log-cfg\")\n\t\tconfig.BindPFlag(\"no_detach\", flags.Lookup(\"no-detach\"))\n\t}\n\n\t\/\/ deprecated flags\n\tflags.Bool(\"no-eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\tflags.Bool(\"eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\n\t\/\/ bind env vars to config automatically\n\tconfig.AutomaticEnv()\n}\n\n\/\/ Read in configuration from environment, flags, and specified or default config file.\nfunc NewConfigFromEnv() (*Config, error) {\n\tif err := flags.Parse(os.Args[1:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif h, _ := flags.GetBool(\"help\"); h {\n\t\tusage()\n\t\treturn nil, ErrUsage\n\t}\n\n\tif v, _ := flags.GetBool(\"version\"); v {\n\t\tversion()\n\t\treturn nil, ErrUsage\n\t}\n\n\tc := &Config{}\n\n\t\/\/ read in config file if it's there\n\tconfigFile := config.GetString(\"config_file\")\n\tconfig.SetConfigFile(configFile)\n\tif err := config.ReadInConfig(); err != nil && configFile != defaultConfigFile {\n\t\treturn nil, err\n\t}\n\n\t\/\/ override daemonize setting for platforms that don't support it\n\tif !utils.CanDaemonize {\n\t\tconfig.Set(\"no_detach\", true)\n\t}\n\n\t\/\/ unmarshal environment config into our Config object here\n\tdecoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{\n\t\tResult:           c,\n\t\tWeaklyTypedInput: true,\n\t\tDecodeHook:       decodeHook,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = decoder.Decode(config.AllSettings()); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ explicitly set destination fields since they are nested\n\tc.Destination.Host = config.GetString(\"destination.host\")\n\tc.Destination.Port = config.GetInt(\"destination.port\")\n\tc.Destination.Protocol = config.GetString(\"destination.protocol\")\n\tc.Destination.Token = config.GetString(\"destination.token\")\n\n\t\/\/ explicitly set destination protocol if we've asked for tcp or tls\n\tif c.TLS {\n\t\tc.Destination.Protocol = \"tls\"\n\t}\n\tif c.TCP {\n\t\tc.Destination.Protocol = \"tcp\"\n\t}\n\n\t\/\/ figure out where to create a pidfile if none was configured\n\tif c.PidFile == \"\" {\n\t\tc.PidFile = getPidFile()\n\t}\n\n\t\/\/ collect any extra args passed on the command line and add them to our file list\n\tfor _, file := range flags.Args() {\n\t\tfiles, err := decodeLogFiles([]interface{}{file})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc.Files = append(c.Files, files...)\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *Config) Validate() error {\n\tif c.Destination.Host == \"\" {\n\t\treturn fmt.Errorf(\"No destination hostname specified\")\n\t}\n\n\tif c.NewFileCheckInterval < 1*time.Second {\n\t\treturn fmt.Errorf(\"new_file_check_interval is too small, try setting >= 1\")\n\t}\n\n\treturn nil\n}\n\nfunc decodeDuration(f interface{}) (time.Duration, error) {\n\tvar (\n\t\ti   int\n\t\terr error\n\t)\n\n\tswitch val := f.(type) {\n\tcase string:\n\t\ti, err = strconv.Atoi(val)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\tcase int:\n\t\ti = val\n\n\tcase time.Duration:\n\t\treturn val, nil\n\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Invalid duration: %#v\", val)\n\t}\n\n\treturn time.Duration(i) * time.Second, nil\n}\n\nfunc decodeRegexps(f interface{}) ([]*regexp.Regexp, error) {\n\trs, ok := f.([]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid input type for regular expression %#v\", f)\n\t}\n\n\texps := make([]*regexp.Regexp, len(rs))\n\tfor i, r := range rs {\n\t\tstr, ok := r.(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Invalid input type for regular expression %#v\", r)\n\t\t}\n\n\t\texp, err := regexp.Compile(str)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\texps[i] = exp\n\t}\n\n\treturn exps, nil\n}\n\nfunc decodeLogFiles(f interface{}) ([]LogFile, error) {\n\tvar (\n\t\tfiles []LogFile\n\t)\n\n\tvals, ok := f.([]interface{})\n\tif !ok {\n\t\treturn files, fmt.Errorf(\"Invalid input type for files: %#v\", f)\n\t}\n\n\tfor _, v := range vals {\n\t\tswitch val := v.(type) {\n\t\tcase string:\n\t\t\tlf := strings.Split(val, \"=\")\n\t\t\tswitch len(lf) {\n\t\t\tcase 2:\n\t\t\t\tfiles = append(files, LogFile{Tag: lf[0], Path: lf[1]})\n\t\t\tcase 1:\n\t\t\t\tfiles = append(files, LogFile{Path: val})\n\t\t\tdefault:\n\t\t\t\treturn files, fmt.Errorf(\"Invalid log file name %s\", val)\n\t\t\t}\n\n\t\tcase map[interface{}]interface{}:\n\t\t\tvar (\n\t\t\t\ttag  string\n\t\t\t\tpath string\n\t\t\t)\n\n\t\t\ttag, _ = val[\"tag\"].(string)\n\t\t\tpath, _ = val[\"path\"].(string)\n\n\t\t\tif path == \"\" {\n\t\t\t\treturn files, fmt.Errorf(\"Invalid log file %#v\", val)\n\t\t\t}\n\n\t\t\tfiles = append(files, LogFile{Tag: tag, Path: path})\n\n\t\tdefault:\n\t\t\tpanic(vals)\n\t\t}\n\t}\n\n\treturn files, nil\n}\n\nfunc decodePriority(p interface{}) (interface{}, error) {\n\tps, ok := p.(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Invalid priority: %#v\", p)\n\t}\n\n\tpri, err := syslog.Severity(ps)\n\tif err == nil {\n\t\treturn pri, nil\n\t}\n\n\t\/\/ if it's not a severity, try facility\n\tpri, err = syslog.Facility(ps)\n\tif err == nil {\n\t\treturn pri, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"%s: %s\", err.Error(), ps)\n}\n\nfunc decodeHook(from reflect.Type, to reflect.Type, data interface{}) (interface{}, error) {\n\tswitch to {\n\tcase reflect.TypeOf([]LogFile{}):\n\t\treturn decodeLogFiles(data)\n\tcase reflect.TypeOf([]*regexp.Regexp{}):\n\t\treturn decodeRegexps(data)\n\tcase reflect.TypeOf(syslog.Priority(0)):\n\t\treturn decodePriority(data)\n\tcase reflect.TypeOf(time.Duration(0)):\n\t\treturn decodeDuration(data)\n\t}\n\n\treturn data, nil\n}\n\nfunc getPidFile() 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\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\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\n\t\treturn f\n\t}\n\n\treturn \"\/tmp\/remote_syslog.pid\"\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage of %s %s:\\n\", envPrefix, Version)\n\tflags.PrintDefaults()\n}\n\nfunc version() {\n\tfmt.Fprintf(os.Stderr, \"%s %s\\n\", envPrefix, Version)\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"strconv\"\n\t\"os\"\n\t\"io\"\n\t\"context\"\n)\n\ntype Config map[string]interface{}\n\n\/\/ GetString return string config value\nfunc (conf Config) GetString(path string) string {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Если строка, то это результат\n\tswitch val := result.(type) {\n\tcase string: return val\n\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n\/\/ GetArray return array config value\nfunc (conf Config) GetArray(path string) []interface{} {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn []interface{}{}\n\t}\n\n\tswitch val := result.(type) {\n\tcase []interface{}: return val\n\n\tdefault:\n\t\treturn []interface{}{}\n\t}\n}\n\n\/\/ GetBool return bool config value\nfunc (conf Config) GetBool(path string) bool {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn false\n\t}\n\n\tswitch val := result.(type) {\n\tcase bool: return val\n\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ GetInt return int64 config value. It may be in hex & oct variants\nfunc (conf Config) GetInt(path string) int64 {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn 0\n\t}\n\n\tswitch val := result.(type) {\n\tcase int: return int64(val)\n\tcase int64: return val\n\tcase json.Number:\n\t\tif res, err := strconv.ParseInt(string(val), 0, 64); err != nil {\n\t\t\treturn 0\n\t\t} else {\n\t\t\treturn res\n\t\t}\n\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\/\/ GetFloat64 return float64 config value\nfunc (conf Config) GetFloat64(path string) float64 {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn 0\n\t}\n\n\tswitch val := result.(type) {\n\tcase float64: return val\n\tcase int: return float64(val)\n\tcase int64: return float64(val)\n\tcase json.Number:\n\t\tif res, err := strconv.ParseFloat(string(val), 64); err != nil {\n\t\t\treturn 0\n\t\t} else {\n\t\t\treturn res\n\t\t}\n\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\/\/ Get return config value by dotted path in json tree. Path should be like this \"root.option.item\"\nfunc (conf Config) Get(path string) interface{} {\n\titems := strings.Split(path, \".\")\n\n\tidx := 0\n\tvalue := map[string]interface{}(conf)\n\n\t\/\/ Перебор до предпоследнего элемента\n\tfor idx < len(items) - 1 {\n\t\ttmp, ok := value[items[idx]]\n\t\tif !ok {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tvalue = tmp.(map[string]interface{})\n\t\tidx++\n\t}\n\n\t\/\/ Последний элемент\n\treturn value[items[idx]]\n}\n\n\/\/ New create config from file\nfunc New(filename string) Config {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn NewFromIO(file)\n}\n\n\/\/ NewFromIO create config from io.Reader\nfunc NewFromIO(input io.Reader) Config {\n\tdecoder := json.NewDecoder(input)\n\tdecoder.UseNumber()\n\n\tres := make(Config)\n\tif err := decoder.Decode(&res); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn res\n}\n\ntype key int\n\nconst keyConfig key = iota\n\n\/\/ NewContext create new context with config\nfunc NewContext(ctx context.Context, filename string) context.Context {\n\treturn context.WithValue(ctx, keyConfig, New(filename))\n}\n\n\/\/ FromContext return config from context\nfunc FromContext(ctx context.Context) (Config, bool) {\n\tvalue, ok := ctx.Value(keyConfig).(Config)\n\treturn value, ok\n}<commit_msg>New returns error<commit_after>package config\n\nimport (\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"strconv\"\n\t\"os\"\n\t\"io\"\n\t\"context\"\n)\n\ntype Config map[string]interface{}\n\n\/\/ GetString return string config value\nfunc (conf Config) GetString(path string) string {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Если строка, то это результат\n\tswitch val := result.(type) {\n\tcase string: return val\n\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n\/\/ GetArray return array config value\nfunc (conf Config) GetArray(path string) []interface{} {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn []interface{}{}\n\t}\n\n\tswitch val := result.(type) {\n\tcase []interface{}: return val\n\n\tdefault:\n\t\treturn []interface{}{}\n\t}\n}\n\n\/\/ GetBool return bool config value\nfunc (conf Config) GetBool(path string) bool {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn false\n\t}\n\n\tswitch val := result.(type) {\n\tcase bool: return val\n\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ GetInt return int64 config value. It may be in hex & oct variants\nfunc (conf Config) GetInt(path string) int64 {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn 0\n\t}\n\n\tswitch val := result.(type) {\n\tcase int: return int64(val)\n\tcase int64: return val\n\tcase json.Number:\n\t\tif res, err := strconv.ParseInt(string(val), 0, 64); err != nil {\n\t\t\treturn 0\n\t\t} else {\n\t\t\treturn res\n\t\t}\n\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\/\/ GetFloat64 return float64 config value\nfunc (conf Config) GetFloat64(path string) float64 {\n\n\tresult := conf.Get(path)\n\tif result == nil {\n\t\treturn 0\n\t}\n\n\tswitch val := result.(type) {\n\tcase float64: return val\n\tcase int: return float64(val)\n\tcase int64: return float64(val)\n\tcase json.Number:\n\t\tif res, err := strconv.ParseFloat(string(val), 64); err != nil {\n\t\t\treturn 0\n\t\t} else {\n\t\t\treturn res\n\t\t}\n\n\tdefault:\n\t\treturn 0\n\t}\n}\n\n\/\/ Get return config value by dotted path in json tree. Path should be like this \"root.option.item\"\nfunc (conf Config) Get(path string) interface{} {\n\titems := strings.Split(path, \".\")\n\n\tidx := 0\n\tvalue := map[string]interface{}(conf)\n\n\t\/\/ Перебор до предпоследнего элемента\n\tfor idx < len(items) - 1 {\n\t\ttmp, ok := value[items[idx]]\n\t\tif !ok {\n\t\t\treturn \"\"\n\t\t}\n\n\t\tvalue = tmp.(map[string]interface{})\n\t\tidx++\n\t}\n\n\t\/\/ Последний элемент\n\treturn value[items[idx]]\n}\n\n\/\/ New create config from file\nfunc New(filename string) (*Config, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewFromIO(file), nil\n}\n\n\/\/ NewFromIO create config from io.Reader\nfunc NewFromIO(input io.Reader) *Config {\n\tdecoder := json.NewDecoder(input)\n\tdecoder.UseNumber()\n\n\tres := new(Config)\n\tif err := decoder.Decode(res); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn res\n}\n\ntype key int\n\nconst keyConfig key = iota\n\n\/\/ NewContext create new context with config\nfunc NewContext(ctx context.Context, filename string) (context.Context, error) {\n\tif conf, err := New(filename); err != nil {\n\t\treturn ctx, err\n\t} else {\n\t\treturn context.WithValue(ctx, keyConfig, conf), nil\n\t}\n}\n\n\/\/ FromContext return config from context\nfunc FromContext(ctx context.Context) (*Config, bool) {\n\tvalue, ok := ctx.Value(keyConfig).(*Config)\n\treturn value, ok\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 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 resourcemgr\n\nimport (\n\t\"context\"\n\n\tapi \"github.com\/projectcalico\/libcalico-go\/lib\/apis\/v2\"\n\tclient \"github.com\/projectcalico\/libcalico-go\/lib\/clientv2\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/options\"\n)\n\nfunc init() {\n\tregisterResource(\n\t\tapi.NewBGPConfiguration(),\n\t\tapi.NewBGPConfigurationList(),\n\t\tfalse,\n\t\t[]string{\"bgpconfiguration\", \"bgpconfigurations\", \"bgpconfig\", \"bgpconfigs\"},\n\t\t[]string{\"NAME\", \"LOGSEVERITY\", \"MESHENABLED\", \"DEFAULTASN\"},\n\t\t[]string{\"NAME\", \"LOGSEVERITY\", \"MESHENABLED\", \"DEFAULTASN\"},\n\t\tmap[string]string{\n\t\t\t\"NAME\":        \"{{.ObjectMeta.Name}}\",\n\t\t\t\"LOGSEVERITY\": \"{{.Spec.LogSeverityScreen}}\",\n\t\t\t\"MESHENABLED\": \"{{if .Spec.NodeToNodeMeshEnabled}}{{.Spec.NodeToNodeMeshEnabled}}{{ else }}-{{ end }}\",\n\t\t\t\"DEFAULTASN\":  \"{{if .Spec.DefaultNodeASNumber}}{{.Spec.DefaultNodeASNumber}}{{ else }}-{{ end }}\",\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Create(ctx, r, options.SetOptions{})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Update(ctx, r, options.SetOptions{})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Delete(ctx, r.Name, options.DeleteOptions{ResourceVersion: r.ResourceVersion})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Get(ctx, r.Name, options.GetOptions{ResourceVersion: r.ResourceVersion})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceListObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().List(ctx, options.ListOptions{ResourceVersion: r.ResourceVersion, Name: r.Name})\n\t\t},\n\t)\n}\n<commit_msg>bugfix: calicoctl get bgpconfig command panics<commit_after>\/\/ Copyright (c) 2017 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 resourcemgr\n\nimport (\n\t\"context\"\n\n\tapi \"github.com\/projectcalico\/libcalico-go\/lib\/apis\/v2\"\n\tclient \"github.com\/projectcalico\/libcalico-go\/lib\/clientv2\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/options\"\n)\n\nfunc init() {\n\tregisterResource(\n\t\tapi.NewBGPConfiguration(),\n\t\tapi.NewBGPConfigurationList(),\n\t\tfalse,\n\t\t[]string{\"bgpconfiguration\", \"bgpconfigurations\", \"bgpconfig\", \"bgpconfigs\"},\n\t\t[]string{\"NAME\", \"LOGSEVERITY\", \"MESHENABLED\", \"ASNUMBER\"},\n\t\t[]string{\"NAME\", \"LOGSEVERITY\", \"MESHENABLED\", \"ASNUMBER\"},\n\t\tmap[string]string{\n\t\t\t\"NAME\":        \"{{.ObjectMeta.Name}}\",\n\t\t\t\"LOGSEVERITY\": \"{{.Spec.LogSeverityScreen}}\",\n\t\t\t\"MESHENABLED\": \"{{if .Spec.NodeToNodeMeshEnabled}}{{.Spec.NodeToNodeMeshEnabled}}{{ else }}-{{ end }}\",\n\t\t\t\"ASNUMBER\":  \"{{if .Spec.ASNumber}}{{.Spec.ASNumber}}{{ else }}-{{ end }}\",\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Create(ctx, r, options.SetOptions{})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Update(ctx, r, options.SetOptions{})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Delete(ctx, r.Name, options.DeleteOptions{ResourceVersion: r.ResourceVersion})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().Get(ctx, r.Name, options.GetOptions{ResourceVersion: r.ResourceVersion})\n\t\t},\n\t\tfunc(ctx context.Context, client client.Interface, resource ResourceObject) (ResourceListObject, error) {\n\t\t\tr := resource.(*api.BGPConfiguration)\n\t\t\treturn client.BGPConfigurations().List(ctx, options.ListOptions{ResourceVersion: r.ResourceVersion, Name: r.Name})\n\t\t},\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package storagenode\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/jacksontj\/dataman\/src\/query\"\n\t\"github.com\/jacksontj\/dataman\/src\/metadata\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\ntype HTTPApi struct {\n\tstorageNode *StorageNode\n}\n\nfunc NewHTTPApi(storageNode *StorageNode) *HTTPApi {\n\tapi := &HTTPApi{\n\t\tstorageNode: storageNode,\n\t}\n\n\treturn api\n}\n\n\/\/ Register any endpoints to the router\nfunc (h *HTTPApi) Start(router *httprouter.Router) {\n\trouter.POST(\"\/v1\/data\/raw\", h.rawQueryHandler)\n}\n\n\/\/ TODO: streaming parser\nfunc (h *HTTPApi) rawQueryHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tdefer r.Body.Close()\n\tbytes, _ := ioutil.ReadAll(r.Body)\n\n\tvar queries []map[query.QueryType]query.QueryArgs\n\n\tif err := json.Unmarshal(bytes, &queries); err != nil {\n\t\t\/\/ TODO: correct status code, 4xx for invalid request\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\t\/\/ At this point we have a list of queries that we need to do, so lets do it\n\t\t\/\/ TODO: we should actually do these in parallel (potentially with some\n\t\t\/\/ config of *how* parallel)\n\t\tresults := make([]*query.Result, len(queries))\n\n\t\t\/\/ We specifically want to load this once for the batch so we don't have mixed\n\t\t\/\/ schema information across this batch of queries\n\t\tmeta := h.storageNode.Meta.Load().(*metadata.Meta)\n\n\t\tfor i, queryMap := range queries {\n\t\t\t\/\/ We only allow a single method to be defined per item\n\t\t\tif len(queryMap) == 1 {\n\t\t\t\tfor queryType, queryArgs := range queryMap {\n\t\t\t\t\t\/\/ Verify that the table is within our domain\n\t\t\t\t\tif _, err := meta.GetTable(queryArgs[\"db\"].(string), queryArgs[\"table\"].(string)); err != nil {\n\t\t\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\t\t\tError: err.Error(),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ TODO: have a map or some other switch from query -> interface?\n\t\t\t\t\t\/\/ This will need to get more complex as we support multiple\n\t\t\t\t\t\/\/ storage interfaces\n\t\t\t\t\tswitch queryType {\n\t\t\t\t\tcase query.Get:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Get(queryArgs)\n\t\t\t\t\tcase query.Set:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Set(queryArgs)\n\t\t\t\t\tcase query.Filter:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Filter(queryArgs)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\t\t\tError: \"Unsupported query type \" + string(queryType),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\tError: \"Only one QueryType supported per query\",\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Now we need to return the results\n\t\tif bytes, err := json.Marshal(results); err != nil {\n\t\t\t\/\/ TODO: log this better?\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write(bytes)\n\t\t}\n\t}\n}\n<commit_msg>Notes to self<commit_after>package storagenode\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/jacksontj\/dataman\/src\/query\"\n\t\"github.com\/jacksontj\/dataman\/src\/metadata\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\ntype HTTPApi struct {\n\tstorageNode *StorageNode\n}\n\nfunc NewHTTPApi(storageNode *StorageNode) *HTTPApi {\n\tapi := &HTTPApi{\n\t\tstorageNode: storageNode,\n\t}\n\n\treturn api\n}\n\n\/\/ REST API methods:\n\/\/ \t GET - READ\/list\n\/\/\t PUT - UPDATE\n\/\/   POST - CREATE\n\/\/   DELETE - DELETE\n\/\/ Register any endpoints to the router\nfunc (h *HTTPApi) Start(router *httprouter.Router) {\n\trouter.POST(\"\/v1\/data\/raw\", h.rawQueryHandler)\n}\n\n\/\/ TODO: streaming parser\nfunc (h *HTTPApi) rawQueryHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tdefer r.Body.Close()\n\tbytes, _ := ioutil.ReadAll(r.Body)\n\n\tvar queries []map[query.QueryType]query.QueryArgs\n\n\tif err := json.Unmarshal(bytes, &queries); err != nil {\n\t\t\/\/ TODO: correct status code, 4xx for invalid request\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t} else {\n\t\t\/\/ At this point we have a list of queries that we need to do, so lets do it\n\t\t\/\/ TODO: we should actually do these in parallel (potentially with some\n\t\t\/\/ config of *how* parallel)\n\t\tresults := make([]*query.Result, len(queries))\n\n\t\t\/\/ We specifically want to load this once for the batch so we don't have mixed\n\t\t\/\/ schema information across this batch of queries\n\t\tmeta := h.storageNode.Meta.Load().(*metadata.Meta)\n\n\t\tfor i, queryMap := range queries {\n\t\t\t\/\/ We only allow a single method to be defined per item\n\t\t\tif len(queryMap) == 1 {\n\t\t\t\tfor queryType, queryArgs := range queryMap {\n\t\t\t\t\t\/\/ Verify that the table is within our domain\n\t\t\t\t\tif _, err := meta.GetTable(queryArgs[\"db\"].(string), queryArgs[\"table\"].(string)); err != nil {\n\t\t\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\t\t\tError: err.Error(),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ TODO: have a map or some other switch from query -> interface?\n\t\t\t\t\t\/\/ This will need to get more complex as we support multiple\n\t\t\t\t\t\/\/ storage interfaces\n\t\t\t\t\tswitch queryType {\n\t\t\t\t\tcase query.Get:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Get(queryArgs)\n\t\t\t\t\tcase query.Set:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Set(queryArgs)\n\t\t\t\t\tcase query.Filter:\n\t\t\t\t\t\tresults[i] = h.storageNode.Store.Filter(queryArgs)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\t\t\tError: \"Unsupported query type \" + string(queryType),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tresults[i] = &query.Result{\n\t\t\t\t\tError: \"Only one QueryType supported per query\",\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Now we need to return the results\n\t\tif bytes, err := json.Marshal(results); err != nil {\n\t\t\t\/\/ TODO: log this better?\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t} else {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write(bytes)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\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\/kinesis\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsKinesisStream() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsKinesisStreamCreate,\n\t\tRead:   resourceAwsKinesisStreamRead,\n\t\tUpdate: resourceAwsKinesisStreamUpdate,\n\t\tDelete: resourceAwsKinesisStreamDelete,\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\n\t\t\t\"shard_count\": &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\n\t\t\t\"arn\": &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\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsKinesisStreamCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\tcreateOpts := &kinesis.CreateStreamInput{\n\t\tShardCount: aws.Int64(int64(d.Get(\"shard_count\").(int))),\n\t\tStreamName: aws.String(sn),\n\t}\n\n\t_, err := conn.CreateStream(createOpts)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\treturn fmt.Errorf(\"[WARN] Error creating Kinesis Stream: \\\"%s\\\", code: \\\"%s\\\"\", awsErr.Message(), awsErr.Code())\n\t\t}\n\t\treturn err\n\t}\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"CREATING\"},\n\t\tTarget:     \"ACTIVE\",\n\t\tRefresh:    streamStateRefreshFunc(conn, sn),\n\t\tTimeout:    5 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tstreamRaw, err := stateConf.WaitForState()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for Kinesis Stream (%s) to become active: %s\",\n\t\t\tsn, err)\n\t}\n\n\ts := streamRaw.(*kinesis.StreamDescription)\n\td.SetId(*s.StreamARN)\n\td.Set(\"arn\", s.StreamARN)\n\n\treturn resourceAwsKinesisStreamUpdate(d, meta)\n}\n\nfunc resourceAwsKinesisStreamUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\n\td.Partial(true)\n\tif err := setTagsKinesis(conn, d); err != nil {\n\t\treturn err\n\t}\n\n\td.SetPartial(\"tags\")\n\td.Partial(false)\n\n\treturn resourceAwsKinesisStreamRead(d, meta)\n}\n\nfunc resourceAwsKinesisStreamRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\tdescribeOpts := &kinesis.DescribeStreamInput{\n\t\tStreamName: aws.String(sn),\n\t}\n\tresp, err := conn.DescribeStream(describeOpts)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\tif awsErr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\td.SetId(\"\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"[WARN] Error reading Kinesis Stream: \\\"%s\\\", code: \\\"%s\\\"\", awsErr.Message(), awsErr.Code())\n\t\t}\n\t\treturn err\n\t}\n\n\ts := resp.StreamDescription\n\td.Set(\"arn\", *s.StreamARN)\n\td.Set(\"shard_count\", len(s.Shards))\n\n\t\/\/ set tags\n\tdescribeTagsOpts := &kinesis.ListTagsForStreamInput{\n\t\tStreamName: aws.String(sn),\n\t}\n\ttagsResp, err := conn.ListTagsForStream(describeTagsOpts)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error retrieving tags for Stream: %s. %s\", sn, err)\n\t} else {\n\t\td.Set(\"tags\", tagsToMapKinesis(tagsResp.Tags))\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsKinesisStreamDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\t_, err := conn.DeleteStream(&kinesis.DeleteStreamInput{\n\t\tStreamName: aws.String(sn),\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"DELETING\"},\n\t\tTarget:     \"DESTROYED\",\n\t\tRefresh:    streamStateRefreshFunc(conn, sn),\n\t\tTimeout:    5 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, err = stateConf.WaitForState()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for Stream (%s) to be destroyed: %s\",\n\t\t\tsn, err)\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc streamStateRefreshFunc(conn *kinesis.Kinesis, sn string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tdescribeOpts := &kinesis.DescribeStreamInput{\n\t\t\tStreamName: aws.String(sn),\n\t\t}\n\t\tresp, err := conn.DescribeStream(describeOpts)\n\t\tif err != nil {\n\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\tif awsErr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\t\treturn 42, \"DESTROYED\", nil\n\t\t\t\t}\n\t\t\t\treturn nil, awsErr.Code(), err\n\t\t\t}\n\t\t\treturn nil, \"failed\", err\n\t\t}\n\n\t\treturn resp.StreamDescription, *resp.StreamDescription.StreamStatus, nil\n\t}\n}\n<commit_msg>provider\/aws: Kinesis DescribeStream pagination<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\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\/kinesis\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsKinesisStream() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsKinesisStreamCreate,\n\t\tRead:   resourceAwsKinesisStreamRead,\n\t\tUpdate: resourceAwsKinesisStreamUpdate,\n\t\tDelete: resourceAwsKinesisStreamDelete,\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\n\t\t\t\"shard_count\": &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\n\t\t\t\"arn\": &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\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsKinesisStreamCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\tcreateOpts := &kinesis.CreateStreamInput{\n\t\tShardCount: aws.Int64(int64(d.Get(\"shard_count\").(int))),\n\t\tStreamName: aws.String(sn),\n\t}\n\n\t_, err := conn.CreateStream(createOpts)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\treturn fmt.Errorf(\"[WARN] Error creating Kinesis Stream: \\\"%s\\\", code: \\\"%s\\\"\", awsErr.Message(), awsErr.Code())\n\t\t}\n\t\treturn err\n\t}\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"CREATING\"},\n\t\tTarget:     \"ACTIVE\",\n\t\tRefresh:    streamStateRefreshFunc(conn, sn),\n\t\tTimeout:    5 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tstreamRaw, err := stateConf.WaitForState()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for Kinesis Stream (%s) to become active: %s\",\n\t\t\tsn, err)\n\t}\n\n\ts := streamRaw.(kinesisStreamState)\n\td.SetId(s.arn)\n\td.Set(\"arn\", s.arn)\n\td.Set(\"shard_count\", s.shardCount)\n\n\treturn resourceAwsKinesisStreamUpdate(d, meta)\n}\n\nfunc resourceAwsKinesisStreamUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\n\td.Partial(true)\n\tif err := setTagsKinesis(conn, d); err != nil {\n\t\treturn err\n\t}\n\n\td.SetPartial(\"tags\")\n\td.Partial(false)\n\n\treturn resourceAwsKinesisStreamRead(d, meta)\n}\n\nfunc resourceAwsKinesisStreamRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\n\tstate, err := readKinesisStreamState(conn, sn)\n\tif err != nil {\n\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\tif awsErr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\td.SetId(\"\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"[WARN] Error reading Kinesis Stream: \\\"%s\\\", code: \\\"%s\\\"\", awsErr.Message(), awsErr.Code())\n\t\t}\n\t\treturn err\n\n\t}\n\td.Set(\"arn\", state.arn)\n\td.Set(\"shard_count\", state.shardCount)\n\n\t\/\/ set tags\n\tdescribeTagsOpts := &kinesis.ListTagsForStreamInput{\n\t\tStreamName: aws.String(sn),\n\t}\n\ttagsResp, err := conn.ListTagsForStream(describeTagsOpts)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error retrieving tags for Stream: %s. %s\", sn, err)\n\t} else {\n\t\td.Set(\"tags\", tagsToMapKinesis(tagsResp.Tags))\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsKinesisStreamDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).kinesisconn\n\tsn := d.Get(\"name\").(string)\n\t_, err := conn.DeleteStream(&kinesis.DeleteStreamInput{\n\t\tStreamName: aws.String(sn),\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"DELETING\"},\n\t\tTarget:     \"DESTROYED\",\n\t\tRefresh:    streamStateRefreshFunc(conn, sn),\n\t\tTimeout:    5 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, err = stateConf.WaitForState()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for Stream (%s) to be destroyed: %s\",\n\t\t\tsn, err)\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n\ntype kinesisStreamState struct {\n\tarn        string\n\tstatus     string\n\tshardCount int\n}\n\nfunc readKinesisStreamState(conn *kinesis.Kinesis, sn string) (kinesisStreamState, error) {\n\tdescribeOpts := &kinesis.DescribeStreamInput{\n\t\tStreamName: aws.String(sn),\n\t}\n\n\tvar state kinesisStreamState\n\terr := conn.DescribeStreamPages(describeOpts, func(page *kinesis.DescribeStreamOutput, last bool) (shouldContinue bool) {\n\t\tstate.arn = aws.StringValue(page.StreamDescription.StreamARN)\n\t\tstate.status = aws.StringValue(page.StreamDescription.StreamStatus)\n\t\tstate.shardCount += len(page.StreamDescription.Shards)\n\t\treturn !last\n\t})\n\treturn state, err\n}\n\nfunc streamStateRefreshFunc(conn *kinesis.Kinesis, sn string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tstate, err := readKinesisStreamState(conn, sn)\n\t\tif err != nil {\n\t\t\tif awsErr, ok := err.(awserr.Error); ok {\n\t\t\t\tif awsErr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\t\treturn 42, \"DESTROYED\", nil\n\t\t\t\t}\n\t\t\t\treturn nil, awsErr.Code(), err\n\t\t\t}\n\t\t\treturn nil, \"failed\", err\n\t\t}\n\n\t\treturn state, state.status, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package redis\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/go-redis\/redis\/v8\/internal\/pool\"\n\t\"github.com\/go-redis\/redis\/v8\/internal\/proto\"\n)\n\n\/\/ ErrClosed performs any operation on the closed client will return this error.\nvar ErrClosed = pool.ErrClosed\n\ntype Error interface {\n\terror\n\n\t\/\/ RedisError is a no-op function but\n\t\/\/ serves to distinguish types that are Redis\n\t\/\/ errors from ordinary errors: a type is a\n\t\/\/ Redis error if it has a RedisError method.\n\tRedisError()\n}\n\nvar _ Error = proto.RedisError(\"\")\n\nfunc shouldRetry(err error, retryTimeout bool) bool {\n\tswitch err {\n\tcase io.EOF, io.ErrUnexpectedEOF:\n\t\treturn true\n\tcase nil, context.Canceled, context.DeadlineExceeded:\n\t\treturn false\n\t}\n\n\tif v, ok := err.(timeoutError); ok {\n\t\tif v.Timeout() {\n\t\t\treturn retryTimeout\n\t\t}\n\t\treturn true\n\t}\n\n\ts := err.Error()\n\tif s == \"ERR max number of clients reached\" {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"LOADING \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"READONLY \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"CLUSTERDOWN \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"TRYAGAIN \") {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isRedisError(err error) bool {\n\t_, ok := err.(proto.RedisError)\n\treturn ok\n}\n\nfunc isBadConn(err error, allowTimeout bool, addr string) bool {\n\tswitch err {\n\tcase nil:\n\t\treturn false\n\tcase context.Canceled, context.DeadlineExceeded:\n\t\treturn true\n\t}\n\n\tif isRedisError(err) {\n\t\tswitch {\n\t\tcase isReadOnlyError(err):\n\t\t\t\/\/ Close connections in read only state in case domain addr is used\n\t\t\t\/\/ and domain resolves to a different Redis Server. See #790.\n\t\t\treturn true\n\t\tcase isMovedSameConnAddr(err, addr):\n\t\t\t\/\/ Close connections when we are asked to move to the same addr\n\t\t\t\/\/ of the connection. Force a DNS resolution when all connections\n\t\t\t\/\/ of the pool are recycled\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif allowTimeout {\n\t\tif netErr, ok := err.(net.Error); ok && netErr.Timeout() {\n\t\t\treturn !netErr.Temporary()\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc isMovedError(err error) (moved bool, ask bool, addr string) {\n\tif !isRedisError(err) {\n\t\treturn\n\t}\n\n\ts := err.Error()\n\tswitch {\n\tcase strings.HasPrefix(s, \"MOVED \"):\n\t\tmoved = true\n\tcase strings.HasPrefix(s, \"ASK \"):\n\t\task = true\n\tdefault:\n\t\treturn\n\t}\n\n\tind := strings.LastIndex(s, \" \")\n\tif ind == -1 {\n\t\treturn false, false, \"\"\n\t}\n\taddr = s[ind+1:]\n\treturn\n}\n\nfunc isLoadingError(err error) bool {\n\treturn strings.HasPrefix(err.Error(), \"LOADING \")\n}\n\nfunc isReadOnlyError(err error) bool {\n\treturn strings.HasPrefix(err.Error(), \"READONLY \")\n}\n\nfunc isMovedSameConnAddr(err error, addr string) bool {\n\tredisError := err.Error()\n\tif !strings.HasPrefix(redisError, \"MOVED \") {\n\t\treturn false\n\t}\n\treturn strings.HasSuffix(redisError, \" \"+addr)\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype timeoutError interface {\n\tTimeout() bool\n}\n<commit_msg>chore: fix golangci-lint<commit_after>package redis\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/go-redis\/redis\/v8\/internal\/pool\"\n\t\"github.com\/go-redis\/redis\/v8\/internal\/proto\"\n)\n\n\/\/ ErrClosed performs any operation on the closed client will return this error.\nvar ErrClosed = pool.ErrClosed\n\ntype Error interface {\n\terror\n\n\t\/\/ RedisError is a no-op function but\n\t\/\/ serves to distinguish types that are Redis\n\t\/\/ errors from ordinary errors: a type is a\n\t\/\/ Redis error if it has a RedisError method.\n\tRedisError()\n}\n\nvar _ Error = proto.RedisError(\"\")\n\nfunc shouldRetry(err error, retryTimeout bool) bool {\n\tswitch err {\n\tcase io.EOF, io.ErrUnexpectedEOF:\n\t\treturn true\n\tcase nil, context.Canceled, context.DeadlineExceeded:\n\t\treturn false\n\t}\n\n\tif v, ok := err.(timeoutError); ok {\n\t\tif v.Timeout() {\n\t\t\treturn retryTimeout\n\t\t}\n\t\treturn true\n\t}\n\n\ts := err.Error()\n\tif s == \"ERR max number of clients reached\" {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"LOADING \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"READONLY \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"CLUSTERDOWN \") {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(s, \"TRYAGAIN \") {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isRedisError(err error) bool {\n\t_, ok := err.(proto.RedisError)\n\treturn ok\n}\n\nfunc isBadConn(err error, allowTimeout bool, addr string) bool {\n\tswitch err {\n\tcase nil:\n\t\treturn false\n\tcase context.Canceled, context.DeadlineExceeded:\n\t\treturn true\n\t}\n\n\tif isRedisError(err) {\n\t\tswitch {\n\t\tcase isReadOnlyError(err):\n\t\t\t\/\/ Close connections in read only state in case domain addr is used\n\t\t\t\/\/ and domain resolves to a different Redis Server. See #790.\n\t\t\treturn true\n\t\tcase isMovedSameConnAddr(err, addr):\n\t\t\t\/\/ Close connections when we are asked to move to the same addr\n\t\t\t\/\/ of the connection. Force a DNS resolution when all connections\n\t\t\t\/\/ of the pool are recycled\n\t\t\treturn true\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n\n\tif allowTimeout {\n\t\tif netErr, ok := err.(net.Error); ok && netErr.Timeout() {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc isMovedError(err error) (moved bool, ask bool, addr string) {\n\tif !isRedisError(err) {\n\t\treturn\n\t}\n\n\ts := err.Error()\n\tswitch {\n\tcase strings.HasPrefix(s, \"MOVED \"):\n\t\tmoved = true\n\tcase strings.HasPrefix(s, \"ASK \"):\n\t\task = true\n\tdefault:\n\t\treturn\n\t}\n\n\tind := strings.LastIndex(s, \" \")\n\tif ind == -1 {\n\t\treturn false, false, \"\"\n\t}\n\taddr = s[ind+1:]\n\treturn\n}\n\nfunc isLoadingError(err error) bool {\n\treturn strings.HasPrefix(err.Error(), \"LOADING \")\n}\n\nfunc isReadOnlyError(err error) bool {\n\treturn strings.HasPrefix(err.Error(), \"READONLY \")\n}\n\nfunc isMovedSameConnAddr(err error, addr string) bool {\n\tredisError := err.Error()\n\tif !strings.HasPrefix(redisError, \"MOVED \") {\n\t\treturn false\n\t}\n\treturn strings.HasSuffix(redisError, \" \"+addr)\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype timeoutError interface {\n\tTimeout() bool\n}\n<|endoftext|>"}
{"text":"<commit_before>package calendar\n\n\/\/ locale: en_US\n\n\/\/ NOTE: Work in progress!\n\n\/\/ Anything that's specific to the US, with the exception of some movable dates which are in movable.go\n\/\/ This calendar has a corresponding locale code in the NewCalendar function in calendar.go\n\nimport (\n\t\"time\"\n)\n\ntype USCalendar struct{}\n\n\/\/ Create a new US calendar\nfunc NewUSCalendar() USCalendar {\n\treturn USCalendar{}\n}\n\n\/\/ Finds the US name for a day of the week.\n\/\/ Note that time.Weekday starts at 0 with Sunday, not Monday.\nfunc (nc USCalendar) DayName(day time.Weekday) string {\n\treturn day.String()\n}\n\n\/\/ Finds the US name for a given month\nfunc (nc USCalendar) MonthName(month time.Month) string {\n\treturn month.String()\n}\n\n\/\/ Checks if a given date is a \"red day\" (public holiday) in the US calendar.\n\/\/ Returns true\/false, a description and true\/false for if it's a flag day.\n\/\/ The dates will never overlap.\nfunc (nc USCalendar) RedDay(date time.Time) (bool, string, bool) {\n\n\t\/\/ Source: http:\/\/en.wikipedia.org\/wiki\/Public_holidays_in_the_United_States\n\t\/\/ Source: http:\/\/timpanogos.wordpress.com\/flag-fly-dates\/\n\n\tvar (\n\t\tdesc string\n\t\tflag bool\n\t)\n\n\t\/\/ Sundays\n\tif date.Weekday() == time.Sunday {\n\t\tdesc = \"Sunday\"\n\t}\n\n\t\/\/ Election Day\n\tif atElectionDay(date) {\n\t\tdesc = \"Election Day\"\n\t\tflag = false\n\t}\n\n\t\/\/ New Year's Day\n\tif atMD(date, 1, 1) {\n\t\tdesc = \"New Year's Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Birthday of Dr. Martin Luther King, Jr.\n\tif atNthWeekdayOfMonth(date, 3, time.Monday, time.January) {\n\t\tdesc = \"Martin Luther King Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Inauguration Day\n\tif atInaugurationDay(date) {\n\t\tdesc = \"Inauguration Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Lincoln's birthday\n\tif atMD(date, 2, 12) {\n\t\tdesc = \"Lincoln's birthday\"\n\t\tflag = true\n\t}\n\n\t\/\/ Washington's Birthday \/ Presidents' Day\n\tif atNthWeekdayOfMonth(date, 3, time.Monday, time.February) {\n\t\tdesc = \"Presidents' Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Armed Forces Day\n\tif atNthWeekdayOfMonth(date, 3, time.Saturday, time.May) {\n\t\tdesc = \"Armed Forces Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Memorial Day\n\tif atLastWeekday(date, time.Monday, time.May) {\n\t\tdesc = \"Memorial Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ 4th of July\n\tif atMD(date, 7, 4) {\n\t\tdesc = \"Independence Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Labor Day\n\tif atNthWeekdayOfMonth(date, 1, time.Monday, time.September) {\n\t\tdesc = \"Labor Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Columbus Day\n\tif atNthWeekdayOfMonth(date, 2, time.Monday, time.October) {\n\t\tdesc = \"Columbus Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Veterans Day\n\tif atMD(date, 11, 11) {\n\t\tdesc = \"Veterans Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Thanksgiving Day\n\tif atNthWeekdayOfMonth(date, 4, time.Thursday, time.November) {\n\t\tdesc = \"Thanksgiving Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Christmas\n\tif atMD(date, 12, 25) {\n\t\tdesc = \"Christmas Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Red days\n\tif desc != \"\" {\n\t\t\/\/ Then return\n\t\treturn true, desc, flag\n\t}\n\n\t\/\/ Normal days\n\treturn false, desc, false\n}\n\n\/\/ Some days are not red, but special in one way or another.\n\/\/ Checks if a given date is notable. Returns true\/false if the\n\/\/ given date is notable, a comma separated description (in case there are more\n\/\/ than one notable event that day) and true\/false depending on if it's a flag\n\/\/ flying day or not.\nfunc (nc USCalendar) NotableDay(date time.Time) (bool, string, bool) {\n\n\tvar (\n\t\/\/descriptions []string\n\t\/\/flag         bool\n\t)\n\n\t\/\/ Since days may overlap, \"flaggdager\" must come first for the flag\n\t\/\/ flying days to be correct.\n\n\t\/\/ --- Flag days ---\n\n\t\/\/ --- Non-flag days ---\n\n\t\/\/ No notable events\n\treturn false, \"\", false\n}\n\n\/\/ Checks if a given date is in a notable time range (summer holidays, for instance)\nfunc (nc USCalendar) NotablePeriod(date time.Time) (bool, string) {\n\t\/\/ TODO:\n\t\/\/ christmas time\n\t\/\/ summer\/winter\/spring\/autumn time\n\t\/\/ etc\n\treturn false, \"\"\n}\n\n\/\/ An ordinary day\nfunc (nc USCalendar) NormalDay() string {\n\treturn \"Ordinary\"\n}\n<commit_msg>Better comments<commit_after>package calendar\n\n\/\/ locale: en_US\n\n\/\/ NOTE: Work in progress!\n\n\/\/ Anything that's specific to the US, with the exception of some movable dates which are in movable.go\n\/\/ This calendar has a corresponding locale code in the NewCalendar function in calendar.go\n\nimport (\n\t\"time\"\n)\n\ntype USCalendar struct{}\n\n\/\/ Create a new US calendar\nfunc NewUSCalendar() USCalendar {\n\treturn USCalendar{}\n}\n\n\/\/ Finds the US name for a day of the week.\n\/\/ Note that time.Weekday starts at 0 with Sunday, not Monday.\nfunc (nc USCalendar) DayName(day time.Weekday) string {\n\treturn day.String()\n}\n\n\/\/ Finds the US name for a given month\nfunc (nc USCalendar) MonthName(month time.Month) string {\n\treturn month.String()\n}\n\n\/\/ Checks if a given date is a \"red day\" (public holiday) in the US calendar.\n\/\/ Returns true\/false, a description and true\/false for if it's a flag day.\n\/\/ The dates will never overlap.\nfunc (nc USCalendar) RedDay(date time.Time) (bool, string, bool) {\n\n\t\/\/ Source: http:\/\/en.wikipedia.org\/wiki\/Public_holidays_in_the_United_States\n\t\/\/ Source: http:\/\/timpanogos.wordpress.com\/flag-fly-dates\/\n\n\tvar (\n\t\tdesc string\n\t\tflag bool\n\t)\n\n\t\/\/ Sundays\n\tif date.Weekday() == time.Sunday {\n\t\tdesc = \"Sunday\"\n\t}\n\n\t\/\/ Election Day\n\tif atElectionDay(date) {\n\t\tdesc = \"Election Day\"\n\t\tflag = false\n\t}\n\n\t\/\/ New Year's Day\n\tif atMD(date, 1, 1) {\n\t\tdesc = \"New Year's Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Birthday of Dr. Martin Luther King, Jr.\n\tif atNthWeekdayOfMonth(date, 3, time.Monday, time.January) {\n\t\tdesc = \"Martin Luther King Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Inauguration Day\n\tif atInaugurationDay(date) {\n\t\tdesc = \"Inauguration Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Lincoln's birthday\n\tif atMD(date, 2, 12) {\n\t\tdesc = \"Lincoln's birthday\"\n\t\tflag = true\n\t}\n\n\t\/\/ Washington's Birthday \/ Presidents' Day\n\tif atNthWeekdayOfMonth(date, 3, time.Monday, time.February) {\n\t\tdesc = \"Presidents' Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Armed Forces Day\n\tif atNthWeekdayOfMonth(date, 3, time.Saturday, time.May) {\n\t\tdesc = \"Armed Forces Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Memorial Day\n\tif atLastWeekday(date, time.Monday, time.May) {\n\t\tdesc = \"Memorial Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ 4th of July\n\tif atMD(date, 7, 4) {\n\t\tdesc = \"Independence Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Labor Day\n\tif atNthWeekdayOfMonth(date, 1, time.Monday, time.September) {\n\t\tdesc = \"Labor Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Columbus Day\n\tif atNthWeekdayOfMonth(date, 2, time.Monday, time.October) {\n\t\tdesc = \"Columbus Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Veterans Day\n\tif atMD(date, 11, 11) {\n\t\tdesc = \"Veterans Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Thanksgiving Day\n\tif atNthWeekdayOfMonth(date, 4, time.Thursday, time.November) {\n\t\tdesc = \"Thanksgiving Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Christmas\n\tif atMD(date, 12, 25) {\n\t\tdesc = \"Christmas Day\"\n\t\tflag = true\n\t}\n\n\t\/\/ Red days\n\tif desc != \"\" {\n\t\t\/\/ Then return\n\t\treturn true, desc, flag\n\t}\n\n\t\/\/ Normal days\n\treturn false, desc, false\n}\n\n\/\/ Some days are not red, but special in one way or another.\n\/\/ Checks if a given date is notable. Returns true\/false if the\n\/\/ given date is notable, a comma separated description (in case there are more\n\/\/ than one notable event that day) and true\/false depending on if it's a flag\n\/\/ flying day or not.\nfunc (nc USCalendar) NotableDay(date time.Time) (bool, string, bool) {\n\n\tvar (\n\t\/\/descriptions []string\n\t\/\/flag         bool\n\t)\n\n\t\/\/ Since days may overlap, flag flying days must come first.\n\n\t\/\/ --- Flag flying days ---\n\n\t\/\/ --- Other days ---\n\n\t\/\/ No notable events\n\treturn false, \"\", false\n}\n\n\/\/ Checks if a given date is in a notable time range (summer holidays, for instance)\nfunc (nc USCalendar) NotablePeriod(date time.Time) (bool, string) {\n\t\/\/ TODO:\n\t\/\/ Christmas time\n\t\/\/ summer\/winter\/spring\/autumn time\n\t\/\/ etc\n\treturn false, \"\"\n}\n\n\/\/ An ordinary day\nfunc (nc USCalendar) NormalDay() string {\n\treturn \"Ordinary\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package video\n\nimport \"github.com\/32bitkid\/bitreader\"\n\ntype GroupOfPicturesHeader struct {\n\ttimeCode   uint32 \/\/ 25 bslbf\n\tClosedGOP  bool   \/\/ 1 uimsbf\n\tBrokenLink bool   \/\/ 1 uimsbf\n}\n\n\/\/ ReadGOPHeader parses a group_of_pictures header from the given bitstream.\nfunc ReadGOPHeader(br bitreader.BitReader) (*GroupOfPicturesHeader, error) {\n\tif err := GroupStartCode.Assert(br); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgoph := GroupOfPicturesHeader{}\n\n\tif time_code, err := br.Read32(25); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.timeCode = time_code\n\t}\n\n\tif closed_gop, err := br.ReadBit(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.ClosedGOP = closed_gop\n\t}\n\n\tif broken_link, err := br.ReadBit(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.BrokenLink = broken_link\n\t}\n\n\treturn &goph, next_start_code(br)\n}\n\n\/\/ TimeCode represents the associated time code with the first picture following the\n\/\/ Group of Pictures header with a TemporalReference = 0. DropFrame will only be true\n\/\/ if the desired framerate is 29.97Hz.\n\/\/\n\/\/ TimeCode appears in the bitstream as a 25-bit integer that has the following layout:\n\/\/\n\/\/  ├1b┤\n\/\/  ┌──┬──────────────────┬──────────────────────┬──┬──────────────────────┬──────────────────────┐\n\/\/  │DF│Hours             │Minutes               │MB│Seconds               │Pictures              │\n\/\/  └──┴──────────────────┴──────────────────────┴──┴──────────────────────┴──────────────────────┘\n\/\/  ├───────────────────────────────────────────25 bits───────────────────────────────────────────┤\ntype TimeCode struct {\n\tDropFrame bool\n\tHours     int\n\tMinutes   int\n\tSeconds   int\n\tPictures  int\n}\n\n\/\/ Returns a parsed TimeCode from the raw GOP header data.\nfunc (gop *GroupOfPicturesHeader) TimeCode() TimeCode {\n\treturn TimeCode{\n\t\tDropFrame: (gop.timeCode >> 24) == 1,\n\t\tHours:     (gop.timeCode >> 19) & 0x1F,\n\t\tMinutes:   (gop.timeCode >> 13) & 0x3F,\n\t\tSeconds:   (gop.timeCode >> 6) & 0x3F,\n\t\tPictures:  (gop.timeCode) & 0x3F,\n\t}\n}\n<commit_msg>updating documentation.<commit_after>package video\n\nimport \"github.com\/32bitkid\/bitreader\"\nimport \"fmt\"\n\ntype GroupOfPicturesHeader struct {\n\ttimeCode   int32 \/\/ 25 bslbf\n\tClosedGOP  bool  \/\/ 1 uimsbf\n\tBrokenLink bool  \/\/ 1 uimsbf\n}\n\n\/\/ ReadGOPHeader parses a group_of_pictures header from the given bitstream.\nfunc ReadGOPHeader(br bitreader.BitReader) (*GroupOfPicturesHeader, error) {\n\tif err := GroupStartCode.Assert(br); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgoph := GroupOfPicturesHeader{}\n\n\tif time_code, err := br.Read32(25); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.timeCode = int32(time_code)\n\t}\n\n\tif closed_gop, err := br.ReadBit(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.ClosedGOP = closed_gop\n\t}\n\n\tif broken_link, err := br.ReadBit(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tgoph.BrokenLink = broken_link\n\t}\n\n\treturn &goph, next_start_code(br)\n}\n\n\/\/ Returns a parsed TimeCode from the raw GOP header data.\nfunc (gop *GroupOfPicturesHeader) TimeCode() TimeCode {\n\treturn TimeCode{\n\t\tDropFrame: (gop.timeCode >> 24) == 1,\n\t\tHours:     (gop.timeCode >> 19) & 0x1F,\n\t\tMinutes:   (gop.timeCode >> 13) & 0x3F,\n\t\tSeconds:   (gop.timeCode >> 6) & 0x3F,\n\t\tPictures:  (gop.timeCode) & 0x3F,\n\t}\n}\n\n\/\/ TimeCode represents the associated time code with the first picture following the\n\/\/ Group of Pictures header with a TemporalReference = 0. DropFrame will only be true\n\/\/ if the desired framerate is 29.97Hz.\n\/\/\n\/\/ TimeCode appears in the bitstream as a 25-bit integer that has the following layout:\n\/\/\n\/\/  ┌──┬──────────────────┬──────────────────────┬──┬──────────────────────┬──────────────────────┐\n\/\/  │DF│Hours             │Minutes               │MB│Seconds               │Pictures              │\n\/\/  └──┴──────────────────┴──────────────────────┴──┴──────────────────────┴──────────────────────┘\n\/\/  ├───────────────────────────────────────────25 bits───────────────────────────────────────────┤\ntype TimeCode struct {\n\tDropFrame bool  \/\/ 1-bit\n\tHours     int32 \/\/ 5-bit\n\tMinutes   int32 \/\/ 6-bit\n\tSeconds   int32 \/\/ 6-bit\n\tPictures  int32 \/\/ 6-bit\n}\n\n\/\/ String formats the time code as a string in SMPTE format: \"HH:MM:SS:FF\". If the timecode is\n\/\/ in drop frame, then the separator between seconds and frames is replaced with a \";\" character.\nfunc (tc TimeCode) String() string {\n\tsecondsFramesSep := \":\"\n\tif tc.DropFrame {\n\t\tsecondsFramesSep = \";\"\n\t}\n\treturn fmt.Sprintf(\"%d:%02d:%02d%s%02d\", tc.Hours, tc.Minutes, tc.Seconds, secondsFramesSep, tc.Pictures)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/Microsoft\/hcsshim\/internal\/wclayer\"\n\t\"github.com\/urfave\/cli\"\n)\n\nconst (\n\tdirArgName = \"dir\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"zapdir\"\n\tapp.Usage = \"Delete a directory\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  dirArgName,\n\t\t\tValue: \"\",\n\t\t\tUsage: \"Directory to delete\",\n\t\t},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\t\tdir := c.String(dirArgName)\n\n\t\tif dir == \"\" {\n\t\t\treturn errors.New(\"dir must be supplied\")\n\t\t}\n\n\t\t\/\/ DestroyLayer requires an absolute path.\n\t\tdir, err := filepath.Abs(dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := os.Stat(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := wclayer.DestroyLayer(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n}\n<commit_msg>Improve zapdir error reporting<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/Microsoft\/hcsshim\/internal\/wclayer\"\n\t\"github.com\/urfave\/cli\"\n)\n\nconst (\n\tdirArgName = \"dir\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"zapdir\"\n\tapp.Usage = \"Delete a directory\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  dirArgName,\n\t\t\tValue: \"\",\n\t\t\tUsage: \"Directory to delete\",\n\t\t},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\t\tdir := c.String(dirArgName)\n\n\t\tif dir == \"\" {\n\t\t\treturn errors.New(\"dir must be supplied\")\n\t\t}\n\n\t\t\/\/ DestroyLayer requires an absolute path.\n\t\tdir, err := filepath.Abs(dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err := os.Stat(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := wclayer.DestroyLayer(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tfmt.Fprintln(cli.ErrWriter, err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ttlstore\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/orian\/utils\/ptime\"\n\n\t\"container\/heap\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype actionTimestamp struct {\n\tKey           interface{}\n\tTimestmapNsec int64\n}\n\ntype ActionTimestmapHeap []*actionTimestamp\n\nfunc (h ActionTimestmapHeap) Len() int { return len(h) }\nfunc (h ActionTimestmapHeap) Less(i, j int) bool {\n\treturn h[i].TimestmapNsec > h[j].TimestmapNsec\n}\nfunc (h ActionTimestmapHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *ActionTimestmapHeap) Push(x interface{}) {\n\t\/\/ Push and Pop use pointer receivers because they modify the slice's length,\n\t\/\/ not just its contents.\n\t*h = append(*h, x.(*actionTimestamp))\n}\n\nfunc (h *ActionTimestmapHeap) Pop() interface{} {\n\told := *h\n\tn := len(old) - 1\n\tx := old[n]\n\told[n] = nil\n\t*h = old[0:n]\n\treturn x\n}\n\ntype DeleteHook func(key interface{})\n\ntype Deleter struct {\n\tc          chan *actionTimestamp\n\tDeleteFunc DeleteHook\n\tInterval   time.Duration\n\tName       string\n\n\tlastActionTimestamp map[interface{}]int64\n\tmaxAge              time.Duration\n\tkeepNum             int\n\n\tm        *sync.Mutex\n\tend      chan bool\n\tfinished chan bool\n\tlogger   logrus.FieldLogger\n}\n\nvar _ Janitor = &Deleter{}\n\nfunc NewDeleter(name string, del DeleteHook, maxAge, runInterval time.Duration, bufSize, keep int,\n\tlogger logrus.FieldLogger) *Deleter {\n\n\tif logger == nil {\n\t\tlogger = logrus.New()\n\t\tlogger.Out = ioutil.Discard\n\t}\n\n\treturn &Deleter{\n\t\tmake(chan *actionTimestamp, bufSize),\n\t\tdel,\n\t\trunInterval,\n\t\tname,\n\t\tmake(map[interface{}]int64),\n\t\tmaxAge,\n\t\tkeep,\n\t\t&sync.Mutex{},\n\t\tmake(chan bool, 1),\n\t\tmake(chan bool, 2),\n\t\tlogger,\n\t}\n}\n\nfunc (d *Deleter) Set(key interface{}, insert time.Time) {\n\td.c <- &actionTimestamp{key, insert.UnixNano()}\n}\n\ntype DeleterProvider func(name string, hook DeleteHook) *Deleter\n\nfunc NewDeleterProvider(maxAge, interval time.Duration, bufSize, keep int) DeleterProvider {\n\treturn func(name string, del DeleteHook) *Deleter {\n\t\treturn NewDeleter(name, del, maxAge, interval, bufSize, keep)\n\t}\n}\n\nfunc (d *Deleter) DeleteTooOld() {\n\tnum := 0\n\tthresholdUsec := time.Now().Add(-d.maxAge).UnixNano()\n\tt := ptime.NewTimer()\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tfor k, v := range d.lastActionTimestamp {\n\t\tif v < thresholdUsec {\n\t\t\tif d.DeleteFunc != nil {\n\t\t\t\td.DeleteFunc(k)\n\t\t\t}\n\t\t\tdelete(d.lastActionTimestamp, k)\n\t\t\tnum++\n\t\t}\n\t}\n\td.logger.Infof(\"[%s] deleted %d too old (%s) items, kept %d, took: %s\",\n\t\td.Name, num, d.maxAge, len(d.lastActionTimestamp), t.Duration())\n}\n\nfunc (d *Deleter) deleteUntilBelowMaxUuid() {\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tl := len(d.lastActionTimestamp)\n\tif l < int(float32(d.keepNum)*1.1) {\n\t\treturn\n\t}\n\n\tt := ptime.NewTimer()\n\tnum := 0\n\th := &ActionTimestmapHeap{}\n\tnumToRemove := len(d.lastActionTimestamp) - d.keepNum\n\tinitDone := false\n\tfor k, v := range d.lastActionTimestamp {\n\t\theap.Push(h, &actionTimestamp{k, v})\n\t\tif initDone {\n\t\t\theap.Pop(h)\n\t\t} else if h.Len() >= numToRemove {\n\t\t\theap.Init(h)\n\t\t\tinitDone = true\n\t\t}\n\t}\n\n\tfor i := h.Len(); i > 0; i-- {\n\t\ta := heap.Pop(h).(*actionTimestamp)\n\t\tif d.DeleteFunc != nil {\n\t\t\td.DeleteFunc(a.Key)\n\t\t}\n\t\tdelete(d.lastActionTimestamp, a.Key)\n\t\tnum++\n\t}\n\td.logger.Infof(\"[%s] deleted %d items because too many, kept: %d, took: %s\",\n\t\td.Name, num, len(d.lastActionTimestamp), t.Duration())\n}\n\nfunc (d *Deleter) Process() {\n\td.logger.Infof(\"[%s] process started\", d.Name)\n\tfor t := range d.c {\n\t\td.m.Lock()\n\t\tif v := d.lastActionTimestamp[t.Key]; v < t.TimestmapNsec {\n\t\t\td.lastActionTimestamp[t.Key] = t.TimestmapNsec\n\t\t}\n\t\td.m.Unlock()\n\t}\n\td.finished <- true\n\td.logger.Infof(\"[%s] process finished\", d.Name)\n}\n\nfunc (d *Deleter) Deleting() {\n\td.logger.Infof(\"[%s] deleting started\", d.Name)\n\ttmr := time.NewTicker(d.Interval)\n\tfor {\n\t\tselect {\n\t\tcase <-d.end:\n\t\t\tgoto end\n\t\tcase <-tmr.C:\n\t\t\td.DeleteTooOld()\n\t\t\td.deleteUntilBelowMaxUuid()\n\t\t}\n\t}\nend:\n\ttmr.Stop()\n\td.finished <- true\n\td.logger.Infof(\"[%s] deleting finished\", d.Name)\n}\n\nfunc (d *Deleter) Start() {\n\tgo d.Deleting()\n\td.Process()\n}\n\nfunc (d *Deleter) Stop() {\n\tclose(d.c)\n\td.end <- true\n\t<-d.finished\n\t<-d.finished\n}\n<commit_msg>fix provider and ifc<commit_after>package ttlstore\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/orian\/utils\/ptime\"\n\n\t\"container\/heap\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype actionTimestamp struct {\n\tKey           interface{}\n\tTimestmapNsec int64\n}\n\ntype ActionTimestmapHeap []*actionTimestamp\n\nfunc (h ActionTimestmapHeap) Len() int { return len(h) }\nfunc (h ActionTimestmapHeap) Less(i, j int) bool {\n\treturn h[i].TimestmapNsec > h[j].TimestmapNsec\n}\nfunc (h ActionTimestmapHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *ActionTimestmapHeap) Push(x interface{}) {\n\t\/\/ Push and Pop use pointer receivers because they modify the slice's length,\n\t\/\/ not just its contents.\n\t*h = append(*h, x.(*actionTimestamp))\n}\n\nfunc (h *ActionTimestmapHeap) Pop() interface{} {\n\told := *h\n\tn := len(old) - 1\n\tx := old[n]\n\told[n] = nil\n\t*h = old[0:n]\n\treturn x\n}\n\ntype DeleteHook func(key interface{})\n\ntype Deleter struct {\n\tc          chan *actionTimestamp\n\tDeleteFunc DeleteHook\n\tInterval   time.Duration\n\tName       string\n\n\tlastActionTimestamp map[interface{}]int64\n\tmaxAge              time.Duration\n\tkeepNum             int\n\n\tm        *sync.Mutex\n\tend      chan bool\n\tfinished chan bool\n\tlogger   logrus.FieldLogger\n}\n\nvar _ Janitor = &Deleter{}\n\nfunc NewDeleter(name string, del DeleteHook, maxAge, runInterval time.Duration, bufSize, keep int,\n\tlogger logrus.FieldLogger) *Deleter {\n\n\tif logger == nil {\n\t\tl := logrus.New()\n\t\tl.Out = ioutil.Discard\n\t\tlogger = l\n\t}\n\n\treturn &Deleter{\n\t\tmake(chan *actionTimestamp, bufSize),\n\t\tdel,\n\t\trunInterval,\n\t\tname,\n\t\tmake(map[interface{}]int64),\n\t\tmaxAge,\n\t\tkeep,\n\t\t&sync.Mutex{},\n\t\tmake(chan bool, 1),\n\t\tmake(chan bool, 2),\n\t\tlogger,\n\t}\n}\n\nfunc (d *Deleter) Set(key interface{}, insert time.Time) {\n\td.c <- &actionTimestamp{key, insert.UnixNano()}\n}\n\ntype DeleterProvider func(name string, hook DeleteHook) *Deleter\n\nfunc NewDeleterProvider(maxAge, interval time.Duration, bufSize, keep int) DeleterProvider {\n\treturn func(name string, del DeleteHook) *Deleter {\n\t\treturn NewDeleter(name, del, maxAge, interval, bufSize, keep, nil)\n\t}\n}\n\nfunc (d *Deleter) DeleteTooOld() {\n\tnum := 0\n\tthresholdUsec := time.Now().Add(-d.maxAge).UnixNano()\n\tt := ptime.NewTimer()\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tfor k, v := range d.lastActionTimestamp {\n\t\tif v < thresholdUsec {\n\t\t\tif d.DeleteFunc != nil {\n\t\t\t\td.DeleteFunc(k)\n\t\t\t}\n\t\t\tdelete(d.lastActionTimestamp, k)\n\t\t\tnum++\n\t\t}\n\t}\n\td.logger.Infof(\"[%s] deleted %d too old (%s) items, kept %d, took: %s\",\n\t\td.Name, num, d.maxAge, len(d.lastActionTimestamp), t.Duration())\n}\n\nfunc (d *Deleter) deleteUntilBelowMaxUuid() {\n\td.m.Lock()\n\tdefer d.m.Unlock()\n\tl := len(d.lastActionTimestamp)\n\tif l < int(float32(d.keepNum)*1.1) {\n\t\treturn\n\t}\n\n\tt := ptime.NewTimer()\n\tnum := 0\n\th := &ActionTimestmapHeap{}\n\tnumToRemove := len(d.lastActionTimestamp) - d.keepNum\n\tinitDone := false\n\tfor k, v := range d.lastActionTimestamp {\n\t\theap.Push(h, &actionTimestamp{k, v})\n\t\tif initDone {\n\t\t\theap.Pop(h)\n\t\t} else if h.Len() >= numToRemove {\n\t\t\theap.Init(h)\n\t\t\tinitDone = true\n\t\t}\n\t}\n\n\tfor i := h.Len(); i > 0; i-- {\n\t\ta := heap.Pop(h).(*actionTimestamp)\n\t\tif d.DeleteFunc != nil {\n\t\t\td.DeleteFunc(a.Key)\n\t\t}\n\t\tdelete(d.lastActionTimestamp, a.Key)\n\t\tnum++\n\t}\n\td.logger.Infof(\"[%s] deleted %d items because too many, kept: %d, took: %s\",\n\t\td.Name, num, len(d.lastActionTimestamp), t.Duration())\n}\n\nfunc (d *Deleter) Process() {\n\td.logger.Infof(\"[%s] process started\", d.Name)\n\tfor t := range d.c {\n\t\td.m.Lock()\n\t\tif v := d.lastActionTimestamp[t.Key]; v < t.TimestmapNsec {\n\t\t\td.lastActionTimestamp[t.Key] = t.TimestmapNsec\n\t\t}\n\t\td.m.Unlock()\n\t}\n\td.finished <- true\n\td.logger.Infof(\"[%s] process finished\", d.Name)\n}\n\nfunc (d *Deleter) Deleting() {\n\td.logger.Infof(\"[%s] deleting started\", d.Name)\n\ttmr := time.NewTicker(d.Interval)\n\tfor {\n\t\tselect {\n\t\tcase <-d.end:\n\t\t\tgoto end\n\t\tcase <-tmr.C:\n\t\t\td.DeleteTooOld()\n\t\t\td.deleteUntilBelowMaxUuid()\n\t\t}\n\t}\nend:\n\ttmr.Stop()\n\td.finished <- true\n\td.logger.Infof(\"[%s] deleting finished\", d.Name)\n}\n\nfunc (d *Deleter) Start() {\n\tgo d.Deleting()\n\td.Process()\n}\n\nfunc (d *Deleter) Stop() {\n\tclose(d.c)\n\td.end <- true\n\t<-d.finished\n\t<-d.finished\n}\n<|endoftext|>"}
{"text":"<commit_before>package manager\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype requestLog struct {\n\tdata      []string\n\tlogData   []string\n\tstartTime time.Time\n\treq       *http.Request\n\tlogId     int64\n}\n\nfunc NewRequestLog(req *http.Request) *requestLog {\n\trlog := &requestLog{req: req}\n\trlog.reset()\n\treturn rlog\n}\n\nfunc (rlog *requestLog) print() {\n\tif len(rlog.logData) == 0 {\n\t\treturn\n\t}\n\tused := time.Now().Sub(rlog.startTime)\n\tlog.Println(\"logid:\", rlog.logId,\n\t\trlog.req.Method, rlog.req.URL.String(),\n\t\tstrings.Join(rlog.data, \" \"),\n\t\tstrings.Join(rlog.logData, \" \"),\n\t\t\"used:\", used.String())\n\trlog.reset()\n}\n\nfunc (rlog *requestLog) setLog(arg ...interface{}) {\n\trlog.data = append(rlog.logData, fmt.Sprint(arg))\n}\nfunc (rlog *requestLog) addLog(arg ...interface{}) {\n\trlog.logData = append(rlog.logData, fmt.Sprint(arg))\n}\nfunc (rlog *requestLog) reset() {\n\trlog.startTime = time.Now()\n\trlog.logData = []string{}\n}\n\ntype HttpClient struct {\n\tProxyManager *ProxyManager\n}\n\nfunc NewHttpClient(manager *ProxyManager) *HttpClient {\n\tlog.Println(\"loading http client...\")\n\tproxy := new(HttpClient)\n\tproxy.ProxyManager = manager\n\n\treturn proxy\n}\n\nfunc (httpClient *HttpClient) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\trlog := NewRequestLog(req)\n\n\trlog.logId = httpClient.ProxyManager.reqNum + time.Now().Unix()\n\n\tdefer rlog.print()\n\tuser := getAuthorInfo(req)\n\trlog.setLog(\"uname\", user.Name)\n\n\tif PROXY_DEBUG {\n\t\tdump, _ := httputil.DumpRequest(req, true)\n\t\tlog.Println(\"req dump:\\n\", string(dump))\n\t}\n\n\tif !httpClient.ProxyManager.checkHttpAuth(user) {\n\t\trlog.addLog(\"auth\", \"failed\")\n\t\tw.Header().Set(\"Proxy-Authenticate\", \"Basic realm=auth need\")\n\t\tw.WriteHeader(407)\n\t\tw.Write([]byte(\"auth failed\"))\n\t\treturn\n\t}\n\n\treq.RequestURI = \"\"\n\treq.Header.Del(\"Connection\")\n\treq.Header.Del(\"Proxy-Connection\")\n\n\t_statusOk := strings.Split(req.Header.Get(\"X-Man-Status-Ok\"), \",\")\n\tstatusOk := make(map[int]int)\n\tfor _, v := range _statusOk {\n\t\t_code := int(getInt64(v))\n\t\tif _code > 0 {\n\t\t\tstatusOk[_code] = 1\n\t\t}\n\t}\n\t_clientReTry := -1\n\tx_man_retry := req.Header.Get(\"X-Man-ReTry\")\n\tif x_man_retry != \"\" {\n\t\t_clientReTry = int(getInt64(x_man_retry))\n\t}\n\n\tfor k := range req.Header {\n\t\tif strings.HasPrefix(strings.ToLower(k), \"x-man\") {\n\t\t\treq.Header.Del(k)\n\t\t}\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tmax_re_try := httpClient.ProxyManager.config.reTry + 1\n\tif _clientReTry >= 0 && _clientReTry <= httpClient.ProxyManager.config.reTryMax {\n\t\tmax_re_try = _clientReTry + 1\n\t}\n\tno := 1\n\tfor ; no <= max_re_try; no++ {\n\t\trlog.addLog(\"try\", fmt.Sprintf(\"%d\/%d\", no, max_re_try))\n\t\tproxy, err := httpClient.ProxyManager.proxyPool.GetOneProxy(user.Name)\n\t\tif err != nil {\n\t\t\trlog.addLog(\"get_proxy_faield\", err)\n\t\t\trlog.print()\n\t\t\tbreak\n\t\t}\n\t\trlog.addLog(\"proxy\", proxy.proxy)\n\t\trlog.addLog(\"proxyUsed\", proxy.Used)\n\t\tclient, err := NewClient(proxy.URL, httpClient.ProxyManager.config.timeout)\n\t\tif err != nil {\n\t\t\trlog.addLog(\"get http client failed\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresp, err = client.Do(req)\n\t\tif err == nil {\n\t\t\tif len(statusOk) != 0 {\n\t\t\t\tif _, has := statusOk[resp.StatusCode]; !has {\n\t\t\t\t\trlog.addLog(\"statusCode wrong\", resp.StatusCode)\n\t\t\t\t\tgoto failed\n\t\t\t\t}\n\t\t\t}\n\t\t\thttpClient.ProxyManager.proxyPool.MarkProxyStatus(proxy, PROXY_USED_SUC)\n\t\t\tbreak\n\t\t} else {\n\t\t\trlog.addLog(\"resErr\", err.Error())\n\t\t}\n\n\tfailed:\n\t\t{\n\t\t\thttpClient.ProxyManager.proxyPool.MarkProxyStatus(proxy, PROXY_USED_FAILED)\n\t\t\trlog.addLog(\"failed\")\n\t\t\tif no == max_re_try {\n\t\t\t\trlog.addLog(\"all failed\")\n\t\t\t}\n\t\t\trlog.print()\n\t\t}\n\t}\n\n\tw.Header().Set(\"x-man-try\", fmt.Sprintf(\"%d\/%d\", no, max_re_try))\n\tw.Header().Set(\"x-man-id\", fmt.Sprintf(\"%d\", rlog.logId))\n\n\tif err != nil || resp == nil {\n\t\tw.WriteHeader(550)\n\t\tw.Write([]byte(\"all failed,\" + fmt.Sprintf(\"try:%d\", no)))\n\t\treturn\n\t}\n\n\tresp.Header.Del(\"Content-Length\")\n\tresp.Header.Del(\"Connection\")\n\n\tcopyHeaders(w.Header(), resp.Header)\n\trlog.addLog(\"status:\", resp.StatusCode)\n\n\tw.WriteHeader(resp.StatusCode)\n\n\tn, err := io.Copy(w, resp.Body)\n\trlog.addLog(\"res_len:\", n)\n\tif err != nil {\n\t\t\/\/client may be not read the body\n\t\trlog.addLog(\"io.copy_err:\", err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\trlog.addLog(\"close response body err:\", err)\n\t}\n\trlog.addLog(\"OK\")\n}\n\nfunc copyHeaders(dst, src http.Header) {\n\tfor k, vs := range src {\n\t\tif len(k) > 5 && k[:6] == \"Proxy-\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range vs {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n<commit_msg>clean header<commit_after>package manager\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype requestLog struct {\n\tdata      []string\n\tlogData   []string\n\tstartTime time.Time\n\treq       *http.Request\n\tlogId     int64\n}\n\nfunc NewRequestLog(req *http.Request) *requestLog {\n\trlog := &requestLog{req: req}\n\trlog.reset()\n\treturn rlog\n}\n\nfunc (rlog *requestLog) print() {\n\tif len(rlog.logData) == 0 {\n\t\treturn\n\t}\n\tused := time.Now().Sub(rlog.startTime)\n\tlog.Println(\"logid:\", rlog.logId,\n\t\trlog.req.Method, rlog.req.URL.String(),\n\t\tstrings.Join(rlog.data, \" \"),\n\t\tstrings.Join(rlog.logData, \" \"),\n\t\t\"used:\", used.String())\n\trlog.reset()\n}\n\nfunc (rlog *requestLog) setLog(arg ...interface{}) {\n\trlog.data = append(rlog.logData, fmt.Sprint(arg))\n}\nfunc (rlog *requestLog) addLog(arg ...interface{}) {\n\trlog.logData = append(rlog.logData, fmt.Sprint(arg))\n}\nfunc (rlog *requestLog) reset() {\n\trlog.startTime = time.Now()\n\trlog.logData = []string{}\n}\n\ntype HttpClient struct {\n\tProxyManager *ProxyManager\n}\n\nfunc NewHttpClient(manager *ProxyManager) *HttpClient {\n\tlog.Println(\"loading http client...\")\n\tproxy := new(HttpClient)\n\tproxy.ProxyManager = manager\n\n\treturn proxy\n}\n\nfunc (httpClient *HttpClient) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\trlog := NewRequestLog(req)\n\n\trlog.logId = httpClient.ProxyManager.reqNum + time.Now().Unix()\n\n\tdefer rlog.print()\n\tuser := getAuthorInfo(req)\n\trlog.setLog(\"uname\", user.Name)\n\n\tif PROXY_DEBUG {\n\t\tdump, _ := httputil.DumpRequest(req, true)\n\t\tlog.Println(\"req dump:\\n\", string(dump))\n\t}\n\n\tif !httpClient.ProxyManager.checkHttpAuth(user) {\n\t\trlog.addLog(\"auth\", \"failed\")\n\t\tw.Header().Set(\"Proxy-Authenticate\", \"Basic realm=auth need\")\n\t\tw.WriteHeader(407)\n\t\tw.Write([]byte(\"auth failed\"))\n\t\treturn\n\t}\n\n\treq.RequestURI = \"\"\n\treq.Header.Del(\"Connection\")\n\treq.Header.Del(\"Proxy-Connection\")\n\n\t_statusOk := strings.Split(req.Header.Get(\"X-Man-Status-Ok\"), \",\")\n\tstatusOk := make(map[int]int)\n\tfor _, v := range _statusOk {\n\t\t_code := int(getInt64(v))\n\t\tif _code > 0 {\n\t\t\tstatusOk[_code] = 1\n\t\t}\n\t}\n\t_clientReTry := -1\n\tx_man_retry := req.Header.Get(\"X-Man-ReTry\")\n\tif x_man_retry != \"\" {\n\t\t_clientReTry = int(getInt64(x_man_retry))\n\t}\n\n\tfor k := range req.Header {\n\t\tk=strings.ToLower(k)\n\t\tif strings.HasPrefix(k, \"x-man\") ||strings.HasPrefix(k,\"proxy-\"){\n\t\t\treq.Header.Del(k)\n\t\t}\n\t}\n\n\tvar resp *http.Response\n\tvar err error\n\n\tmax_re_try := httpClient.ProxyManager.config.reTry + 1\n\tif _clientReTry >= 0 && _clientReTry <= httpClient.ProxyManager.config.reTryMax {\n\t\tmax_re_try = _clientReTry + 1\n\t}\n\tno := 1\n\tfor ; no <= max_re_try; no++ {\n\t\trlog.addLog(\"try\", fmt.Sprintf(\"%d\/%d\", no, max_re_try))\n\t\tproxy, err := httpClient.ProxyManager.proxyPool.GetOneProxy(user.Name)\n\t\tif err != nil {\n\t\t\trlog.addLog(\"get_proxy_faield\", err)\n\t\t\trlog.print()\n\t\t\tbreak\n\t\t}\n\t\trlog.addLog(\"proxy\", proxy.proxy)\n\t\trlog.addLog(\"proxyUsed\", proxy.Used)\n\t\tclient, err := NewClient(proxy.URL, httpClient.ProxyManager.config.timeout)\n\t\tif err != nil {\n\t\t\trlog.addLog(\"get http client failed\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresp, err = client.Do(req)\n\t\tif err == nil {\n\t\t\tif len(statusOk) != 0 {\n\t\t\t\tif _, has := statusOk[resp.StatusCode]; !has {\n\t\t\t\t\trlog.addLog(\"statusCode wrong\", resp.StatusCode)\n\t\t\t\t\tgoto failed\n\t\t\t\t}\n\t\t\t}\n\t\t\thttpClient.ProxyManager.proxyPool.MarkProxyStatus(proxy, PROXY_USED_SUC)\n\t\t\tbreak\n\t\t} else {\n\t\t\trlog.addLog(\"resErr\", err.Error())\n\t\t}\n\n\tfailed:\n\t\t{\n\t\t\thttpClient.ProxyManager.proxyPool.MarkProxyStatus(proxy, PROXY_USED_FAILED)\n\t\t\trlog.addLog(\"failed\")\n\t\t\tif no == max_re_try {\n\t\t\t\trlog.addLog(\"all failed\")\n\t\t\t}\n\t\t\trlog.print()\n\t\t}\n\t}\n\n\tw.Header().Set(\"x-man-try\", fmt.Sprintf(\"%d\/%d\", no, max_re_try))\n\tw.Header().Set(\"x-man-id\", fmt.Sprintf(\"%d\", rlog.logId))\n\n\tif err != nil || resp == nil {\n\t\tw.WriteHeader(550)\n\t\tw.Write([]byte(\"all failed,\" + fmt.Sprintf(\"try:%d\", no)))\n\t\treturn\n\t}\n\n\tresp.Header.Del(\"Content-Length\")\n\tresp.Header.Del(\"Connection\")\n\n\tcopyHeaders(w.Header(), resp.Header)\n\trlog.addLog(\"status:\", resp.StatusCode)\n\n\tw.WriteHeader(resp.StatusCode)\n\n\tn, err := io.Copy(w, resp.Body)\n\trlog.addLog(\"res_len:\", n)\n\tif err != nil {\n\t\t\/\/client may be not read the body\n\t\trlog.addLog(\"io.copy_err:\", err)\n\t}\n\n\tif err := resp.Body.Close(); err != nil {\n\t\trlog.addLog(\"close response body err:\", err)\n\t}\n\trlog.addLog(\"OK\")\n}\n\nfunc copyHeaders(dst, src http.Header) {\n\tfor k, vs := range src {\n\t\tif len(k) > 5 && k[:6] == \"Proxy-\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range vs {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package jserver\n\nimport (\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestListPath(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"},{\"age\":15,\"id\":\"2\",\"name\":\"serval\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestIDPath(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test\/1\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterString(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?name=kaban\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterNumber(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?age=14\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterNotExistsKey(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?invalid=14\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"},{\"age\":15,\"id\":\"2\",\"name\":\"serval\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n<commit_msg>add test case.<commit_after>package jserver\n\nimport (\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestListPath(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"},{\"age\":15,\"id\":\"2\",\"name\":\"serval\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestIDPath(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test\/1\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestIDPathNotFound(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test\/9999\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `{\"error\":\"Not Found.\"}` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterString(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?name=kaban\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterStringNoRecord(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?name=invalid\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterNumber(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?age=14\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterNumberInvalid(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?age=invalid\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n\nfunc TestFilterNotExistsKey(t *testing.T) {\n\tjsonRouter := NewJsonRouter()\n\tjsonRouter.Add(\"\/test\", \".\/test.json\")\n\n\tts := httptest.NewServer(jsonRouter)\n\tdefer ts.Close()\n\n\tres, err := http.Get(ts.URL + \"\/test?invalid=14\")\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tt.Error(\"unexpected\")\n\t\treturn\n\t}\n\n\tif string(body) != `[{\"age\":14,\"id\":\"1\",\"name\":\"kaban\"},{\"age\":15,\"id\":\"2\",\"name\":\"serval\"}]` {\n\t\tt.Error(\"response body invalid\")\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package glfw3\n\n\/\/#include <GLFW\/glfw3.h>\n\/\/void glfwSetErrorCallbackCB();\nimport \"C\"\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ErrorCode corresponds to an error code.\ntype ErrorCode int\n\n\/\/Error codes.\nconst (\n\tNotInitialized     ErrorCode = C.GLFW_NOT_INITIALIZED     \/\/GLFW has not been initialized.\n\tNoCurrentContext   ErrorCode = C.GLFW_NO_CURRENT_CONTEXT  \/\/No context is current.\n\tInvalidEnum        ErrorCode = C.GLFW_INVALID_ENUM        \/\/One of the enum parameters for the function was given an invalid enum.\n\tInvalidValue       ErrorCode = C.GLFW_INVALID_VALUE       \/\/One of the parameters for the function was given an invalid value.\n\tOutOfMemory        ErrorCode = C.GLFW_OUT_OF_MEMORY       \/\/A memory allocation failed.\n\tApiUnavailable     ErrorCode = C.GLFW_API_UNAVAILABLE     \/\/GLFW could not find support for the requested client API on the system.\n\tVersionUnavailable ErrorCode = C.GLFW_VERSION_UNAVAILABLE \/\/The requested client API version is not available.\n\tPlatformError      ErrorCode = C.GLFW_PLATFORM_ERROR      \/\/A platform-specific error occurred that does not match any of the more specific categories.\n\tFormatUnavailable  ErrorCode = C.GLFW_FORMAT_UNAVAILABLE  \/\/The clipboard did not contain data in the requested format.\n)\n\n\/\/GlfwError holds error code and description.\ntype GlfwError struct {\n\tCode ErrorCode\n\tDesc string\n}\n\n\/\/Holds the value of the last error\nvar lastError = make(chan *GlfwError, 1)\n\n\/\/Function that will be called back when there is an error. Updates lastError.\nvar fErrorHolder = func(code ErrorCode, desc string) {\n\tlastError <- &GlfwError{code, desc}\n}\n\n\/\/export goErrorCB\nfunc goErrorCB(code C.int, desc *C.char) {\n\tfErrorHolder(ErrorCode(code), C.GoString(desc))\n}\n\n\/\/Error prints the error code and description in a readable format.\nfunc (e *GlfwError) Error() string {\n\treturn fmt.Sprintf(\"Error %d: %s\", e.Code, e.Desc)\n}\n\n\/\/Set the glfw callback internally\nfunc init() {\n\tC.glfwSetErrorCallbackCB()\n}\n<commit_msg>Remove extra function call<commit_after>package glfw3\n\n\/\/#include <GLFW\/glfw3.h>\n\/\/void glfwSetErrorCallbackCB();\nimport \"C\"\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ErrorCode corresponds to an error code.\ntype ErrorCode int\n\n\/\/Error codes.\nconst (\n\tNotInitialized     ErrorCode = C.GLFW_NOT_INITIALIZED     \/\/GLFW has not been initialized.\n\tNoCurrentContext   ErrorCode = C.GLFW_NO_CURRENT_CONTEXT  \/\/No context is current.\n\tInvalidEnum        ErrorCode = C.GLFW_INVALID_ENUM        \/\/One of the enum parameters for the function was given an invalid enum.\n\tInvalidValue       ErrorCode = C.GLFW_INVALID_VALUE       \/\/One of the parameters for the function was given an invalid value.\n\tOutOfMemory        ErrorCode = C.GLFW_OUT_OF_MEMORY       \/\/A memory allocation failed.\n\tApiUnavailable     ErrorCode = C.GLFW_API_UNAVAILABLE     \/\/GLFW could not find support for the requested client API on the system.\n\tVersionUnavailable ErrorCode = C.GLFW_VERSION_UNAVAILABLE \/\/The requested client API version is not available.\n\tPlatformError      ErrorCode = C.GLFW_PLATFORM_ERROR      \/\/A platform-specific error occurred that does not match any of the more specific categories.\n\tFormatUnavailable  ErrorCode = C.GLFW_FORMAT_UNAVAILABLE  \/\/The clipboard did not contain data in the requested format.\n)\n\n\/\/GlfwError holds error code and description.\ntype GlfwError struct {\n\tCode ErrorCode\n\tDesc string\n}\n\n\/\/Holds the value of the last error\nvar lastError = make(chan *GlfwError, 1)\n\n\/\/export goErrorCB\nfunc goErrorCB(code C.int, desc *C.char) {\n\tlastError <- &GlfwError{ErrorCode(code), C.GoString(desc)}\n}\n\n\/\/Error prints the error code and description in a readable format.\nfunc (e *GlfwError) Error() string {\n\treturn fmt.Sprintf(\"Error %d: %s\", e.Code, e.Desc)\n}\n\n\/\/Set the glfw callback internally\nfunc init() {\n\tC.glfwSetErrorCallbackCB()\n}\n<|endoftext|>"}
{"text":"<commit_before>package heroku\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/bgentry\/heroku-go\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccHerokuApp_Basic(t *testing.T) {\n\tvar app heroku.App\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckHerokuAppDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckHerokuAppConfig_basic,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckHerokuAppExists(\"heroku_app.foobar\", &app),\n\t\t\t\t\ttestAccCheckHerokuAppAttributes(&app),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"heroku_app.foobar\", \"name\", \"terraform-test-app\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"heroku_app.foobar\", \"config_vars.0.foo\", \"bar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckHerokuAppDestroy(s *terraform.State) error {\n\tclient := testAccProvider.client\n\n\tfor _, rs := range s.Resources {\n\t\tif rs.Type != \"heroku_app\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := client.AppInfo(rs.ID)\n\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"App still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckHerokuAppAttributes(app *heroku.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tclient := testAccProvider.client\n\n\t\tif app.Region.Name != \"us\" {\n\t\t\treturn fmt.Errorf(\"Bad region: %s\", app.Region.Name)\n\t\t}\n\n\t\tif app.Stack.Name != \"cedar\" {\n\t\t\treturn fmt.Errorf(\"Bad stack: %s\", app.Stack.Name)\n\t\t}\n\n\t\tif app.Name != \"terraform-test-app\" {\n\t\t\treturn fmt.Errorf(\"Bad name: %s\", app.Name)\n\t\t}\n\n\t\tvars, err := client.ConfigVarInfo(app.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif vars[\"foo\"] != \"bar\" {\n\t\t\treturn fmt.Errorf(\"Bad config vars: %v\", vars)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckHerokuAppExists(n string, app *heroku.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.Resources[n]\n\t\tfmt.Printf(\"resources %#v\", s.Resources)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No App Name is set\")\n\t\t}\n\n\t\tclient := testAccProvider.client\n\n\t\tfoundApp, err := client.AppInfo(rs.ID)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif foundApp.Name != rs.ID {\n\t\t\treturn fmt.Errorf(\"App not found\")\n\t\t}\n\n\t\t*app = *foundApp\n\n\t\treturn nil\n\t}\n}\n\nconst testAccCheckHerokuAppConfig_basic = `\nresource \"heroku_app\" \"foobar\" {\n    name = \"terraform-test-app\"\n\n    config_vars = {\n    \tFOO = bar\n    }\n}`\n<commit_msg>providers\/heroku: handle case sensitivity<commit_after>package heroku\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/bgentry\/heroku-go\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccHerokuApp_Basic(t *testing.T) {\n\tvar app heroku.App\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckHerokuAppDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckHerokuAppConfig_basic,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckHerokuAppExists(\"heroku_app.foobar\", &app),\n\t\t\t\t\ttestAccCheckHerokuAppAttributes(&app),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"heroku_app.foobar\", \"name\", \"terraform-test-app\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"heroku_app.foobar\", \"config_vars.0.FOO\", \"bar\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckHerokuAppDestroy(s *terraform.State) error {\n\tclient := testAccProvider.client\n\n\tfor _, rs := range s.Resources {\n\t\tif rs.Type != \"heroku_app\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := client.AppInfo(rs.ID)\n\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"App still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckHerokuAppAttributes(app *heroku.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tclient := testAccProvider.client\n\n\t\tif app.Region.Name != \"us\" {\n\t\t\treturn fmt.Errorf(\"Bad region: %s\", app.Region.Name)\n\t\t}\n\n\t\tif app.Stack.Name != \"cedar\" {\n\t\t\treturn fmt.Errorf(\"Bad stack: %s\", app.Stack.Name)\n\t\t}\n\n\t\tif app.Name != \"terraform-test-app\" {\n\t\t\treturn fmt.Errorf(\"Bad name: %s\", app.Name)\n\t\t}\n\n\t\tvars, err := client.ConfigVarInfo(app.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif vars[\"FOO\"] != \"bar\" {\n\t\t\treturn fmt.Errorf(\"Bad config vars: %v\", vars)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckHerokuAppExists(n string, app *heroku.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.Resources[n]\n\t\tfmt.Printf(\"resources %#v\", s.Resources)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No App Name is set\")\n\t\t}\n\n\t\tclient := testAccProvider.client\n\n\t\tfoundApp, err := client.AppInfo(rs.ID)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif foundApp.Name != rs.ID {\n\t\t\treturn fmt.Errorf(\"App not found\")\n\t\t}\n\n\t\t*app = *foundApp\n\n\t\treturn nil\n\t}\n}\n\nconst testAccCheckHerokuAppConfig_basic = `\nresource \"heroku_app\" \"foobar\" {\n    name = \"terraform-test-app\"\n\n    config_vars = {\n    \tFOO = bar\n    }\n}`\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Add `Update` for renaming an existing `DocAction`<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc throw(f string, a ...interface{}) {\n\tpanic(errors.New(fmt.Sprintf(f, a...)))\n}\n\nfunc catch() {\n\tif err := recover(); err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc rethrow(f string, a ...interface{}) {\n\tif err := recover(); err != nil {\n\t\tthrow(fmt.Sprint(err)+\": \"+f, a...)\n\t}\n}\n<commit_msg>Переработана подсистема исключений<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\n\/\/ throw вызывает panic с указанным сообщением, помещенным в error.\nfunc throw(f string, a ...interface{}) {\n\tpanic(fmt.Errorf(f, a...))\n}\n\n\/\/ rethrow прекращает panic, извлекает сообщение, добавляет к нему префикс\n\/\/ и снова вызывает panic(). Функция должна вызываться только с помощью defer.\nfunc rethrow(f string, a ...interface{}) {\n\tif err := recover(); err != nil {\n\t\tthrow(f+\": \"+fmt.Sprint(err), a...)\n\t}\n}\n\n\/\/ exit отлавливает panic, выводит сообщение в stdout и stderr? и завершает\n\/\/ работу программы с кодом 1. Если не было panic, то ничего не делает.\n\/\/ Должна вызываться только с помощью defer и из main().\nfunc exit() {\n\tif err := recover(); err != nil {\n\t\tlog.Println(err)\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package state\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/docker\/swarm-v2\/api\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/transport\"\n)\n\n\/\/ Raft represents a connection to a raft member\ntype Raft struct {\n\tapi.RaftClient\n\tConn *grpc.ClientConn\n}\n\n\/\/ GetRaftClient returns a raft client object to communicate\n\/\/ with other raft members\nfunc GetRaftClient(addr string, timeout time.Duration) (*Raft, error) {\n\tconn, err := dial(addr, \"tcp\", timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Raft{\n\t\tRaftClient: api.NewRaftClient(conn),\n\t\tConn:       conn,\n\t}, nil\n}\n\n\/\/ dial returns a grpc client connection\nfunc dial(addr string, protocol string, timeout time.Duration) (*grpc.ClientConn, error) {\n\tgrpcOptions := []grpc.DialOption{grpc.WithInsecure(), grpc.WithPicker(&reconnectPicker{target: addr})}\n\tif timeout != 0 {\n\t\tgrpcOptions = append(grpcOptions, grpc.WithTimeout(timeout))\n\t}\n\treturn grpc.Dial(addr, grpcOptions...)\n}\n\n\/\/ Register registers the node raft server\nfunc Register(server *grpc.Server, node *Node) {\n\tapi.RegisterRaftServer(server, node)\n}\n\n\/\/ reconnectPicker is a Picker which attempts a new connection if necessary\n\/\/ before each request. It's used to work around GRPC's exponential backoff,\n\/\/ which is undesired for raft.\ntype reconnectPicker struct {\n\ttarget string\n\tconn   *grpc.Conn\n\tcc     *grpc.ClientConn\n\n\tmu sync.Mutex\n}\n\nfunc (p *reconnectPicker) Init(cc *grpc.ClientConn) error {\n\t\/\/ Init does not need to hold the mutex, because it's either being\n\t\/\/ called from Dial before anything else can use the picker, or from\n\t\/\/ Pick, which holds the mutex.\n\n\tp.cc = cc\n\tc, err := grpc.NewConn(cc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.conn = c\n\treturn nil\n}\n\nfunc (p *reconnectPicker) Pick(ctx context.Context) (transport.ClientTransport, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\t\/\/ TODO(aaronl): This is a very poor way of triggering a new connection\n\t\/\/ attempt. We really need some way of telling the existing p.conn to\n\t\/\/ try again. Unfortunately, NotifyReset doesn't seem to do anything\n\t\/\/ immediate when a connection is in its retry cycle.\n\tif p.conn.State() != grpc.Ready {\n\t\t_ = p.conn.Close()\n\t\tif err := p.Init(p.cc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn p.conn.Wait(ctx)\n}\n\nfunc (p *reconnectPicker) PickAddr() (string, error) {\n\treturn p.target, nil\n}\n\nfunc (p *reconnectPicker) State() (grpc.ConnectivityState, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\treturn p.conn.State(), nil\n}\n\nfunc (p *reconnectPicker) WaitForStateChange(ctx context.Context, sourceState grpc.ConnectivityState) (grpc.ConnectivityState, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\treturn p.conn.WaitForStateChange(ctx, sourceState)\n}\n\nfunc (p *reconnectPicker) Close() error {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\n\tif p.conn != nil {\n\t\treturn p.conn.Close()\n\t}\n\treturn nil\n}\n<commit_msg>Use configrable GRPC backoff for raft<commit_after>package state\n\nimport (\n\t\"time\"\n\n\t\"github.com\/docker\/swarm-v2\/api\"\n\t\"google.golang.org\/grpc\"\n)\n\n\/\/ Raft represents a connection to a raft member\ntype Raft struct {\n\tapi.RaftClient\n\tConn *grpc.ClientConn\n}\n\n\/\/ GetRaftClient returns a raft client object to communicate\n\/\/ with other raft members\nfunc GetRaftClient(addr string, timeout time.Duration) (*Raft, error) {\n\tconn, err := dial(addr, \"tcp\", timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Raft{\n\t\tRaftClient: api.NewRaftClient(conn),\n\t\tConn:       conn,\n\t}, nil\n}\n\n\/\/ dial returns a grpc client connection\nfunc dial(addr string, protocol string, timeout time.Duration) (*grpc.ClientConn, error) {\n\tbackoffConfig := *grpc.DefaultBackoffConfig\n\tbackoffConfig.MaxDelay = 2 * time.Second\n\n\tgrpcOptions := []grpc.DialOption{\n\t\tgrpc.WithInsecure(),\n\t\tgrpc.WithBackoffConfig(&backoffConfig),\n\t}\n\tif timeout != 0 {\n\t\tgrpcOptions = append(grpcOptions, grpc.WithTimeout(timeout))\n\t}\n\treturn grpc.Dial(addr, grpcOptions...)\n}\n\n\/\/ Register registers the node raft server\nfunc Register(server *grpc.Server, node *Node) {\n\tapi.RegisterRaftServer(server, node)\n}\n<|endoftext|>"}
{"text":"<commit_before>package flags\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\/\/ ErrorType represents the type of error.\ntype ErrorType uint\n\nconst (\n\t\/\/ ErrUnknown indicates a generic error.\n\tErrUnknown ErrorType = iota\n\n\t\/\/ ErrExpectedArgument indicates that an argument was expected.\n\tErrExpectedArgument\n\n\t\/\/ ErrUnknownFlag indicates an unknown flag.\n\tErrUnknownFlag\n\n\t\/\/ ErrUnknownGroup indicates an unknown group.\n\tErrUnknownGroup\n\n\t\/\/ ErrMarshal indicates a marshalling error while converting values.\n\tErrMarshal\n\n\t\/\/ ErrHelp indicates that the built-in help was shown (the error\n\t\/\/ contains the help message).\n\tErrHelp\n\n\t\/\/ ErrNoArgumentForBool indicates that an argument was given for a\n\t\/\/ boolean flag (which don't not take any arguments).\n\tErrNoArgumentForBool\n\n\t\/\/ ErrRequired indicates that a required flag was not provided.\n\tErrRequired\n\n\t\/\/ ErrShortNameTooLong indicates that a short flag name was specified,\n\t\/\/ longer than one character.\n\tErrShortNameTooLong\n\n\t\/\/ ErrDuplicatedFlag indicates that a short or long flag has been\n\t\/\/ defined more than once\n\tErrDuplicatedFlag\n\n\t\/\/ ErrTag indicates an error while parsing flag tags.\n\tErrTag\n\n\t\/\/ ErrCommandRequired indicates that a command was required but not\n\t\/\/ specified\n\tErrCommandRequired\n\n\t\/\/ ErrUnknownCommand indicates that an unknown command was specified.\n\tErrUnknownCommand\n)\n\nfunc (e ErrorType) String() string {\n\treturn reflect.TypeOf(e).Name()\n}\n\n\/\/ Error represents a parser error. The error returned from Parse is of this\n\/\/ type. The error contains both a Type and Message.\ntype Error struct {\n\t\/\/ The type of error\n\tType ErrorType\n\n\t\/\/ The error message\n\tMessage string\n}\n\n\/\/ Error returns the error's message\nfunc (e *Error) Error() string {\n\treturn e.Message\n}\n\nfunc newError(tp ErrorType, message string) *Error {\n\treturn &Error{\n\t\tType:    tp,\n\t\tMessage: message,\n\t}\n}\n\nfunc newErrorf(tp ErrorType, format string, args ...interface{}) *Error {\n\treturn newError(tp, fmt.Sprintf(format, args...))\n}\n\nfunc wrapError(err error) *Error {\n\tret, ok := err.(*Error)\n\n\tif !ok {\n\t\treturn newError(ErrUnknown, err.Error())\n\t}\n\n\treturn ret\n}\n<commit_msg>Fix error type to string<commit_after>package flags\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ ErrorType represents the type of error.\ntype ErrorType uint\n\nconst (\n\t\/\/ ErrUnknown indicates a generic error.\n\tErrUnknown ErrorType = iota\n\n\t\/\/ ErrExpectedArgument indicates that an argument was expected.\n\tErrExpectedArgument\n\n\t\/\/ ErrUnknownFlag indicates an unknown flag.\n\tErrUnknownFlag\n\n\t\/\/ ErrUnknownGroup indicates an unknown group.\n\tErrUnknownGroup\n\n\t\/\/ ErrMarshal indicates a marshalling error while converting values.\n\tErrMarshal\n\n\t\/\/ ErrHelp indicates that the built-in help was shown (the error\n\t\/\/ contains the help message).\n\tErrHelp\n\n\t\/\/ ErrNoArgumentForBool indicates that an argument was given for a\n\t\/\/ boolean flag (which don't not take any arguments).\n\tErrNoArgumentForBool\n\n\t\/\/ ErrRequired indicates that a required flag was not provided.\n\tErrRequired\n\n\t\/\/ ErrShortNameTooLong indicates that a short flag name was specified,\n\t\/\/ longer than one character.\n\tErrShortNameTooLong\n\n\t\/\/ ErrDuplicatedFlag indicates that a short or long flag has been\n\t\/\/ defined more than once\n\tErrDuplicatedFlag\n\n\t\/\/ ErrTag indicates an error while parsing flag tags.\n\tErrTag\n\n\t\/\/ ErrCommandRequired indicates that a command was required but not\n\t\/\/ specified\n\tErrCommandRequired\n\n\t\/\/ ErrUnknownCommand indicates that an unknown command was specified.\n\tErrUnknownCommand\n)\n\nfunc (e ErrorType) String() string {\n\tswitch e {\n\tcase ErrUnknown:\n\t\treturn \"unknown\"\n\tcase ErrExpectedArgument:\n\t\treturn \"expected argument\"\n\tcase ErrUnknownFlag:\n\t\treturn \"unknown flag\"\n\tcase ErrUnknownGroup:\n\t\treturn \"unknown group\"\n\tcase ErrMarshal:\n\t\treturn \"marshal\"\n\tcase ErrHelp:\n\t\treturn \"help\"\n\tcase ErrNoArgumentForBool:\n\t\treturn \"no argument for bool\"\n\tcase ErrRequired:\n\t\treturn \"required\"\n\tcase ErrShortNameTooLong:\n\t\treturn \"short name too long\"\n\tcase ErrDuplicatedFlag:\n\t\treturn \"duplicated flag\"\n\tcase ErrTag:\n\t\treturn \"tag\"\n\tcase ErrCommandRequired:\n\t\treturn \"command required\"\n\tcase ErrUnknownCommand:\n\t\treturn \"unknown command\"\n\t}\n\n\treturn \"unrecognized error type\"\n}\n\n\/\/ Error represents a parser error. The error returned from Parse is of this\n\/\/ type. The error contains both a Type and Message.\ntype Error struct {\n\t\/\/ The type of error\n\tType ErrorType\n\n\t\/\/ The error message\n\tMessage string\n}\n\n\/\/ Error returns the error's message\nfunc (e *Error) Error() string {\n\treturn e.Message\n}\n\nfunc newError(tp ErrorType, message string) *Error {\n\treturn &Error{\n\t\tType:    tp,\n\t\tMessage: message,\n\t}\n}\n\nfunc newErrorf(tp ErrorType, format string, args ...interface{}) *Error {\n\treturn newError(tp, fmt.Sprintf(format, args...))\n}\n\nfunc wrapError(err error) *Error {\n\tret, ok := err.(*Error)\n\n\tif !ok {\n\t\treturn newError(ErrUnknown, err.Error())\n\t}\n\n\treturn ret\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\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ EpicsService handles communication with the epic related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html\ntype EpicsService struct {\n\tclient *Client\n}\n\n\/\/ EpicAuthor represents a author of the epic.\ntype EpicAuthor struct {\n\tID        int    `json:\"id\"`\n\tState     string `json:\"state\"`\n\tWebURL    string `json:\"web_url\"`\n\tName      string `json:\"name\"`\n\tAvatarURL string `json:\"avatar_url\"`\n\tUsername  string `json:\"username\"`\n}\n\n\/\/ Epic represents a GitLab epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html\ntype Epic struct {\n\tID                      int         `json:\"id\"`\n\tIID                     int         `json:\"iid\"`\n\tGroupID                 int         `json:\"group_id\"`\n\tParentID                int         `json:\"parent_id\"`\n\tTitle                   string      `json:\"title\"`\n\tDescription             string      `json:\"description\"`\n\tState                   string      `json:\"state\"`\n\tWebURL                  string      `json:\"web_url\"`\n\tAuthor                  *EpicAuthor `json:\"author\"`\n\tStartDate               *ISOTime    `json:\"start_date\"`\n\tStartDateIsFixed        bool        `json:\"start_date_is_fixed\"`\n\tStartDateFixed          *ISOTime    `json:\"start_date_fixed\"`\n\tStartDateFromMilestones *ISOTime    `json:\"start_date_from_milestones\"`\n\tDueDate                 *ISOTime    `json:\"due_date\"`\n\tDueDateIsFixed          bool        `json:\"due_date_is_fixed\"`\n\tDueDateFixed            *ISOTime    `json:\"due_date_fixed\"`\n\tDueDateFromMilestones   *ISOTime    `json:\"due_date_from_milestones\"`\n\tCreatedAt               *time.Time  `json:\"created_at\"`\n\tUpdatedAt               *time.Time  `json:\"updated_at\"`\n\tClosedAt                *time.Time  `json:\"closed_at\"`\n\tLabels                  []string    `json:\"labels\"`\n\tUpvotes                 int         `json:\"upvotes\"`\n\tDownvotes               int         `json:\"downvotes\"`\n\tUserNotesCount          int         `json:\"user_notes_count\"`\n\tURL                     string      `json:\"url\"`\n}\n\nfunc (e Epic) String() string {\n\treturn Stringify(e)\n}\n\n\/\/ ListGroupEpicsOptions represents the available ListGroupEpics() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#list-epics-for-a-group\ntype ListGroupEpicsOptions struct {\n\tListOptions\n\tAuthorID                *int       `url:\"author_id,omitempty\" json:\"author_id,omitempty\"`\n\tLabels                  *Labels    `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tWithLabelDetails        *bool      `url:\"with_labels_details,omitempty\" json:\"with_labels_details,omitempty\"`\n\tOrderBy                 *string    `url:\"order_by,omitempty\" json:\"order_by,omitempty\"`\n\tSort                    *string    `url:\"sort,omitempty\" json:\"sort,omitempty\"`\n\tSearch                  *string    `url:\"search,omitempty\" json:\"search,omitempty\"`\n\tState                   *string    `url:\"state,omitempty\" json:\"state,omitempty\"`\n\tCreatedAfter            *time.Time `url:\"created_after,omitempty\" json:\"created_after,omitempty\"`\n\tCreatedBefore           *time.Time `url:\"created_before,omitempty\" json:\"created_before,omitempty\"`\n\tUpdatedAfter            *time.Time `url:\"updated_after,omitempty\" json:\"updated_after,omitempty\"`\n\tUpdatedBefore           *time.Time `url:\"updated_before,omitempty\" json:\"updated_before,omitempty\"`\n\tIncludeAncestorGroups   *bool      `url:\"include_ancestor_groups,omitempty\" json:\"include_ancestor_groups,omitempty\"`\n\tIncludeDescendantGroups *bool      `url:\"include_descendant_groups,omitempty\" json:\"include_descendant_groups,omitempty\"`\n\tMyReactionEmoji         *string    `url:\"my_reaction_emoji,omitempty\" json:\"my_reaction_emoji,omitempty\"`\n}\n\n\/\/ ListGroupEpics gets a list of group epics. This function accepts pagination\n\/\/ parameters page and per_page to return the list of group epics.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#list-epics-for-a-group\nfunc (s *EpicsService) ListGroupEpics(gid interface{}, opt *ListGroupEpicsOptions, options ...RequestOptionFunc) ([]*Epic, *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\", PathEscape(group))\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar es []*Epic\n\tresp, err := s.client.Do(req, &es)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn es, resp, err\n}\n\n\/\/ GetEpic gets a single group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#single-epic\nfunc (s *EpicsService) GetEpic(gid interface{}, epic int, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ GetEpicLinks gets all child epics of an epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epic_links.html\nfunc (s *EpicsService) GetEpicLinks(gid interface{}, epic int, options ...RequestOptionFunc) ([]*Epic, *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\/epics\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar e []*Epic\n\tresp, err := s.client.Do(req, &e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ CreateEpicOptions represents the available CreateEpic() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#new-epic\ntype CreateEpicOptions struct {\n\tTitle            *string  `url:\"title,omitempty\" json:\"title,omitempty\"`\n\tDescription      *string  `url:\"description,omitempty\" json:\"description,omitempty\"`\n\tLabels           *Labels  `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tStartDateIsFixed *bool    `url:\"start_date_is_fixed,omitempty\" json:\"start_date_is_fixed,omitempty\"`\n\tStartDateFixed   *ISOTime `url:\"start_date_fixed,omitempty\" json:\"start_date_fixed,omitempty\"`\n\tDueDateIsFixed   *bool    `url:\"due_date_is_fixed,omitempty\" json:\"due_date_is_fixed,omitempty\"`\n\tDueDateFixed     *ISOTime `url:\"due_date_fixed,omitempty\" json:\"due_date_fixed,omitempty\"`\n}\n\n\/\/ CreateEpic creates a new group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#new-epic\nfunc (s *EpicsService) CreateEpic(gid interface{}, opt *CreateEpicOptions, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group))\n\n\treq, err := s.client.NewRequest(http.MethodPost, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ UpdateEpicOptions represents the available UpdateEpic() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#update-epic\ntype UpdateEpicOptions struct {\n\tTitle            *string  `url:\"title,omitempty\" json:\"title,omitempty\"`\n\tDescription      *string  `url:\"description,omitempty\" json:\"description,omitempty\"`\n\tLabels           *Labels  `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tStartDateIsFixed *bool    `url:\"start_date_is_fixed,omitempty\" json:\"start_date_is_fixed,omitempty\"`\n\tStartDateFixed   *ISOTime `url:\"start_date_fixed,omitempty\" json:\"start_date_fixed,omitempty\"`\n\tDueDateIsFixed   *bool    `url:\"due_date_is_fixed,omitempty\" json:\"due_date_is_fixed,omitempty\"`\n\tDueDateFixed     *ISOTime `url:\"due_date_fixed,omitempty\" json:\"due_date_fixed,omitempty\"`\n\tStateEvent       *string  `url:\"state_event,omitempty\" json:\"state_event,omitempty\"`\n}\n\n\/\/ UpdateEpic updates an existing group epic. This function is also used\n\/\/ to mark an epic as closed.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#update-epic\nfunc (s *EpicsService) UpdateEpic(gid interface{}, epic int, opt *UpdateEpicOptions, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodPut, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ DeleteEpic deletes a single group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#delete-epic\nfunc (s *EpicsService) DeleteEpic(gid interface{}, epic int, options ...RequestOptionFunc) (*Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodDelete, u, nil, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(req, nil)\n}\n<commit_msg>feat: Add attribute Confidential to UpdateEpicOptions<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\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ EpicsService handles communication with the epic related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html\ntype EpicsService struct {\n\tclient *Client\n}\n\n\/\/ EpicAuthor represents a author of the epic.\ntype EpicAuthor struct {\n\tID        int    `json:\"id\"`\n\tState     string `json:\"state\"`\n\tWebURL    string `json:\"web_url\"`\n\tName      string `json:\"name\"`\n\tAvatarURL string `json:\"avatar_url\"`\n\tUsername  string `json:\"username\"`\n}\n\n\/\/ Epic represents a GitLab epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html\ntype Epic struct {\n\tID                      int         `json:\"id\"`\n\tIID                     int         `json:\"iid\"`\n\tGroupID                 int         `json:\"group_id\"`\n\tParentID                int         `json:\"parent_id\"`\n\tTitle                   string      `json:\"title\"`\n\tDescription             string      `json:\"description\"`\n\tState                   string      `json:\"state\"`\n\tWebURL                  string      `json:\"web_url\"`\n\tAuthor                  *EpicAuthor `json:\"author\"`\n\tStartDate               *ISOTime    `json:\"start_date\"`\n\tStartDateIsFixed        bool        `json:\"start_date_is_fixed\"`\n\tStartDateFixed          *ISOTime    `json:\"start_date_fixed\"`\n\tStartDateFromMilestones *ISOTime    `json:\"start_date_from_milestones\"`\n\tDueDate                 *ISOTime    `json:\"due_date\"`\n\tDueDateIsFixed          bool        `json:\"due_date_is_fixed\"`\n\tDueDateFixed            *ISOTime    `json:\"due_date_fixed\"`\n\tDueDateFromMilestones   *ISOTime    `json:\"due_date_from_milestones\"`\n\tCreatedAt               *time.Time  `json:\"created_at\"`\n\tUpdatedAt               *time.Time  `json:\"updated_at\"`\n\tClosedAt                *time.Time  `json:\"closed_at\"`\n\tLabels                  []string    `json:\"labels\"`\n\tUpvotes                 int         `json:\"upvotes\"`\n\tDownvotes               int         `json:\"downvotes\"`\n\tUserNotesCount          int         `json:\"user_notes_count\"`\n\tURL                     string      `json:\"url\"`\n}\n\nfunc (e Epic) String() string {\n\treturn Stringify(e)\n}\n\n\/\/ ListGroupEpicsOptions represents the available ListGroupEpics() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#list-epics-for-a-group\ntype ListGroupEpicsOptions struct {\n\tListOptions\n\tAuthorID                *int       `url:\"author_id,omitempty\" json:\"author_id,omitempty\"`\n\tLabels                  *Labels    `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tWithLabelDetails        *bool      `url:\"with_labels_details,omitempty\" json:\"with_labels_details,omitempty\"`\n\tOrderBy                 *string    `url:\"order_by,omitempty\" json:\"order_by,omitempty\"`\n\tSort                    *string    `url:\"sort,omitempty\" json:\"sort,omitempty\"`\n\tSearch                  *string    `url:\"search,omitempty\" json:\"search,omitempty\"`\n\tState                   *string    `url:\"state,omitempty\" json:\"state,omitempty\"`\n\tCreatedAfter            *time.Time `url:\"created_after,omitempty\" json:\"created_after,omitempty\"`\n\tCreatedBefore           *time.Time `url:\"created_before,omitempty\" json:\"created_before,omitempty\"`\n\tUpdatedAfter            *time.Time `url:\"updated_after,omitempty\" json:\"updated_after,omitempty\"`\n\tUpdatedBefore           *time.Time `url:\"updated_before,omitempty\" json:\"updated_before,omitempty\"`\n\tIncludeAncestorGroups   *bool      `url:\"include_ancestor_groups,omitempty\" json:\"include_ancestor_groups,omitempty\"`\n\tIncludeDescendantGroups *bool      `url:\"include_descendant_groups,omitempty\" json:\"include_descendant_groups,omitempty\"`\n\tMyReactionEmoji         *string    `url:\"my_reaction_emoji,omitempty\" json:\"my_reaction_emoji,omitempty\"`\n}\n\n\/\/ ListGroupEpics gets a list of group epics. This function accepts pagination\n\/\/ parameters page and per_page to return the list of group epics.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#list-epics-for-a-group\nfunc (s *EpicsService) ListGroupEpics(gid interface{}, opt *ListGroupEpicsOptions, options ...RequestOptionFunc) ([]*Epic, *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\", PathEscape(group))\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar es []*Epic\n\tresp, err := s.client.Do(req, &es)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn es, resp, err\n}\n\n\/\/ GetEpic gets a single group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#single-epic\nfunc (s *EpicsService) GetEpic(gid interface{}, epic int, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ GetEpicLinks gets all child epics of an epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epic_links.html\nfunc (s *EpicsService) GetEpicLinks(gid interface{}, epic int, options ...RequestOptionFunc) ([]*Epic, *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\/epics\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodGet, u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar e []*Epic\n\tresp, err := s.client.Do(req, &e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ CreateEpicOptions represents the available CreateEpic() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#new-epic\ntype CreateEpicOptions struct {\n\tTitle            *string  `url:\"title,omitempty\" json:\"title,omitempty\"`\n\tDescription      *string  `url:\"description,omitempty\" json:\"description,omitempty\"`\n\tLabels           *Labels  `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tStartDateIsFixed *bool    `url:\"start_date_is_fixed,omitempty\" json:\"start_date_is_fixed,omitempty\"`\n\tStartDateFixed   *ISOTime `url:\"start_date_fixed,omitempty\" json:\"start_date_fixed,omitempty\"`\n\tDueDateIsFixed   *bool    `url:\"due_date_is_fixed,omitempty\" json:\"due_date_is_fixed,omitempty\"`\n\tDueDateFixed     *ISOTime `url:\"due_date_fixed,omitempty\" json:\"due_date_fixed,omitempty\"`\n}\n\n\/\/ CreateEpic creates a new group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#new-epic\nfunc (s *EpicsService) CreateEpic(gid interface{}, opt *CreateEpicOptions, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group))\n\n\treq, err := s.client.NewRequest(http.MethodPost, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ UpdateEpicOptions represents the available UpdateEpic() options.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#update-epic\ntype UpdateEpicOptions struct {\n\tTitle            *string  `url:\"title,omitempty\" json:\"title,omitempty\"`\n\tDescription      *string  `url:\"description,omitempty\" json:\"description,omitempty\"`\n\tLabels           *Labels  `url:\"labels,comma,omitempty\" json:\"labels,omitempty\"`\n\tStartDateIsFixed *bool    `url:\"start_date_is_fixed,omitempty\" json:\"start_date_is_fixed,omitempty\"`\n\tStartDateFixed   *ISOTime `url:\"start_date_fixed,omitempty\" json:\"start_date_fixed,omitempty\"`\n\tDueDateIsFixed   *bool    `url:\"due_date_is_fixed,omitempty\" json:\"due_date_is_fixed,omitempty\"`\n\tDueDateFixed     *ISOTime `url:\"due_date_fixed,omitempty\" json:\"due_date_fixed,omitempty\"`\n\tStateEvent       *string  `url:\"state_event,omitempty\" json:\"state_event,omitempty\"`\n\tConfidential     *bool    `url:\"confidential\" json:\"confidential\"`\n}\n\n\/\/ UpdateEpic updates an existing group epic. This function is also used\n\/\/ to mark an epic as closed.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#update-epic\nfunc (s *EpicsService) UpdateEpic(gid interface{}, epic int, opt *UpdateEpicOptions, options ...RequestOptionFunc) (*Epic, *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\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodPut, u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\te := new(Epic)\n\tresp, err := s.client.Do(req, e)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn e, resp, err\n}\n\n\/\/ DeleteEpic deletes a single group epic.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epics.html#delete-epic\nfunc (s *EpicsService) DeleteEpic(gid interface{}, epic int, options ...RequestOptionFunc) (*Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\", PathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(http.MethodDelete, u, nil, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.client.Do(req, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package finder\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-graphite\/carbonapi\/pkg\/parser\"\n\t\"github.com\/lomik\/graphite-clickhouse\/helper\/clickhouse\"\n)\n\ntype taggedTermOp int\n\nconst (\n\ttaggedTermEq       taggedTermOp = 1\n\ttaggedTermMatch    taggedTermOp = 2\n\ttaggedTermNe       taggedTermOp = 3\n\ttaggedTermNotMatch taggedTermOp = 4\n)\n\ntype taggedTerm struct {\n\tkey   string\n\top    taggedTermOp\n\tvalue string\n}\n\ntype taggedTermList []taggedTerm\n\nfunc (s taggedTermList) Len() int {\n\treturn len(s)\n}\nfunc (s taggedTermList) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\nfunc (s taggedTermList) Less(i, j int) bool {\n\treturn s[i].op < s[j].op\n}\n\ntype TaggedFinder struct {\n\twrapped        Finder\n\tctx            context.Context \/\/ for clickhouse.Query\n\turl            string          \/\/ clickhouse dsn\n\ttable          string          \/\/ graphite_tag table\n\ttimeout        time.Duration   \/\/ clickhouse query timeout\n\tbody           []byte          \/\/ clickhouse response\n\tfromTimestamp  int64\n\tuntilTimestamp int64\n\tisSeriesByTag  bool\n}\n\nfunc WrapTagged(f Finder, ctx context.Context, url string, table string, timeout time.Duration, fromTimestamp int64, untilTimestamp int64) *TaggedFinder {\n\treturn &TaggedFinder{\n\t\twrapped:        f,\n\t\tctx:            ctx,\n\t\turl:            url,\n\t\ttable:          table,\n\t\ttimeout:        timeout,\n\t\tfromTimestamp:  fromTimestamp,\n\t\tuntilTimestamp: untilTimestamp,\n\t}\n}\n\nfunc taggedTermWhere1(term *taggedTerm) string {\n\tswitch term.op {\n\tcase taggedTermEq:\n\t\treturn fmt.Sprintf(\"Tag1=%s\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermNe:\n\t\treturn fmt.Sprintf(\"Tag1!=%s\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"(Tag1 LIKE %s) AND (match(Tag1, %s))\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\n\tcase taggedTermNotMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"NOT ((Tag1 LIKE %s) AND (match(Tag1, %s)))\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc taggedTermWhereN(term *taggedTerm) string {\n\t\/\/ arrayExists((x) -> %s, Tags)\n\tswitch term.op {\n\tcase taggedTermEq:\n\t\treturn fmt.Sprintf(\"arrayExists((x) -> x=%s, Tags)\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermNe:\n\t\treturn fmt.Sprintf(\"NOT arrayExists((x) -> x=%s, Tags)\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"arrayExists((x) -> (x LIKE %s) AND (match(x, %s)), Tags)\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\n\tcase taggedTermNotMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"NOT arrayExists((x) -> (x LIKE %s) AND (match(x, %s)), Tags)\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc (t *TaggedFinder) makeWhere(query string) (string, error) {\n\texpr, _, err := parser.ParseExpr(query)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalidationError := fmt.Errorf(\"wrong seriesByTag call: %#v\", query)\n\n\t\/\/ check\n\tif !expr.IsFunc() {\n\t\treturn \"\", validationError\n\t}\n\tif expr.Target() != \"seriesByTag\" {\n\t\treturn \"\", validationError\n\t}\n\n\targs := expr.Args()\n\tif len(args) < 1 {\n\t\treturn \"\", validationError\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif !args[i].IsString() {\n\t\t\treturn \"\", validationError\n\t\t}\n\t}\n\n\tterms := make([]taggedTerm, len(args))\n\n\tfor i := 0; i < len(args); i++ {\n\t\ts := args[i].StringValue()\n\t\ta := strings.SplitN(s, \"=\", 2)\n\t\tif len(a) != 2 {\n\t\t\treturn \"\", validationError\n\t\t}\n\n\t\ta[0] = strings.TrimSpace(a[0])\n\t\ta[1] = strings.TrimSpace(a[1])\n\n\t\top := \"=\"\n\n\t\tif len(a[0]) > 0 && a[0][len(a[0])-1] == '!' {\n\t\t\top = \"!\" + op\n\t\t\ta[0] = strings.TrimSpace(a[0][:len(a[0])-1])\n\t\t}\n\n\t\tif len(a[1]) > 0 && a[1][0] == '~' {\n\t\t\top = op + \"~\"\n\t\t\ta[1] = strings.TrimSpace(a[1][1:])\n\t\t}\n\n\t\tterms[i].key = a[0]\n\t\tterms[i].value = a[1]\n\n\t\tif terms[i].key == \"name\" {\n\t\t\tterms[i].key = \"__name__\"\n\t\t}\n\n\t\tswitch op {\n\t\tcase \"=\":\n\t\t\tterms[i].op = taggedTermEq\n\t\tcase \"!=\":\n\t\t\tterms[i].op = taggedTermNe\n\t\tcase \"=~\":\n\t\t\tterms[i].op = taggedTermMatch\n\t\tcase \"!=~\":\n\t\t\tterms[i].op = taggedTermNotMatch\n\t\tdefault:\n\t\t\treturn \"\", validationError\n\t\t}\n\t}\n\n\tsort.Sort(taggedTermList(terms))\n\n\tw := NewWhere()\n\tw.And(taggedTermWhere1(&terms[0]))\n\n\tfor i := 1; i < len(terms); i++ {\n\t\tw.And(taggedTermWhereN(&terms[i]))\n\t}\n\n\treturn w.String(), nil\n\n}\n\nfunc (t *TaggedFinder) Execute(query string) error {\n\tif !strings.HasPrefix(strings.TrimSpace(query), \"seriesByTag\") {\n\t\treturn t.wrapped.Execute(query)\n\t}\n\n\tt.isSeriesByTag = true\n\n\tw, err := t.makeWhere(query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsql := fmt.Sprintf(\"SELECT Path FROM %s WHERE %s GROUP BY Path\", t.table, w)\n\tt.body, err = clickhouse.Query(t.ctx, t.url, sql, t.timeout)\n\treturn err\n}\n\nfunc (t *TaggedFinder) List() [][]byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.List()\n\t}\n\n\tif t.body == nil {\n\t\treturn [][]byte{}\n\t}\n\n\trows := bytes.Split(t.body, []byte{'\\n'})\n\n\tskip := 0\n\tfor i := 0; i < len(rows); i++ {\n\t\tif len(rows[i]) == 0 {\n\t\t\tskip++\n\t\t\tcontinue\n\t\t}\n\t\tif skip > 0 {\n\t\t\trows[i-skip] = rows[i]\n\t\t}\n\t}\n\n\trows = rows[:len(rows)-skip]\n\n\treturn rows\n}\n\nfunc (t *TaggedFinder) Series() [][]byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.Series()\n\t}\n\n\treturn t.List()\n}\n\nfunc (t *TaggedFinder) Abs(v []byte) []byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.Abs(v)\n\t}\n\n\tu, err := url.Parse(string(v))\n\tif err != nil {\n\t\treturn v\n\t}\n\n\ttags := make([]string, 0, len(u.Query()))\n\tfor k, v := range u.Query() {\n\t\ttags = append(tags, fmt.Sprintf(\"%s=%s\", k, v[0]))\n\t}\n\n\tsort.Strings(tags)\n\tif len(tags) == 0 {\n\t\treturn []byte(u.Path)\n\t}\n\n\treturn []byte(fmt.Sprintf(\"%s;%s\", u.Path, strings.Join(tags, \";\")))\n}\n<commit_msg>deleted<commit_after>package finder\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-graphite\/carbonapi\/pkg\/parser\"\n\t\"github.com\/lomik\/graphite-clickhouse\/helper\/clickhouse\"\n)\n\ntype taggedTermOp int\n\nconst (\n\ttaggedTermEq       taggedTermOp = 1\n\ttaggedTermMatch    taggedTermOp = 2\n\ttaggedTermNe       taggedTermOp = 3\n\ttaggedTermNotMatch taggedTermOp = 4\n)\n\ntype taggedTerm struct {\n\tkey   string\n\top    taggedTermOp\n\tvalue string\n}\n\ntype taggedTermList []taggedTerm\n\nfunc (s taggedTermList) Len() int {\n\treturn len(s)\n}\nfunc (s taggedTermList) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\nfunc (s taggedTermList) Less(i, j int) bool {\n\treturn s[i].op < s[j].op\n}\n\ntype TaggedFinder struct {\n\twrapped        Finder\n\tctx            context.Context \/\/ for clickhouse.Query\n\turl            string          \/\/ clickhouse dsn\n\ttable          string          \/\/ graphite_tag table\n\ttimeout        time.Duration   \/\/ clickhouse query timeout\n\tbody           []byte          \/\/ clickhouse response\n\tfromTimestamp  int64\n\tuntilTimestamp int64\n\tisSeriesByTag  bool\n}\n\nfunc WrapTagged(f Finder, ctx context.Context, url string, table string, timeout time.Duration, fromTimestamp int64, untilTimestamp int64) *TaggedFinder {\n\treturn &TaggedFinder{\n\t\twrapped:        f,\n\t\tctx:            ctx,\n\t\turl:            url,\n\t\ttable:          table,\n\t\ttimeout:        timeout,\n\t\tfromTimestamp:  fromTimestamp,\n\t\tuntilTimestamp: untilTimestamp,\n\t}\n}\n\nfunc taggedTermWhere1(term *taggedTerm) string {\n\tswitch term.op {\n\tcase taggedTermEq:\n\t\treturn fmt.Sprintf(\"Tag1=%s\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermNe:\n\t\treturn fmt.Sprintf(\"Tag1!=%s\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"(Tag1 LIKE %s) AND (match(Tag1, %s))\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\n\tcase taggedTermNotMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"NOT ((Tag1 LIKE %s) AND (match(Tag1, %s)))\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc taggedTermWhereN(term *taggedTerm) string {\n\t\/\/ arrayExists((x) -> %s, Tags)\n\tswitch term.op {\n\tcase taggedTermEq:\n\t\treturn fmt.Sprintf(\"arrayExists((x) -> x=%s, Tags)\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermNe:\n\t\treturn fmt.Sprintf(\"NOT arrayExists((x) -> x=%s, Tags)\", Q(fmt.Sprintf(\"%s=%s\", term.key, term.value)))\n\tcase taggedTermMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"arrayExists((x) -> (x LIKE %s) AND (match(x, %s)), Tags)\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\n\tcase taggedTermNotMatch:\n\t\treturn fmt.Sprintf(\n\t\t\t\"NOT arrayExists((x) -> (x LIKE %s) AND (match(x, %s)), Tags)\",\n\t\t\tQ(fmt.Sprintf(\"%s=%%\", term.key)),\n\t\t\tQ(fmt.Sprintf(\"%s=%s\", term.key, term.value)),\n\t\t)\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nfunc (t *TaggedFinder) makeWhere(query string) (string, error) {\n\texpr, _, err := parser.ParseExpr(query)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalidationError := fmt.Errorf(\"wrong seriesByTag call: %#v\", query)\n\n\t\/\/ check\n\tif !expr.IsFunc() {\n\t\treturn \"\", validationError\n\t}\n\tif expr.Target() != \"seriesByTag\" {\n\t\treturn \"\", validationError\n\t}\n\n\targs := expr.Args()\n\tif len(args) < 1 {\n\t\treturn \"\", validationError\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif !args[i].IsString() {\n\t\t\treturn \"\", validationError\n\t\t}\n\t}\n\n\tterms := make([]taggedTerm, len(args))\n\n\tfor i := 0; i < len(args); i++ {\n\t\ts := args[i].StringValue()\n\t\ta := strings.SplitN(s, \"=\", 2)\n\t\tif len(a) != 2 {\n\t\t\treturn \"\", validationError\n\t\t}\n\n\t\ta[0] = strings.TrimSpace(a[0])\n\t\ta[1] = strings.TrimSpace(a[1])\n\n\t\top := \"=\"\n\n\t\tif len(a[0]) > 0 && a[0][len(a[0])-1] == '!' {\n\t\t\top = \"!\" + op\n\t\t\ta[0] = strings.TrimSpace(a[0][:len(a[0])-1])\n\t\t}\n\n\t\tif len(a[1]) > 0 && a[1][0] == '~' {\n\t\t\top = op + \"~\"\n\t\t\ta[1] = strings.TrimSpace(a[1][1:])\n\t\t}\n\n\t\tterms[i].key = a[0]\n\t\tterms[i].value = a[1]\n\n\t\tif terms[i].key == \"name\" {\n\t\t\tterms[i].key = \"__name__\"\n\t\t}\n\n\t\tswitch op {\n\t\tcase \"=\":\n\t\t\tterms[i].op = taggedTermEq\n\t\tcase \"!=\":\n\t\t\tterms[i].op = taggedTermNe\n\t\tcase \"=~\":\n\t\t\tterms[i].op = taggedTermMatch\n\t\tcase \"!=~\":\n\t\t\tterms[i].op = taggedTermNotMatch\n\t\tdefault:\n\t\t\treturn \"\", validationError\n\t\t}\n\t}\n\n\tsort.Sort(taggedTermList(terms))\n\n\tw := NewWhere()\n\tw.And(taggedTermWhere1(&terms[0]))\n\n\tfor i := 1; i < len(terms); i++ {\n\t\tw.And(taggedTermWhereN(&terms[i]))\n\t}\n\n\treturn w.String(), nil\n\n}\n\nfunc (t *TaggedFinder) Execute(query string) error {\n\tif !strings.HasPrefix(strings.TrimSpace(query), \"seriesByTag\") {\n\t\treturn t.wrapped.Execute(query)\n\t}\n\n\tt.isSeriesByTag = true\n\n\tw, err := t.makeWhere(query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsql := fmt.Sprintf(\"SELECT Path FROM %s WHERE %s GROUP BY Path HAVING argMax(Deleted, Version)==0\", t.table, w)\n\tt.body, err = clickhouse.Query(t.ctx, t.url, sql, t.timeout)\n\treturn err\n}\n\nfunc (t *TaggedFinder) List() [][]byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.List()\n\t}\n\n\tif t.body == nil {\n\t\treturn [][]byte{}\n\t}\n\n\trows := bytes.Split(t.body, []byte{'\\n'})\n\n\tskip := 0\n\tfor i := 0; i < len(rows); i++ {\n\t\tif len(rows[i]) == 0 {\n\t\t\tskip++\n\t\t\tcontinue\n\t\t}\n\t\tif skip > 0 {\n\t\t\trows[i-skip] = rows[i]\n\t\t}\n\t}\n\n\trows = rows[:len(rows)-skip]\n\n\treturn rows\n}\n\nfunc (t *TaggedFinder) Series() [][]byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.Series()\n\t}\n\n\treturn t.List()\n}\n\nfunc (t *TaggedFinder) Abs(v []byte) []byte {\n\tif !t.isSeriesByTag {\n\t\treturn t.wrapped.Abs(v)\n\t}\n\n\tu, err := url.Parse(string(v))\n\tif err != nil {\n\t\treturn v\n\t}\n\n\ttags := make([]string, 0, len(u.Query()))\n\tfor k, v := range u.Query() {\n\t\ttags = append(tags, fmt.Sprintf(\"%s=%s\", k, v[0]))\n\t}\n\n\tsort.Strings(tags)\n\tif len(tags) == 0 {\n\t\treturn []byte(u.Path)\n\t}\n\n\treturn []byte(fmt.Sprintf(\"%s;%s\", u.Path, strings.Join(tags, \";\")))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\n\t\"github.com\/ovn-org\/libovsdb\"\n)\n\n\/\/ Silly game that detects creation of Bridge named \"stop\" and exits\n\/\/ Just a demonstration of how an app can use libovsdb library to configure and manage OVS\nconst (\n\tbridgeTable = \"Bridge\"\n\tovsDb       = \"Open_vSwitch\"\n\tovsTable    = ovsDb\n)\n\nvar quit chan bool\nvar update chan *libovsdb.TableUpdates\nvar cache map[string]map[string]libovsdb.Row\n\nfunc play(ovs *libovsdb.OvsdbClient) {\n\tgo processInput(ovs)\n\tfor currUpdate := range update {\n\t\tfor table, tableUpdate := range currUpdate.Updates {\n\t\t\tif table == bridgeTable {\n\t\t\t\tfor uuid, row := range tableUpdate.Rows {\n\t\t\t\t\trowData, err := ovs.API.GetRowData(bridgeTable, &row.New)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"ERROR getting Bridge Data\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := rowData[\"name\"]; ok {\n\t\t\t\t\t\tname := rowData[\"name\"].(string)\n\t\t\t\t\t\tif name == \"stop\" {\n\t\t\t\t\t\t\tfmt.Println(\"Bridge stop detected : \", uuid)\n\t\t\t\t\t\t\tovs.Disconnect()\n\t\t\t\t\t\t\tquit <- 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 createBridge(ovs *libovsdb.OvsdbClient, bridgeName string) {\n\tnamedUUID := \"gopher\"\n\t\/\/ bridge row to insert\n\tbridge := make(map[string]interface{})\n\tbridge[\"name\"] = bridgeName\n\tbridge[\"external_ids\"] = map[string]string{\"purpose\": \"fun\"}\n\n\tbrow, err := ovs.API.NewRow(bridgeTable, bridge)\n\tif err != nil {\n\t\tfmt.Printf(\"Row Error: %s\", err.Error())\n\t\tos.Exit(1)\n\n\t}\n\t\/\/ simple insert operation\n\tinsertOp := libovsdb.Operation{\n\t\tOp:       \"insert\",\n\t\tTable:    bridgeTable,\n\t\tRow:      brow,\n\t\tUUIDName: namedUUID,\n\t}\n\n\t\/\/ Inserting a Bridge row in Bridge table requires mutating the open_vswitch table.\n\tmutation, err := ovs.API.NewMutation(ovsTable, \"bridges\", \"insert\", []string{namedUUID})\n\tif err != nil {\n\t\tfmt.Printf(\"Mutation Error: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\tcondition, err := ovs.API.NewCondition(ovsTable, \"_uuid\", \"==\", getRootUUID())\n\tif err != nil {\n\t\tfmt.Printf(\"Condition Error: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ simple mutate operation\n\tmutateOp := libovsdb.Operation{\n\t\tOp:        \"mutate\",\n\t\tTable:     \"ovsTable\",\n\t\tMutations: []interface{}{mutation},\n\t\tWhere:     []interface{}{condition},\n\t}\n\n\toperations := []libovsdb.Operation{insertOp, mutateOp}\n\treply, _ := ovs.Transact(operations...)\n\n\tif len(reply) < len(operations) {\n\t\tfmt.Println(\"Number of Replies should be atleast equal to number of Operations\")\n\t}\n\tok := true\n\tfor i, o := range reply {\n\t\tif o.Error != \"\" && i < len(operations) {\n\t\t\tfmt.Println(\"Transaction Failed due to an error :\", o.Error, \" details:\", o.Details, \" in \", operations[i])\n\t\t\tok = false\n\t\t} else if o.Error != \"\" {\n\t\t\tfmt.Println(\"Transaction Failed due to an error :\", o.Error)\n\t\t\tok = false\n\t\t}\n\t}\n\tif ok {\n\t\tfmt.Println(\"Bridge Addition Successful : \", reply[0].UUID.GoUUID)\n\t}\n}\n\nfunc processInput(ovs *libovsdb.OvsdbClient) {\n\tfor {\n\t\tfmt.Printf(\"\\n Enter a Bridge Name : \")\n\t\tvar bridgeName string\n\t\tfmt.Scanf(\"%s\", &bridgeName)\n\t\tcreateBridge(ovs, bridgeName)\n\t}\n}\n\nfunc getRootUUID() string {\n\tfor uuid := range cache[ovsTable] {\n\t\treturn uuid\n\t}\n\treturn \"\"\n}\n\nfunc populateCache(updates libovsdb.TableUpdates) {\n\tfor table, tableUpdate := range updates.Updates {\n\t\tif _, ok := cache[table]; !ok {\n\t\t\tcache[table] = make(map[string]libovsdb.Row)\n\n\t\t}\n\t\tfor uuid, row := range tableUpdate.Rows {\n\t\t\tempty := libovsdb.Row{}\n\t\t\tif !reflect.DeepEqual(row.New, empty) {\n\t\t\t\tcache[table][uuid] = row.New\n\t\t\t} else {\n\t\t\t\tdelete(cache[table], uuid)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tquit = make(chan bool)\n\tupdate = make(chan *libovsdb.TableUpdates)\n\tcache = make(map[string]map[string]libovsdb.Row)\n\n\t\/\/ By default libovsdb connects to 127.0.0.0:6400.\n\tovs, err := libovsdb.Connect(\"tcp:\", \"Open_vSwitch\", nil)\n\n\t\/\/ If you prefer to connect to OVS in a specific location :\n\t\/\/ ovs, err := libovsdb.Connect(\"tcp:192.168.56.101:6640\", nil)\n\n\tif err != nil {\n\t\tfmt.Println(\"Unable to Connect \", err)\n\t\tos.Exit(1)\n\t}\n\tvar notifier myNotifier\n\tovs.Register(notifier)\n\n\tinitial, _ := ovs.MonitorAll(\"\")\n\tpopulateCache(*initial)\n\n\tfmt.Println(`Silly game of stopping this app when a Bridge with name \"stop\" is monitored !`)\n\tgo play(ovs)\n\t<-quit\n}\n\ntype myNotifier struct {\n}\n\nfunc (n myNotifier) Update(context interface{}, tableUpdates libovsdb.TableUpdates) {\n\tpopulateCache(tableUpdates)\n\tupdate <- &tableUpdates\n}\nfunc (n myNotifier) Locked([]interface{}) {\n}\nfunc (n myNotifier) Stolen([]interface{}) {\n}\nfunc (n myNotifier) Echo([]interface{}) {\n}\nfunc (n myNotifier) Disconnected() {\n}\n<commit_msg>play_with_ovs: Fix validation error<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\n\t\"github.com\/ovn-org\/libovsdb\"\n)\n\n\/\/ Silly game that detects creation of Bridge named \"stop\" and exits\n\/\/ Just a demonstration of how an app can use libovsdb library to configure and manage OVS\nconst (\n\tbridgeTable = \"Bridge\"\n\tovsDb       = \"Open_vSwitch\"\n\tovsTable    = ovsDb\n)\n\nvar quit chan bool\nvar update chan *libovsdb.TableUpdates\nvar cache map[string]map[string]libovsdb.Row\n\nfunc play(ovs *libovsdb.OvsdbClient) {\n\tgo processInput(ovs)\n\tfor currUpdate := range update {\n\t\tfor table, tableUpdate := range currUpdate.Updates {\n\t\t\tif table == bridgeTable {\n\t\t\t\tfor uuid, row := range tableUpdate.Rows {\n\t\t\t\t\trowData, err := ovs.API.GetRowData(bridgeTable, &row.New)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(\"ERROR getting Bridge Data\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif _, ok := rowData[\"name\"]; ok {\n\t\t\t\t\t\tname := rowData[\"name\"].(string)\n\t\t\t\t\t\tif name == \"stop\" {\n\t\t\t\t\t\t\tfmt.Println(\"Bridge stop detected : \", uuid)\n\t\t\t\t\t\t\tovs.Disconnect()\n\t\t\t\t\t\t\tquit <- 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 createBridge(ovs *libovsdb.OvsdbClient, bridgeName string) {\n\tnamedUUID := \"gopher\"\n\t\/\/ bridge row to insert\n\tbridge := make(map[string]interface{})\n\tbridge[\"name\"] = bridgeName\n\tbridge[\"external_ids\"] = map[string]string{\"purpose\": \"fun\"}\n\n\tbrow, err := ovs.API.NewRow(bridgeTable, bridge)\n\tif err != nil {\n\t\tlog.Fatalf(\"Row Error: %s\", err.Error())\n\t}\n\t\/\/ simple insert operation\n\tinsertOp := libovsdb.Operation{\n\t\tOp:       \"insert\",\n\t\tTable:    bridgeTable,\n\t\tRow:      brow,\n\t\tUUIDName: namedUUID,\n\t}\n\n\t\/\/ Inserting a Bridge row in Bridge table requires mutating the open_vswitch table.\n\tmutation, err := ovs.API.NewMutation(ovsTable, \"bridges\", \"insert\", []string{namedUUID})\n\tif err != nil {\n\t\tlog.Fatalf(\"Mutation Error: %s\", err.Error())\n\t}\n\tcondition, err := ovs.API.NewCondition(ovsTable, \"_uuid\", \"==\", getRootUUID())\n\tif err != nil {\n\t\tlog.Fatalf(\"Condition Error: %s\", err.Error())\n\t}\n\n\t\/\/ simple mutate operation\n\tmutateOp := libovsdb.Operation{\n\t\tOp:        \"mutate\",\n\t\tTable:     ovsTable,\n\t\tMutations: []interface{}{mutation},\n\t\tWhere:     []interface{}{condition},\n\t}\n\n\toperations := []libovsdb.Operation{insertOp, mutateOp}\n\treply, err := ovs.Transact(operations...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif len(reply) < len(operations) {\n\t\tfmt.Println(\"Number of Replies should be atleast equal to number of Operations\")\n\t}\n\tok := true\n\tfor i, o := range reply {\n\t\tif o.Error != \"\" && i < len(operations) {\n\t\t\tfmt.Println(\"Transaction Failed due to an error :\", o.Error, \" details:\", o.Details, \" in \", operations[i])\n\t\t\tok = false\n\t\t} else if o.Error != \"\" {\n\t\t\tfmt.Println(\"Transaction Failed due to an error :\", o.Error)\n\t\t\tok = false\n\t\t}\n\t}\n\tif ok {\n\t\tfmt.Println(\"Bridge Addition Successful : \", reply[0].UUID.GoUUID)\n\t}\n}\n\nfunc processInput(ovs *libovsdb.OvsdbClient) {\n\tfor {\n\t\tfmt.Printf(\"\\n Enter a Bridge Name : \")\n\t\tvar bridgeName string\n\t\tfmt.Scanf(\"%s\", &bridgeName)\n\t\tcreateBridge(ovs, bridgeName)\n\t}\n}\n\nfunc getRootUUID() string {\n\tfor uuid := range cache[ovsTable] {\n\t\treturn uuid\n\t}\n\treturn \"\"\n}\n\nfunc populateCache(updates libovsdb.TableUpdates) {\n\tfor table, tableUpdate := range updates.Updates {\n\t\tif _, ok := cache[table]; !ok {\n\t\t\tcache[table] = make(map[string]libovsdb.Row)\n\n\t\t}\n\t\tfor uuid, row := range tableUpdate.Rows {\n\t\t\tempty := libovsdb.Row{}\n\t\t\tif !reflect.DeepEqual(row.New, empty) {\n\t\t\t\tcache[table][uuid] = row.New\n\t\t\t} else {\n\t\t\t\tdelete(cache[table], uuid)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tquit = make(chan bool)\n\tupdate = make(chan *libovsdb.TableUpdates)\n\tcache = make(map[string]map[string]libovsdb.Row)\n\n\t\/\/ By default libovsdb connects to 127.0.0.0:6400.\n\tovs, err := libovsdb.Connect(\"tcp:\", \"Open_vSwitch\", nil)\n\n\t\/\/ If you prefer to connect to OVS in a specific location :\n\t\/\/ ovs, err := libovsdb.Connect(\"tcp:192.168.56.101:6640\", nil)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to Connect \", err)\n\t}\n\tvar notifier myNotifier\n\tovs.Register(notifier)\n\n\tinitial, _ := ovs.MonitorAll(\"\")\n\tpopulateCache(*initial)\n\n\tfmt.Println(`Silly game of stopping this app when a Bridge with name \"stop\" is monitored !`)\n\tgo play(ovs)\n\t<-quit\n}\n\ntype myNotifier struct {\n}\n\nfunc (n myNotifier) Update(context interface{}, tableUpdates libovsdb.TableUpdates) {\n\tpopulateCache(tableUpdates)\n\tupdate <- &tableUpdates\n}\nfunc (n myNotifier) Locked([]interface{}) {\n}\nfunc (n myNotifier) Stolen([]interface{}) {\n}\nfunc (n myNotifier) Echo([]interface{}) {\n}\nfunc (n myNotifier) Disconnected() {\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\npackage blocks\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"strings\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/inpututil\"\n)\n\ntype GamepadScene struct {\n\tgamepadID         int\n\tcurrentIndex      int\n\tcountAfterSetting int\n\tbuttonStates      []string\n}\n\nfunc (s *GamepadScene) Update(state *GameState) error {\n\tif s.currentIndex == 0 {\n\t\tstate.Input.gamepadConfig.Reset()\n\t\tstate.Input.gamepadConfig.SetGamepadID(s.gamepadID)\n\t}\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEscape) {\n\t\tstate.Input.gamepadConfig.Reset()\n\t\tstate.SceneManager.GoTo(&TitleScene{})\n\t}\n\n\tif s.buttonStates == nil {\n\t\ts.buttonStates = make([]string, len(virtualGamepadButtons))\n\t}\n\tfor i, b := range virtualGamepadButtons {\n\t\tif i < s.currentIndex {\n\t\t\ts.buttonStates[i] = strings.ToUpper(state.Input.gamepadConfig.ButtonName(b))\n\t\t\tcontinue\n\t\t}\n\t\tif s.currentIndex == i {\n\t\t\ts.buttonStates[i] = \"_\"\n\t\t\tcontinue\n\t\t}\n\t\ts.buttonStates[i] = \"\"\n\t}\n\n\tif 0 < s.countAfterSetting {\n\t\ts.countAfterSetting--\n\t\tif s.countAfterSetting <= 0 {\n\t\t\tstate.SceneManager.GoTo(&TitleScene{})\n\t\t}\n\t\treturn nil\n\t}\n\n\tb := virtualGamepadButtons[s.currentIndex]\n\tif state.Input.gamepadConfig.Scan(b) {\n\t\ts.currentIndex++\n\t\tif s.currentIndex == len(virtualGamepadButtons) {\n\t\t\ts.countAfterSetting = ebiten.MaxTPS()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *GamepadScene) Draw(screen *ebiten.Image) {\n\tscreen.Fill(color.Black)\n\n\tif s.buttonStates == nil {\n\t\treturn\n\t}\n\n\tf := `GAMEPAD CONFIGURATION\n(PRESS ESC TO CANCEL)\n\n\nMOVE LEFT:    %s\n\nMOVE RIGHT:   %s\n\nDROP:         %s\n\nROTATE LEFT:  %s\n\nROTATE RIGHT: %s\n\n\n\n%s`\n\tmsg := \"\"\n\tif s.currentIndex == len(virtualGamepadButtons) {\n\t\tmsg = \"OK!\"\n\t}\n\tstr := fmt.Sprintf(f, s.buttonStates[0], s.buttonStates[1], s.buttonStates[2], s.buttonStates[3], s.buttonStates[4], msg)\n\tdrawTextWithShadow(screen, str, 16, 16, 1, color.White)\n}\n<commit_msg>examples\/blocks: Bug fix: ESC key caused crashing<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\npackage blocks\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"strings\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/inpututil\"\n)\n\ntype GamepadScene struct {\n\tgamepadID         int\n\tcurrentIndex      int\n\tcountAfterSetting int\n\tbuttonStates      []string\n}\n\nfunc (s *GamepadScene) Update(state *GameState) error {\n\tif s.currentIndex == 0 {\n\t\tstate.Input.gamepadConfig.Reset()\n\t\tstate.Input.gamepadConfig.SetGamepadID(s.gamepadID)\n\t}\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEscape) {\n\t\tstate.Input.gamepadConfig.Reset()\n\t\tstate.SceneManager.GoTo(&TitleScene{})\n\t\treturn nil\n\t}\n\n\tif s.buttonStates == nil {\n\t\ts.buttonStates = make([]string, len(virtualGamepadButtons))\n\t}\n\tfor i, b := range virtualGamepadButtons {\n\t\tif i < s.currentIndex {\n\t\t\ts.buttonStates[i] = strings.ToUpper(state.Input.gamepadConfig.ButtonName(b))\n\t\t\tcontinue\n\t\t}\n\t\tif s.currentIndex == i {\n\t\t\ts.buttonStates[i] = \"_\"\n\t\t\tcontinue\n\t\t}\n\t\ts.buttonStates[i] = \"\"\n\t}\n\n\tif 0 < s.countAfterSetting {\n\t\ts.countAfterSetting--\n\t\tif s.countAfterSetting <= 0 {\n\t\t\tstate.SceneManager.GoTo(&TitleScene{})\n\t\t}\n\t\treturn nil\n\t}\n\n\tb := virtualGamepadButtons[s.currentIndex]\n\tif state.Input.gamepadConfig.Scan(b) {\n\t\ts.currentIndex++\n\t\tif s.currentIndex == len(virtualGamepadButtons) {\n\t\t\ts.countAfterSetting = ebiten.MaxTPS()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *GamepadScene) Draw(screen *ebiten.Image) {\n\tscreen.Fill(color.Black)\n\n\tif s.buttonStates == nil {\n\t\treturn\n\t}\n\n\tf := `GAMEPAD CONFIGURATION\n(PRESS ESC TO CANCEL)\n\n\nMOVE LEFT:    %s\n\nMOVE RIGHT:   %s\n\nDROP:         %s\n\nROTATE LEFT:  %s\n\nROTATE RIGHT: %s\n\n\n\n%s`\n\tmsg := \"\"\n\tif s.currentIndex == len(virtualGamepadButtons) {\n\t\tmsg = \"OK!\"\n\t}\n\tstr := fmt.Sprintf(f, s.buttonStates[0], s.buttonStates[1], s.buttonStates[2], s.buttonStates[3], s.buttonStates[4], msg)\n\tdrawTextWithShadow(screen, str, 16, 16, 1, color.White)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"testing\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"strings\"\n\t\"tdformat\"\n\t\"bytes\"\n)\n\nfunc TestGeneral(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"holder\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"w1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n\n\"w2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder\" holds 0x123 (java.lang.Object)\n- w1\n- w2\n\n`, \"\\n\" + out.String())\n}\n\n\/*\n\tA special test for Object.wait() because the thread is then both locker and waiting.\n*\/\nfunc TestObjectWait(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"D3D Screen Updater\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x00000000c0092b98> (a java.lang.Object)\n\t- locked <0x00000000c0092b98> (a java.lang.Object)\n\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"D3D Screen Updater\" holds 0x00000000c0092b98 (java.lang.Object)\n- D3D Screen Updater\n\n`, \"\\n\" + out.String())\n}\n\nfunc TestClassFilter(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"filteredOut\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"holder1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x456> (a a.b.C)\n\n\"holder2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x789> (a a.b.C)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"a.b.C\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder1\" holds 0x456 (a.b.C)\n\n\"holder2\" holds 0x789 (a.b.C)\n\n`, \"\\n\" + out.String())\n}\n\nfunc TestMinWaiting(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"holder\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x456> (a java.lang.Object)\n\n\"w1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x456> (a java.lang.Object)\n\n\"w2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x456> (a java.lang.Object)\n\n\"holder2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"w3\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 2, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder\" holds 0x456 (java.lang.Object)\n- w1\n- w2\n\n`, \"\\n\" + out.String())\n}\n<commit_msg>fixed test<commit_after>package main\n\nimport (\n\t\"testing\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"strings\"\n\t\"tdformat\"\n\t\"bytes\"\n)\n\nfunc TestGeneral(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"holder\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"w1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n\n\"w2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder\" holds 0x123 (java.lang.Object)\n- w1\n- w2\n\n`, \"\\n\" + out.String())\n}\n\n\/*\n\tA special test for Object.wait() because the thread is then both locker and waiting.\n*\/\nfunc TestObjectWait(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"D3D Screen Updater\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x00000000c0092b98> (a java.lang.Object)\n\t- locked <0x00000000c0092b98> (a java.lang.Object)\n\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"D3D Screen Updater\" holds 0x00000000c0092b98 (java.lang.Object)\n- D3D Screen Updater\n\n`, \"\\n\" + out.String())\n}\n\nfunc TestClassFilter(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"filteredOut\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"holder1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x456> (a a.b.C)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 0, \"a.b.C\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder1\" holds 0x456 (a.b.C)\n\n`, \"\\n\" + out.String())\n}\n\nfunc TestMinWaiting(t *testing.T) {\n\treader := strings.NewReader(`\n2014-12-31 11:01:49\nFull thread dump Java HotSpot(TM) 64-Bit Server VM (24.65-b04 mixed mode):\n\n\"holder\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x456> (a java.lang.Object)\n\n\"w1\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x456> (a java.lang.Object)\n\n\"w2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x456> (a java.lang.Object)\n\n\"holder2\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- locked <0x123> (a java.lang.Object)\n\n\"w3\" daemon prio=8 tid=0x00000000094ce800 nid=0xe2c in Object.wait() [0x000000000ce3e000]\n   java.lang.Thread.State: TIMED_WAITING (on object monitor)\n\t- waiting on <0x123> (a java.lang.Object)\n`)\n\t\n\tparser := tdformat.NewParser(reader)\n\tassert.NotNil(t, parser)\n\n\tvar out bytes.Buffer\n\n\tlistLocks(parser, 2, \"\", &out)\n\tassert.Equal(t, `\nDump: 2014-12-31 11:01:49\n\"holder\" holds 0x456 (java.lang.Object)\n- w1\n- w2\n\n`, \"\\n\" + out.String())\n}\n<|endoftext|>"}
{"text":"<commit_before>package dashing\n\n\/\/ An Event contains the widget ID, a body of data,\n\/\/ and an optional target (only \"dashboard\" for now).\ntype Event struct {\n\tID     string\n\tBody   map[string]interface{}\n\tTarget string\n}\n\n\/\/ A Broker broadcasts events to multiple clients.\ntype Broker struct {\n\t\/\/ Create a map of clients, the keys of the map are the channels\n\t\/\/ over which we can push messages to attached clients. (The values\n\t\/\/ are just booleans and are meaningless)\n\tclients map[chan *Event]bool\n\n\t\/\/ Channel into which new clients can be pushed\n\tnewClients chan chan *Event\n\n\t\/\/ Channel into which disconnected clients should be pushed\n\tdefunctClients chan chan *Event\n\n\t\/\/ Channel into which events are pushed to be broadcast out\n\t\/\/ to attached clients\n\tevents chan *Event\n}\n\n\/\/ Start managing client connections and event broadcasts.\nfunc (b *Broker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t\/\/ Block until we receive from one of the\n\t\t\t\/\/ three following channels.\n\t\t\tselect {\n\t\t\tcase s := <-b.newClients:\n\t\t\t\t\/\/ There is a new client attached and we\n\t\t\t\t\/\/ want to start sending them events.\n\t\t\t\tb.clients[s] = true\n\t\t\t\t\/\/ log.Println(\"Added new client\")\n\t\t\tcase s := <-b.defunctClients:\n\t\t\t\t\/\/ A client has detached and we want to\n\t\t\t\t\/\/ stop sending them events.\n\t\t\t\tdelete(b.clients, s)\n\t\t\t\t\/\/ log.Println(\"Removed client\")\n\t\t\tcase event := <-b.events:\n\t\t\t\t\/\/ There is a new event to send. For each\n\t\t\t\t\/\/ attached client, push the new event\n\t\t\t\t\/\/ into the client's channel.\n\t\t\t\tfor s := range b.clients {\n\t\t\t\t\ts <- event\n\t\t\t\t}\n\t\t\t\t\/\/ log.Printf(\"Broadcast event to %d clients\", len(b.clients))\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ NewBroker creates a Broker instance.\nfunc NewBroker() *Broker {\n\treturn &Broker{\n\t\tmake(map[chan *Event]bool),\n\t\tmake(chan (chan *Event)),\n\t\tmake(chan (chan *Event)),\n\t\tmake(chan *Event),\n\t}\n}\n<commit_msg>Cache events so that new clients don't miss out<commit_after>package dashing\n\n\/\/ An Event contains the widget ID, a body of data,\n\/\/ and an optional target (only \"dashboard\" for now).\ntype Event struct {\n\tID     string\n\tBody   map[string]interface{}\n\tTarget string\n}\n\n\/\/ An eventCache stores the latest event for each key, so that new clients can\n\/\/ catch up.\ntype eventCache map[string]*Event\n\n\/\/ A Broker broadcasts events to multiple clients.\ntype Broker struct {\n\t\/\/ Create a map of clients, the keys of the map are the channels\n\t\/\/ over which we can push messages to attached clients. (The values\n\t\/\/ are just booleans and are meaningless)\n\tclients map[chan *Event]bool\n\n\t\/\/ Channel into which new clients can be pushed\n\tnewClients chan chan *Event\n\n\t\/\/ Channel into which disconnected clients should be pushed\n\tdefunctClients chan chan *Event\n\n\t\/\/ Channel into which events are pushed to be broadcast out\n\t\/\/ to attached clients\n\tevents chan *Event\n\n\t\/\/ Cache for most recent events with a certain ID\n\tcache eventCache\n}\n\n\/\/ Start managing client connections and event broadcasts.\nfunc (b *Broker) Start() {\n\tgo func() {\n\t\tfor {\n\t\t\t\/\/ Block until we receive from one of the\n\t\t\t\/\/ three following channels.\n\t\t\tselect {\n\t\t\tcase s := <-b.newClients:\n\t\t\t\t\/\/ There is a new client attached and we\n\t\t\t\t\/\/ want to start sending them events.\n\t\t\t\tb.clients[s] = true\n\t\t\t\t\/\/ Send all the cached events so that when a new client connects, it\n\t\t\t\t\/\/ doesn't miss previous events\n\t\t\t\tfor _, e := range b.cache {\n\t\t\t\t\ts <- e\n\t\t\t\t}\n\t\t\t\t\/\/ log.Println(\"Added new client\")\n\t\t\tcase s := <-b.defunctClients:\n\t\t\t\t\/\/ A client has detached and we want to\n\t\t\t\t\/\/ stop sending them events.\n\t\t\t\tdelete(b.clients, s)\n\t\t\t\t\/\/ log.Println(\"Removed client\")\n\t\t\tcase event := <-b.events:\n\t\t\t\tb.cache[event.ID] = event\n\t\t\t\t\/\/ There is a new event to send. For each\n\t\t\t\t\/\/ attached client, push the new event\n\t\t\t\t\/\/ into the client's channel.\n\t\t\t\tfor s := range b.clients {\n\t\t\t\t\ts <- event\n\t\t\t\t}\n\t\t\t\t\/\/ log.Printf(\"Broadcast event to %d clients\", len(b.clients))\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ NewBroker creates a Broker instance.\nfunc NewBroker() *Broker {\n\treturn &Broker{\n\t\tmake(map[chan *Event]bool),\n\t\tmake(chan (chan *Event)),\n\t\tmake(chan (chan *Event)),\n\t\tmake(chan *Event),\n\t\tmap[string]*Event{},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 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\npackage docker\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype APIEvents struct {\n\tStatus string\n\tID     string\n\tFrom   string\n\tTime   int64\n}\n\ntype EventMonitoringState struct {\n\tsync.RWMutex\n\tenabled   bool\n\tlastSeen  int64\n\tC         chan *APIEvents\n\terrC      chan error\n\tlisteners []chan *APIEvents\n}\n\nvar eventMonitor EventMonitoringState\nvar ErrNoListeners = errors.New(\"No listeners to send event to...\")\n\nfunc (c *Client) AddEventListener(listener chan *APIEvents) error {\n\terr := eventMonitor.enableEventMonitoring(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventMonitor.addListener(listener)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Client) RemoveEventListener(listener chan *APIEvents) error {\n\terr := eventMonitor.removeListener(listener)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(eventMonitor.listeners) == 0 {\n\t\terr = eventMonitor.disableEventMonitoring()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) addListener(listener chan *APIEvents) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif listenerExists(listener, &eventState.listeners) {\n\t\treturn fmt.Errorf(\"Listener already exists\")\n\t}\n\teventState.listeners = append(eventState.listeners, listener)\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) removeListener(listener chan *APIEvents) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tvar newListeners []chan *APIEvents\n\tif listenerExists(listener, &eventState.listeners) {\n\t\tfor _, l := range eventState.listeners {\n\t\t\tif l != listener {\n\t\t\t\tnewListeners = append(newListeners, l)\n\t\t\t}\n\t\t}\n\t\teventState.listeners = newListeners\n\t}\n\treturn nil\n}\n\nfunc listenerExists(a chan *APIEvents, list *[]chan *APIEvents) 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\nfunc (eventState *EventMonitoringState) enableEventMonitoring(c *Client) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif !eventState.enabled {\n\t\teventState.enabled = true\n\t\teventState.C = make(chan *APIEvents, 100)\n\t\teventState.errC = make(chan error, 1)\n\t\tgo eventState.monitorEvents(c)\n\t}\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) disableEventMonitoring() error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif !eventState.enabled {\n\t\teventState.enabled = false\n\t\tclose(eventState.C)\n\t\tclose(eventState.errC)\n\t}\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) monitorEvents(c *Client) {\n\tvar retries int\n\tvar err error\n\n\t\/\/ wait for first listener\n\tfor len(eventState.listeners) == 0 {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfor err = c.eventHijack(uint32(eventState.lastSeen), eventState.C, eventState.errC); err != nil && retries < 5; retries++ {\n\t\twaitTime := int64(float64(10) * math.Pow(2, float64(retries)))\n\t\ttime.Sleep(time.Duration(waitTime) * time.Millisecond)\n\t\terr = c.eventHijack(uint32(eventState.lastSeen), eventState.C, eventState.errC)\n\t}\n\n\tif err != nil {\n\t\teventState.terminate(err)\n\t}\n\n\tfor eventState.enabled {\n\t\ttimeout := time.After(100 * time.Millisecond)\n\t\tselect {\n\t\tcase ev := <-eventState.C:\n\t\t\t\/\/ send the event\n\t\t\tgo eventState.sendEvent(ev)\n\n\t\t\t\/\/ update lastSeen if appropriate\n\t\t\tgo func(e *APIEvents) {\n\t\t\t\teventState.Lock()\n\t\t\t\tdefer eventState.Unlock()\n\t\t\t\tif eventState.lastSeen < e.Time {\n\t\t\t\t\teventState.lastSeen = e.Time\n\t\t\t\t}\n\t\t\t}(ev)\n\n\t\tcase err = <-eventState.errC:\n\t\t\tif err == ErrNoListeners {\n\t\t\t\t\/\/ if there are no listeners, exit normally\n\t\t\t\teventState.terminate(nil)\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\t\/\/ otherwise, trigger a restart via the error channel\n\t\t\t\tdefer func() { go eventState.monitorEvents(c) }()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (eventState *EventMonitoringState) sendEvent(event *APIEvents) {\n\n\teventState.RLock()\n\tdefer eventState.RUnlock()\n\tif len(eventState.listeners) == 0 {\n\t\teventState.errC <- ErrNoListeners\n\t}\n\tfor _, listener := range eventState.listeners {\n\t\tlistener <- event\n\t}\n}\n\nfunc (eventState *EventMonitoringState) terminate(err error) {\n\teventState.disableEventMonitoring()\n}\n\nfunc (c *Client) eventHijack(startTime uint32, eventChan chan *APIEvents, errChan chan error) error {\n\n\turi := \"\/events\"\n\n\tif startTime != 0 {\n\t\turi += fmt.Sprintf(\"?since=%d\", startTime)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", c.getURL(uri), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\tprotocol := c.endpointURL.Scheme\n\taddress := c.endpointURL.Path\n\tif protocol != \"unix\" {\n\t\tprotocol = \"tcp\"\n\t\taddress = c.endpointURL.Host\n\t}\n\n\tdial, err := net.Dial(protocol, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientconn := httputil.NewClientConn(dial, nil)\n\tclientconn.Do(req)\n\n\tconn, rwc := clientconn.Hijack()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func(rwc io.Reader) {\n\n\t\tdefer clientconn.Close()\n\t\tdefer conn.Close()\n\n\t\tscanner := bufio.NewScanner(rwc)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\n\t\t\t\/\/ Only pay attention to lines that start as json objects\n\t\t\tif strings.HasPrefix(line, \"{\") {\n\t\t\t\tvar e APIEvents\n\t\t\t\terr = json.Unmarshal([]byte(line), &e)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t}\n\t\t\t\teventChan <- &e\n\t\t\t}\n\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\terrChan <- err\n\t\t}\n\t}(rwc)\n\n\treturn nil\n}\n<commit_msg>correct logic error on disabling monitoring<commit_after>\/\/ Copyright 2013 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\npackage docker\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype APIEvents struct {\n\tStatus string\n\tID     string\n\tFrom   string\n\tTime   int64\n}\n\ntype EventMonitoringState struct {\n\tsync.RWMutex\n\tenabled   bool\n\tlastSeen  int64\n\tC         chan *APIEvents\n\terrC      chan error\n\tlisteners []chan *APIEvents\n}\n\nvar eventMonitor EventMonitoringState\nvar ErrNoListeners = errors.New(\"No listeners to send event to...\")\n\nfunc (c *Client) AddEventListener(listener chan *APIEvents) error {\n\terr := eventMonitor.enableEventMonitoring(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = eventMonitor.addListener(listener)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Client) RemoveEventListener(listener chan *APIEvents) error {\n\terr := eventMonitor.removeListener(listener)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(eventMonitor.listeners) == 0 {\n\t\terr = eventMonitor.disableEventMonitoring()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) addListener(listener chan *APIEvents) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif listenerExists(listener, &eventState.listeners) {\n\t\treturn fmt.Errorf(\"Listener already exists\")\n\t}\n\teventState.listeners = append(eventState.listeners, listener)\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) removeListener(listener chan *APIEvents) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tvar newListeners []chan *APIEvents\n\tif listenerExists(listener, &eventState.listeners) {\n\t\tfor _, l := range eventState.listeners {\n\t\t\tif l != listener {\n\t\t\t\tnewListeners = append(newListeners, l)\n\t\t\t}\n\t\t}\n\t\teventState.listeners = newListeners\n\t}\n\treturn nil\n}\n\nfunc listenerExists(a chan *APIEvents, list *[]chan *APIEvents) 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\nfunc (eventState *EventMonitoringState) enableEventMonitoring(c *Client) error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif !eventState.enabled {\n\t\teventState.enabled = true\n\t\teventState.C = make(chan *APIEvents, 100)\n\t\teventState.errC = make(chan error, 1)\n\t\tgo eventState.monitorEvents(c)\n\t}\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) disableEventMonitoring() error {\n\teventState.Lock()\n\tdefer eventState.Unlock()\n\tif eventState.enabled {\n\t\teventState.enabled = false\n\t\tclose(eventState.C)\n\t\tclose(eventState.errC)\n\t}\n\treturn nil\n}\n\nfunc (eventState *EventMonitoringState) monitorEvents(c *Client) {\n\tvar retries int\n\tvar err error\n\n\t\/\/ wait for first listener\n\tfor len(eventState.listeners) == 0 {\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\n\tfor err = c.eventHijack(uint32(eventState.lastSeen), eventState.C, eventState.errC); err != nil && retries < 5; retries++ {\n\t\twaitTime := int64(float64(10) * math.Pow(2, float64(retries)))\n\t\ttime.Sleep(time.Duration(waitTime) * time.Millisecond)\n\t\terr = c.eventHijack(uint32(eventState.lastSeen), eventState.C, eventState.errC)\n\t}\n\n\tif err != nil {\n\t\teventState.terminate(err)\n\t}\n\n\tfor eventState.enabled {\n\t\ttimeout := time.After(100 * time.Millisecond)\n\t\tselect {\n\t\tcase ev := <-eventState.C:\n\t\t\t\/\/ send the event\n\t\t\tgo eventState.sendEvent(ev)\n\n\t\t\t\/\/ update lastSeen if appropriate\n\t\t\tgo func(e *APIEvents) {\n\t\t\t\teventState.Lock()\n\t\t\t\tdefer eventState.Unlock()\n\t\t\t\tif eventState.lastSeen < e.Time {\n\t\t\t\t\teventState.lastSeen = e.Time\n\t\t\t\t}\n\t\t\t}(ev)\n\n\t\tcase err = <-eventState.errC:\n\t\t\tif err == ErrNoListeners {\n\t\t\t\t\/\/ if there are no listeners, exit normally\n\t\t\t\teventState.terminate(nil)\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\t\/\/ otherwise, trigger a restart via the error channel\n\t\t\t\tdefer func() { go eventState.monitorEvents(c) }()\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-timeout:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (eventState *EventMonitoringState) sendEvent(event *APIEvents) {\n\n\teventState.RLock()\n\tdefer eventState.RUnlock()\n\tif len(eventState.listeners) == 0 {\n\t\teventState.errC <- ErrNoListeners\n\t}\n\tfor _, listener := range eventState.listeners {\n\t\tlistener <- event\n\t}\n}\n\nfunc (eventState *EventMonitoringState) terminate(err error) {\n\teventState.disableEventMonitoring()\n}\n\nfunc (c *Client) eventHijack(startTime uint32, eventChan chan *APIEvents, errChan chan error) error {\n\n\turi := \"\/events\"\n\n\tif startTime != 0 {\n\t\turi += fmt.Sprintf(\"?since=%d\", startTime)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", c.getURL(uri), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"plain\/text\")\n\tprotocol := c.endpointURL.Scheme\n\taddress := c.endpointURL.Path\n\tif protocol != \"unix\" {\n\t\tprotocol = \"tcp\"\n\t\taddress = c.endpointURL.Host\n\t}\n\n\tdial, err := net.Dial(protocol, address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientconn := httputil.NewClientConn(dial, nil)\n\tclientconn.Do(req)\n\n\tconn, rwc := clientconn.Hijack()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo func(rwc io.Reader) {\n\n\t\tdefer clientconn.Close()\n\t\tdefer conn.Close()\n\n\t\tscanner := bufio.NewScanner(rwc)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\n\t\t\t\/\/ Only pay attention to lines that start as json objects\n\t\t\tif strings.HasPrefix(line, \"{\") {\n\t\t\t\tvar e APIEvents\n\t\t\t\terr = json.Unmarshal([]byte(line), &e)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t}\n\t\t\t\teventChan <- &e\n\t\t\t}\n\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\terrChan <- err\n\t\t}\n\t}(rwc)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sagemaker\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/validation\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/keyvaluetags\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/service\/sagemaker\/finder\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/service\/sagemaker\/waiter\"\n)\n\nfunc resourceAwsSagemakerImage() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSagemakerImageCreate,\n\t\tRead:   resourceAwsSagemakerImageRead,\n\t\tUpdate: resourceAwsSagemakerImageUpdate,\n\t\tDelete: resourceAwsSagemakerImageDelete,\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\n\t\t\t\"image_name\": {\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.All(\n\t\t\t\t\tvalidation.StringLenBetween(1, 63),\n\t\t\t\t\tvalidation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9](-*[a-zA-Z0-9])*$`), \"Valid characters are a-z, A-Z, 0-9, and - (hyphen).\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t\"role_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validateArn,\n\t\t\t},\n\t\t\t\"display_name\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringLenBetween(1, 128),\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\tValidateFunc: validation.StringLenBetween(1, 512),\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsSagemakerImageCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\n\tname := d.Get(\"image_name\").(string)\n\tinput := &sagemaker.CreateImageInput{\n\t\tImageName: aws.String(name),\n\t\tRoleArn:   aws.String(d.Get(\"role_arn\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"display_name\"); ok {\n\t\tinput.DisplayName = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok {\n\t\tinput.Description = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"tags\"); ok {\n\t\tinput.Tags = keyvaluetags.New(v.(map[string]interface{})).IgnoreAws().SagemakerTags()\n\t}\n\n\tlog.Printf(\"[DEBUG] sagemaker Image create config: %#v\", *input)\n\t_, err := conn.CreateImage(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating SageMaker Image: %w\", err)\n\t}\n\n\td.SetId(name)\n\n\tif _, err := waiter.ImageCreated(conn, d.Id()); err != nil {\n\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to create: %w\", d.Id(), err)\n\t}\n\n\treturn resourceAwsSagemakerImageRead(d, meta)\n}\n\nfunc resourceAwsSagemakerImageRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\tignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig\n\n\timage, err := finder.ImageByName(conn, d.Id())\n\tif err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\td.SetId(\"\")\n\t\t\tlog.Printf(\"[WARN] Unable to find SageMaker Image (%s); removing from state\", d.Id())\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error reading SageMaker Image (%s): %w\", d.Id(), err)\n\n\t}\n\n\tarn := aws.StringValue(image.ImageArn)\n\td.Set(\"image_name\", image.ImageName)\n\td.Set(\"arn\", arn)\n\td.Set(\"role_arn\", image.RoleArn)\n\td.Set(\"display_name\", image.DisplayName)\n\td.Set(\"description\", image.Description)\n\n\ttags, err := keyvaluetags.SagemakerListTags(conn, arn)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for SageMaker Image (%s): %w\", d.Id(), err)\n\t}\n\n\tif err := d.Set(\"tags\", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {\n\t\treturn fmt.Errorf(\"error setting tags: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSagemakerImageUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\tneedsUpdate := false\n\n\tinput := &sagemaker.UpdateImageInput{\n\t\tImageName: aws.String(d.Id()),\n\t}\n\n\tvar deleteProperties []*string\n\n\tif d.HasChange(\"role_arn\") {\n\t\tinput.RoleArn= aws.String(d.Get(\"role_arn\").(string))\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\tif v, ok := d.GetOk(\"description\"); ok {\n\t\t\tinput.Description = aws.String(v.(string))\n\t\t} else {\n\t\t\tdeleteProperties = append(deleteProperties, aws.String(\"Description\"))\n\t\t\tinput.DeleteProperties = deleteProperties\n\t\t}\n\t\tneedsUpdate = true\n\t}\n\n\tif d.HasChange(\"display_name\") {\n\t\tif v, ok := d.GetOk(\"display_name\"); ok {\n\t\t\tinput.DisplayName = aws.String(v.(string))\n\t\t} else {\n\t\t\tdeleteProperties = append(deleteProperties, aws.String(\"DisplayName\"))\n\t\t\tinput.DeleteProperties = deleteProperties\n\t\t}\n\t\tneedsUpdate = true\n\t}\n\n\tif needsUpdate {\n\t\tlog.Printf(\"[DEBUG] sagemaker Image update config: %#v\", *input)\n\t\t_, err := conn.UpdateImage(input)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updating SageMaker Image: %w\", err)\n\t\t}\n\n\t\tif _, err := waiter.ImageCreated(conn, d.Id()); err != nil {\n\t\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to update: %w\", 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.SagemakerUpdateTags(conn, d.Get(\"arn\").(string), o, n); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating SageMaker Image (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsSagemakerImageRead(d, meta)\n}\n\nfunc resourceAwsSagemakerImageDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\n\tinput := &sagemaker.DeleteImageInput{\n\t\tImageName: aws.String(d.Id()),\n\t}\n\n\tif _, err := conn.DeleteImage(input); err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error deleting SageMaker Image (%s): %w\", d.Id(), err)\n\t}\n\n\tif _, err := waiter.ImageDeleted(conn, d.Id()); err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to delete: %w\", d.Id(), err)\n\n\t}\n\n\treturn nil\n}\n<commit_msg>Update aws\/resource_aws_sagemaker_image.go<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sagemaker\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/validation\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/keyvaluetags\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/service\/sagemaker\/finder\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/service\/sagemaker\/waiter\"\n)\n\nfunc resourceAwsSagemakerImage() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSagemakerImageCreate,\n\t\tRead:   resourceAwsSagemakerImageRead,\n\t\tUpdate: resourceAwsSagemakerImageUpdate,\n\t\tDelete: resourceAwsSagemakerImageDelete,\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\n\t\t\t\"image_name\": {\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.All(\n\t\t\t\t\tvalidation.StringLenBetween(1, 63),\n\t\t\t\t\tvalidation.StringMatch(regexp.MustCompile(`^[a-zA-Z0-9](-*[a-zA-Z0-9])*$`), \"Valid characters are a-z, A-Z, 0-9, and - (hyphen).\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t\"role_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validateArn,\n\t\t\t},\n\t\t\t\"display_name\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringLenBetween(1, 128),\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\tValidateFunc: validation.StringLenBetween(1, 512),\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsSagemakerImageCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\n\tname := d.Get(\"image_name\").(string)\n\tinput := &sagemaker.CreateImageInput{\n\t\tImageName: aws.String(name),\n\t\tRoleArn:   aws.String(d.Get(\"role_arn\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"display_name\"); ok {\n\t\tinput.DisplayName = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok {\n\t\tinput.Description = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"tags\"); ok {\n\t\tinput.Tags = keyvaluetags.New(v.(map[string]interface{})).IgnoreAws().SagemakerTags()\n\t}\n\n\tlog.Printf(\"[DEBUG] sagemaker Image create config: %#v\", *input)\n\t_, err := conn.CreateImage(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating SageMaker Image: %w\", err)\n\t}\n\n\td.SetId(name)\n\n\tif _, err := waiter.ImageCreated(conn, d.Id()); err != nil {\n\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to create: %w\", d.Id(), err)\n\t}\n\n\treturn resourceAwsSagemakerImageRead(d, meta)\n}\n\nfunc resourceAwsSagemakerImageRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\tignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig\n\n\timage, err := finder.ImageByName(conn, d.Id())\n\tif err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\td.SetId(\"\")\n\t\t\tlog.Printf(\"[WARN] Unable to find SageMaker Image (%s); removing from state\", d.Id())\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error reading SageMaker Image (%s): %w\", d.Id(), err)\n\n\t}\n\n\tarn := aws.StringValue(image.ImageArn)\n\td.Set(\"image_name\", image.ImageName)\n\td.Set(\"arn\", arn)\n\td.Set(\"role_arn\", image.RoleArn)\n\td.Set(\"display_name\", image.DisplayName)\n\td.Set(\"description\", image.Description)\n\n\ttags, err := keyvaluetags.SagemakerListTags(conn, arn)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for SageMaker Image (%s): %w\", d.Id(), err)\n\t}\n\n\tif err := d.Set(\"tags\", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map()); err != nil {\n\t\treturn fmt.Errorf(\"error setting tags: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSagemakerImageUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\tneedsUpdate := false\n\n\tinput := &sagemaker.UpdateImageInput{\n\t\tImageName: aws.String(d.Id()),\n\t}\n\n\tvar deleteProperties []*string\n\n\tif d.HasChange(\"role_arn\") {\n\t\tinput.RoleArn = aws.String(d.Get(\"role_arn\").(string))\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\tif v, ok := d.GetOk(\"description\"); ok {\n\t\t\tinput.Description = aws.String(v.(string))\n\t\t} else {\n\t\t\tdeleteProperties = append(deleteProperties, aws.String(\"Description\"))\n\t\t\tinput.DeleteProperties = deleteProperties\n\t\t}\n\t\tneedsUpdate = true\n\t}\n\n\tif d.HasChange(\"display_name\") {\n\t\tif v, ok := d.GetOk(\"display_name\"); ok {\n\t\t\tinput.DisplayName = aws.String(v.(string))\n\t\t} else {\n\t\t\tdeleteProperties = append(deleteProperties, aws.String(\"DisplayName\"))\n\t\t\tinput.DeleteProperties = deleteProperties\n\t\t}\n\t\tneedsUpdate = true\n\t}\n\n\tif needsUpdate {\n\t\tlog.Printf(\"[DEBUG] sagemaker Image update config: %#v\", *input)\n\t\t_, err := conn.UpdateImage(input)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updating SageMaker Image: %w\", err)\n\t\t}\n\n\t\tif _, err := waiter.ImageCreated(conn, d.Id()); err != nil {\n\t\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to update: %w\", 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.SagemakerUpdateTags(conn, d.Get(\"arn\").(string), o, n); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating SageMaker Image (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsSagemakerImageRead(d, meta)\n}\n\nfunc resourceAwsSagemakerImageDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).sagemakerconn\n\n\tinput := &sagemaker.DeleteImageInput{\n\t\tImageName: aws.String(d.Id()),\n\t}\n\n\tif _, err := conn.DeleteImage(input); err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error deleting SageMaker Image (%s): %w\", d.Id(), err)\n\t}\n\n\tif _, err := waiter.ImageDeleted(conn, d.Id()); err != nil {\n\t\tif isAWSErr(err, sagemaker.ErrCodeResourceNotFound, \"No Image with the name\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"error waiting for SageMaker Image (%s) to delete: %w\", d.Id(), err)\n\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package scaniigo\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ ProcessedFileResponse holds the returned value from a call to\n\/\/ the previously processed file endpoint\ntype ProcessFileResponse struct {\n\tID            string   `json:\"id\"`\n\tChecksum      string   `json:\"checksum\"`\n\tContentLength int      `json:\"content_length\"`\n\tFindings      []string `json:\"findings\"`\n\tCreationDate  string   `json:\"creation_date\"`\n\tContentType   string   `json:\"content_type\"`\n}\n\n\/\/ ProcessFileRequest holds; the options needed for the given API call\ntype ProcessFileParams struct {\n\tFileLocation string\n\tCallback     string\n\tMetadata     string\n}\n\n\/\/ RetrieveProcessedFile retrieves a previously processed file resource\nfunc (c *Client) RetrieveProcessedFile(id string) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"GET\", c.Endpoint+FilePath+\"\/\"+id, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n\n\/\/ ProcessFileSync submits a file for processing synchronously\nfunc (c *Client) ProcessFileSync(pfp *ProcessFileParams) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"POST\", c.Endpoint+FilePath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\treq.Header.Set(\"Content-Type\", \"multipart\/form-data\")\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n\n\/\/ ProcessFileAsync submits a file for processing synchronously\nfunc (c *Client) ProcessFileAsync(pfp *ProcessFileParams) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"POST\", c.Endpoint+FileAsyncPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\treq.Header.Set(\"Content-Type\", \"multipart\/form-data\")\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n<commit_msg>added documentation, flesh out more file scan functionality<commit_after>package scaniigo\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ ProcessedFileResponse holds the returned value from a call to\n\/\/ the previously processed file endpoint\ntype ProcessFileResponse struct {\n\tID            string   `json:\"id\"`\n\tChecksum      string   `json:\"checksum\"`\n\tContentLength int      `json:\"content_length\"`\n\tFindings      []string `json:\"findings\"`\n\tCreationDate  string   `json:\"creation_date\"`\n\tContentType   string   `json:\"content_type\"`\n}\n\n\/\/ ProcessFileRequest holds the options needed for processing calls\ntype ProcessFileParams struct {\n\t\/\/ File has the contents of the file to be processed\n\tFile string\n\n\t\/\/ Callback is an optional callback URL to be notified once processing is completed\n\tCallback string\n\n\t\/\/ Metadata is an optional metadata argument to be stored with the resource\n\tMetadata string\n}\n\n\/\/ ProcessFileAsyncRequest holds the options needed for async process calls\ntype ProcessFileAsyncParams struct {\n\t\/\/ Location contains the URL of the file to be fetched and processed\n\tLocation string\n\n\t\/\/ Callback is an optional callback URL to be notified once processing is completed\n\tCallback string\n\n\t\/\/ Metadata is an optional metadata argument to be stored with the resource\n\tMetadata string\n}\n\n\/\/ RetrieveProcessedFile retrieves a previously processed file resource\nfunc (c *Client) RetrieveProcessedFile(id string) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"GET\", c.Endpoint+FilePath+\"\/\"+id, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n\n\/\/ ProcessFileSync submits a file for processing synchronously\nfunc (c *Client) ProcessFileSync(pfp *ProcessFileParams) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"POST\", c.Endpoint+FilePath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\treq.Header.Set(\"Content-Type\", \"multipart\/form-data\")\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n\n\/\/ ProcessFileAsync submits a file for processing synchronously\nfunc (c *Client) ProcessFileAsync(pfp *ProcessFileParams) (*ProcessFileResponse, error) {\n\treq, err := http.NewRequest(\"POST\", c.Endpoint+FileAsyncPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.SetBasicAuth(c.APIAuth.Key, c.APIAuth.Secret)\n\treq.Header.Set(\"Content-Type\", \"multipart\/form-data\")\n\n\tres, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tvar pfr ProcessFileResponse\n\tif err := json.NewDecoder(res.Body).Decode(&pfr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pfr, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>PACKAGE MAIN\n\nIMPORT (\n  \"FMT\"\n  \"OS\"\n  \"PATH\/FILEPATH\"\n\n  \"GITHUB.COM\/KR\/PRETTY\"\n  \"GITHUB.COM\/URFAVE\/CLI\"\n)\n\nVAR COMMAND_LOCAL = CLI.COMMAND{\n  NAME:      \"LOCAL\",\n  ALIASES:   []STRING{\"L\"},\n  USAGE:     \"DEPLY IMAGE CONFIG DATA TO CURRENT DIR\",\n  ARGSUSAGE: \"[OPTIONS...] IMAGE[:TAG] [COMMANDS...]\",\n  FLAGS: []CLI.FLAG{\n    CLI.BOOLFLAG{\n      NAME:  \"FORCE, F\",\n      USAGE: \"IGNORE CONFIRM\",\n    },\n    CLI.INTFLAG{\n      NAME:  \"NUM, N\",\n      VALUE: 0,\n      USAGE: \"SPECIFY THE NUMBER OF THE IMAGE CONFIG DATA\",\n    },\n    CLI.BOOLFLAG{\n      NAME:  \"REMOVE, R\",\n      USAGE: \"REMOVE THIS IMAGE CONFIG DATA FROM A CURRENT CONFIG FILE\",\n    },\n    CLI.BOOLFLAG{\n      NAME:  \"CHECK, C\",\n      USAGE: \"CHECK AND REWITE A CURRENT CONFIG FILE\",\n    },\n    CLI.STRINGSLICEFLAG{\n      NAME:  \"ENVIRONMENT, E\",\n      USAGE: \"ENVIRONMENT VARIABLE USED IN SCRIPT\",\n    },\n  },\n\n  ACTION: LOCAL,\n}\n\nFUNC LOCAL(C *CLI.CONTEXT) {\n  ISFORCE := C.BOOL(\"FORCE\")\n\n  IF ISV {\n    FMT.PRINTLN(\"DCENV LOCAL \", C.ARGS())\n  }\n\n  P, ERR := OS.GETWD()\n  IF ERR != NIL {\n    FMT.PRINTLN(ERR)\n    RETURN\n  }\n\n  FNAME := FILEPATH.JOIN(P, \".DCENV_\"+ENVSHELL)\n  CFG := GETCONFIG(FNAME)\n  IF !C.BOOL(\"CHECK\") {\n    IF LEN(C.ARGS()) < 1 {\n      FMT.PRINTLN(\"NO IMAGE NAME.\")\n      CLI.SHOWSUBCOMMANDHELP(C)\n      RETURN\n    }\n    TNAME, TCOMMAND, TTAG := PARSEIMAGETAG(C.ARGS()[0])\n    IF !C.BOOL(\"REMOVE\") {\n      TC := SEARCHIMAGEFROMYARD(TNAME, TCOMMAND, TTAG, C.INT(\"NUM\"))\n      IF LEN(C.ARGS()) > 2 {\n        TC.MAKECOMMANDS(C.ARGS()[1:], C.STRINGSLICE(\"ENVIRONMENT\"))\n      }\n      CFG.ADDIMAGE(TC, TNAME, ISFORCE)\n    } ELSE {\n      CFG.DELIMAGE(TNAME, ISFORCE)\n    }\n  }\n  CFG.WRITETOFILE(FNAME)\n  FMT.PRINTLN(\"COMPLETE!.\")\n  IF ISV {\n    PRETTY.PRINTF(\"--- COFIG %S:\\N%# V\\N\\N\", FNAME, CFG)\n  }\n}\n<commit_msg>revert local.go<commit_after>package main\n\nimport (\n  \"fmt\"\n  \"os\"\n  \"path\/filepath\"\n\n  \"github.com\/kr\/pretty\"\n  \"github.com\/urfave\/cli\"\n)\n\nvar Command_local = cli.Command{\n  Name:      \"local\",\n  Aliases:   []string{\"l\"},\n  Usage:     \"Deply image config data to current dir\",\n  ArgsUsage: \"[options...] image[:tag] [commands...]\",\n  Flags: []cli.Flag{\n    cli.BoolFlag{\n      Name:  \"force, f\",\n      Usage: \"Ignore confirm\",\n    },\n    cli.IntFlag{\n      Name:  \"num, n\",\n      Value: 0,\n      Usage: \"Specify the number of the image config data\",\n    },\n    cli.BoolFlag{\n      Name:  \"remove, r\",\n      Usage: \"Remove this image config data from a current config file\",\n    },\n    cli.BoolFlag{\n      Name:  \"check, c\",\n      Usage: \"Check and rewite a current config file\",\n    },\n    cli.StringSliceFlag{\n      Name:  \"environment, e\",\n      Usage: \"Environment variable used in script\",\n    },\n  },\n\n  Action: local,\n}\n\nfunc local(c *cli.Context) {\n  isForce := c.Bool(\"force\")\n\n  if isV {\n    fmt.Println(\"dcenv local \", c.Args())\n  }\n\n  p, err := os.Getwd()\n  if err != nil {\n    fmt.Println(err)\n    return\n  }\n\n  fname := filepath.Join(p, \".dcenv_\"+envShell)\n  cfg := GetConfig(fname)\n  if !c.Bool(\"check\") {\n    if len(c.Args()) < 1 {\n      fmt.Println(\"No image name.\")\n      cli.ShowSubcommandHelp(c)\n      return\n    }\n    tName, tCommand, tTag := ParseImageTag(c.Args()[0])\n    if !c.Bool(\"remove\") {\n      tc := SearchImageFromYard(tName, tCommand, tTag, c.Int(\"num\"))\n      if len(c.Args()) > 2 {\n        tc.MakeCommands(c.Args()[1:], c.StringSlice(\"environment\"))\n      }\n      cfg.AddImage(tc, tName, isForce)\n    } else {\n      cfg.DelImage(tName, isForce)\n    }\n  }\n  cfg.WriteToFile(fname)\n  fmt.Println(\"Complete!.\")\n  if isV {\n    pretty.Printf(\"--- cofig %s:\\n%# v\\n\\n\", fname, cfg)\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>package grpcer_test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\tjsoniter \"github.com\/json-iterator\/go\"\n\t\"github.com\/tgulacsi\/oracall\/custom\"\n)\n\nfunc TestDateTime(t *testing.T) {\n\ttype testStruct struct {\n\t\tT   time.Time\n\t\tTP  *time.Time\n\t\tDT  custom.DateTime\n\t\tDTP *custom.DateTime\n\t}\n\n\tnow := time.Date(2006, 1, 2, 15, 4, 5, 6, time.UTC)\n\tx := testStruct{\n\t\tTP:  &now,\n\t\tDTP: &custom.DateTime{Time: now},\n\t}\n\n\tvar w strings.Builder\n\terr := jsoniter.NewEncoder(&w).Encode(x)\n\tif err != nil {\n\t\tt.Fatalf(\"encode %#v: %w\", x, err)\n\t}\n\tt.Log(w.String())\n\ts := w.String()\n\n\tvar y testStruct\n\tif err = jsoniter.NewDecoder(strings.NewReader(s)).Decode(&y); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(y)\n\n\ty = testStruct{}\n\tif err = jsoniter.NewDecoder(strings.NewReader(\n\t\t`{\"DT\":\"2006-01-02 16:04\"}`,\n\t)).Decode(&y); err != nil {\n\t\tt.Error(err)\n\t}\n}\n<commit_msg>Fix %w in test<commit_after>package grpcer_test\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\tjsoniter \"github.com\/json-iterator\/go\"\n\t\"github.com\/tgulacsi\/oracall\/custom\"\n)\n\nfunc TestDateTime(t *testing.T) {\n\ttype testStruct struct {\n\t\tT   time.Time\n\t\tTP  *time.Time\n\t\tDT  custom.DateTime\n\t\tDTP *custom.DateTime\n\t}\n\n\tnow := time.Date(2006, 1, 2, 15, 4, 5, 6, time.UTC)\n\tx := testStruct{\n\t\tTP:  &now,\n\t\tDTP: &custom.DateTime{Time: now},\n\t}\n\n\tvar w strings.Builder\n\terr := jsoniter.NewEncoder(&w).Encode(x)\n\tif err != nil {\n\t\tt.Fatalf(\"encode %#v: %+v\", x, err)\n\t}\n\tt.Log(w.String())\n\ts := w.String()\n\n\tvar y testStruct\n\tif err = jsoniter.NewDecoder(strings.NewReader(s)).Decode(&y); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Log(y)\n\n\ty = testStruct{}\n\tif err = jsoniter.NewDecoder(strings.NewReader(\n\t\t`{\"DT\":\"2006-01-02 16:04\"}`,\n\t)).Decode(&y); err != nil {\n\t\tt.Error(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015, Markus Mäkelä\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\/\/ * Neither the name of jsontodyncol 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED 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\npackage main\n\nimport (\n    \"fmt\"\n    \"encoding\/json\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"flag\"\n\t\"path\/filepath\"\n\t\"io\"\n)\n\n\/\/ Command line flags\nvar insert_size = flag.Int(\"insert-size\", 1, \"Number of inserted values in each statement\")\nvar help = flag.Bool(\"help\", false, \"Show this message\")\nvar pretty = flag.Bool(\"pretty\", false, \"Pretty-print output\")\nvar database = flag.String(\"database\", \"\", \"Database name\")\nvar table = flag.String(\"table\", \"\", \"Table name\")\nvar column = flag.String(\"column\", \"\", \"Column name\")\n\n\/\/ Print usage\nfunc Usage(){\n\tfmt.Println(\"JSON to MariaDB Dynamic Column converter 0.1\")\n\tfmt.Println(\"Usage:\", filepath.Base(os.Args[0]), \"-table TABLE -column COLUMN FILE\")\n\tflag.PrintDefaults()\n\n}\n\n\/\/ Main function.\n\/\/ Parses first argument as a file with one or more JSON objects\n\/\/ and converts them into dynamic column insert statements.\nfunc main(){\n    flag.Parse()\n\n    switch {\n\tcase *help:\n\t\tUsage()\n        os.Exit(0)\n\tcase len(flag.Args()) < 1 :\n        fmt.Fprintln(os.Stderr, \"No file provided! See -help output for more info.\")\n        os.Exit(1)\n\tcase len(*table) == 0:\n        fmt.Fprintln(os.Stderr, \"No table name provided! See -help output for more info.\")\n        os.Exit(1)\n\tcase len(*column) == 0:\n\t\tfmt.Fprintln(os.Stderr, \"No column provided! See -help output for more info.\")\n        os.Exit(1)\n\tdefault:\n\t}\n\n    file, err := os.Open(flag.Args()[0])\n    if err != nil{\n        fmt.Fprintln(os.Stderr, \"Fatal error:\", err)\n        os.Exit(1)\n    }\n\n    decoder := json.NewDecoder(file)\n\tvar err_d error = nil\n\tvalues := 0\n    for err_d == nil{\n        str := \"INSERT INTO \"\n\t\tif len(*database) > 0 {\n\t\t\tstr += *database + \".\"\n\t\t}\n\t\tstr += *table + \"(\" + *column + \") values\"\n\n\t\tn_inserts := *insert_size\n\t\tfor err_d == nil{\n\t\t\tvar obj map[string]interface{}\n\t\t\tif err_d = decoder.Decode(&obj); err_d != nil {\n\t\t\t\tstr = strings.TrimRight(str, \",\\n\")\n\t\t\t\tstr += \";\"\n\n\t\t\t\tif err_d != io.EOF {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, err_d)\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tstr += \" (\"\n\t\t\t\tstr += PrintObject(&obj)\n\t\t\t\tn_inserts--\n\t\t\t\tvalues++\n\t\t\t\tif n_inserts <= 0{\n\t\t\t\t\t\/\/ Last value\n\t\t\t\t\tstr += \");\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t\/\/ More values to insert\n\t\t\t\tstr += \"),\"\n\t\t\t\tif *pretty {\n\t\t\t\t\tstr += \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ At least one value was read\n\t\tif n_inserts < *insert_size {\n\t\t\tfmt.Println(str)\n\t\t}\n    }\n\n\tif values == 0 {\n\t\tfmt.Fprintln(os.Stderr, \"No valid values read.\")\n\t}\n\n}\n\n\/\/ Print a JSON array as a comma-separated list strings\nfunc PrintList(mylist []interface{}) string{\n    str := \"\"\n    for _, elem := range mylist {\n\t\tif len(str) > 0 {\n\t\t\tstr += \",\"\n\t\t}\n        switch v := elem.(type) {\n        case string:\n            str += fmt.Sprintf(\"%q\", v)\n\n        case bool:\n            str += strconv.FormatBool(v)\n\n        case float64:\n            str += strconv.FormatFloat(v, 'f', -1, 64)\n\n        default:\n\t\t\tfmt.Fprintln(os.Stderr, \"Unknown type:\", v)\n\t\t\t\/\/ Unknown value\n        }\n    }\n    return str\n}\n\n\/\/ String cleanup function\nfunc FormatStr(str string) string {\n    replacer := strings.NewReplacer(\"'\", \"\\\\'\", \"\\\"\", \"\\\\\\\"\")\n    return strconv.QuoteToASCII(replacer.Replace(str))\n}\n\n\/\/ Print a JSON object and format it as a COLUMN_CREATE statement\nfunc PrintObject(obj* map[string]interface{}) string{\n    str := \"COLUMN_CREATE(\"\n    for key, value := range *obj {\n\n        switch conv := value.(type) {\n        case []interface{}:\n            str += FormatStr(key) + \",\" + FormatStr(PrintList(conv))\n\n        case map[string]interface{}:\n            str += FormatStr(key) + \",\" +  PrintObject(&conv)\n\n        case string:\n            str += FormatStr(key) + \",\" + FormatStr(conv)\n\n        case float64:\n            str += FormatStr(key) + \",\" + FormatStr(strconv.FormatFloat(conv, 'f', -1, 64))\n        }\n        str += \",\"\n    }\n    str = str[0:len(str) - 1] + \")\"\n    return str\n}\n<commit_msg>Added stdin as an input source<commit_after>\/\/ Copyright (c) 2015, Markus Mäkelä\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\/\/ * Neither the name of jsontodyncol 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 \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED 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\npackage main\n\nimport (\n    \"fmt\"\n    \"encoding\/json\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"flag\"\n\t\"path\/filepath\"\n\t\"io\"\n)\n\n\/\/ Command line flags\nvar insert_size = flag.Int(\"insert-size\", 1, \"Number of inserted values in each statement\")\nvar help = flag.Bool(\"help\", false, \"Show this message\")\nvar pretty = flag.Bool(\"pretty\", false, \"Pretty-print output\")\nvar database = flag.String(\"database\", \"\", \"Database name\")\nvar table = flag.String(\"table\", \"\", \"Table name\")\nvar column = flag.String(\"column\", \"\", \"Column name\")\n\n\/\/ Print usage\nfunc Usage(){\n\tfmt.Println(\"JSON to MariaDB Dynamic Column converter 0.1\")\n\tfmt.Println(\"Usage:\", filepath.Base(os.Args[0]), \"-table TABLE -column COLUMN FILE\")\n\tflag.PrintDefaults()\n}\n\n\/\/ Main function.\n\/\/ Parses first argument as a file with one or more JSON objects\n\/\/ and converts them into dynamic column insert statements.\nfunc main(){\n    flag.Parse()\n\n    switch {\n\tcase *help:\n\t\tUsage()\n        os.Exit(0)\n\tcase len(*table) == 0:\n        fmt.Fprintln(os.Stderr, \"No table name provided! See -help output for more info.\")\n        os.Exit(1)\n\tcase len(*column) == 0:\n\t\tfmt.Fprintln(os.Stderr, \"No column provided! See -help output for more info.\")\n        os.Exit(1)\n\tdefault:\n\t}\n\n\t\/\/ If no inputs provided, use Stdin\n\tvar input *os.File\n\tif len(flag.Args()) < 1 {\n\t\tinput = os.Stdin\n\t} else {\n\t\tfile, err := os.Open(flag.Args()[0])\n\t\tif err != nil{\n\t\t\tfmt.Fprintln(os.Stderr, \"Fatal error:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tinput = file\n\t}\n\n    decoder := json.NewDecoder(input)\n\tvar err_d error = nil\n\tvalues := 0\n    for err_d == nil{\n        str := \"INSERT INTO \"\n\t\tif len(*database) > 0 {\n\t\t\tstr += *database + \".\"\n\t\t}\n\t\tstr += *table + \"(\" + *column + \") values\"\n\n\t\tn_inserts := *insert_size\n\t\tfor err_d == nil{\n\t\t\tvar obj map[string]interface{}\n\t\t\tif err_d = decoder.Decode(&obj); err_d != nil {\n\t\t\t\tstr = strings.TrimRight(str, \",\\n\")\n\t\t\t\tstr += \";\"\n\n\t\t\t\tif err_d != io.EOF {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, err_d)\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tstr += \" (\"\n\t\t\t\tstr += PrintObject(&obj)\n\t\t\t\tn_inserts--\n\t\t\t\tvalues++\n\t\t\t\tif n_inserts <= 0{\n\t\t\t\t\t\/\/ Last value\n\t\t\t\t\tstr += \");\"\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t\/\/ More values to insert\n\t\t\t\tstr += \"),\"\n\t\t\t\tif *pretty {\n\t\t\t\t\tstr += \"\\n\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ At least one value was read\n\t\tif n_inserts < *insert_size {\n\t\t\tfmt.Println(str)\n\t\t}\n    }\n\n\tif values == 0 {\n\t\tfmt.Fprintln(os.Stderr, \"No valid values read.\")\n\t}\n\n}\n\n\/\/ Print a JSON array as a comma-separated list strings\nfunc PrintList(mylist []interface{}) string{\n    str := \"\"\n    for _, elem := range mylist {\n\t\tif len(str) > 0 {\n\t\t\tstr += \",\"\n\t\t}\n        switch v := elem.(type) {\n        case string:\n            str += fmt.Sprintf(\"%q\", v)\n\n        case bool:\n            str += strconv.FormatBool(v)\n\n        case float64:\n            str += strconv.FormatFloat(v, 'f', -1, 64)\n\n        default:\n\t\t\tfmt.Fprintln(os.Stderr, \"Unknown type:\", v)\n\t\t\t\/\/ Unknown value\n        }\n    }\n    return str\n}\n\n\/\/ String cleanup function\nfunc FormatStr(str string) string {\n    replacer := strings.NewReplacer(\"'\", \"\\\\'\", \"\\\"\", \"\\\\\\\"\")\n    return strconv.QuoteToASCII(replacer.Replace(str))\n}\n\n\/\/ Print a JSON object and format it as a COLUMN_CREATE statement\nfunc PrintObject(obj* map[string]interface{}) string{\n    str := \"COLUMN_CREATE(\"\n    for key, value := range *obj {\n\n        switch conv := value.(type) {\n        case []interface{}:\n            str += FormatStr(key) + \",\" + FormatStr(PrintList(conv))\n\n        case map[string]interface{}:\n            str += FormatStr(key) + \",\" +  PrintObject(&conv)\n\n        case string:\n            str += FormatStr(key) + \",\" + FormatStr(conv)\n\n        case float64:\n            str += FormatStr(key) + \",\" + FormatStr(strconv.FormatFloat(conv, 'f', -1, 64))\n        }\n        str += \",\"\n    }\n    str = str[0:len(str) - 1] + \")\"\n    return str\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.\n\n\/\/ Package client is the reference client implementation for the watefall service\npackage client\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/google\/waterfall\/golang\/stream\"\n\twaterfall_grpc \"github.com\/google\/waterfall\/proto\/waterfall_go_grpc\"\n\t\"golang.org\/x\/sync\/errgroup\"\n)\n\n\/\/ Echo streams back the contents of the request. Useful for testing the connection.\nfunc Echo(ctx context.Context, client waterfall_grpc.WaterfallClient, r []byte) ([]byte, error) {\n\tstream, err := client.Echo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teg := &errgroup.Group{}\n\trec := new(bytes.Buffer)\n\teg.Go(func() error {\n\t\tfor {\n\t\t\tin, err := stream.Recv()\n\t\t\tif err == io.EOF {\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\trec.Write(in.Payload)\n\t\t}\n\t})\n\teg.Go(func() error {\n\t\tsend := bytes.NewBuffer(r)\n\t\tb := make([]byte, 32*1024)\n\t\tfor {\n\t\t\tn, err := send.Read(b)\n\t\t\tif n > 0 {\n\t\t\t\tp := &waterfall_grpc.Message{Payload: b[0:n]}\n\t\t\t\tif err := stream.Send(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\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 stream.CloseSend()\n\t})\n\tif err := eg.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn rec.Bytes(), nil\n}\n\n\/\/ Push pushes a tar stream to the server running in the device.\nfunc Push(ctx context.Context, client waterfall_grpc.WaterfallClient, src, dst string) error {\n\trpc, err := client.Push(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, w := io.Pipe()\n\tdefer r.Close()\n\n\teg := &errgroup.Group{}\n\teg.Go(func() error {\n\t\terr := stream.Tar(w, src)\n\t\tw.Close()\n\t\treturn err\n\t})\n\n\tbuff := make([]byte, 64*1024)\n\teg.Go(func() error {\n\t\tfor {\n\t\t\tn, err := r.Read(buff)\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif n > 0 {\n\t\t\t\txfer := &waterfall_grpc.Transfer{Path: dst, Payload: buff[0:n]}\n\t\t\t\tif err := rpc.Send(xfer); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err == io.EOF {\n\t\t\t\tr, err := rpc.CloseAndRecv()\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 !r.Success {\n\t\t\t\t\treturn fmt.Errorf(string(r.Err))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t})\n\treturn eg.Wait()\n}\n\n\/\/ Pull request a file\/directory from the device and unpacks the contents into the desired path.\nfunc Pull(ctx context.Context, client waterfall_grpc.WaterfallClient, src, dst string) error {\n\tif _, err := os.Stat(filepath.Dir(dst)); err != nil {\n\t\treturn err\n\t}\n\n\txstream, err := client.Pull(ctx, &waterfall_grpc.Transfer{Path: src})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, w := io.Pipe()\n\teg := &errgroup.Group{}\n\teg.Go(func() error {\n\t\terr := stream.Untar(r, dst)\n\t\tr.Close()\n\t\treturn err\n\t})\n\n\teg.Go(func() error {\n\t\tdefer w.Close()\n\t\tfor {\n\t\t\tfgmt, err := xstream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := w.Write(fgmt.Payload); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t})\n\treturn eg.Wait()\n}\n\ntype execMessageWriter struct{}\n\n\/\/ BuildMsg returns a reference to a new CmdProgress struct.\nfunc (em execMessageWriter) BuildMsg() interface{} {\n\treturn new(waterfall_grpc.CmdProgress)\n}\n\n\/\/ SetBytes writes the payload b to stdin.\nfunc (em execMessageWriter) SetBytes(m interface{}, b []byte) {\n\tmsg, ok := m.(*waterfall_grpc.CmdProgress)\n\tif !ok {\n\t\t\/\/ this never happens\n\t\tpanic(\"incorrect type\")\n\t}\n\tnb := make([]byte, len(b))\n\tcopy(nb, b)\n\tmsg.Stdin = nb\n}\n\n\/\/ Exec executes the requested command on the device. Semantics are the same as execve.\nfunc Exec(ctx context.Context, client waterfall_grpc.WaterfallClient, stdout, stderr io.Writer, stdin io.Reader, cmd string, args ...string) (int, error) {\n\txstream, err := client.Exec(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ initializes the command execution on the server\n\tif err := xstream.Send(\n\t\t&waterfall_grpc.CmdProgress{\n\t\t\tCmd: &waterfall_grpc.Cmd{Path: cmd,\n\t\t\t\tArgs:   args,\n\t\t\t\tPipeIn: stdin != nil}}); err != nil {\n\t\treturn 0, err\n\t}\n\n\teg := &errgroup.Group{}\n\n\tif stdin != nil {\n\t\teg.Go(func() error {\n\t\t\t_, err := io.Copy(stream.NewWriter(xstream, execMessageWriter{}), stdin)\n\t\t\tif err == nil || err == io.EOF {\n\t\t\t\treturn xstream.CloseSend()\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t}\n\n\tvar last *waterfall_grpc.CmdProgress\n\tfor {\n\t\tpgrs, err := xstream.Recv()\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 0, err\n\t\t}\n\n\t\tif pgrs.Stdout != nil {\n\t\t\tif _, err := stdout.Write(pgrs.Stdout); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tif pgrs.Stderr != nil {\n\t\t\tif _, err := stdout.Write(pgrs.Stderr); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tlast = pgrs\n\t}\n\n\tif err := eg.Wait(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(last.ExitCode), nil\n}\n<commit_msg>Close input stream when no stdin in Exec<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.\n\n\/\/ Package client is the reference client implementation for the watefall service\npackage client\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/google\/waterfall\/golang\/stream\"\n\twaterfall_grpc \"github.com\/google\/waterfall\/proto\/waterfall_go_grpc\"\n\t\"golang.org\/x\/sync\/errgroup\"\n)\n\n\/\/ Echo streams back the contents of the request. Useful for testing the connection.\nfunc Echo(ctx context.Context, client waterfall_grpc.WaterfallClient, r []byte) ([]byte, error) {\n\tstream, err := client.Echo(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teg := &errgroup.Group{}\n\trec := new(bytes.Buffer)\n\teg.Go(func() error {\n\t\tfor {\n\t\t\tin, err := stream.Recv()\n\t\t\tif err == io.EOF {\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\trec.Write(in.Payload)\n\t\t}\n\t})\n\teg.Go(func() error {\n\t\tsend := bytes.NewBuffer(r)\n\t\tb := make([]byte, 32*1024)\n\t\tfor {\n\t\t\tn, err := send.Read(b)\n\t\t\tif n > 0 {\n\t\t\t\tp := &waterfall_grpc.Message{Payload: b[0:n]}\n\t\t\t\tif err := stream.Send(p); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\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 stream.CloseSend()\n\t})\n\tif err := eg.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn rec.Bytes(), nil\n}\n\n\/\/ Push pushes a tar stream to the server running in the device.\nfunc Push(ctx context.Context, client waterfall_grpc.WaterfallClient, src, dst string) error {\n\trpc, err := client.Push(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, w := io.Pipe()\n\tdefer r.Close()\n\n\teg := &errgroup.Group{}\n\teg.Go(func() error {\n\t\terr := stream.Tar(w, src)\n\t\tw.Close()\n\t\treturn err\n\t})\n\n\tbuff := make([]byte, 64*1024)\n\teg.Go(func() error {\n\t\tfor {\n\t\t\tn, err := r.Read(buff)\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif n > 0 {\n\t\t\t\txfer := &waterfall_grpc.Transfer{Path: dst, Payload: buff[0:n]}\n\t\t\t\tif err := rpc.Send(xfer); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err == io.EOF {\n\t\t\t\tr, err := rpc.CloseAndRecv()\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 !r.Success {\n\t\t\t\t\treturn fmt.Errorf(string(r.Err))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t})\n\treturn eg.Wait()\n}\n\n\/\/ Pull request a file\/directory from the device and unpacks the contents into the desired path.\nfunc Pull(ctx context.Context, client waterfall_grpc.WaterfallClient, src, dst string) error {\n\tif _, err := os.Stat(filepath.Dir(dst)); err != nil {\n\t\treturn err\n\t}\n\n\txstream, err := client.Pull(ctx, &waterfall_grpc.Transfer{Path: src})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr, w := io.Pipe()\n\teg := &errgroup.Group{}\n\teg.Go(func() error {\n\t\terr := stream.Untar(r, dst)\n\t\tr.Close()\n\t\treturn err\n\t})\n\n\teg.Go(func() error {\n\t\tdefer w.Close()\n\t\tfor {\n\t\t\tfgmt, err := xstream.Recv()\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif _, err := w.Write(fgmt.Payload); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t})\n\treturn eg.Wait()\n}\n\ntype execMessageWriter struct{}\n\n\/\/ BuildMsg returns a reference to a new CmdProgress struct.\nfunc (em execMessageWriter) BuildMsg() interface{} {\n\treturn new(waterfall_grpc.CmdProgress)\n}\n\n\/\/ SetBytes writes the payload b to stdin.\nfunc (em execMessageWriter) SetBytes(m interface{}, b []byte) {\n\tmsg, ok := m.(*waterfall_grpc.CmdProgress)\n\tif !ok {\n\t\t\/\/ this never happens\n\t\tpanic(\"incorrect type\")\n\t}\n\tnb := make([]byte, len(b))\n\tcopy(nb, b)\n\tmsg.Stdin = nb\n}\n\n\/\/ Exec executes the requested command on the device. Semantics are the same as execve.\nfunc Exec(ctx context.Context, client waterfall_grpc.WaterfallClient, stdout, stderr io.Writer, stdin io.Reader, cmd string, args ...string) (int, error) {\n\txstream, err := client.Exec(ctx)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ initializes the command execution on the server\n\tif err := xstream.Send(\n\t\t&waterfall_grpc.CmdProgress{\n\t\t\tCmd: &waterfall_grpc.Cmd{Path: cmd,\n\t\t\t\tArgs:   args,\n\t\t\t\tPipeIn: stdin != nil}}); err != nil {\n\t\treturn 0, err\n\t}\n\n\teg := &errgroup.Group{}\n\n\tif stdin != nil {\n\t\teg.Go(func() error {\n\t\t\t_, err := io.Copy(stream.NewWriter(xstream, execMessageWriter{}), stdin)\n\t\t\tif err == nil || err == io.EOF {\n\t\t\t\treturn xstream.CloseSend()\n\t\t\t}\n\t\t\treturn err\n\t\t})\n\t} else {\n\t\tif err = xstream.CloseSend(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvar last *waterfall_grpc.CmdProgress\n\tfor {\n\t\tpgrs, err := xstream.Recv()\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 0, err\n\t\t}\n\n\t\tif pgrs.Stdout != nil {\n\t\t\tif _, err := stdout.Write(pgrs.Stdout); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tif pgrs.Stderr != nil {\n\t\t\tif _, err := stdout.Write(pgrs.Stderr); err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t}\n\t\tlast = pgrs\n\t}\n\n\tif err := eg.Wait(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(last.ExitCode), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t. \"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\t\"github.com\/cloudfoundry\/cli\/flags\"\n\t\"github.com\/cloudfoundry\/cli\/flags\/flag\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/api\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/api\/app_instances\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/command_registry\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/core_config\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/manifest\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/models\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/requirements\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/terminal\"\n)\n\ntype CreateAppManifest struct {\n\tui               terminal.UI\n\tconfig           core_config.Reader\n\tappSummaryRepo   api.AppSummaryRepository\n\tappInstancesRepo app_instances.AppInstancesRepository\n\tappReq           requirements.ApplicationRequirement\n\tmanifest         manifest.AppManifest\n}\n\nfunc init() {\n\tcommand_registry.Register(&CreateAppManifest{})\n}\n\nfunc (cmd *CreateAppManifest) MetaData() command_registry.CommandMetadata {\n\tfs := make(map[string]flags.FlagSet)\n\tfs[\"p\"] = &cliFlags.StringFlag{Name: \"p\", Usage: T(\"Specify a path for file creation. If path not specified, manifest file is created in current working directory.\")}\n\n\treturn command_registry.CommandMetadata{\n\t\tName:        \"create-app-manifest\",\n\t\tDescription: T(\"Create an app manifest for an app that has been pushed successfully.\"),\n\t\tUsage:       T(\"CF_NAME create-app-manifest APP_NAME [-p \/path\/to\/<app-name>-manifest.yml ]\"),\n\t\tFlags:       fs,\n\t}\n}\n\nfunc (cmd *CreateAppManifest) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {\n\tif len(fc.Args()) != 1 {\n\t\tcmd.ui.Failed(T(\"Incorrect Usage. Requires APP_NAME as argument\\n\\n\") + command_registry.Commands.CommandUsage(\"create-app-manifest\"))\n\t}\n\n\tcmd.appReq = requirementsFactory.NewApplicationRequirement(fc.Args()[0])\n\n\treqs = []requirements.Requirement{\n\t\trequirementsFactory.NewLoginRequirement(),\n\t\trequirementsFactory.NewTargetedSpaceRequirement(),\n\t\tcmd.appReq,\n\t}\n\treturn\n}\n\nfunc (cmd *CreateAppManifest) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {\n\tcmd.ui = deps.Ui\n\tcmd.config = deps.Config\n\tcmd.appSummaryRepo = deps.RepoLocator.GetAppSummaryRepository()\n\tcmd.manifest = deps.AppManifest\n\treturn cmd\n}\n\nfunc (cmd *CreateAppManifest) Execute(c flags.FlagContext) {\n\tapp := cmd.appReq.GetApplication()\n\n\tapplication, apiErr := cmd.appSummaryRepo.GetSummary(app.Guid)\n\tfmt.Println(\"app cmd field\", application.Command)\n\n\tif apiErr != nil {\n\t\tcmd.ui.Failed(T(\"Error getting application summary: \") + apiErr.Error())\n\t}\n\n\tcmd.ui.Say(T(\"Creating an app manifest from current settings of app \") + application.Name + \" ...\")\n\tcmd.ui.Say(\"\")\n\n\tsavePath := \".\/\" + application.Name + \"_manifest.yml\"\n\n\tif c.String(\"p\") != \"\" {\n\t\tsavePath = c.String(\"p\")\n\t}\n\n\tcmd.createManifest(application, savePath)\n}\n\nfunc (cmd *CreateAppManifest) createManifest(app models.Application, savePath string) error {\n\tcmd.manifest.FileSavePath(savePath)\n\tcmd.manifest.Memory(app.Name, app.Memory)\n\tcmd.manifest.Instances(app.Name, app.InstanceCount)\n\n\tif app.Command != \"\" {\n\t\tcmd.manifest.StartCommand(app.Name, app.Command)\n\t}\n\n\tif app.BuildpackUrl != \"\" {\n\t\tcmd.manifest.BuildpackUrl(app.Name, app.BuildpackUrl)\n\t}\n\n\tif len(app.Services) > 0 {\n\t\tfor _, service := range app.Services {\n\t\t\tcmd.manifest.Service(app.Name, service.Name)\n\t\t}\n\t}\n\n\tif app.HealthCheckTimeout > 0 {\n\t\tcmd.manifest.HealthCheckTimeout(app.Name, app.HealthCheckTimeout)\n\t}\n\n\tif len(app.EnvironmentVars) > 0 {\n\t\tsorted := sortEnvVar(app.EnvironmentVars)\n\t\tfor _, envVarKey := range sorted {\n\t\t\tswitch app.EnvironmentVars[envVarKey].(type) {\n\t\t\tdefault:\n\t\t\t\tcmd.ui.Failed(T(\"Failed to create manifest, unable to parse environment variable: \") + envVarKey)\n\t\t\tcase float64:\n\t\t\t\t\/\/json.Unmarshal turn all numbers to float64\n\t\t\t\tvalue := int(app.EnvironmentVars[envVarKey].(float64))\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf(\"%d\", value))\n\t\t\tcase bool:\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf(\"%t\", app.EnvironmentVars[envVarKey].(bool)))\n\t\t\tcase string:\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, \"\\\"\"+app.EnvironmentVars[envVarKey].(string)+\"\\\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(app.Routes) > 0 {\n\t\tfor i := 0; i < len(app.Routes); i++ {\n\t\t\tcmd.manifest.Domain(app.Name, app.Routes[i].Host, app.Routes[i].Domain.Name)\n\t\t}\n\t}\n\n\terr := cmd.manifest.Save()\n\tif err != nil {\n\t\tcmd.ui.Failed(T(\"Error creating manifest file: \") + err.Error())\n\t}\n\n\tcmd.ui.Ok()\n\tcmd.ui.Say(T(\"Manifest file created successfully at \") + savePath)\n\tcmd.ui.Say(\"\")\n\n\treturn nil\n}\n\nfunc sortEnvVar(vars map[string]interface{}) []string {\n\tvar varsAry []string\n\tfor k, _ := range vars {\n\t\tvarsAry = append(varsAry, k)\n\t}\n\tsort.Strings(varsAry)\n\n\treturn varsAry\n}\n<commit_msg>remove debugging message in create-app-manifest<commit_after>package commands\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t. \"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\t\"github.com\/cloudfoundry\/cli\/flags\"\n\t\"github.com\/cloudfoundry\/cli\/flags\/flag\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/api\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/api\/app_instances\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/command_registry\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/core_config\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/manifest\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/models\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/requirements\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/terminal\"\n)\n\ntype CreateAppManifest struct {\n\tui               terminal.UI\n\tconfig           core_config.Reader\n\tappSummaryRepo   api.AppSummaryRepository\n\tappInstancesRepo app_instances.AppInstancesRepository\n\tappReq           requirements.ApplicationRequirement\n\tmanifest         manifest.AppManifest\n}\n\nfunc init() {\n\tcommand_registry.Register(&CreateAppManifest{})\n}\n\nfunc (cmd *CreateAppManifest) MetaData() command_registry.CommandMetadata {\n\tfs := make(map[string]flags.FlagSet)\n\tfs[\"p\"] = &cliFlags.StringFlag{Name: \"p\", Usage: T(\"Specify a path for file creation. If path not specified, manifest file is created in current working directory.\")}\n\n\treturn command_registry.CommandMetadata{\n\t\tName:        \"create-app-manifest\",\n\t\tDescription: T(\"Create an app manifest for an app that has been pushed successfully.\"),\n\t\tUsage:       T(\"CF_NAME create-app-manifest APP_NAME [-p \/path\/to\/<app-name>-manifest.yml ]\"),\n\t\tFlags:       fs,\n\t}\n}\n\nfunc (cmd *CreateAppManifest) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) (reqs []requirements.Requirement, err error) {\n\tif len(fc.Args()) != 1 {\n\t\tcmd.ui.Failed(T(\"Incorrect Usage. Requires APP_NAME as argument\\n\\n\") + command_registry.Commands.CommandUsage(\"create-app-manifest\"))\n\t}\n\n\tcmd.appReq = requirementsFactory.NewApplicationRequirement(fc.Args()[0])\n\n\treqs = []requirements.Requirement{\n\t\trequirementsFactory.NewLoginRequirement(),\n\t\trequirementsFactory.NewTargetedSpaceRequirement(),\n\t\tcmd.appReq,\n\t}\n\treturn\n}\n\nfunc (cmd *CreateAppManifest) SetDependency(deps command_registry.Dependency, pluginCall bool) command_registry.Command {\n\tcmd.ui = deps.Ui\n\tcmd.config = deps.Config\n\tcmd.appSummaryRepo = deps.RepoLocator.GetAppSummaryRepository()\n\tcmd.manifest = deps.AppManifest\n\treturn cmd\n}\n\nfunc (cmd *CreateAppManifest) Execute(c flags.FlagContext) {\n\tapp := cmd.appReq.GetApplication()\n\n\tapplication, apiErr := cmd.appSummaryRepo.GetSummary(app.Guid)\n\tif apiErr != nil {\n\t\tcmd.ui.Failed(T(\"Error getting application summary: \") + apiErr.Error())\n\t}\n\n\tcmd.ui.Say(T(\"Creating an app manifest from current settings of app \") + application.Name + \" ...\")\n\tcmd.ui.Say(\"\")\n\n\tsavePath := \".\/\" + application.Name + \"_manifest.yml\"\n\n\tif c.String(\"p\") != \"\" {\n\t\tsavePath = c.String(\"p\")\n\t}\n\n\tcmd.createManifest(application, savePath)\n}\n\nfunc (cmd *CreateAppManifest) createManifest(app models.Application, savePath string) error {\n\tcmd.manifest.FileSavePath(savePath)\n\tcmd.manifest.Memory(app.Name, app.Memory)\n\tcmd.manifest.Instances(app.Name, app.InstanceCount)\n\n\tif app.Command != \"\" {\n\t\tcmd.manifest.StartCommand(app.Name, app.Command)\n\t}\n\n\tif app.BuildpackUrl != \"\" {\n\t\tcmd.manifest.BuildpackUrl(app.Name, app.BuildpackUrl)\n\t}\n\n\tif len(app.Services) > 0 {\n\t\tfor _, service := range app.Services {\n\t\t\tcmd.manifest.Service(app.Name, service.Name)\n\t\t}\n\t}\n\n\tif app.HealthCheckTimeout > 0 {\n\t\tcmd.manifest.HealthCheckTimeout(app.Name, app.HealthCheckTimeout)\n\t}\n\n\tif len(app.EnvironmentVars) > 0 {\n\t\tsorted := sortEnvVar(app.EnvironmentVars)\n\t\tfor _, envVarKey := range sorted {\n\t\t\tswitch app.EnvironmentVars[envVarKey].(type) {\n\t\t\tdefault:\n\t\t\t\tcmd.ui.Failed(T(\"Failed to create manifest, unable to parse environment variable: \") + envVarKey)\n\t\t\tcase float64:\n\t\t\t\t\/\/json.Unmarshal turn all numbers to float64\n\t\t\t\tvalue := int(app.EnvironmentVars[envVarKey].(float64))\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf(\"%d\", value))\n\t\t\tcase bool:\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, fmt.Sprintf(\"%t\", app.EnvironmentVars[envVarKey].(bool)))\n\t\t\tcase string:\n\t\t\t\tcmd.manifest.EnvironmentVars(app.Name, envVarKey, \"\\\"\"+app.EnvironmentVars[envVarKey].(string)+\"\\\"\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(app.Routes) > 0 {\n\t\tfor i := 0; i < len(app.Routes); i++ {\n\t\t\tcmd.manifest.Domain(app.Name, app.Routes[i].Host, app.Routes[i].Domain.Name)\n\t\t}\n\t}\n\n\terr := cmd.manifest.Save()\n\tif err != nil {\n\t\tcmd.ui.Failed(T(\"Error creating manifest file: \") + err.Error())\n\t}\n\n\tcmd.ui.Ok()\n\tcmd.ui.Say(T(\"Manifest file created successfully at \") + savePath)\n\tcmd.ui.Say(\"\")\n\n\treturn nil\n}\n\nfunc sortEnvVar(vars map[string]interface{}) []string {\n\tvar varsAry []string\n\tfor k, _ := range vars {\n\t\tvarsAry = append(varsAry, k)\n\t}\n\tsort.Strings(varsAry)\n\n\treturn varsAry\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/aflashyrhetoric\/backlog-cli\/utils\"\n\te \"github.com\/kyokomi\/emoji\"\n\ta \"github.com\/logrusorgru\/aurora\"\n\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ PullRequest .. a PARTIAL struct for a PullRequest on Backlog\ntype PullRequest struct {\n\tNumber      int               `json:\"number\"`\n\tSummary     string            `json:\"summary\"`\n\tDescription string            `json:\"description\"`\n\tBase        string            `json:\"base\"`\n\tBranch      string            `json:\"branch\"`\n\tIssue       Issue             `json:\"issue\"`\n\tStatus      pullRequestStatus `json:\"status\"`\n}\n\ntype pullRequestStatus struct {\n\tID   int    `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\n\/\/ The branch that we wish to merge to\nvar BaseBranch string\n\nvar prCmd = &cobra.Command{\n\tUse:   \"pr\",\n\tShort: \"Create pull requests or open them (if there is only one associated pull request)\",\n}\n\nvar prCreateCmd = &cobra.Command{\n\tUse:   \"create\",\n\tShort: \"Creates a Backlog Pull Request for the current branch to (master) or some other branch\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ ---------------------------------------------------------\n\n\t\tcb := GlobalConfig.CurrentBranch\n\t\tp := GlobalConfig.ProjectKey\n\t\tr := GlobalConfig.RepositoryName\n\t\tapiURL := \"\/api\/v2\/projects\/\" + p + \"\/git\/repositories\/\" + r + \"\/pullRequests\"\n\n\t\t\/\/apiURL = \"test\"\n\t\tendpoint := Endpoint(apiURL)\n\n\t\texistingPRs, err := checkForExistingPullRequests(endpoint)\n\n\t\tif len(existingPRs) > 0 {\n\t\t\tlistPRs(existingPRs)\n\t\t\treader := bufio.NewReader(os.Stdin)\n\t\t\tfmt.Printf(\"\\n\\nPull Requests for this issue already exist - would you still like to create one? (y\\\\n) \")\n\t\t\ttext, _ := reader.ReadString('\\n')\n\t\t\ttext = strings.TrimSpace(text)\n\n\t\t\tif text != \"y\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Proceed with PR creation\n\t\tif cb == \"staging\" || cb == \"dev\" || cb == \"develop\" || cb == \"beta\" {\n\t\t\te.Printf(\":rotating_light: CAUTION: You are on %s.\\n\", cb)\n\t\t\tfmt.Printf(\"Creating PR: %s --> %s branch.\\n\", cb, BaseBranch)\n\t\t} else if cb == \"0\" {\n\t\t\tfmt.Println(\"Invalid branch. Try again.\")\n\t\t} else {\n\t\t\te.Printf(\"Creating PR: %s --> %s branch. :zap: \\n\", cb, BaseBranch)\n\t\t}\n\n\t\t\/\/ Create the form, request, and send the POST request\n\t\t\/\/ ---------------------------------------------------------\n\t\tform := url.Values{}\n\t\tform.Add(\"summary\", Truncate(GlobalConfig.CurrentIssue.Summary))\n\t\tform.Add(\"description\", GlobalConfig.CurrentIssue.Description)\n\t\t\/\/ Branch to merge to\n\t\tform.Add(\"base\", BaseBranch)\n\t\t\/\/ Branch of branch we are merging\n\t\tform.Add(\"branch\", cb)\n\t\tform.Add(\"assigneeId\", strconv.Itoa(GlobalConfig.User.ID))\n\n\t\t\/\/ Add issueID if it exists\n\t\tif GlobalConfig.CurrentIssue.ID != 0 {\n\t\t\tform.Add(\"issueId\", strconv.Itoa(GlobalConfig.CurrentIssue.ID))\n\t\t}\n\n\t\tresponseData, err := utils.Post(endpoint, form)\n\t\tErrorPanic(err)\n\n\t\tvar returnedPullRequest PullRequest\n\t\tjson.Unmarshal(responseData, &returnedPullRequest)\n\n\t\tlinkToPR := getPRLink(returnedPullRequest.Number)\n\t\tfmt.Printf(\"Link to PR: %s\", linkToPR)\n\t},\n}\n\nfunc listPRs(PRList []PullRequest) {\n\te.Print(\"\\n\\n:hand:\")\n\tfmt.Println(a.White(\"[Existing Pull Requests found]\").BgBrightBlack())\n\tcount := 1\n\tfor _, pr := range PRList {\n\n\t\t\/\/ If there are open PRs with a matching issue ID\n\t\tif pr.Status.ID == 1 && pr.Issue.ID == GlobalConfig.CurrentIssue.ID {\n\t\t\tfmt.Printf(\"%v: %s\\n\", count, getPRLink(pr.Number))\n\t\t\tfmt.Printf(\"   %s %s %s\\n\", a.Cyan(pr.Branch), a.Bold(\"-->\"), a.Cyan(pr.Base))\n\t\t\tcount++\n\t\t}\n\t}\n\n}\n\nfunc getPRLink(n int) string {\n\treturn fmt.Sprintf(\"%s\/git\/%s\/%s\/pullRequests\/%d\", GlobalConfig.BaseURL, GlobalConfig.ProjectKey, GlobalConfig.RepositoryName, n)\n}\n\nfunc checkForExistingPullRequests(endpoint string) ([]PullRequest, error) {\n\n\t\/\/ params for pull requests\n\tparams := map[string]int{\n\t\t\"statusId[]\": 1,\n\t}\n\n\tresponseData := utils.GetParams(endpoint, params)\n\n\t\/\/ List of Pull Requests that already exist and share the ID\n\tvar existingPullRequests []PullRequest\n\n\t\/\/ List of returned pull requests\n\tvar returnedPullRequests []PullRequest\n\terr := json.Unmarshal(responseData, &returnedPullRequests)\n\n\tErrorCheck(err)\n\n\tfor _, element := range returnedPullRequests {\n\t\t\/\/ fmt.Println(GlobalConfig.CurrentIssue)\n\t\t\/\/ fmt.Println(element)\n\t\tif element.Issue.ID == GlobalConfig.CurrentIssue.ID {\n\t\t\texistingPullRequests = append(existingPullRequests, element)\n\t\t}\n\t}\n\n\treturn existingPullRequests, err\n}\n\nfunc init() {\n\tprCreateCmd.Flags().StringVarP(&BaseBranch, \"branch\", \"b\", \"master\", \"Designate a branch (other than master) to merge to.\")\n\tprCmd.AddCommand(prCreateCmd)\n\tRootCmd.AddCommand(prCmd)\n}\n<commit_msg>Added ability to open and list pull reuqests<commit_after>package cmd\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/aflashyrhetoric\/backlog-cli\/utils\"\n\te \"github.com\/kyokomi\/emoji\"\n\ta \"github.com\/logrusorgru\/aurora\"\n\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ PullRequest .. a PARTIAL struct for a PullRequest on Backlog\ntype PullRequest struct {\n\tNumber      int               `json:\"number\"`\n\tSummary     string            `json:\"summary\"`\n\tDescription string            `json:\"description\"`\n\tBase        string            `json:\"base\"`\n\tBranch      string            `json:\"branch\"`\n\tIssue       Issue             `json:\"issue\"`\n\tStatus      pullRequestStatus `json:\"status\"`\n}\n\ntype pullRequestStatus struct {\n\tID   int    `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\n\/\/ The branch that we wish to merge to\nvar BaseBranch string\n\nvar prCmd = &cobra.Command{\n\tUse:   \"pr\",\n\tShort: \"Create pull requests or open them (if there is only one associated pull request)\",\n}\n\nvar prCreateCmd = &cobra.Command{\n\tUse:     \"create\",\n\tAliases: []string{\"c\"},\n\tShort:   \"Creates a Backlog Pull Request for the current branch to (master) or some other branch\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ ---------------------------------------------------------\n\n\t\tcb := GlobalConfig.CurrentBranch\n\t\tp := GlobalConfig.ProjectKey\n\t\tr := GlobalConfig.RepositoryName\n\t\tapiURL := \"\/api\/v2\/projects\/\" + p + \"\/git\/repositories\/\" + r + \"\/pullRequests\"\n\n\t\t\/\/apiURL = \"test\"\n\t\tendpoint := Endpoint(apiURL)\n\n\t\texistingPRs, err := checkForExistingPullRequests(endpoint)\n\n\t\tif len(existingPRs) > 0 {\n\t\t\tlistPRs(\"hand\", \"Existing Pull Requests found\", existingPRs)\n\t\t\treader := bufio.NewReader(os.Stdin)\n\t\t\tfmt.Printf(\"\\n\\nPull Requests for this issue already exist - would you still like to create one? (y\\\\n) \")\n\t\t\ttext, _ := reader.ReadString('\\n')\n\t\t\ttext = strings.TrimSpace(text)\n\t\t\tif text != \"y\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Proceed with PR creation\n\t\tif cb == \"staging\" || cb == \"dev\" || cb == \"develop\" || cb == \"beta\" {\n\t\t\te.Printf(\":rotating_light: CAUTION: You are on %s.\\n\", cb)\n\t\t\tfmt.Printf(\"Creating PR: %s --> %s branch.\\n\", cb, BaseBranch)\n\t\t} else if cb == \"0\" {\n\t\t\tfmt.Println(\"Invalid branch. Try again.\")\n\t\t} else {\n\t\t\te.Printf(\"Creating PR: %s --> %s branch. :zap: \\n\", cb, BaseBranch)\n\t\t}\n\n\t\t\/\/ Create the form, request, and send the POST request\n\t\t\/\/ ---------------------------------------------------------\n\t\tform := url.Values{}\n\t\tform.Add(\"summary\", Truncate(GlobalConfig.CurrentIssue.Summary))\n\t\tform.Add(\"description\", GlobalConfig.CurrentIssue.Description)\n\t\t\/\/ Branch to merge to\n\t\tform.Add(\"base\", BaseBranch)\n\t\t\/\/ Branch of branch we are merging\n\t\tform.Add(\"branch\", cb)\n\t\tform.Add(\"assigneeId\", strconv.Itoa(GlobalConfig.User.ID))\n\n\t\t\/\/ Add issueID if it exists\n\t\tif GlobalConfig.CurrentIssue.ID != 0 {\n\t\t\tform.Add(\"issueId\", strconv.Itoa(GlobalConfig.CurrentIssue.ID))\n\t\t}\n\n\t\tresponseData, err := utils.Post(endpoint, form)\n\t\tErrorPanic(err)\n\n\t\tvar returnedPullRequest PullRequest\n\t\tjson.Unmarshal(responseData, &returnedPullRequest)\n\n\t\tlinkToPR := getPRLink(returnedPullRequest.Number)\n\t\tfmt.Printf(\"Link to PR: %s\", linkToPR)\n\t},\n}\nvar prOpenCmd = &cobra.Command{\n\tUse:     \"open\",\n\tAliases: []string{\"o\"},\n\tShort:   \"If there's a single PR, open it in a browser.\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ ---------------------------------------------------------\n\n\t\tp := GlobalConfig.ProjectKey\n\t\tr := GlobalConfig.RepositoryName\n\t\tapiURL := \"\/api\/v2\/projects\/\" + p + \"\/git\/repositories\/\" + r + \"\/pullRequests\"\n\n\t\t\/\/apiURL = \"test\"\n\t\tendpoint := Endpoint(apiURL)\n\n\t\texistingPRs, err := checkForExistingPullRequests(endpoint)\n\t\tErrorCheck(err)\n\n\t\tif len(existingPRs) == 1 {\n\t\t\tfmt.Println(\"Opening associated PR\")\n\t\t\topenBrowser(getPRLink(existingPRs[0].Number))\n\t\t}\n\t},\n}\n\nvar prListCmd = &cobra.Command{\n\tUse:     \"list\",\n\tAliases: []string{\"ls\"},\n\tShort:   \"List links to all associated pull requests\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ ---------------------------------------------------------\n\n\t\tp := GlobalConfig.ProjectKey\n\t\tr := GlobalConfig.RepositoryName\n\t\tapiURL := \"\/api\/v2\/projects\/\" + p + \"\/git\/repositories\/\" + r + \"\/pullRequests\"\n\n\t\t\/\/apiURL = \"test\"\n\t\tendpoint := Endpoint(apiURL)\n\n\t\texistingPRs, err := checkForExistingPullRequests(endpoint)\n\t\tErrorCheck(err)\n\n\t\tif len(existingPRs) == 0 {\n\t\t\tfmt.Println(\"There are no pull requests associated to this issue.\")\n\t\t}\n\t\tif len(existingPRs) > 0 {\n\t\t\tlistPRs(\"sparkles\", fmt.Sprintf(\"Pull Requests for %s\", GlobalConfig.CurrentIssue.IssueKey), existingPRs)\n\t\t}\n\n\t},\n}\n\nfunc listPRs(emoji string, message string, PRList []PullRequest) {\n\te.Print(\"\\n\\n:\" + emoji + \":\")\n\tfmt.Println(a.White(\"[\" + message + \"]\").BgBrightBlack())\n\tcount := 1\n\tfor _, pr := range PRList {\n\n\t\t\/\/ If there are open PRs with a matching issue ID\n\t\tif pr.Status.ID == 1 && pr.Issue.ID == GlobalConfig.CurrentIssue.ID {\n\t\t\tfmt.Printf(\"%v: %s\\n\", count, getPRLink(pr.Number))\n\t\t\tfmt.Printf(\"   %s %s %s\\n\", a.Cyan(pr.Branch), a.Bold(\"-->\"), a.Cyan(pr.Base))\n\t\t\tcount++\n\t\t}\n\t}\n\n}\n\nfunc getPRLink(n int) string {\n\treturn fmt.Sprintf(\"%s\/git\/%s\/%s\/pullRequests\/%d\", GlobalConfig.BaseURL, GlobalConfig.ProjectKey, GlobalConfig.RepositoryName, n)\n}\n\nfunc checkForExistingPullRequests(endpoint string) ([]PullRequest, error) {\n\n\t\/\/ params for pull requests\n\tparams := map[string]int{\n\t\t\"statusId[]\": 1,\n\t}\n\n\tresponseData := utils.GetParams(endpoint, params)\n\n\t\/\/ List of Pull Requests that already exist and share the ID\n\tvar existingPullRequests []PullRequest\n\n\t\/\/ List of returned pull requests\n\tvar returnedPullRequests []PullRequest\n\terr := json.Unmarshal(responseData, &returnedPullRequests)\n\n\tErrorCheck(err)\n\n\tfor _, element := range returnedPullRequests {\n\t\t\/\/ fmt.Println(GlobalConfig.CurrentIssue)\n\t\t\/\/ fmt.Println(element)\n\t\tif element.Issue.ID == GlobalConfig.CurrentIssue.ID {\n\t\t\texistingPullRequests = append(existingPullRequests, element)\n\t\t}\n\t}\n\n\treturn existingPullRequests, err\n}\n\nfunc init() {\n\tprCreateCmd.Flags().StringVarP(&BaseBranch, \"branch\", \"b\", \"master\", \"Designate a branch (other than master) to merge to.\")\n\tprCmd.AddCommand(prCreateCmd)\n\tprCmd.AddCommand(prOpenCmd)\n\tprCmd.AddCommand(prListCmd)\n\tRootCmd.AddCommand(prCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/dickeyxxx\/speakeasy\"\n)\n\nvar loginTopic = &Topic{\n\tName:        \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n}\n\nvar loginCmd = &Command{\n\tTopic:       \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n\tRun: func(ctx *Context) {\n\t\tlogin()\n\t},\n}\n\nvar authLoginCmd = &Command{\n\tTopic:       \"auth\",\n\tCommand:     \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n\tRun: func(ctx *Context) {\n\t\tlogin()\n\t},\n}\n\nfunc login() {\n\tPrintln(\"Enter your Heroku credentials.\")\n\temail := getString(\"Email: \")\n\tpassword := getPassword()\n\n\ttoken, err := v2login(email, password, \"\")\n\t\/\/ TODO: use createOauthToken (v3 API)\n\t\/\/ token, err := createOauthToken(email, password, \"\")\n\tif err != nil {\n\t\tPrintError(err)\n\t\treturn\n\t}\n\tsaveOauthToken(email, token)\n\tPrintln(\"Logged in as \" + cyan(email))\n}\n\nfunc saveOauthToken(email, token string) {\n\tnetrc := getNetrc()\n\tnetrc.RemoveMachine(apiHost())\n\tnetrc.RemoveMachine(httpGitHost())\n\tnetrc.AddMachine(apiHost(), email, token)\n\tnetrc.AddMachine(httpGitHost(), email, token)\n\tExitIfError(netrc.Save())\n}\n\nfunc getString(prompt string) string {\n\tvar s string\n\tErr(prompt)\n\tif _, err := fmt.Scanln(&s); err != nil {\n\t\tif err.Error() == \"unexpected newline\" {\n\t\t\treturn getString(prompt)\n\t\t}\n\t\tif err.Error() == \"EOF\" {\n\t\t\tErrln()\n\t\t\tos.Exit(1)\n\t\t}\n\t\tExitIfError(err)\n\t}\n\treturn s\n}\n\nfunc getPassword() string {\n\tpassword, err := speakeasy.Ask(\"Password (typing will be hidden): \")\n\tif err != nil {\n\t\tPrintError(err)\n\t}\n\treturn password\n}\n\nfunc v2login(email, password, secondFactor string) (string, error) {\n\treq := apiRequestBase(\"\")\n\treq.Method = \"POST\"\n\treq.Uri = req.Uri + \"\/login?username=\" + url.QueryEscape(email) + \"&password=\" + url.QueryEscape(password)\n\tif secondFactor != \"\" {\n\t\treq.AddHeader(\"Heroku-Two-Factor-Code\", secondFactor)\n\t}\n\tres, err := req.Do()\n\tExitIfError(err)\n\ttype Doc struct {\n\t\tAPIKey string `json:\"api_key\"`\n\t}\n\tvar doc Doc\n\tres.Body.FromJsonTo(&doc)\n\tif res.StatusCode == 403 {\n\t\treturn v2login(email, password, getString(\"Two-factor code: \"))\n\t}\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"Authentication failure.\")\n\t}\n\treturn doc.APIKey, nil\n}\n\nfunc createOauthToken(email, password, secondFactor string) (string, error) {\n\treq := apiRequest(\"\")\n\treq.Method = \"POST\"\n\treq.Uri = req.Uri + \"\/oauth\/authorizations\"\n\treq.BasicAuthUsername = email\n\treq.BasicAuthPassword = password\n\treq.Body = map[string]interface{}{\n\t\t\"scope\":       []string{\"global\"},\n\t\t\"description\": \"Toolbelt CLI login from \" + time.Now().UTC().Format(time.RFC3339),\n\t\t\"expires_in\":  60 * 60 * 24 * 30, \/\/ 30 days\n\t}\n\tif secondFactor != \"\" {\n\t\treq.AddHeader(\"Heroku-Two-Factor-Code\", secondFactor)\n\t}\n\tres, err := req.Do()\n\tExitIfError(err)\n\ttype Doc struct {\n\t\tID          string\n\t\tMessage     string\n\t\tAccessToken struct {\n\t\t\tToken string\n\t\t} `json:\"access_token\"`\n\t}\n\tvar doc Doc\n\tres.Body.FromJsonTo(&doc)\n\tif doc.ID == \"two_factor\" {\n\t\treturn createOauthToken(email, password, getString(\"Two-factor code: \"))\n\t}\n\tif res.StatusCode != 201 {\n\t\treturn \"\", errors.New(doc.Message)\n\t}\n\treturn doc.AccessToken.Token, nil\n}\n<commit_msg>quit if error reading password<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/dickeyxxx\/speakeasy\"\n)\n\nvar loginTopic = &Topic{\n\tName:        \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n}\n\nvar loginCmd = &Command{\n\tTopic:       \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n\tRun: func(ctx *Context) {\n\t\tlogin()\n\t},\n}\n\nvar authLoginCmd = &Command{\n\tTopic:       \"auth\",\n\tCommand:     \"login\",\n\tDescription: \"Login with your Heroku credentials.\",\n\tRun: func(ctx *Context) {\n\t\tlogin()\n\t},\n}\n\nfunc login() {\n\tPrintln(\"Enter your Heroku credentials.\")\n\temail := getString(\"Email: \")\n\tpassword := getPassword()\n\n\ttoken, err := v2login(email, password, \"\")\n\t\/\/ TODO: use createOauthToken (v3 API)\n\t\/\/ token, err := createOauthToken(email, password, \"\")\n\tif err != nil {\n\t\tPrintError(err)\n\t\treturn\n\t}\n\tsaveOauthToken(email, token)\n\tPrintln(\"Logged in as \" + cyan(email))\n}\n\nfunc saveOauthToken(email, token string) {\n\tnetrc := getNetrc()\n\tnetrc.RemoveMachine(apiHost())\n\tnetrc.RemoveMachine(httpGitHost())\n\tnetrc.AddMachine(apiHost(), email, token)\n\tnetrc.AddMachine(httpGitHost(), email, token)\n\tExitIfError(netrc.Save())\n}\n\nfunc getString(prompt string) string {\n\tvar s string\n\tErr(prompt)\n\tif _, err := fmt.Scanln(&s); err != nil {\n\t\tif err.Error() == \"unexpected newline\" {\n\t\t\treturn getString(prompt)\n\t\t}\n\t\tif err.Error() == \"EOF\" {\n\t\t\tErrln()\n\t\t\tos.Exit(1)\n\t\t}\n\t\tExitIfError(err)\n\t}\n\treturn s\n}\n\nfunc getPassword() string {\n\tpassword, err := speakeasy.Ask(\"Password (typing will be hidden): \")\n\tExitIfError(err)\n\treturn password\n}\n\nfunc v2login(email, password, secondFactor string) (string, error) {\n\treq := apiRequestBase(\"\")\n\treq.Method = \"POST\"\n\treq.Uri = req.Uri + \"\/login?username=\" + url.QueryEscape(email) + \"&password=\" + url.QueryEscape(password)\n\tif secondFactor != \"\" {\n\t\treq.AddHeader(\"Heroku-Two-Factor-Code\", secondFactor)\n\t}\n\tres, err := req.Do()\n\tExitIfError(err)\n\ttype Doc struct {\n\t\tAPIKey string `json:\"api_key\"`\n\t}\n\tvar doc Doc\n\tres.Body.FromJsonTo(&doc)\n\tif res.StatusCode == 403 {\n\t\treturn v2login(email, password, getString(\"Two-factor code: \"))\n\t}\n\tif res.StatusCode != 200 {\n\t\treturn \"\", errors.New(\"Authentication failure.\")\n\t}\n\treturn doc.APIKey, nil\n}\n\nfunc createOauthToken(email, password, secondFactor string) (string, error) {\n\treq := apiRequest(\"\")\n\treq.Method = \"POST\"\n\treq.Uri = req.Uri + \"\/oauth\/authorizations\"\n\treq.BasicAuthUsername = email\n\treq.BasicAuthPassword = password\n\treq.Body = map[string]interface{}{\n\t\t\"scope\":       []string{\"global\"},\n\t\t\"description\": \"Toolbelt CLI login from \" + time.Now().UTC().Format(time.RFC3339),\n\t\t\"expires_in\":  60 * 60 * 24 * 30, \/\/ 30 days\n\t}\n\tif secondFactor != \"\" {\n\t\treq.AddHeader(\"Heroku-Two-Factor-Code\", secondFactor)\n\t}\n\tres, err := req.Do()\n\tExitIfError(err)\n\ttype Doc struct {\n\t\tID          string\n\t\tMessage     string\n\t\tAccessToken struct {\n\t\t\tToken string\n\t\t} `json:\"access_token\"`\n\t}\n\tvar doc Doc\n\tres.Body.FromJsonTo(&doc)\n\tif doc.ID == \"two_factor\" {\n\t\treturn createOauthToken(email, password, getString(\"Two-factor code: \"))\n\t}\n\tif res.StatusCode != 201 {\n\t\treturn \"\", errors.New(doc.Message)\n\t}\n\treturn doc.AccessToken.Token, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n  Go only has one way of looping through things: for.\n  There are three different ways of writing for, though.\n*\/\n\npackage main\nimport \"fmt\"\nfunc main() {\n  \/\/ The first is the basic conditional\n  i := 1\n  for i <= 3 {\n    fmt.Println(i)\n    i = i + 1\n  }\n  \n  \/\/ The other is the classic initial; condition; increment\n  for j := 1; j <= 3; j++ {\n    fmt.Println(j)\n  }\n  \n  \/\/ The last is an infinite loop\n  for {\n    fmt.Println(\"again!\")\n    break\n  }\n  \n  \/*\n    If\/else if\/else conditionals are similar to Javascript in Go.\n    But like for loops, they don't require parenthesis.\n  *\/\n  \n  if 7 % 2 == 0 {\n    fmt.Println(\"7 is even\")\n  } else {\n    fmt.Println(\"7 is odd\")\n  }\n  \n  \/\/ We can also declare variables before\/in a conditional:\n  if num := 9; num < 0 {\n    fmt.Println(num, \" is negative\")\n  } else if num < 10 {\n    fmt.Println(num, \" has 1 digit\")\n  } else {\n    fmt.Println(num, \" has multiple digits\")\n  }\n  \n  \/\/ Switches are pretty similar\n  switch time.Now().Weekday() {\n    case time.Saturday, time.Sunday:\n      fmt.Println(\"it's the weekend\")\n    default:\n      fmt.Println(\"it's a weekday\")\n  }\n  \n  \/\/ But may also be written in some different ways:\n  t := time.Now()\n  switch {\n    case t.Hour() < 12:\n      fmt.Println(\"it's before noon\")\n    default:\n      fmt.Println(\"it's after noon\")\n  }\n}\n<commit_msg>Add middle case<commit_after>\/*\n  Go only has one way of looping through things: for.\n  There are three different ways of writing for, though.\n*\/\n\npackage main\nimport \"fmt\"\nfunc main() {\n  \/\/ The first is the basic conditional\n  i := 1\n  for i <= 3 {\n    fmt.Println(i)\n    i = i + 1\n  }\n  \n  \/\/ The other is the classic initial; condition; increment\n  for j := 1; j <= 3; j++ {\n    fmt.Println(j)\n  }\n  \n  \/\/ The last is an infinite loop\n  for {\n    fmt.Println(\"again!\")\n    break\n  }\n  \n  \/*\n    If\/else if\/else conditionals are similar to Javascript in Go.\n    But like for loops, they don't require parenthesis.\n  *\/\n  \n  if 7 % 2 == 0 {\n    fmt.Println(\"7 is even\")\n  } else {\n    fmt.Println(\"7 is odd\")\n  }\n  \n  \/\/ We can also declare variables before\/in a conditional:\n  if num := 9; num < 0 {\n    fmt.Println(num, \" is negative\")\n  } else if num < 10 {\n    fmt.Println(num, \" has 1 digit\")\n  } else {\n    fmt.Println(num, \" has multiple digits\")\n  }\n  \n  \/\/ Switches are pretty similar\n  switch time.Now().Weekday() {\n    case time.Saturday, time.Sunday:\n      fmt.Println(\"it's the weekend\")\n    default:\n      fmt.Println(\"it's a weekday\")\n  }\n  \n  \/\/ But may also be written in some different ways:\n  t := time.Now()\n  switch {\n    case t.Hour() < 12:\n      fmt.Println(\"it's before noon\")\n    case t.Hour() == 12:\n      fmt.Println(\"it's noon!\")\n    default:\n      fmt.Println(\"it's after noon\")\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2016, TEECOM\n *\n * This code is provided for free, as is, under the MIT license\n * (see LICENSE.md).\n *\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\n\/\/ Strucures; the actual information is separated from updates\ntype line struct {\n\tName  string\n\tID    string\n\tTimes []int\n\tColor string\n}\n\ntype coordinates struct {\n\tLat float64\n\tLon float64\n}\n\ntype station struct {\n\tName  string\n\tID    string\n\tCoord coordinates\n\n\tDirections [2]string\n\n\tLines [2]map[string]*line\n}\n\ntype system struct {\n\tName    string\n\tTagline string\n\tStops   []station\n\tTimeMax int\n\tstopMap map[string]*station\n\trwLock  *sync.RWMutex\n}\n\n\/\/ Update structures (externally generated)\ntype lineUpdate struct {\n\tLineID string\n\tIndex  int\n\tTimes  []int\n}\n\ntype stationUpdate struct {\n\tStationID string\n\tLines     []lineUpdate\n}\n\ntype update struct {\n\tStops []stationUpdate\n}\n\n\/\/ This is the main system information; fill this as appropriate\nvar mainSystem system = system{\n\tName:    \"TEECOM Shuttle Service\",\n\tTagline: \"San Francisco Bay Area\",\n\tStops: []station{\n\t\tstation{\n\t\t\tName: \"TEECOM\",\n\t\t\tID:   \"tee\",\n\t\t\tCoord: coordinates{\n\t\t\t\tLat: 10.5,\n\t\t\t\tLon: 10.5,\n\t\t\t},\n\t\t\tDirections: [2]string{\"Northbound\", \"Southbound\"},\n\t\t\tLines: [2]map[string]*line{\n\t\t\t\tmap[string]*line{\n\t\t\t\t\t\"sh\": &line{\n\t\t\t\t\t\tName:  \"Shuttle\",\n\t\t\t\t\t\tID:    \"sh\",\n\t\t\t\t\t\tColor: \"#ff0000\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n\n\tTimeMax: 45,\n\n\tstopMap: make(map[string]*station),\n\trwLock:  &sync.RWMutex{},\n}\n\n\/\/ Where static files will be found\nconst staticDirectory string = \"static\"\n\nfunc prepareSystem() {\n\t\/\/ Cache system IDs for future lookup.\n\t\/\/ No need to do any locking as the server hasn't\n\t\/\/ started up yet.\n\tfor i := 0; i < len(mainSystem.Stops); i++ {\n\t\tstop := &mainSystem.Stops[i]\n\t\tmainSystem.stopMap[stop.ID] = stop\n\t}\n}\n\nfunc main() {\n\tlog.Println(\"Starting server\")\n\tprepareSystem()\n\n\t\/\/ Setup routing\n\thttp.HandleFunc(\"\/info\", handleInfo)\n\thttp.HandleFunc(\"\/update\", handleUpdate)\n\thttp.HandleFunc(\"\/stop\", handleStopInfo)\n\n\t\/\/ Run server on port 8080\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/\/ JSON encode all of the information\nfunc handleInfo(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Obtain a read lock for the system\n\tmainSystem.rwLock.RLock()\n\tdefer mainSystem.rwLock.RUnlock()\n\n\tif err := json.NewEncoder(w).Encode(mainSystem); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Internal Server Error\")\n\t}\n}\n\nfunc handleStopInfo(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Check for valid GET parameters\n\tstopID := r.URL.Query()[\"id\"]\n\tif stopID == nil || len(stopID) != 1 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(w, \"400 Bad Request: Missing stop ID\")\n\t\treturn\n\t}\n\n\t\/\/ Obtain a read lock for the system\n\tmainSystem.rwLock.RLock()\n\tdefer mainSystem.rwLock.RUnlock()\n\n\t\/\/ Try to find the correct stop\n\tstop := mainSystem.stopMap[stopID[0]]\n\tif stop == nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"400 Bad Request: Invalid stop id (%s)\\n\", stopID[0])\n\t\treturn\n\t}\n\n\t\/\/ Send the response\n\tif err := json.NewEncoder(w).Encode(stop); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Internal Server Error\")\n\t}\n}\n\n\/\/ Handle update request\nfunc handleUpdate(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Ensure we are dealing with a POST request\n\tif r.Method != \"POST\" {\n\t\tserve(w, \"update.html\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Decode the JSON\n\tvar new update\n\tif err := json.NewDecoder(r.Body).Decode(&new); err != nil {\n\t\tserve(w, \"badupdate.html\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Try to apply the updates\n\tif err := processUpdates(&new); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"400 Bad Request: %s\\n\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc processUpdates(u *update) error {\n\t\/\/ Obtain a writer lock\n\tmainSystem.rwLock.Lock()\n\tdefer mainSystem.rwLock.Unlock()\n\n\tfor _, su := range u.Stops {\n\t\tstop := mainSystem.stopMap[su.StationID]\n\t\tif stop == nil {\n\t\t\treturn errors.New(\"Invalid station ID\")\n\t\t}\n\n\t\tfor _, lu := range su.Lines {\n\t\t\tif lu.Index > 1 {\n\t\t\t\treturn errors.New(\"Line index out of bounds\")\n\t\t\t}\n\n\t\t\tln := stop.Lines[lu.Index][lu.LineID]\n\t\t\tif ln == nil {\n\t\t\t\treturn errors.New(\"Invalid line ID\")\n\t\t\t}\n\n\t\t\tln.Times = lu.Times\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc serve(w http.ResponseWriter, f string, code int) {\n\ttext, err := ioutil.ReadFile(staticDirectory + \"\/\" + f)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"500 Internal Server Error\")\n\t\treturn\n\t}\n\n\tw.WriteHeader(code)\n\tfmt.Fprintf(w, \"%s\", text)\n}\n<commit_msg>Use embedded RWMutex in system.<commit_after>\/*\n * Copyright (c) 2016, TEECOM\n *\n * This code is provided for free, as is, under the MIT license\n * (see LICENSE.md).\n *\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\n\/\/ Strucures; the actual information is separated from updates\ntype line struct {\n\tName  string\n\tID    string\n\tTimes []int\n\tColor string\n}\n\ntype coordinates struct {\n\tLat float64\n\tLon float64\n}\n\ntype station struct {\n\tName  string\n\tID    string\n\tCoord coordinates\n\n\tDirections [2]string\n\n\tLines [2]map[string]*line\n}\n\ntype system struct {\n\tsync.RWMutex \/\/ Protects everything below\n\tName         string\n\tTagline      string\n\tStops        []station\n\tTimeMax      int\n\tstopMap      map[string]*station\n}\n\n\/\/ Update structures (externally generated)\ntype lineUpdate struct {\n\tLineID string\n\tIndex  int\n\tTimes  []int\n}\n\ntype stationUpdate struct {\n\tStationID string\n\tLines     []lineUpdate\n}\n\ntype update struct {\n\tStops []stationUpdate\n}\n\n\/\/ This is the main system information; fill this as appropriate\nvar mainSystem system = system{\n\tName:    \"TEECOM Shuttle Service\",\n\tTagline: \"San Francisco Bay Area\",\n\tStops: []station{\n\t\tstation{\n\t\t\tName: \"TEECOM\",\n\t\t\tID:   \"tee\",\n\t\t\tCoord: coordinates{\n\t\t\t\tLat: 10.5,\n\t\t\t\tLon: 10.5,\n\t\t\t},\n\t\t\tDirections: [2]string{\"Northbound\", \"Southbound\"},\n\t\t\tLines: [2]map[string]*line{\n\t\t\t\tmap[string]*line{\n\t\t\t\t\t\"sh\": &line{\n\t\t\t\t\t\tName:  \"Shuttle\",\n\t\t\t\t\t\tID:    \"sh\",\n\t\t\t\t\t\tColor: \"#ff0000\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n\n\tTimeMax: 45,\n\n\tstopMap: make(map[string]*station),\n}\n\n\/\/ Where static files will be found\nconst staticDirectory string = \"static\"\n\nfunc prepareSystem() {\n\t\/\/ Cache system IDs for future lookup.\n\t\/\/ No need to do any locking as the server hasn't\n\t\/\/ started up yet.\n\tfor i := 0; i < len(mainSystem.Stops); i++ {\n\t\tstop := &mainSystem.Stops[i]\n\t\tmainSystem.stopMap[stop.ID] = stop\n\t}\n}\n\nfunc main() {\n\tlog.Println(\"Starting server\")\n\tprepareSystem()\n\n\t\/\/ Setup routing\n\thttp.HandleFunc(\"\/info\", handleInfo)\n\thttp.HandleFunc(\"\/update\", handleUpdate)\n\thttp.HandleFunc(\"\/stop\", handleStopInfo)\n\n\t\/\/ Run server on port 8080\n\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/\/ JSON encode all of the information\nfunc handleInfo(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Obtain a read lock for the system\n\tmainSystem.RLock()\n\tdefer mainSystem.RUnlock()\n\n\tif err := json.NewEncoder(w).Encode(mainSystem); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Internal Server Error\")\n\t}\n}\n\nfunc handleStopInfo(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Check for valid GET parameters\n\tstopID := r.URL.Query()[\"id\"]\n\tif stopID == nil || len(stopID) != 1 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(w, \"400 Bad Request: Missing stop ID\")\n\t\treturn\n\t}\n\n\t\/\/ Obtain a read lock for the system\n\tmainSystem.RLock()\n\tdefer mainSystem.RUnlock()\n\n\t\/\/ Try to find the correct stop\n\tstop := mainSystem.stopMap[stopID[0]]\n\tif stop == nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"400 Bad Request: Invalid stop id (%s)\\n\", stopID[0])\n\t\treturn\n\t}\n\n\t\/\/ Send the response\n\tif err := json.NewEncoder(w).Encode(stop); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Internal Server Error\")\n\t}\n}\n\n\/\/ Handle update request\nfunc handleUpdate(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Ensure we are dealing with a POST request\n\tif r.Method != \"POST\" {\n\t\tserve(w, \"update.html\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Decode the JSON\n\tvar new update\n\tif err := json.NewDecoder(r.Body).Decode(&new); err != nil {\n\t\tserve(w, \"badupdate.html\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Try to apply the updates\n\tif err := processUpdates(&new); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"400 Bad Request: %s\\n\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc processUpdates(u *update) error {\n\t\/\/ Obtain a writer lock\n\tmainSystem.Lock()\n\tdefer mainSystem.Unlock()\n\n\tfor _, su := range u.Stops {\n\t\tstop := mainSystem.stopMap[su.StationID]\n\t\tif stop == nil {\n\t\t\treturn errors.New(\"Invalid station ID\")\n\t\t}\n\n\t\tfor _, lu := range su.Lines {\n\t\t\tif lu.Index > 1 {\n\t\t\t\treturn errors.New(\"Line index out of bounds\")\n\t\t\t}\n\n\t\t\tln := stop.Lines[lu.Index][lu.LineID]\n\t\t\tif ln == nil {\n\t\t\t\treturn errors.New(\"Invalid line ID\")\n\t\t\t}\n\n\t\t\tln.Times = lu.Times\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc serve(w http.ResponseWriter, f string, code int) {\n\ttext, err := ioutil.ReadFile(staticDirectory + \"\/\" + f)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"500 Internal Server Error\")\n\t\treturn\n\t}\n\n\tw.WriteHeader(code)\n\tfmt.Fprintf(w, \"%s\", text)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/ymotongpoo\/goltsv\"\n)\n\nvar KEYS_LIST = regexp.MustCompile(`(?:[^,\\\\]|\\\\.)*`)\n\nfunc ParseKeysList(list string) []string {\n\tkeys := KEYS_LIST.FindAllString(list, -1)\n\tfor i := 0; i < len(keys); i++ {\n\t\tkeys[i] = strings.Replace(keys[i], `\\,`, `,`, -1)\n\t\tkeys[i] = strings.Replace(keys[i], `\\\\`, `\\`, -1)\n\t}\n\treturn keys\n}\n\ntype LTSVScanner struct {\n\tkeys   []string\n\tline   string\n\terr    error\n\treader *goltsv.LTSVReader\n}\n\nfunc NewLTSVScanner(keys []string, r io.Reader) *LTSVScanner {\n\treturn &LTSVScanner{\n\t\tkeys:   keys,\n\t\treader: goltsv.NewReader(r),\n\t}\n}\n\nfunc (l *LTSVScanner) Scan() bool {\n\tif l.err != nil {\n\t\treturn false\n\t}\n\n\trecode, err := l.reader.Read()\n\tif err != nil {\n\t\tl.err = err\n\t\treturn false\n\t}\n\n\tvar values []string\n\tfor _, key := range l.keys {\n\t\tvalues = append(values, recode[key])\n\t}\n\tl.line = strings.Join(values, \"\\t\")\n\n\treturn true\n}\n\nfunc (l *LTSVScanner) Err() error {\n\tif l.err == io.EOF {\n\t\treturn nil\n\t}\n\treturn l.err\n}\n\nfunc (l *LTSVScanner) Text() string {\n\treturn l.line\n}\n<commit_msg>Make LTSVScanner.Text returns \"\" after the end<commit_after>package main\n\nimport (\n\t\"io\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/ymotongpoo\/goltsv\"\n)\n\nvar KEYS_LIST = regexp.MustCompile(`(?:[^,\\\\]|\\\\.)*`)\n\nfunc ParseKeysList(list string) []string {\n\tkeys := KEYS_LIST.FindAllString(list, -1)\n\tfor i := 0; i < len(keys); i++ {\n\t\tkeys[i] = strings.Replace(keys[i], `\\,`, `,`, -1)\n\t\tkeys[i] = strings.Replace(keys[i], `\\\\`, `\\`, -1)\n\t}\n\treturn keys\n}\n\ntype LTSVScanner struct {\n\tkeys   []string\n\tline   string\n\terr    error\n\treader *goltsv.LTSVReader\n}\n\nfunc NewLTSVScanner(keys []string, r io.Reader) *LTSVScanner {\n\treturn &LTSVScanner{\n\t\tkeys:   keys,\n\t\treader: goltsv.NewReader(r),\n\t}\n}\n\nfunc (l *LTSVScanner) Scan() bool {\n\tif l.err != nil {\n\t\treturn false\n\t}\n\n\trecode, err := l.reader.Read()\n\tif err != nil {\n\t\tl.err = err\n\t\tl.line = \"\"\n\t\treturn false\n\t}\n\n\tvar values []string\n\tfor _, key := range l.keys {\n\t\tvalues = append(values, recode[key])\n\t}\n\tl.line = strings.Join(values, \"\\t\")\n\n\treturn true\n}\n\nfunc (l *LTSVScanner) Err() error {\n\tif l.err == io.EOF {\n\t\treturn nil\n\t}\n\treturn l.err\n}\n\nfunc (l *LTSVScanner) Text() string {\n\treturn l.line\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 commitlog\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/m3db\/m3db\/clock\"\n\t\"github.com\/m3db\/m3db\/context\"\n\t\"github.com\/m3db\/m3db\/ts\"\n\t\"github.com\/m3db\/m3x\/log\"\n\t\"github.com\/m3db\/m3x\/time\"\n\n\t\"github.com\/uber-go\/tally\"\n)\n\nvar (\n\terrCommitLogClosed    = errors.New(\"commit log is closed\")\n\terrCommitLogQueueFull = errors.New(\"commit log queue is full\")\n\n\ttimeZero = time.Time{}\n)\n\ntype newCommitLogWriterFn func(flushFn flushFn, opts Options) commitLogWriter\n\ntype commitLogFailFn func(err error)\n\ntype completionFn func(err error)\n\ntype commitLog struct {\n\tsync.RWMutex\n\topts    Options\n\tnowFn   clock.NowFn\n\tscope   tally.Scope\n\tmetrics commitLogMetrics\n\n\tlog xlog.Logger\n\n\tnewCommitLogWriterFn newCommitLogWriterFn\n\tcommitLogFailFn      commitLogFailFn\n\twriter               commitLogWriter\n\n\t\/\/ TODO(r): replace buffered channel with concurrent striped\n\t\/\/ circular buffer to avoid central write lock contention\n\twrites chan commitLogWrite\n\n\tflushMutex      sync.RWMutex\n\tlastFlushAt     time.Time\n\tpendingFlushFns []completionFn\n\n\tbitset         bitset\n\twriterExpireAt time.Time\n\tclosed         bool\n\tcloseErr       chan error\n}\n\ntype commitLogMetrics struct {\n\tqueued      tally.Gauge\n\tsuccess     tally.Counter\n\terrors      tally.Counter\n\topenErrors  tally.Counter\n\tcloseErrors tally.Counter\n\tflushErrors tally.Counter\n\tflushDone   tally.Counter\n}\n\ntype valueType int\n\nconst (\n\twriteValueType valueType = iota\n\tflushValueType\n)\n\ntype commitLogWrite struct {\n\tvalueType valueType\n\n\tseries       Series\n\tdatapoint    ts.Datapoint\n\tunit         xtime.Unit\n\tannotation   ts.Annotation\n\tcompletionFn completionFn\n}\n\n\/\/ NewCommitLog creates a new commit log\nfunc NewCommitLog(opts Options) CommitLog {\n\tiopts := opts.InstrumentOptions().SetMetricsScope(\n\t\topts.InstrumentOptions().MetricsScope().SubScope(\"commitlog\"))\n\tscope := iopts.MetricsScope()\n\n\tcommitLog := &commitLog{\n\t\topts:  opts,\n\t\tnowFn: opts.ClockOptions().NowFn(),\n\t\tscope: scope,\n\t\tmetrics: commitLogMetrics{\n\t\t\tqueued:      scope.Gauge(\"writes.queued\"),\n\t\t\tsuccess:     scope.Counter(\"writes.success\"),\n\t\t\terrors:      scope.Counter(\"writes.errors\"),\n\t\t\topenErrors:  scope.Counter(\"writes.open-errors\"),\n\t\t\tcloseErrors: scope.Counter(\"writes.close-errors\"),\n\t\t\tflushErrors: scope.Counter(\"writes.flush-errors\"),\n\t\t\tflushDone:   scope.Counter(\"writes.flush-done\"),\n\t\t},\n\t\tlog:                  iopts.Logger(),\n\t\tnewCommitLogWriterFn: newCommitLogWriter,\n\t\twrites:               make(chan commitLogWrite, opts.BacklogQueueSize()),\n\t\tcloseErr:             make(chan error),\n\t}\n\n\treturn commitLog\n}\n\nfunc (l *commitLog) Open() error {\n\t\/\/ Open the buffered commit log writer\n\tif err := l.openWriter(l.nowFn()); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Flush the info header to ensure we can write to disk\n\tif err := l.writer.Flush(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ NB(r): In the future we can introduce a commit log failure policy\n\t\/\/ similar to Cassandra's \"stop\", for example see:\n\t\/\/ https:\/\/github.com\/apache\/cassandra\/blob\/6dfc1e7eeba539774784dfd650d3e1de6785c938\/conf\/cassandra.yaml#L232\n\t\/\/ Right now it is a large amount of coordination to implement something similiar.\n\tvar fails int64\n\n\tl.commitLogFailFn = func(err error) {\n\t\tcurrFails := atomic.AddInt64(&fails, 1)\n\n\t\tif currFails < 3 {\n\t\t\tgo func() {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tatomic.AddInt64(&fails, -1)\n\t\t\t}()\n\n\t\t\treturn\n\t\t}\n\n\t\tl.log.Fatalf(\"fatal commit log error: %v\", err)\n\t}\n\n\t\/\/ Asynchronously write\n\tgo l.write()\n\n\tif flushInterval := l.opts.FlushInterval(); flushInterval > 0 {\n\t\t\/\/ Continually flush the commit log at given interval if set\n\t\tgo l.flushEvery(flushInterval)\n\t}\n\n\treturn nil\n}\n\nfunc (l *commitLog) flushEvery(interval time.Duration) {\n\t\/\/ Periodically flush the underlying commit log writer to cover\n\t\/\/ the case when writes stall for a considerable time\n\tvar sleepForOverride time.Duration\n\n\tfor {\n\t\tl.metrics.queued.Update(int64(len(l.writes)))\n\n\t\tsleepFor := interval\n\n\t\tif sleepForOverride > 0 {\n\t\t\tsleepFor = sleepForOverride\n\t\t\tsleepForOverride = 0\n\t\t}\n\n\t\ttime.Sleep(sleepFor)\n\n\t\tl.flushMutex.RLock()\n\t\tlastFlushAt := l.lastFlushAt\n\t\tl.flushMutex.RUnlock()\n\n\t\tif sinceFlush := l.nowFn().Sub(lastFlushAt); sinceFlush < interval {\n\t\t\t\/\/ Flushed already recently, sleep until we would next consider flushing\n\t\t\tsleepForOverride = interval - sinceFlush\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Request a flush\n\t\tl.RLock()\n\t\tif l.closed {\n\t\t\tl.RUnlock()\n\t\t\treturn\n\t\t}\n\n\t\tl.writes <- commitLogWrite{valueType: flushValueType}\n\t\tl.RUnlock()\n\t}\n}\n\nfunc (l *commitLog) write() {\n\tfor write := range l.writes {\n\t\t\/\/ For writes requiring acks add to pending acks\n\t\tif write.completionFn != nil {\n\t\t\tl.pendingFlushFns = append(l.pendingFlushFns, write.completionFn)\n\t\t}\n\n\t\tif write.valueType == flushValueType {\n\t\t\tl.writer.Flush()\n\t\t\tcontinue\n\t\t}\n\n\t\tif now := l.nowFn(); !now.Before(l.writerExpireAt) {\n\t\t\tif err := l.openWriter(now); err != nil {\n\t\t\t\tl.metrics.errors.Inc(1)\n\t\t\t\tl.metrics.openErrors.Inc(1)\n\t\t\t\tl.log.Errorf(\"failed to open commit log: %v\", err)\n\n\t\t\t\tif l.commitLogFailFn != nil {\n\t\t\t\t\tl.commitLogFailFn(err)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\terr := l.writer.Write(\n\t\t\twrite.series, write.datapoint, write.unit, write.annotation)\n\t\twrite.series.ID.OnClose()\n\n\t\tif err != nil {\n\t\t\tl.metrics.errors.Inc(1)\n\t\t\tl.log.Errorf(\"failed to write to commit log: %v\", err)\n\n\t\t\tif l.commitLogFailFn != nil {\n\t\t\t\tl.commitLogFailFn(err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tl.metrics.success.Inc(1)\n\t}\n\n\tl.Lock()\n\tdefer l.Unlock()\n\n\twriter := l.writer\n\tl.writer = nil\n\tl.closeErr <- writer.Close()\n}\n\nfunc (l *commitLog) onFlush(err error) {\n\tl.flushMutex.Lock()\n\tl.lastFlushAt = l.nowFn()\n\tl.flushMutex.Unlock()\n\n\tif err != nil {\n\t\tl.metrics.errors.Inc(1)\n\t\tl.metrics.flushErrors.Inc(1)\n\t\tl.log.Errorf(\"failed to flush commit log: %v\", err)\n\n\t\tif l.commitLogFailFn != nil {\n\t\t\tl.commitLogFailFn(err)\n\t\t}\n\t}\n\n\t\/\/ onFlush only ever called by \"write()\" and \"openWriter\" or\n\t\/\/ before \"write()\" begins on \"Open()\" and there are no other\n\t\/\/ accessors of \"pendingFlushFns\" so it is safe to read and mutate\n\t\/\/ without a lock here\n\tif len(l.pendingFlushFns) == 0 {\n\t\tl.metrics.flushDone.Inc(1)\n\t\treturn\n\t}\n\n\tfor i := range l.pendingFlushFns {\n\t\tl.pendingFlushFns[i](err)\n\t}\n\n\tl.pendingFlushFns = l.pendingFlushFns[:0]\n\tl.metrics.flushDone.Inc(1)\n}\n\nfunc (l *commitLog) openWriter(now time.Time) error {\n\tif l.writer != nil {\n\t\tif err := l.writer.Close(); err != nil {\n\t\t\tl.metrics.closeErrors.Inc(1)\n\t\t\tl.log.Errorf(\"failed to close commit log: %v\", err)\n\n\t\t\t\/\/ If we failed to close then create a new commit log writer\n\t\t\tl.writer = nil\n\t\t}\n\t}\n\n\tif l.writer == nil {\n\t\tl.writer = l.newCommitLogWriterFn(l.onFlush, l.opts)\n\t}\n\n\tblockSize := l.opts.RetentionOptions().BlockSize()\n\tstart := now.Truncate(blockSize)\n\n\tif err := l.writer.Open(start, blockSize); err != nil {\n\t\treturn err\n\t}\n\n\tl.writerExpireAt = start.Add(blockSize)\n\n\treturn nil\n}\n\nfunc (l *commitLog) Write(\n\tctx context.Context,\n\tseries Series,\n\tdatapoint ts.Datapoint,\n\tunit xtime.Unit,\n\tannotation ts.Annotation,\n) error {\n\tl.RLock()\n\tif l.closed {\n\t\tl.RUnlock()\n\t\treturn errCommitLogClosed\n\t}\n\n\tvar (\n\t\twg     sync.WaitGroup\n\t\tresult error\n\t)\n\n\twg.Add(1)\n\n\tcompletion := func(err error) {\n\t\tresult = err\n\t\twg.Done()\n\t}\n\n\twrite := commitLogWrite{\n\t\tseries:       series,\n\t\tdatapoint:    datapoint,\n\t\tunit:         unit,\n\t\tannotation:   annotation,\n\t\tcompletionFn: completion,\n\t}\n\n\tenqueued := false\n\n\tselect {\n\tcase l.writes <- write:\n\t\tenqueued = true\n\tdefault:\n\t}\n\n\tl.RUnlock()\n\n\tif !enqueued {\n\t\treturn errCommitLogQueueFull\n\t}\n\n\twg.Wait()\n\n\treturn result\n}\n\nfunc (l *commitLog) WriteBehind(\n\tctx context.Context,\n\tseries Series,\n\tdatapoint ts.Datapoint,\n\tunit xtime.Unit,\n\tannotation ts.Annotation,\n) error {\n\tl.RLock()\n\tif l.closed {\n\t\tl.RUnlock()\n\t\treturn errCommitLogClosed\n\t}\n\n\twrite := commitLogWrite{\n\t\tseries:     series,\n\t\tdatapoint:  datapoint,\n\t\tunit:       unit,\n\t\tannotation: annotation,\n\t}\n\n\tenqueued := false\n\n\tselect {\n\tcase l.writes <- write:\n\t\tenqueued = true\n\tdefault:\n\t}\n\n\tl.RUnlock()\n\n\tif !enqueued {\n\t\treturn errCommitLogQueueFull\n\t}\n\n\treturn nil\n}\n\nfunc (l *commitLog) Iter() (Iterator, error) {\n\treturn NewIterator(l.opts)\n}\n\nfunc (l *commitLog) Close() error {\n\tl.Lock()\n\tif l.closed {\n\t\tl.Unlock()\n\t\treturn nil\n\t}\n\n\tl.closed = true\n\tclose(l.writes)\n\tl.Unlock()\n\n\t\/\/ Receive the result of closing the writer from asynchronous writer\n\treturn <-l.closeErr\n}\n<commit_msg>Halt on commit log failure instead of using sliding window of 3 failures (#131)<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 commitlog\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/m3db\/m3db\/clock\"\n\t\"github.com\/m3db\/m3db\/context\"\n\t\"github.com\/m3db\/m3db\/ts\"\n\t\"github.com\/m3db\/m3x\/log\"\n\t\"github.com\/m3db\/m3x\/time\"\n\n\t\"github.com\/uber-go\/tally\"\n)\n\nvar (\n\terrCommitLogClosed    = errors.New(\"commit log is closed\")\n\terrCommitLogQueueFull = errors.New(\"commit log queue is full\")\n\n\ttimeZero = time.Time{}\n)\n\ntype newCommitLogWriterFn func(flushFn flushFn, opts Options) commitLogWriter\n\ntype commitLogFailFn func(err error)\n\ntype completionFn func(err error)\n\ntype commitLog struct {\n\tsync.RWMutex\n\topts    Options\n\tnowFn   clock.NowFn\n\tscope   tally.Scope\n\tmetrics commitLogMetrics\n\n\tlog xlog.Logger\n\n\tnewCommitLogWriterFn newCommitLogWriterFn\n\tcommitLogFailFn      commitLogFailFn\n\twriter               commitLogWriter\n\n\t\/\/ TODO(r): replace buffered channel with concurrent striped\n\t\/\/ circular buffer to avoid central write lock contention\n\twrites chan commitLogWrite\n\n\tflushMutex      sync.RWMutex\n\tlastFlushAt     time.Time\n\tpendingFlushFns []completionFn\n\n\tbitset         bitset\n\twriterExpireAt time.Time\n\tclosed         bool\n\tcloseErr       chan error\n}\n\ntype commitLogMetrics struct {\n\tqueued      tally.Gauge\n\tsuccess     tally.Counter\n\terrors      tally.Counter\n\topenErrors  tally.Counter\n\tcloseErrors tally.Counter\n\tflushErrors tally.Counter\n\tflushDone   tally.Counter\n}\n\ntype valueType int\n\nconst (\n\twriteValueType valueType = iota\n\tflushValueType\n)\n\ntype commitLogWrite struct {\n\tvalueType valueType\n\n\tseries       Series\n\tdatapoint    ts.Datapoint\n\tunit         xtime.Unit\n\tannotation   ts.Annotation\n\tcompletionFn completionFn\n}\n\n\/\/ NewCommitLog creates a new commit log\nfunc NewCommitLog(opts Options) CommitLog {\n\tiopts := opts.InstrumentOptions().SetMetricsScope(\n\t\topts.InstrumentOptions().MetricsScope().SubScope(\"commitlog\"))\n\tscope := iopts.MetricsScope()\n\n\tcommitLog := &commitLog{\n\t\topts:  opts,\n\t\tnowFn: opts.ClockOptions().NowFn(),\n\t\tscope: scope,\n\t\tmetrics: commitLogMetrics{\n\t\t\tqueued:      scope.Gauge(\"writes.queued\"),\n\t\t\tsuccess:     scope.Counter(\"writes.success\"),\n\t\t\terrors:      scope.Counter(\"writes.errors\"),\n\t\t\topenErrors:  scope.Counter(\"writes.open-errors\"),\n\t\t\tcloseErrors: scope.Counter(\"writes.close-errors\"),\n\t\t\tflushErrors: scope.Counter(\"writes.flush-errors\"),\n\t\t\tflushDone:   scope.Counter(\"writes.flush-done\"),\n\t\t},\n\t\tlog:                  iopts.Logger(),\n\t\tnewCommitLogWriterFn: newCommitLogWriter,\n\t\twrites:               make(chan commitLogWrite, opts.BacklogQueueSize()),\n\t\tcloseErr:             make(chan error),\n\t}\n\n\treturn commitLog\n}\n\nfunc (l *commitLog) Open() error {\n\t\/\/ Open the buffered commit log writer\n\tif err := l.openWriter(l.nowFn()); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Flush the info header to ensure we can write to disk\n\tif err := l.writer.Flush(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ NB(r): In the future we can introduce a commit log failure policy\n\t\/\/ similar to Cassandra's \"stop\", for example see:\n\t\/\/ https:\/\/github.com\/apache\/cassandra\/blob\/6dfc1e7eeba539774784dfd650d3e1de6785c938\/conf\/cassandra.yaml#L232\n\t\/\/ Right now it is a large amount of coordination to implement something similiar.\n\tl.commitLogFailFn = func(err error) {\n\t\tl.log.Fatalf(\"fatal commit log error: %v\", err)\n\t}\n\n\t\/\/ Asynchronously write\n\tgo l.write()\n\n\tif flushInterval := l.opts.FlushInterval(); flushInterval > 0 {\n\t\t\/\/ Continually flush the commit log at given interval if set\n\t\tgo l.flushEvery(flushInterval)\n\t}\n\n\treturn nil\n}\n\nfunc (l *commitLog) flushEvery(interval time.Duration) {\n\t\/\/ Periodically flush the underlying commit log writer to cover\n\t\/\/ the case when writes stall for a considerable time\n\tvar sleepForOverride time.Duration\n\n\tfor {\n\t\tl.metrics.queued.Update(int64(len(l.writes)))\n\n\t\tsleepFor := interval\n\n\t\tif sleepForOverride > 0 {\n\t\t\tsleepFor = sleepForOverride\n\t\t\tsleepForOverride = 0\n\t\t}\n\n\t\ttime.Sleep(sleepFor)\n\n\t\tl.flushMutex.RLock()\n\t\tlastFlushAt := l.lastFlushAt\n\t\tl.flushMutex.RUnlock()\n\n\t\tif sinceFlush := l.nowFn().Sub(lastFlushAt); sinceFlush < interval {\n\t\t\t\/\/ Flushed already recently, sleep until we would next consider flushing\n\t\t\tsleepForOverride = interval - sinceFlush\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Request a flush\n\t\tl.RLock()\n\t\tif l.closed {\n\t\t\tl.RUnlock()\n\t\t\treturn\n\t\t}\n\n\t\tl.writes <- commitLogWrite{valueType: flushValueType}\n\t\tl.RUnlock()\n\t}\n}\n\nfunc (l *commitLog) write() {\n\tfor write := range l.writes {\n\t\t\/\/ For writes requiring acks add to pending acks\n\t\tif write.completionFn != nil {\n\t\t\tl.pendingFlushFns = append(l.pendingFlushFns, write.completionFn)\n\t\t}\n\n\t\tif write.valueType == flushValueType {\n\t\t\tl.writer.Flush()\n\t\t\tcontinue\n\t\t}\n\n\t\tif now := l.nowFn(); !now.Before(l.writerExpireAt) {\n\t\t\tif err := l.openWriter(now); err != nil {\n\t\t\t\tl.metrics.errors.Inc(1)\n\t\t\t\tl.metrics.openErrors.Inc(1)\n\t\t\t\tl.log.Errorf(\"failed to open commit log: %v\", err)\n\n\t\t\t\tif l.commitLogFailFn != nil {\n\t\t\t\t\tl.commitLogFailFn(err)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\terr := l.writer.Write(\n\t\t\twrite.series, write.datapoint, write.unit, write.annotation)\n\t\twrite.series.ID.OnClose()\n\n\t\tif err != nil {\n\t\t\tl.metrics.errors.Inc(1)\n\t\t\tl.log.Errorf(\"failed to write to commit log: %v\", err)\n\n\t\t\tif l.commitLogFailFn != nil {\n\t\t\t\tl.commitLogFailFn(err)\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tl.metrics.success.Inc(1)\n\t}\n\n\tl.Lock()\n\tdefer l.Unlock()\n\n\twriter := l.writer\n\tl.writer = nil\n\tl.closeErr <- writer.Close()\n}\n\nfunc (l *commitLog) onFlush(err error) {\n\tl.flushMutex.Lock()\n\tl.lastFlushAt = l.nowFn()\n\tl.flushMutex.Unlock()\n\n\tif err != nil {\n\t\tl.metrics.errors.Inc(1)\n\t\tl.metrics.flushErrors.Inc(1)\n\t\tl.log.Errorf(\"failed to flush commit log: %v\", err)\n\n\t\tif l.commitLogFailFn != nil {\n\t\t\tl.commitLogFailFn(err)\n\t\t}\n\t}\n\n\t\/\/ onFlush only ever called by \"write()\" and \"openWriter\" or\n\t\/\/ before \"write()\" begins on \"Open()\" and there are no other\n\t\/\/ accessors of \"pendingFlushFns\" so it is safe to read and mutate\n\t\/\/ without a lock here\n\tif len(l.pendingFlushFns) == 0 {\n\t\tl.metrics.flushDone.Inc(1)\n\t\treturn\n\t}\n\n\tfor i := range l.pendingFlushFns {\n\t\tl.pendingFlushFns[i](err)\n\t}\n\n\tl.pendingFlushFns = l.pendingFlushFns[:0]\n\tl.metrics.flushDone.Inc(1)\n}\n\nfunc (l *commitLog) openWriter(now time.Time) error {\n\tif l.writer != nil {\n\t\tif err := l.writer.Close(); err != nil {\n\t\t\tl.metrics.closeErrors.Inc(1)\n\t\t\tl.log.Errorf(\"failed to close commit log: %v\", err)\n\n\t\t\t\/\/ If we failed to close then create a new commit log writer\n\t\t\tl.writer = nil\n\t\t}\n\t}\n\n\tif l.writer == nil {\n\t\tl.writer = l.newCommitLogWriterFn(l.onFlush, l.opts)\n\t}\n\n\tblockSize := l.opts.RetentionOptions().BlockSize()\n\tstart := now.Truncate(blockSize)\n\n\tif err := l.writer.Open(start, blockSize); err != nil {\n\t\treturn err\n\t}\n\n\tl.writerExpireAt = start.Add(blockSize)\n\n\treturn nil\n}\n\nfunc (l *commitLog) Write(\n\tctx context.Context,\n\tseries Series,\n\tdatapoint ts.Datapoint,\n\tunit xtime.Unit,\n\tannotation ts.Annotation,\n) error {\n\tl.RLock()\n\tif l.closed {\n\t\tl.RUnlock()\n\t\treturn errCommitLogClosed\n\t}\n\n\tvar (\n\t\twg     sync.WaitGroup\n\t\tresult error\n\t)\n\n\twg.Add(1)\n\n\tcompletion := func(err error) {\n\t\tresult = err\n\t\twg.Done()\n\t}\n\n\twrite := commitLogWrite{\n\t\tseries:       series,\n\t\tdatapoint:    datapoint,\n\t\tunit:         unit,\n\t\tannotation:   annotation,\n\t\tcompletionFn: completion,\n\t}\n\n\tenqueued := false\n\n\tselect {\n\tcase l.writes <- write:\n\t\tenqueued = true\n\tdefault:\n\t}\n\n\tl.RUnlock()\n\n\tif !enqueued {\n\t\treturn errCommitLogQueueFull\n\t}\n\n\twg.Wait()\n\n\treturn result\n}\n\nfunc (l *commitLog) WriteBehind(\n\tctx context.Context,\n\tseries Series,\n\tdatapoint ts.Datapoint,\n\tunit xtime.Unit,\n\tannotation ts.Annotation,\n) error {\n\tl.RLock()\n\tif l.closed {\n\t\tl.RUnlock()\n\t\treturn errCommitLogClosed\n\t}\n\n\twrite := commitLogWrite{\n\t\tseries:     series,\n\t\tdatapoint:  datapoint,\n\t\tunit:       unit,\n\t\tannotation: annotation,\n\t}\n\n\tenqueued := false\n\n\tselect {\n\tcase l.writes <- write:\n\t\tenqueued = true\n\tdefault:\n\t}\n\n\tl.RUnlock()\n\n\tif !enqueued {\n\t\treturn errCommitLogQueueFull\n\t}\n\n\treturn nil\n}\n\nfunc (l *commitLog) Iter() (Iterator, error) {\n\treturn NewIterator(l.opts)\n}\n\nfunc (l *commitLog) Close() error {\n\tl.Lock()\n\tif l.closed {\n\t\tl.Unlock()\n\t\treturn nil\n\t}\n\n\tl.closed = true\n\tclose(l.writes)\n\tl.Unlock()\n\n\t\/\/ Receive the result of closing the writer from asynchronous writer\n\treturn <-l.closeErr\n}\n<|endoftext|>"}
{"text":"<commit_before>package iter\n\n\/\/ First is useful when you only expect one (1) item in the iterator.\n\/\/\n\/\/ Note that it will return an error if there is more than one (1) item\n\/\/ in the iterator. (It checks for this.)\n\/\/\n\/\/ Example Usage\n\/\/\n\/\/\titerator := ...\n\/\/\t\n\/\/\terr := iter.First{Iterator: iterator}.Decode(v)\n\/\/\tif nil != err {\n\/\/\t\tswitch {\n\/\/\t\tcase iter.EmptyIteratorComplainer:\n\/\/\t\t\t\/\/@TODO\n\/\/\t\tdefault:\n\/\/\t\t\treturn err\n\/\/\t\t}\n\/\/\t}\ntype First struct {\n\tIterator Iterator\n}\n\nfunc (receiver First) Decode(v interface{}) error {\n\treturn receiver.decode(v)\n}\n\nfunc (receiver First) decode(v interface{}) (err error) {\n\n\titerator := receiver.Iterator\n\tif nil == iterator {\n\t\treturn errNilIterator\n\t}\n\tdefer func(i Iterator){\n\t\tif e := i.Close(); nil != e {\n\t\t\tif nil == err {\n\t\t\t\terr = e\n\t\t\t}\n\t\t}\n\t}(iterator)\n\n\tif ! iterator.Next() {\n\t\treturn errEmptyIterator\n\t}\n\tif err := iterator.Decode(v); nil != err {\n\t\treturn err\n\t}\n\tif iterator.Next() {\n\t\treturn errTooManyIterations\n\t}\n\tif err := iterator.Err(); nil != err {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>removed the \"too many iterations\" check.<commit_after>package iter\n\n\/\/ First is useful when you only expect one (1) item in the iterator.\n\/\/\n\/\/ Note that it will return an error if there is more than one (1) item\n\/\/ in the iterator. (It checks for this.)\n\/\/\n\/\/ Example Usage\n\/\/\n\/\/\titerator := ...\n\/\/\t\n\/\/\terr := iter.First{Iterator: iterator}.Decode(v)\n\/\/\tif nil != err {\n\/\/\t\tswitch {\n\/\/\t\tcase iter.EmptyIteratorComplainer:\n\/\/\t\t\t\/\/@TODO\n\/\/\t\tdefault:\n\/\/\t\t\treturn err\n\/\/\t\t}\n\/\/\t}\ntype First struct {\n\tIterator Iterator\n}\n\nfunc (receiver First) Decode(v interface{}) error {\n\treturn receiver.decode(v)\n}\n\nfunc (receiver First) decode(v interface{}) (err error) {\n\n\titerator := receiver.Iterator\n\tif nil == iterator {\n\t\treturn errNilIterator\n\t}\n\tdefer func(i Iterator){\n\t\tif e := i.Close(); nil != e {\n\t\t\tif nil == err {\n\t\t\t\terr = e\n\t\t\t}\n\t\t}\n\t}(iterator)\n\n\tif ! iterator.Next() {\n\t\treturn errEmptyIterator\n\t}\n\tif err := iterator.Decode(v); nil != err {\n\t\treturn err\n\t}\n\tif err := iterator.Err(); nil != err {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/flynn\/go-discover\/discover\"\n\t\"github.com\/flynn\/lorne\/types\"\n\t\"github.com\/flynn\/rpcplus\"\n\t\"github.com\/flynn\/sampi\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n)\n\nvar state = NewState()\nvar Docker *docker.Client\n\nfunc main() {\n\texternalAddr := flag.String(\"external\", \"\", \"external IP of host\")\n\tconfigFile := flag.String(\"config\", \"\", \"configuration file\")\n\thostID := flag.String(\"id\", randomID(), \"host id\")\n\tflag.Parse()\n\n\tgo server()\n\tgo allocatePorts()\n\n\tdisc, err := discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := disc.Register(\"flynn-lorne.\"+*hostID, \"1113\", nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tservices, err := disc.Services(\"flynn-sampi\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tschedulers := services.Online()\n\tif len(schedulers) == 0 {\n\t\tlog.Fatal(\"No sampi instances found\")\n\t}\n\n\tscheduler, err := rpcplus.DialHTTP(\"tcp\", schedulers[0].Addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Connected to scheduler\")\n\n\tDocker, err = docker.NewClient(\"http:\/\/localhost:4243\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgo streamEvents(Docker)\n\tgo syncScheduler(scheduler)\n\n\tvar host *sampi.Host\n\tif *configFile != \"\" {\n\t\thost, err = parseConfig(*configFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\thost = &sampi.Host{Resources: make(map[string]sampi.ResourceValue)}\n\t}\n\tif _, ok := host.Resources[\"memory\"]; !ok {\n\t\thost.Resources[\"memory\"] = sampi.ResourceValue{Value: 1024}\n\t}\n\thost.ID = *hostID\n\n\tjobs := make(chan *sampi.Job)\n\tscheduler.StreamGo(\"Scheduler.RegisterHost\", host, jobs)\n\tlog.Print(\"Host registered\")\n\tfor job := range jobs {\n\t\tlog.Printf(\"%#v\", job.Config)\n\t\tvar hostConfig *docker.HostConfig\n\t\tif job.TCPPorts > 0 {\n\t\t\tport := strconv.Itoa(<-portAllocator)\n\t\t\tjob.Config.Env = append(job.Config.Env, \"PORT=\"+port)\n\t\t\tjob.Config.ExposedPorts = map[string]struct{}{port + \"\/tcp\": struct{}{}}\n\t\t\tjob.Config.Name = \"flynn-\" + job.ID\n\t\t\thostConfig = &docker.HostConfig{\n\t\t\t\tPortBindings:    map[string][]docker.PortBinding{port + \"\/tcp\": {{HostPort: port}}},\n\t\t\t\tPublishAllPorts: true,\n\t\t\t}\n\t\t}\n\t\tif *externalAddr != \"\" {\n\t\t\tjob.Config.Env = append(job.Config.Env, \"EXTERNAL_IP=\"+*externalAddr, \"SD_HOST=\"+*externalAddr, \"DISCOVERD=\"+*externalAddr+\":1111\")\n\t\t}\n\t\tstate.AddJob(job)\n\t\tcontainer, err := Docker.CreateContainer(job.Config)\n\t\tif err == docker.ErrNoSuchImage {\n\t\t\terr = Docker.PullImage(docker.PullImageOptions{Repository: job.Config.Image}, os.Stdout)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tcontainer, err = Docker.CreateContainer(job.Config)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tstate.SetContainerID(job.ID, container.ID)\n\t\tstate.WaitAttach(job.ID)\n\t\tif err := Docker.StartContainer(container.ID, hostConfig); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tstate.SetStatusRunning(job.ID)\n\t}\n}\n\nfunc syncScheduler(client *rpcplus.Client) {\n\tevents := make(chan lorne.Event)\n\tstate.AddListener(\"all\", events)\n\tfor event := range events {\n\t\tif event.Event != \"stop\" {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"remove job\", event.JobID)\n\t\tif err := client.Call(\"Scheduler.RemoveJobs\", []string{event.JobID}, &struct{}{}); err != nil {\n\t\t\tlog.Println(\"remove job\", event.JobID, \"error:\", err)\n\t\t\t\/\/ TODO: try to reconnect?\n\t\t}\n\t}\n}\n\nfunc streamEvents(client *docker.Client) {\n\tstream, err := client.Events()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor event := range stream.Events {\n\t\tlog.Printf(\"%#v\", event)\n\t\tif event.Status != \"die\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontainer, err := client.InspectContainer(event.ID)\n\t\tif err != nil {\n\t\t\tlog.Println(\"inspect container\", event.ID, \"error:\", err)\n\t\t\t\/\/ TODO: set job status anyway?\n\t\t\tcontinue\n\t\t}\n\t\tstate.SetStatusDone(event.ID, container.State.ExitCode)\n\t}\n\tlog.Println(\"events done\", stream.Error)\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\nvar portAllocator = make(chan int)\n\n\/\/ TODO: fix this, horribly broken\nconst startPort = 55000\nconst endPort = 65535\n\nfunc allocatePorts() {\n\tfor i := startPort; i < endPort; i++ {\n\t\tportAllocator <- i\n\t}\n\t\/\/ TODO: handle wrap-around\n}\n<commit_msg>host: Use sampi client<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/flynn\/go-discover\/discover\"\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)\n\nvar state = NewState()\nvar Docker *docker.Client\n\nfunc main() {\n\texternalAddr := flag.String(\"external\", \"\", \"external IP of host\")\n\tconfigFile := flag.String(\"config\", \"\", \"configuration file\")\n\thostID := flag.String(\"id\", randomID(), \"host id\")\n\tflag.Parse()\n\n\tgo server()\n\tgo allocatePorts()\n\n\tdisc, err := discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := disc.Register(\"flynn-lorne.\"+*hostID, \"1113\", nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tscheduler, err := sampic.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Connected to scheduler\")\n\n\tDocker, err = docker.NewClient(\"http:\/\/localhost:4243\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgo streamEvents(Docker)\n\tgo syncScheduler(scheduler)\n\n\tvar host *sampi.Host\n\tif *configFile != \"\" {\n\t\thost, err = parseConfig(*configFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\thost = &sampi.Host{Resources: make(map[string]sampi.ResourceValue)}\n\t}\n\tif _, ok := host.Resources[\"memory\"]; !ok {\n\t\thost.Resources[\"memory\"] = sampi.ResourceValue{Value: 1024}\n\t}\n\thost.ID = *hostID\n\n\tjobs := make(chan *sampi.Job)\n\tscheduler.RegisterHost(host, jobs)\n\tlog.Print(\"Host registered\")\n\tfor job := range jobs {\n\t\tlog.Printf(\"%#v\", job.Config)\n\t\tvar hostConfig *docker.HostConfig\n\t\tif job.TCPPorts > 0 {\n\t\t\tport := strconv.Itoa(<-portAllocator)\n\t\t\tjob.Config.Env = append(job.Config.Env, \"PORT=\"+port)\n\t\t\tjob.Config.ExposedPorts = map[string]struct{}{port + \"\/tcp\": struct{}{}}\n\t\t\tjob.Config.Name = \"flynn-\" + job.ID\n\t\t\thostConfig = &docker.HostConfig{\n\t\t\t\tPortBindings:    map[string][]docker.PortBinding{port + \"\/tcp\": {{HostPort: port}}},\n\t\t\t\tPublishAllPorts: true,\n\t\t\t}\n\t\t}\n\t\tif *externalAddr != \"\" {\n\t\t\tjob.Config.Env = append(job.Config.Env, \"EXTERNAL_IP=\"+*externalAddr, \"SD_HOST=\"+*externalAddr, \"DISCOVERD=\"+*externalAddr+\":1111\")\n\t\t}\n\t\tstate.AddJob(job)\n\t\tcontainer, err := Docker.CreateContainer(job.Config)\n\t\tif err == docker.ErrNoSuchImage {\n\t\t\terr = Docker.PullImage(docker.PullImageOptions{Repository: job.Config.Image}, os.Stdout)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tcontainer, err = Docker.CreateContainer(job.Config)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tstate.SetContainerID(job.ID, container.ID)\n\t\tstate.WaitAttach(job.ID)\n\t\tif err := Docker.StartContainer(container.ID, hostConfig); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tstate.SetStatusRunning(job.ID)\n\t}\n}\n\nfunc syncScheduler(scheduler *sampic.Client) {\n\tevents := make(chan lorne.Event)\n\tstate.AddListener(\"all\", events)\n\tfor event := range events {\n\t\tif event.Event != \"stop\" {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"remove job\", event.JobID)\n\t\tif err := scheduler.RemoveJobs([]string{event.JobID}); err != nil {\n\t\t\tlog.Println(\"remove job\", event.JobID, \"error:\", err)\n\t\t\t\/\/ TODO: try to reconnect?\n\t\t}\n\t}\n}\n\nfunc streamEvents(client *docker.Client) {\n\tstream, err := client.Events()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor event := range stream.Events {\n\t\tlog.Printf(\"%#v\", event)\n\t\tif event.Status != \"die\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontainer, err := client.InspectContainer(event.ID)\n\t\tif err != nil {\n\t\t\tlog.Println(\"inspect container\", event.ID, \"error:\", err)\n\t\t\t\/\/ TODO: set job status anyway?\n\t\t\tcontinue\n\t\t}\n\t\tstate.SetStatusDone(event.ID, container.State.ExitCode)\n\t}\n\tlog.Println(\"events done\", stream.Error)\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\nvar portAllocator = make(chan int)\n\n\/\/ TODO: fix this, horribly broken\nconst startPort = 55000\nconst endPort = 65535\n\nfunc allocatePorts() {\n\tfor i := startPort; i < endPort; i++ {\n\t\tportAllocator <- i\n\t}\n\t\/\/ TODO: handle wrap-around\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 flags provides an extensive command line option parser.\nThe flags package is similar in functionality to the go built-in flag package\nbut provides more options and uses reflection to provide a convenient and\nsuccinct way of specifying command line options.\n\n\nSupported features\n\nThe following features are supported in go-flags:\n\n    Options with short names (-v)\n    Options with long names (--verbose)\n    Options with and without arguments (bool v.s. other type)\n    Options with optional arguments and default values\n    Option default values from ENVIRONMENT_VARIABLES, including slice and map values\n    Multiple option groups each containing a set of options\n    Generate and print well-formatted help message\n    Passing remaining command line arguments after -- (optional)\n    Ignoring unknown command line options (optional)\n    Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n    Supports multiple short options -aux\n    Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n    Supports same option multiple times (can store in slice or last option counts)\n    Supports maps\n    Supports function callbacks\n    Supports namespaces for (nested) option groups\n\nAdditional features specific to Windows:\n    Options with short names (\/v)\n    Options with long names (\/verbose)\n    Windows-style options with arguments use a colon as the delimiter\n    Modify generated help message with Windows-style \/ options\n    Windows style options can be disabled at build time using the \"forceposix\"\n    build tag\n\n\nBasic usage\n\nThe flags package uses structs, reflection and struct field tags\nto allow users to specify command line options. This results in very simple\nand concise specification of your application options. For example:\n\n    type Options struct {\n        Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n    }\n\nThis specifies one option with a short name -v and a long name --verbose.\nWhen either -v or --verbose is found on the command line, a 'true' value\nwill be appended to the Verbose field. e.g. when specifying -vvv, the\nresulting value of Verbose will be {[true, true, true]}.\n\nSlice options work exactly the same as primitive type options, except that\nwhenever the option is encountered, a value is appended to the slice.\n\nMap options from string to primitive type are also supported. On the command\nline, you specify the value for such an option as key:value. For example\n\n    type Options struct {\n        AuthorInfo string[string] `short:\"a\"`\n    }\n\nThen, the AuthorInfo map can be filled with something like\n-a name:Jesse -a \"surname:van den Kieboom\".\n\nFinally, for full control over the conversion between command line argument\nvalues and options, user defined types can choose to implement the Marshaler\nand Unmarshaler interfaces.\n\n\nAvailable field tags\n\nThe following is a list of tags for struct fields supported by go-flags:\n\n    short:            the short name of the option (single character)\n    long:             the long name of the option\n    required:         if non empty, makes the option required to appear on the command\n                      line. If a required option is not present, the parser will\n                      return ErrRequired (optional)\n    description:      the description of the option (optional)\n    long-description: the long description of the option. Currently only\n                      displayed in generated man pages (optional)\n    no-flag:          if non-empty, this field is ignored as an option (optional)\n\n    optional:       if non-empty, makes the argument of the option optional. When an\n                    argument is optional it can only be specified using\n                    --option=argument (optional)\n    optional-value: the value of an optional option when the option occurs\n                    without an argument. This tag can be specified multiple\n                    times in the case of maps or slices (optional)\n    default:        the default value of an option. This tag can be specified\n                    multiple times in the case of slices or maps (optional)\n    default-mask:   when specified, this value will be displayed in the help\n                    instead of the actual default value. This is useful\n                    mostly for hiding otherwise sensitive information from\n                    showing up in the help. If default-mask takes the special\n                    value \"-\", then no default value will be shown at all\n                    (optional)\n    env:            the default value of the option is overridden from the\n                    specified environment variable, if one has been defined.\n                    (optional)\n    env-delim:      the 'env' default value from environment is split into\n                    multiple values with the given delimiter string, use with\n                    slices and maps (optional)\n    value-name:     the name of the argument value (to be shown in the help)\n                    (optional)\n    choice:         limits the values for an option to a set of values.\n                    This tag can be specified multiple times (optional)\n    hidden:         if non-empty, the option is not visible in the help or man page.\n\n    base: a base (radix) used to convert strings to integer values, the\n          default base is 10 (i.e. decimal) (optional)\n\n    ini-name:       the explicit ini option name (optional)\n    no-ini:         if non-empty this field is ignored as an ini option\n                    (optional)\n\n    group:                when specified on a struct field, makes the struct\n                          field a separate group with the given name (optional)\n    namespace:            when specified on a group struct field, the namespace\n                          gets prepended to every option's long name and\n                          subgroup's namespace of this group, separated by\n                          the parser's namespace delimiter (optional)\n    env-namespace:        when specified on a group struct field, the env-namespace\n                          gets prepended to every option's env key and\n                          subgroup's env-namespace of this group, separated by\n                          the parser's env-namespace delimiter (optional)\n    command:              when specified on a struct field, makes the struct\n                          field a (sub)command with the given name (optional)\n    subcommands-optional: when specified on a command struct field, makes\n                          any subcommands of that command optional (optional)\n    alias:                when specified on a command struct field, adds the\n                          specified name as an alias for the command. Can be\n                          be specified multiple times to add more than one\n                          alias (optional)\n    positional-args:      when specified on a field with a struct type,\n                          uses the fields of that struct to parse remaining\n                          positional command line arguments into (in order\n                          of the fields). If a field has a slice type,\n                          then all remaining arguments will be added to it.\n                          Positional arguments are optional by default,\n                          unless the \"required\" tag is specified together\n                          with the \"positional-args\" tag. The \"required\" tag\n                          can also be set on the individual rest argument\n                          fields, to require only the first N positional\n                          arguments. If the \"required\" tag is set on the\n                          rest arguments slice, then its value determines\n                          the minimum amount of rest arguments that needs to\n                          be provided (e.g. `required:\"2\"`) (optional)\n    positional-arg-name:  used on a field in a positional argument struct; name\n                          of the positional argument placeholder to be shown in\n                          the help (optional)\n\nEither the `short:` tag or the `long:` must be specified to make the field eligible as an\noption.\n\n\nOption groups\n\nOption groups are a simple way to semantically separate your options. All\noptions in a particular group are shown together in the help under the name\nof the group. Namespaces can be used to specify option long names more\nprecisely and emphasize the options affiliation to their group.\n\nThere are currently three ways to specify option groups.\n\n    1. Use NewNamedParser specifying the various option groups.\n    2. Use AddGroup to add a group to an existing parser.\n    3. Add a struct field to the top-level options annotated with the\n       group:\"group-name\" tag.\n\n\n\nCommands\n\nThe flags package also has basic support for commands. Commands are often\nused in monolithic applications that support various commands or actions.\nTake git for example, all of the add, commit, checkout, etc. are called\ncommands. Using commands you can easily separate multiple functions of your\napplication.\n\nThere are currently two ways to specify a command.\n\n    1. Use AddCommand on an existing parser.\n    2. Add a struct field to your options struct annotated with the\n       command:\"command-name\" tag.\n\nThe most common, idiomatic way to implement commands is to define a global\nparser instance and implement each command in a separate file. These\ncommand files should define a go init function which calls AddCommand on\nthe global parser.\n\nWhen parsing ends and there is an active command and that command implements\nthe Commander interface, then its Execute method will be run with the\nremaining command line arguments.\n\nCommand structs can have options which become valid to parse after the\ncommand has been specified on the command line, in addition to the options\nof all the parent commands. I.e. considering a -v flag on the parser and an\nadd command, the following are equivalent:\n\n    .\/app -v add\n    .\/app add -v\n\nHowever, if the -v flag is defined on the add command, then the first of\nthe two examples above would fail since the -v flag is not defined before\nthe add command.\n\n\nCompletion\n\ngo-flags has builtin support to provide bash completion of flags, commands\nand argument values. To use completion, the binary which uses go-flags\ncan be invoked in a special environment to list completion of the current\ncommand line argument. It should be noted that this `executes` your application,\nand it is up to the user to make sure there are no negative side effects (for\nexample from init functions).\n\nSetting the environment variable `GO_FLAGS_COMPLETION=1` enables completion\nby replacing the argument parsing routine with the completion routine which\noutputs completions for the passed arguments. The basic invocation to\ncomplete a set of arguments is therefore:\n\n    GO_FLAGS_COMPLETION=1 .\/completion-example arg1 arg2 arg3\n\nwhere `completion-example` is the binary, `arg1` and `arg2` are\nthe current arguments, and `arg3` (the last argument) is the argument\nto be completed. If the GO_FLAGS_COMPLETION is set to \"verbose\", then\ndescriptions of possible completion items will also be shown, if there\nare more than 1 completion items.\n\nTo use this with bash completion, a simple file can be written which\ncalls the binary which supports go-flags completion:\n\n    _completion_example() {\n        # All arguments except the first one\n        args=(\"${COMP_WORDS[@]:1:$COMP_CWORD}\")\n\n        # Only split on newlines\n        local IFS=$'\\n'\n\n        # Call completion (note that the first element of COMP_WORDS is\n        # the executable itself)\n        COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} \"${args[@]}\"))\n        return 0\n    }\n\n    complete -F _completion_example completion-example\n\nCompletion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.\n\nCustomized completion for argument values is supported by implementing\nthe flags.Completer interface for the argument value type. An example\nof a type which does so is the flags.Filename type, an alias of string\nallowing simple filename completion. A slice or array argument value\nwhose element type implements flags.Completer will also be completed.\n*\/\npackage flags\n<commit_msg>Explain how to use choices<commit_after>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 flags provides an extensive command line option parser.\nThe flags package is similar in functionality to the go built-in flag package\nbut provides more options and uses reflection to provide a convenient and\nsuccinct way of specifying command line options.\n\n\nSupported features\n\nThe following features are supported in go-flags:\n\n    Options with short names (-v)\n    Options with long names (--verbose)\n    Options with and without arguments (bool v.s. other type)\n    Options with optional arguments and default values\n    Option default values from ENVIRONMENT_VARIABLES, including slice and map values\n    Multiple option groups each containing a set of options\n    Generate and print well-formatted help message\n    Passing remaining command line arguments after -- (optional)\n    Ignoring unknown command line options (optional)\n    Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n    Supports multiple short options -aux\n    Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n    Supports same option multiple times (can store in slice or last option counts)\n    Supports maps\n    Supports function callbacks\n    Supports namespaces for (nested) option groups\n\nAdditional features specific to Windows:\n    Options with short names (\/v)\n    Options with long names (\/verbose)\n    Windows-style options with arguments use a colon as the delimiter\n    Modify generated help message with Windows-style \/ options\n    Windows style options can be disabled at build time using the \"forceposix\"\n    build tag\n\n\nBasic usage\n\nThe flags package uses structs, reflection and struct field tags\nto allow users to specify command line options. This results in very simple\nand concise specification of your application options. For example:\n\n    type Options struct {\n        Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n    }\n\nThis specifies one option with a short name -v and a long name --verbose.\nWhen either -v or --verbose is found on the command line, a 'true' value\nwill be appended to the Verbose field. e.g. when specifying -vvv, the\nresulting value of Verbose will be {[true, true, true]}.\n\nSlice options work exactly the same as primitive type options, except that\nwhenever the option is encountered, a value is appended to the slice.\n\nMap options from string to primitive type are also supported. On the command\nline, you specify the value for such an option as key:value. For example\n\n    type Options struct {\n        AuthorInfo string[string] `short:\"a\"`\n    }\n\nThen, the AuthorInfo map can be filled with something like\n-a name:Jesse -a \"surname:van den Kieboom\".\n\nFinally, for full control over the conversion between command line argument\nvalues and options, user defined types can choose to implement the Marshaler\nand Unmarshaler interfaces.\n\n\nAvailable field tags\n\nThe following is a list of tags for struct fields supported by go-flags:\n\n    short:            the short name of the option (single character)\n    long:             the long name of the option\n    required:         if non empty, makes the option required to appear on the command\n                      line. If a required option is not present, the parser will\n                      return ErrRequired (optional)\n    description:      the description of the option (optional)\n    long-description: the long description of the option. Currently only\n                      displayed in generated man pages (optional)\n    no-flag:          if non-empty, this field is ignored as an option (optional)\n\n    optional:       if non-empty, makes the argument of the option optional. When an\n                    argument is optional it can only be specified using\n                    --option=argument (optional)\n    optional-value: the value of an optional option when the option occurs\n                    without an argument. This tag can be specified multiple\n                    times in the case of maps or slices (optional)\n    default:        the default value of an option. This tag can be specified\n                    multiple times in the case of slices or maps (optional)\n    default-mask:   when specified, this value will be displayed in the help\n                    instead of the actual default value. This is useful\n                    mostly for hiding otherwise sensitive information from\n                    showing up in the help. If default-mask takes the special\n                    value \"-\", then no default value will be shown at all\n                    (optional)\n    env:            the default value of the option is overridden from the\n                    specified environment variable, if one has been defined.\n                    (optional)\n    env-delim:      the 'env' default value from environment is split into\n                    multiple values with the given delimiter string, use with\n                    slices and maps (optional)\n    value-name:     the name of the argument value (to be shown in the help)\n                    (optional)\n    choice:         limits the values for an option to a set of values.\n                    Repeat this tag once for each allowable value.\n                    e.g. `long:\"animal\" choice:\"cat\" choice:\"dog\"`\n    hidden:         if non-empty, the option is not visible in the help or man page.\n\n    base: a base (radix) used to convert strings to integer values, the\n          default base is 10 (i.e. decimal) (optional)\n\n    ini-name:       the explicit ini option name (optional)\n    no-ini:         if non-empty this field is ignored as an ini option\n                    (optional)\n\n    group:                when specified on a struct field, makes the struct\n                          field a separate group with the given name (optional)\n    namespace:            when specified on a group struct field, the namespace\n                          gets prepended to every option's long name and\n                          subgroup's namespace of this group, separated by\n                          the parser's namespace delimiter (optional)\n    env-namespace:        when specified on a group struct field, the env-namespace\n                          gets prepended to every option's env key and\n                          subgroup's env-namespace of this group, separated by\n                          the parser's env-namespace delimiter (optional)\n    command:              when specified on a struct field, makes the struct\n                          field a (sub)command with the given name (optional)\n    subcommands-optional: when specified on a command struct field, makes\n                          any subcommands of that command optional (optional)\n    alias:                when specified on a command struct field, adds the\n                          specified name as an alias for the command. Can be\n                          be specified multiple times to add more than one\n                          alias (optional)\n    positional-args:      when specified on a field with a struct type,\n                          uses the fields of that struct to parse remaining\n                          positional command line arguments into (in order\n                          of the fields). If a field has a slice type,\n                          then all remaining arguments will be added to it.\n                          Positional arguments are optional by default,\n                          unless the \"required\" tag is specified together\n                          with the \"positional-args\" tag. The \"required\" tag\n                          can also be set on the individual rest argument\n                          fields, to require only the first N positional\n                          arguments. If the \"required\" tag is set on the\n                          rest arguments slice, then its value determines\n                          the minimum amount of rest arguments that needs to\n                          be provided (e.g. `required:\"2\"`) (optional)\n    positional-arg-name:  used on a field in a positional argument struct; name\n                          of the positional argument placeholder to be shown in\n                          the help (optional)\n\nEither the `short:` tag or the `long:` must be specified to make the field eligible as an\noption.\n\n\nOption groups\n\nOption groups are a simple way to semantically separate your options. All\noptions in a particular group are shown together in the help under the name\nof the group. Namespaces can be used to specify option long names more\nprecisely and emphasize the options affiliation to their group.\n\nThere are currently three ways to specify option groups.\n\n    1. Use NewNamedParser specifying the various option groups.\n    2. Use AddGroup to add a group to an existing parser.\n    3. Add a struct field to the top-level options annotated with the\n       group:\"group-name\" tag.\n\n\n\nCommands\n\nThe flags package also has basic support for commands. Commands are often\nused in monolithic applications that support various commands or actions.\nTake git for example, all of the add, commit, checkout, etc. are called\ncommands. Using commands you can easily separate multiple functions of your\napplication.\n\nThere are currently two ways to specify a command.\n\n    1. Use AddCommand on an existing parser.\n    2. Add a struct field to your options struct annotated with the\n       command:\"command-name\" tag.\n\nThe most common, idiomatic way to implement commands is to define a global\nparser instance and implement each command in a separate file. These\ncommand files should define a go init function which calls AddCommand on\nthe global parser.\n\nWhen parsing ends and there is an active command and that command implements\nthe Commander interface, then its Execute method will be run with the\nremaining command line arguments.\n\nCommand structs can have options which become valid to parse after the\ncommand has been specified on the command line, in addition to the options\nof all the parent commands. I.e. considering a -v flag on the parser and an\nadd command, the following are equivalent:\n\n    .\/app -v add\n    .\/app add -v\n\nHowever, if the -v flag is defined on the add command, then the first of\nthe two examples above would fail since the -v flag is not defined before\nthe add command.\n\n\nCompletion\n\ngo-flags has builtin support to provide bash completion of flags, commands\nand argument values. To use completion, the binary which uses go-flags\ncan be invoked in a special environment to list completion of the current\ncommand line argument. It should be noted that this `executes` your application,\nand it is up to the user to make sure there are no negative side effects (for\nexample from init functions).\n\nSetting the environment variable `GO_FLAGS_COMPLETION=1` enables completion\nby replacing the argument parsing routine with the completion routine which\noutputs completions for the passed arguments. The basic invocation to\ncomplete a set of arguments is therefore:\n\n    GO_FLAGS_COMPLETION=1 .\/completion-example arg1 arg2 arg3\n\nwhere `completion-example` is the binary, `arg1` and `arg2` are\nthe current arguments, and `arg3` (the last argument) is the argument\nto be completed. If the GO_FLAGS_COMPLETION is set to \"verbose\", then\ndescriptions of possible completion items will also be shown, if there\nare more than 1 completion items.\n\nTo use this with bash completion, a simple file can be written which\ncalls the binary which supports go-flags completion:\n\n    _completion_example() {\n        # All arguments except the first one\n        args=(\"${COMP_WORDS[@]:1:$COMP_CWORD}\")\n\n        # Only split on newlines\n        local IFS=$'\\n'\n\n        # Call completion (note that the first element of COMP_WORDS is\n        # the executable itself)\n        COMPREPLY=($(GO_FLAGS_COMPLETION=1 ${COMP_WORDS[0]} \"${args[@]}\"))\n        return 0\n    }\n\n    complete -F _completion_example completion-example\n\nCompletion requires the parser option PassDoubleDash and is therefore enforced if the environment variable GO_FLAGS_COMPLETION is set.\n\nCustomized completion for argument values is supported by implementing\nthe flags.Completer interface for the argument value type. An example\nof a type which does so is the flags.Filename type, an alias of string\nallowing simple filename completion. A slice or array argument value\nwhose element type implements flags.Completer will also be completed.\n*\/\npackage flags\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/codegangsta\/cli\"\n\nvar (\n\tamqpURL            string\n\tamqpExchange       string\n\tamqpCARoot         string\n\tcustomDNSResolvers string\n\thost               string\n\toriginRegexp       string\n\tport               int\n\tdevelopment        bool\n\thostFlag           = cli.StringFlag{\n\t\tName:        \"bind, b\",\n\t\tValue:       \"\",\n\t\tUsage:       \"host to bind the ws server\",\n\t\tEnvVar:      \"WS_BIND_HOST\",\n\t\tDestination: &host,\n\t}\n\tportFlag = cli.IntFlag{\n\t\tName:        \"port, p\",\n\t\tValue:       9090,\n\t\tUsage:       \"port to listen on\",\n\t\tEnvVar:      \"WS_BIND_PORT\",\n\t\tDestination: &port,\n\t}\n\toriginRegexpFlag = cli.StringFlag{\n\t\tName:        \"allow-origin-regexp, r\",\n\t\tValue:       \"\",\n\t\tUsage:       \"a regexp string used to validate request origin header\",\n\t\tEnvVar:      \"WS_ALLOW_ORIGIN_REGEXP\",\n\t\tDestination: &originRegexp,\n\t}\n\tamqpURLFlag = cli.StringFlag{\n\t\tName:        \"amqp-url, u\",\n\t\tUsage:       \"full amqp URL\",\n\t\tEnvVar:      \"AMQP_URL\",\n\t\tDestination: &amqpURL,\n\t}\n\tamqpExchangeFlag = cli.StringFlag{\n\t\tName:        \"amqp-exchange, x\",\n\t\tValue:       \"\",\n\t\tUsage:       \"topic exchange name\",\n\t\tEnvVar:      \"AMQP_EXCHANGE\",\n\t\tDestination: &amqpExchange,\n\t}\n\tamqpCARootFlag = cli.StringFlag{\n\t\tName:        \"amqp-ca-root, c\",\n\t\tValue:       \"\",\n\t\tUsage:       \"AMQP CA root, if applicable\",\n\t\tEnvVar:      \"AMQP_CA_CERT\",\n\t\tDestination: &amqpCARoot,\n\t}\n\tcustomDNSResolversFlag = cli.StringFlag{\n\t\tName:        \"custom-dns-resolvers, d\",\n\t\tValue:       \"\",\n\t\tUsage:       \"custom DNS resolvers, if applicable\",\n\t\tEnvVar:      \"CUSTOM_DNS_RESOLVERS\",\n\t\tDestination: &customDNSResolvers,\n\t}\n\tdevelopmentFlag = cli.BoolFlag{\n\t\tName:        \"development, d\",\n\t\tUsage:       \"run in development mode, without CORS and TLS\",\n\t\tDestination: &development,\n\t}\n)\n<commit_msg>Fix flag override<commit_after>package main\n\nimport \"github.com\/codegangsta\/cli\"\n\nvar (\n\tamqpURL            string\n\tamqpExchange       string\n\tamqpCARoot         string\n\tcustomDNSResolvers string\n\thost               string\n\toriginRegexp       string\n\tport               int\n\tdevelopment        bool\n\thostFlag           = cli.StringFlag{\n\t\tName:        \"bind, b\",\n\t\tValue:       \"\",\n\t\tUsage:       \"host to bind the ws server\",\n\t\tEnvVar:      \"WS_BIND_HOST\",\n\t\tDestination: &host,\n\t}\n\tportFlag = cli.IntFlag{\n\t\tName:        \"port, p\",\n\t\tValue:       9090,\n\t\tUsage:       \"port to listen on\",\n\t\tEnvVar:      \"WS_BIND_PORT\",\n\t\tDestination: &port,\n\t}\n\toriginRegexpFlag = cli.StringFlag{\n\t\tName:        \"allow-origin-regexp, r\",\n\t\tValue:       \"\",\n\t\tUsage:       \"a regexp string used to validate request origin header\",\n\t\tEnvVar:      \"WS_ALLOW_ORIGIN_REGEXP\",\n\t\tDestination: &originRegexp,\n\t}\n\tamqpURLFlag = cli.StringFlag{\n\t\tName:        \"amqp-url, u\",\n\t\tUsage:       \"full amqp URL\",\n\t\tEnvVar:      \"AMQP_URL\",\n\t\tDestination: &amqpURL,\n\t}\n\tamqpExchangeFlag = cli.StringFlag{\n\t\tName:        \"amqp-exchange, x\",\n\t\tValue:       \"\",\n\t\tUsage:       \"topic exchange name\",\n\t\tEnvVar:      \"AMQP_EXCHANGE\",\n\t\tDestination: &amqpExchange,\n\t}\n\tamqpCARootFlag = cli.StringFlag{\n\t\tName:        \"amqp-ca-root, c\",\n\t\tValue:       \"\",\n\t\tUsage:       \"AMQP CA root, if applicable\",\n\t\tEnvVar:      \"AMQP_CA_CERT\",\n\t\tDestination: &amqpCARoot,\n\t}\n\tcustomDNSResolversFlag = cli.StringFlag{\n\t\tName:        \"custom-dns-resolvers\",\n\t\tValue:       \"\",\n\t\tUsage:       \"custom DNS resolvers, if applicable\",\n\t\tEnvVar:      \"CUSTOM_DNS_RESOLVERS\",\n\t\tDestination: &customDNSResolvers,\n\t}\n\tdevelopmentFlag = cli.BoolFlag{\n\t\tName:        \"development, d\",\n\t\tUsage:       \"run in development mode, without CORS and TLS\",\n\t\tDestination: &development,\n\t}\n)\n<|endoftext|>"}
{"text":"<commit_before>package box\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ TODO(ttacon): reconcile this with Folder for one common struct?\ntype File struct {\n\tID                string          `json:\"id,omitempty\"`\n\tFolderUploadEmail *AccessEmail    `json:\"folder_upload_email,omitempty\"`\n\tParent            *Item           `json:\"parent,omitempty\"`\n\tItemStatus        string          `json:\"item_status\"`\n\tItemCollection    *ItemCollection `json:\"item_collection\"`\n\tType              string          `json:\"type\"` \/\/ TODO(ttacon): enum\n\tDescription       string          `json:\"description\"`\n\tSize              int             `json:\"size\"`\n\tCreateBy          *Item           `json:\"created_by\"`\n\tModifiedBy        *Item           `json:\"modified_by\"`\n\tTrashedAt         *string         `json:\"trashed_at\"`          \/\/ TODO(ttacon): change to time.Time\n\tContentModifiedAt *string         `json:\"content_modified_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPurgedAt          *string         `json:\"purged_at\"`           \/\/ TODO(ttacon): change to time.Time, this field isn't documented but I keep getting it back...\n\tSharedLinkg       *string         `json:\"shared_link\"`\n\tSequenceId        string          `json:\"sequence_id\"`\n\tETag              *string         `json:\"etag\"`\n\tName              string          `json:\"name\"`\n\tCreatedAt         *string         `json:\"created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tOwnedBy           *Item           `json:\"owned_by\"`\n\tModifiedAt        *string         `json:\"modified_at\"`        \/\/ TODO(ttacon): change to time.Time\n\tContentCreatedAt  *string         `json:\"content_created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPathCollection    *PathCollection `json:\"path_collection\"`    \/\/ TODO(ttacon): make sure this is the correct kind of struct(ure)\n\tSharedLink        *Link           `json:\"shared_link\"`\n\n\tSHA1 string `json:\"sha1\"`\n}\n\ntype FileCollection struct {\n\tTotalCount int     `json:\"total_count\"`\n\tEntries    []*File `json:\"entries\"`\n}\n\n\/\/ Documentation: https:\/\/developer.box.com\/docs\/#files-get\nfunc (c *Client) GetFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation https:\/\/developer.box.com\/docs\/#files-upload-a-file\n\/\/ TODO(ttacon): deal with handling SHA1 headers\nfunc (c *Client) UploadFile(filePath, parentId string) (*http.Response, *FileCollection, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer file.Close()\n\n\tfileContents, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tbody   = &bytes.Buffer{}\n\t\twriter = multipart.NewWriter(body)\n\t)\n\n\t\/\/ write the file\n\tpart, err := writer.CreateFormFile(\"file\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpart.Write(fileContents)\n\n\t\/\/ write the other form fields we need\n\terr = writer.WriteField(\"filename\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = writer.WriteField(\"parent_id\", parentId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): add in content_created_at, content_modified_at\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"https:\/\/upload.box.com\/api\/2.0\/files\/content\"),\n\t\tbody,\n\t)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data FileCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-delete-a-file\nfunc (c *Client) DeleteFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-copy-a-file\nfunc (c *Client) CopyFile(fileId, parent, name string) (*http.Response, *File, error) {\n\tvar bodyData = map[string]interface{}{\n\t\t\"parent\": map[string]string{\n\t\t\t\"id\": parent,\n\t\t},\n\t\t\"name\": name,\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\/copy\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we return the http.Response as Box may return a 202 if there is not\n\/\/ yet a download link, or a 302 with the link - this allows the user to\n\/\/ decide what to do.\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-download-a-file\nfunc (c *Client) DownloadFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/content\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-versions-of-a-file\n\/\/ TODO(ttacon): don't use file collection, make actual structs specific to file versions\nfunc (c *Client) ViewVersionsOfFile(fileId string) (*http.Response, *FileCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/versions\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *FileCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we only return the response as there are many possible responses that we\n\/\/ feel the user should have control over\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-thumbnail-for-a-file\nfunc (c *Client) GetThumbnail(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/thumbnail.extension\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-create-a-shared-link-for-a-file\nfunc (c *Client) CreateSharedLinkForFile(fileId, access, unsharedAt string, canDownload, canPreview bool) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(access) > 0 {\n\t\tdataMap[\"access\"] = access\n\t}\n\t\/\/ TODO(ttacon): support unshared_at as time.Time\n\t\/\/ TODO(ttacon): validate access is open or company before add permissions\n\tif canDownload {\n\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\"can_download\": canDownload,\n\t\t}\n\t}\n\tif canPreview {\n\t\tif m, ok := dataMap[\"permissions\"]; ok {\n\t\t\tmVal, _ := m.(map[string]bool)\n\t\t\tmVal[\"can_preview\"] = canPreview\n\t\t} else {\n\t\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\t\"can_preview\": canPreview,\n\t\t\t}\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"PUT\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-trashed-file\nfunc (c *Client) GetTrashedFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-restore-a-trashed-item\nfunc (c *Client) RestoreTrashedItem(name, parentId string) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(name) > 0 {\n\t\tdataMap[\"name\"] = name\n\t}\n\tif len(parentId) > 0 {\n\t\tdataMap[\"parent\"] = map[string]string{\n\t\t\t\"id\": parentId,\n\t\t}\n\t}\n\tdataBytes, err := json.Marshal(&dataMap)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(),\n\t\tbytes.NewReader(dataBytes),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data File\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-permanently-delete-a-trashed-file\nfunc (c *Client) PermanentlyDeleteTrashedFile(fileId string) (*http.Response, error) {\n\treq, err := http.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/trash\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Trans.Client().Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-the-comments-on-a-file\nfunc (c *Client) ViewCommentsOnFile(fileId string) (*http.Response, *CommentCollection, error) {\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/comments\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data CommentCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-the-tasks-for-a-file\nfunc (c *Client) GetTasksForFile(fileId string) (*http.Response, *TaskCollection, error) {\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/tasks\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data TaskCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n<commit_msg>refactor restore trashed item<commit_after>package box\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ TODO(ttacon): reconcile this with Folder for one common struct?\ntype File struct {\n\tID                string          `json:\"id,omitempty\"`\n\tFolderUploadEmail *AccessEmail    `json:\"folder_upload_email,omitempty\"`\n\tParent            *Item           `json:\"parent,omitempty\"`\n\tItemStatus        string          `json:\"item_status\"`\n\tItemCollection    *ItemCollection `json:\"item_collection\"`\n\tType              string          `json:\"type\"` \/\/ TODO(ttacon): enum\n\tDescription       string          `json:\"description\"`\n\tSize              int             `json:\"size\"`\n\tCreateBy          *Item           `json:\"created_by\"`\n\tModifiedBy        *Item           `json:\"modified_by\"`\n\tTrashedAt         *string         `json:\"trashed_at\"`          \/\/ TODO(ttacon): change to time.Time\n\tContentModifiedAt *string         `json:\"content_modified_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPurgedAt          *string         `json:\"purged_at\"`           \/\/ TODO(ttacon): change to time.Time, this field isn't documented but I keep getting it back...\n\tSharedLinkg       *string         `json:\"shared_link\"`\n\tSequenceId        string          `json:\"sequence_id\"`\n\tETag              *string         `json:\"etag\"`\n\tName              string          `json:\"name\"`\n\tCreatedAt         *string         `json:\"created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tOwnedBy           *Item           `json:\"owned_by\"`\n\tModifiedAt        *string         `json:\"modified_at\"`        \/\/ TODO(ttacon): change to time.Time\n\tContentCreatedAt  *string         `json:\"content_created_at\"` \/\/ TODO(ttacon): change to time.Time\n\tPathCollection    *PathCollection `json:\"path_collection\"`    \/\/ TODO(ttacon): make sure this is the correct kind of struct(ure)\n\tSharedLink        *Link           `json:\"shared_link\"`\n\n\tSHA1 string `json:\"sha1\"`\n}\n\ntype FileCollection struct {\n\tTotalCount int     `json:\"total_count\"`\n\tEntries    []*File `json:\"entries\"`\n}\n\n\/\/ Documentation: https:\/\/developer.box.com\/docs\/#files-get\nfunc (c *Client) GetFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation https:\/\/developer.box.com\/docs\/#files-upload-a-file\n\/\/ TODO(ttacon): deal with handling SHA1 headers\nfunc (c *Client) UploadFile(filePath, parentId string) (*http.Response, *FileCollection, error) {\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer file.Close()\n\n\tfileContents, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfi, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar (\n\t\tbody   = &bytes.Buffer{}\n\t\twriter = multipart.NewWriter(body)\n\t)\n\n\t\/\/ write the file\n\tpart, err := writer.CreateFormFile(\"file\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tpart.Write(fileContents)\n\n\t\/\/ write the other form fields we need\n\terr = writer.WriteField(\"filename\", fi.Name())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\terr = writer.WriteField(\"parent_id\", parentId)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ TODO(ttacon): add in content_created_at, content_modified_at\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"https:\/\/upload.box.com\/api\/2.0\/files\/content\"),\n\t\tbody,\n\t)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data FileCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-delete-a-file\nfunc (c *Client) DeleteFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-copy-a-file\nfunc (c *Client) CopyFile(fileId, parent, name string) (*http.Response, *File, error) {\n\tvar bodyData = map[string]interface{}{\n\t\t\"parent\": map[string]string{\n\t\t\t\"id\": parent,\n\t\t},\n\t\t\"name\": name,\n\t}\n\n\treq, err := http.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\/copy\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we return the http.Response as Box may return a 202 if there is not\n\/\/ yet a download link, or a 302 with the link - this allows the user to\n\/\/ decide what to do.\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-download-a-file\nfunc (c *Client) DownloadFile(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/content\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req, nil)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-versions-of-a-file\n\/\/ TODO(ttacon): don't use file collection, make actual structs specific to file versions\nfunc (c *Client) ViewVersionsOfFile(fileId string) (*http.Response, *FileCollection, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/versions\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *FileCollection\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ NOTE: we only return the response as there are many possible responses that we\n\/\/ feel the user should have control over\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-thumbnail-for-a-file\nfunc (c *Client) GetThumbnail(fileId string) (*http.Response, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/thumbnail.extension\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-create-a-shared-link-for-a-file\nfunc (c *Client) CreateSharedLinkForFile(fileId, access, unsharedAt string, canDownload, canPreview bool) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(access) > 0 {\n\t\tdataMap[\"access\"] = access\n\t}\n\t\/\/ TODO(ttacon): support unshared_at as time.Time\n\t\/\/ TODO(ttacon): validate access is open or company before add permissions\n\tif canDownload {\n\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\"can_download\": canDownload,\n\t\t}\n\t}\n\tif canPreview {\n\t\tif m, ok := dataMap[\"permissions\"]; ok {\n\t\t\tmVal, _ := m.(map[string]bool)\n\t\t\tmVal[\"can_preview\"] = canPreview\n\t\t} else {\n\t\t\tdataMap[\"permissions\"] = map[string]bool{\n\t\t\t\t\"can_preview\": canPreview,\n\t\t\t}\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"PUT\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-a-trashed-file\nfunc (c *Client) GetTrashedFile(fileId string) (*http.Response, *File, error) {\n\treq, err := c.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"\/files\/%s\/trash\", fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-restore-a-trashed-item\nfunc (c *Client) RestoreTrashedItem(fileId, name, parentId string) (*http.Response, *File, error) {\n\tvar dataMap = make(map[string]interface{})\n\tif len(name) > 0 {\n\t\tdataMap[\"name\"] = name\n\t}\n\tif len(parentId) > 0 {\n\t\tdataMap[\"parent\"] = map[string]string{\n\t\t\t\"id\": parentId,\n\t\t}\n\t}\n\n\treq, err := c.NewRequest(\n\t\t\"POST\",\n\t\tfmt.Sprintf(\"\/files\/%s\", fileId),\n\t\tdataMap,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar data *File\n\tresp, err := c.Do(req, data)\n\treturn resp, data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-permanently-delete-a-trashed-file\nfunc (c *Client) PermanentlyDeleteTrashedFile(fileId string) (*http.Response, error) {\n\treq, err := http.NewRequest(\n\t\t\"DELETE\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/trash\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.Trans.Client().Do(req)\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-view-the-comments-on-a-file\nfunc (c *Client) ViewCommentsOnFile(fileId string) (*http.Response, *CommentCollection, error) {\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/comments\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data CommentCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n\n\/\/ Documentation: https:\/\/developers.box.com\/docs\/#files-get-the-tasks-for-a-file\nfunc (c *Client) GetTasksForFile(fileId string) (*http.Response, *TaskCollection, error) {\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s\/files\/%s\/tasks\", BASE_URL, fileId),\n\t\tnil,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.Trans.Client().Do(req)\n\tif err != nil {\n\t\treturn resp, nil, err\n\t}\n\n\tvar data TaskCollection\n\terr = json.NewDecoder(resp.Body).Decode(&data)\n\treturn resp, &data, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype UnixtimeMacro struct {\n\tduration time.Duration\n\tformat   string\n}\n\nvar PksInputs map[string]string = make(map[string]string)\nvar Md5Inputs map[string]string = make(map[string]string)\nvar Base64Inputs map[string]string = make(map[string]string)\nvar UnixtimeMacros map[string]UnixtimeMacro\nvar PrintTimeMacros map[string]UnixtimeMacro\nvar CommandMacros = make(map[string][]string)\nvar Md5Macros = make(map[string][]string)\nvar Base64Macros = make(map[string][]string)\nvar PksMacros = make(map[string][]string)\n\nvar reArgs = regexp.MustCompile(\"{%ARGS\\\\[(\\\\d+)\\\\]}\")\n\nfunc arrayContains(arr []string, str string) bool {\n\ti := 0\n\tfor i < len(arr) {\n\t\tif str == arr[i] {\n\t\t\tbreak\n\t\t}\n\t\ti += 1\n\t}\n\treturn i < len(arr)\n\n}\n\nfunc addCommandMacro(cmd string, macro string) {\n\tif !arrayContains(CommandMacros[cmd], macro) {\n\t\tCommandMacros[cmd] = append(CommandMacros[cmd], macro)\n\t}\n}\n\nfunc InitSessionLogMacros(sessionLog string) {\n\t\/\/ this will create an entry for a command named \"\\nSessionLog\",\n\t\/\/ the newline will prevent any command named \"SessionLog\" in an ini file from overwriting it\n\tInitMacros(\"\\nSessionLog\", sessionLog)\n}\n\nfunc InitMacros(cmd string, field string) {\n\t_, exists := CommandMacros[cmd]\n\tif !exists {\n\t\tCommandMacros[cmd] = make([]string, 0)\n\t}\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(field, -1) {\n\t\taddCommandMacro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(field, -1) {\n\t\taddCommandMacro(cmd, macro)\n\t}\n}\n\nfunc parseTimeModifier(arg string) (time.Duration, error) {\n\tif len(arg) == 0 {\n\t\treturn time.Duration(0), nil\n\t}\n\n\trx := regexp.MustCompile(\"([\\\\+\\\\-]\\\\d+)(.*)\")\n\tparsed := rx.FindStringSubmatch(arg)\n\tif parsed == nil {\n\t\treturn time.Duration(0), errors.New(fmt.Sprintf(\"time modifier %s is not supported\", arg))\n\t} else {\n\t\tmult, _ := strconv.Atoi(parsed[1]) \/\/ e.g -4, +4, 4\n\t\tif parsed[2] == \"MONTH\" || parsed[2] == \"MONTHS\" {\n\t\t\treturn time.Duration(mult*30*24) * time.Hour, nil\n\t\t} else if parsed[2] == \"DAY\" || parsed[2] == \"DAYS\" {\n\t\t\treturn time.Duration(mult) * 24 * time.Hour, nil\n\t\t} else if parsed[2] == \"HOUR\" || parsed[2] == \"HOURS\" {\n\t\t\treturn time.Duration(mult) * time.Hour, nil\n\t\t} else if parsed[2] == \"MINUTE\" || parsed[2] == \"MINUTES\" {\n\t\t\treturn time.Duration(mult) * time.Minute, nil\n\t\t} else if parsed[2] == \"SECOND\" || parsed[2] == \"SECONDS\" {\n\t\t\treturn time.Duration(mult) * time.Second, nil\n\t\t} else {\n\t\t\treturn time.Duration(0), errors.New(fmt.Sprintf(\"time modifier %s is not supported\", arg))\n\t\t}\n\t}\n}\n\nfunc initUnixtimeMacro(macro string) {\n\tdeclaration := macro[2 : len(macro)-1]\n\tif strings.HasPrefix(declaration, \"UNIXTIME\") {\n\t\targ := declaration[8:]\n\t\trx1, _ := regexp.Compile(\"%(\\\\d+)?x\")\n\t\tfmtmatch := rx1.FindString(arg)\n\t\tformat := \"%d\"\n\t\tif len(fmtmatch) > 0 {\n\t\t\tformat = fmtmatch\n\t\t\targ = strings.Replace(arg, fmtmatch, \"\", -1)\n\t\t}\n\t\tduration, err := parseTimeModifier(arg)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"UNIXTIME macro %s: %s\", declaration, err.Error())\n\t\t} else {\n\t\t\tUnixtimeMacros[macro] = UnixtimeMacro{duration, format}\n\t\t}\n\t}\n}\n\nfunc initPrintTimeMacro(macro string) {\n\tdeclaration := macro[2 : len(macro)-1]\n\tif strings.HasPrefix(declaration, \"TIME\") {\n\t\tformat := \"2006-01-02 15:04:05\"\n\t\targ := declaration[4:]\n\t\tduration, err := parseTimeModifier(arg)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"TIME macro %s: %s\", declaration, err.Error())\n\t\t} else {\n\t\t\tPrintTimeMacros[macro] = UnixtimeMacro{duration, format}\n\t\t}\n\t}\n}\n\nfunc InitUnixtimeMacros() {\n\tPrintTimeMacros = make(map[string]UnixtimeMacro)\n\tUnixtimeMacros = make(map[string]UnixtimeMacro)\n\tfor _, macros := range CommandMacros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n\tfor _, macros := range Base64Macros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n\tfor _, macros := range Md5Macros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n}\n\nfunc addPksMacro(cmd string, macro string) {\n\tif !arrayContains(PksMacros[cmd], macro) {\n\t\tPksMacros[cmd] = append(PksMacros[cmd], macro)\n\t}\n}\n\nfunc InitPksMacro(cmd string, pksInput string) {\n\tif len(pksInput) == 0 {\n\t\treturn\n\t}\n\tPksInputs[cmd] = pksInput\n\tPksMacros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(pksInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(pksInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n} \/\/InitPKSMacro\n\/*\nfunc InitFuncMacro(cmd string, funcInput string) {\n\tif len(funcInput) == 0 {\n\t\treturn\n\t}\n\tPksMacros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(funcInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(funcInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n} \/\/InitFuncMacro\n*\/\nfunc addMd5Macro(cmd string, macro string) {\n\tif !arrayContains(Md5Macros[cmd], macro) {\n\t\tMd5Macros[cmd] = append(Md5Macros[cmd], macro)\n\t}\n}\n\nfunc InitMd5Macro(cmd string, md5Input string) {\n\tif len(md5Input) == 0 {\n\t\treturn\n\t}\n\n\tMd5Inputs[cmd] = md5Input\n\tMd5Macros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(md5Input, -1) {\n\t\taddMd5Macro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(md5Input, -1) {\n\t\taddMd5Macro(cmd, macro)\n\t}\n}\n\nfunc addBase64Macro(cmd string, macro string) {\n\tif !arrayContains(Base64Macros[cmd], macro) {\n\t\tBase64Macros[cmd] = append(Base64Macros[cmd], macro)\n\t}\n}\n\nfunc InitBase64Macro(cmd string, base64Input string) {\n\tif len(base64Input) == 0 {\n\t\treturn\n\t}\n\n\tBase64Inputs[cmd] = base64Input\n\tBase64Macros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(base64Input, -1) {\n\t\taddBase64Macro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(base64Input, -1) {\n\t\taddBase64Macro(cmd, macro)\n\t}\n}\n\nfunc _runnerMacro(command string, declaration string, inputData string, sessionVars map[string]string, reqTime time.Time) string {\n\tif !(strings.HasPrefix(declaration, \"{%\") || strings.HasPrefix(declaration, \"{$\")) || !strings.HasSuffix(declaration, \"}\") {\n\t\treturn \"\"\n\t}\n\t\/\/This func processes the token and returns the string\n\tuxt, ok := UnixtimeMacros[declaration]\n\tprt, ok1 := PrintTimeMacros[declaration]\n\tif ok {\n\t\ttimestamp := reqTime.Add(uxt.duration).UnixNano() \/ (int64(time.Millisecond) \/ int64(time.Nanosecond)) \/\/why not use now instead of reqTime?\n\t\trx, _ := regexp.Compile(\"%(\\\\d+)x\")\n\t\tfmtdigits := rx.FindStringSubmatch(uxt.format)\n\t\tif len(fmtdigits) == 0 {\n\t\t\treturn fmt.Sprintf(uxt.format, timestamp)\n\t\t} else {\n\t\t\tfmtnum, _ := strconv.Atoi(fmtdigits[1])\n\t\t\tif fmtnum >= 12 {\n\t\t\t\treturn fmt.Sprintf(uxt.format, timestamp)\n\t\t\t} else {\n\t\t\t\ttmp := fmt.Sprintf(\"%012x\", timestamp)\n\t\t\t\treturn tmp[0:fmtnum]\n\t\t\t}\n\t\t}\n\t} else if ok1 {\n\t\treturn reqTime.Add(prt.duration).Format(prt.format)\n\t} else if declaration == \"{%MD5SUM}\" {\n\t\ttestMd5 := Md5Inputs[command]\n\t\tfor _, macro := range Md5Macros[command] {\n\t\t\ttestMd5 = strings.Replace(testMd5, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\t\treturn strings.ToUpper(fmt.Sprintf(\"%x\", md5.Sum([]byte(testMd5))))\n\t} else if declaration == \"{%PKSENC}\" {\n\t\tpksInput := PksInputs[command]\n\t\tfor _, macro := range PksMacros[command] {\n\t\t\tpksInput = strings.Replace(pksInput, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\n\t\t\/\/ that's dirty, waiting for proper func management\n\t\tinputs := strings.Split(pksInput, \",\")\n\t\tif len(inputs) != 3 {\n\t\t\treturn \"invalid PKSInput format. Must be pwd,key,keyexp\"\n\t\t}\n\t\tencryptor, err := NewPKSEncryptor(inputs[1], inputs[2], inputs[0])\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tres, err := encryptor.Encrypt()\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\treturn hex.EncodeToString(res)\n\t} else if declaration == \"{%BASE64ENC}\" {\n\t\tbase64In := Base64Inputs[command]\n\t\tfor _, macro := range Base64Macros[command] {\n\t\t\tbase64In = strings.Replace(base64In, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\t\treturn base64.StdEncoding.EncodeToString([]byte(base64In))\n\t} else if strings.HasPrefix(declaration, \"{$\") {\n\t\t\/\/ an env var macro like {$SECRET}\n\t\treturn os.Getenv(declaration[2 : len(declaration)-1])\n\t} else {\n\t\t\/\/ Check if it match {%ARGS[X]}\n\t\targsIndex := reArgs.FindStringSubmatch(declaration) \/\/ regexp.MustCompile(\"{%ARGS\\\\[(\\\\d+)\\\\]}\")\n\t\tif len(argsIndex) > 0 {\n\t\t\ti, _ := strconv.Atoi(argsIndex[1])\n\t\t\tarr := strings.Split(inputData, delimeter)\n\t\t\tif i >= len(arr) {\n\t\t\t\t\/\/ TODO : print error ?\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn arr[i]\n\t\t}\n\t\t\/\/ Check if it match a session var\n\t\tif declaration[1] == '%' {\n\t\t\tsession_var := declaration[2 : len(declaration)-1]\n\t\t\tval, ok := sessionVars[session_var]\n\t\t\tif ok {\n\t\t\t\treturn val\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n} \/\/_runnerMacro replaces the variable reference like {%X} or {$X} with the value stored in the hash table\n\nfunc runnerMacro(command string, declaration string, inputData string, sessionVars map[string]string, reqTime time.Time) string {\n\tif !(strings.HasPrefix(declaration, \"{%\") || strings.HasPrefix(declaration, \"{$\")) || !strings.HasSuffix(declaration, \"}\") {\n\t\treturn \"\"\n\t} \/\/This functions gets passed in a {%X} and {$X} variable reference, looks it up the hash table and returns the string value\n\n\tssrx, _ := regexp.Compile(\"\\\\[(\\\\d+):(\\\\d+)\\\\]}\")\n\tdeclSubstr := ssrx.FindStringSubmatch(declaration)\n\tif len(declSubstr) == 0 {\n\t\treturn _runnerMacro(command, declaration, inputData, sessionVars, reqTime)\n\t} else {\n\t\tdeclaration = strings.Replace(declaration, declSubstr[0], \"}\", 1)\n\t\tresult := _runnerMacro(command, declaration, inputData, sessionVars, reqTime)\n\t\tss0, _ := strconv.Atoi(declSubstr[1])\n\t\tss1, _ := strconv.Atoi(declSubstr[2])\n\t\treturn result[ss0:ss1]\n\t}\n}\n\nfunc RunnerMacros(command string, inputData string, sessionVars map[string]string, reqTime time.Time, field string) string {\n\tfor _, macro := range CommandMacros[command] {\n\t\tfield = strings.Replace(field, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t}\n\treturn field\n}\n\nfunc RunnerMacrosRegexp(command string, inputData string, sessionVars map[string]string, reqTime time.Time, field string) string {\n\tfor _, macro := range CommandMacros[command] {\n\t\treplacement := regexp.QuoteMeta(runnerMacro(command, macro, inputData, sessionVars, reqTime))\n\t\tfield = strings.Replace(field, macro, replacement, -1)\n\t}\n\treturn field\n}\n\nfunc SessionLogMacros(inputData string, sessionVars map[string]string, logTime time.Time, initial string) string {\n\treturn RunnerMacros(\"\\nSessionLog\", inputData, sessionVars, logTime, initial)\n}\n<commit_msg>adding javascript macro support cleanup big comment<commit_after>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype UnixtimeMacro struct {\n\tduration time.Duration\n\tformat   string\n}\n\nvar PksInputs map[string]string = make(map[string]string)\nvar Md5Inputs map[string]string = make(map[string]string)\nvar Base64Inputs map[string]string = make(map[string]string)\nvar UnixtimeMacros map[string]UnixtimeMacro\nvar PrintTimeMacros map[string]UnixtimeMacro\nvar CommandMacros = make(map[string][]string)\nvar Md5Macros = make(map[string][]string)\nvar Base64Macros = make(map[string][]string)\nvar PksMacros = make(map[string][]string)\n\nvar reArgs = regexp.MustCompile(\"{%ARGS\\\\[(\\\\d+)\\\\]}\")\n\nfunc arrayContains(arr []string, str string) bool {\n\ti := 0\n\tfor i < len(arr) {\n\t\tif str == arr[i] {\n\t\t\tbreak\n\t\t}\n\t\ti += 1\n\t}\n\treturn i < len(arr)\n\n}\n\nfunc addCommandMacro(cmd string, macro string) {\n\tif !arrayContains(CommandMacros[cmd], macro) {\n\t\tCommandMacros[cmd] = append(CommandMacros[cmd], macro)\n\t}\n}\n\nfunc InitSessionLogMacros(sessionLog string) {\n\t\/\/ this will create an entry for a command named \"\\nSessionLog\",\n\t\/\/ the newline will prevent any command named \"SessionLog\" in an ini file from overwriting it\n\tInitMacros(\"\\nSessionLog\", sessionLog)\n}\n\nfunc InitMacros(cmd string, field string) {\n\t_, exists := CommandMacros[cmd]\n\tif !exists {\n\t\tCommandMacros[cmd] = make([]string, 0)\n\t}\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(field, -1) {\n\t\taddCommandMacro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(field, -1) {\n\t\taddCommandMacro(cmd, macro)\n\t}\n}\n\nfunc parseTimeModifier(arg string) (time.Duration, error) {\n\tif len(arg) == 0 {\n\t\treturn time.Duration(0), nil\n\t}\n\n\trx := regexp.MustCompile(\"([\\\\+\\\\-]\\\\d+)(.*)\")\n\tparsed := rx.FindStringSubmatch(arg)\n\tif parsed == nil {\n\t\treturn time.Duration(0), errors.New(fmt.Sprintf(\"time modifier %s is not supported\", arg))\n\t} else {\n\t\tmult, _ := strconv.Atoi(parsed[1]) \/\/ e.g -4, +4, 4\n\t\tif parsed[2] == \"MONTH\" || parsed[2] == \"MONTHS\" {\n\t\t\treturn time.Duration(mult*30*24) * time.Hour, nil\n\t\t} else if parsed[2] == \"DAY\" || parsed[2] == \"DAYS\" {\n\t\t\treturn time.Duration(mult) * 24 * time.Hour, nil\n\t\t} else if parsed[2] == \"HOUR\" || parsed[2] == \"HOURS\" {\n\t\t\treturn time.Duration(mult) * time.Hour, nil\n\t\t} else if parsed[2] == \"MINUTE\" || parsed[2] == \"MINUTES\" {\n\t\t\treturn time.Duration(mult) * time.Minute, nil\n\t\t} else if parsed[2] == \"SECOND\" || parsed[2] == \"SECONDS\" {\n\t\t\treturn time.Duration(mult) * time.Second, nil\n\t\t} else {\n\t\t\treturn time.Duration(0), errors.New(fmt.Sprintf(\"time modifier %s is not supported\", arg))\n\t\t}\n\t}\n}\n\nfunc initUnixtimeMacro(macro string) {\n\tdeclaration := macro[2 : len(macro)-1]\n\tif strings.HasPrefix(declaration, \"UNIXTIME\") {\n\t\targ := declaration[8:]\n\t\trx1, _ := regexp.Compile(\"%(\\\\d+)?x\")\n\t\tfmtmatch := rx1.FindString(arg)\n\t\tformat := \"%d\"\n\t\tif len(fmtmatch) > 0 {\n\t\t\tformat = fmtmatch\n\t\t\targ = strings.Replace(arg, fmtmatch, \"\", -1)\n\t\t}\n\t\tduration, err := parseTimeModifier(arg)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"UNIXTIME macro %s: %s\", declaration, err.Error())\n\t\t} else {\n\t\t\tUnixtimeMacros[macro] = UnixtimeMacro{duration, format}\n\t\t}\n\t}\n}\n\nfunc initPrintTimeMacro(macro string) {\n\tdeclaration := macro[2 : len(macro)-1]\n\tif strings.HasPrefix(declaration, \"TIME\") {\n\t\tformat := \"2006-01-02 15:04:05\"\n\t\targ := declaration[4:]\n\t\tduration, err := parseTimeModifier(arg)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"TIME macro %s: %s\", declaration, err.Error())\n\t\t} else {\n\t\t\tPrintTimeMacros[macro] = UnixtimeMacro{duration, format}\n\t\t}\n\t}\n}\n\nfunc InitUnixtimeMacros() {\n\tPrintTimeMacros = make(map[string]UnixtimeMacro)\n\tUnixtimeMacros = make(map[string]UnixtimeMacro)\n\tfor _, macros := range CommandMacros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n\tfor _, macros := range Base64Macros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n\tfor _, macros := range Md5Macros {\n\t\tfor _, macro := range macros {\n\t\t\tinitUnixtimeMacro(macro)\n\t\t\tinitPrintTimeMacro(macro)\n\t\t}\n\t}\n}\n\nfunc addPksMacro(cmd string, macro string) {\n\tif !arrayContains(PksMacros[cmd], macro) {\n\t\tPksMacros[cmd] = append(PksMacros[cmd], macro)\n\t}\n}\n\nfunc InitPksMacro(cmd string, pksInput string) {\n\tif len(pksInput) == 0 {\n\t\treturn\n\t}\n\tPksInputs[cmd] = pksInput\n\tPksMacros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(pksInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(pksInput, -1) {\n\t\taddPksMacro(cmd, macro)\n\t}\n} \/\/InitPKSMacro\nfunc addMd5Macro(cmd string, macro string) {\n\tif !arrayContains(Md5Macros[cmd], macro) {\n\t\tMd5Macros[cmd] = append(Md5Macros[cmd], macro)\n\t}\n}\n\nfunc InitMd5Macro(cmd string, md5Input string) {\n\tif len(md5Input) == 0 {\n\t\treturn\n\t}\n\n\tMd5Inputs[cmd] = md5Input\n\tMd5Macros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(md5Input, -1) {\n\t\taddMd5Macro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(md5Input, -1) {\n\t\taddMd5Macro(cmd, macro)\n\t}\n}\n\nfunc addBase64Macro(cmd string, macro string) {\n\tif !arrayContains(Base64Macros[cmd], macro) {\n\t\tBase64Macros[cmd] = append(Base64Macros[cmd], macro)\n\t}\n}\n\nfunc InitBase64Macro(cmd string, base64Input string) {\n\tif len(base64Input) == 0 {\n\t\treturn\n\t}\n\n\tBase64Inputs[cmd] = base64Input\n\tBase64Macros[cmd] = make([]string, 0)\n\n\trx, _ := regexp.Compile(\"\\\\{%.*?\\\\}\")\n\trxenv, _ := regexp.Compile(\"\\\\{\\\\$.*?\\\\}\")\n\n\tfor _, macro := range rx.FindAllString(base64Input, -1) {\n\t\taddBase64Macro(cmd, macro)\n\t}\n\tfor _, macro := range rxenv.FindAllString(base64Input, -1) {\n\t\taddBase64Macro(cmd, macro)\n\t}\n}\n\nfunc _runnerMacro(command string, declaration string, inputData string, sessionVars map[string]string, reqTime time.Time) string {\n\tif !(strings.HasPrefix(declaration, \"{%\") || strings.HasPrefix(declaration, \"{$\")) || !strings.HasSuffix(declaration, \"}\") {\n\t\treturn \"\"\n\t}\n\t\/\/This func processes the token and returns the string\n\tuxt, ok := UnixtimeMacros[declaration]\n\tprt, ok1 := PrintTimeMacros[declaration]\n\tif ok {\n\t\ttimestamp := reqTime.Add(uxt.duration).UnixNano() \/ (int64(time.Millisecond) \/ int64(time.Nanosecond)) \/\/why not use now instead of reqTime?\n\t\trx, _ := regexp.Compile(\"%(\\\\d+)x\")\n\t\tfmtdigits := rx.FindStringSubmatch(uxt.format)\n\t\tif len(fmtdigits) == 0 {\n\t\t\treturn fmt.Sprintf(uxt.format, timestamp)\n\t\t} else {\n\t\t\tfmtnum, _ := strconv.Atoi(fmtdigits[1])\n\t\t\tif fmtnum >= 12 {\n\t\t\t\treturn fmt.Sprintf(uxt.format, timestamp)\n\t\t\t} else {\n\t\t\t\ttmp := fmt.Sprintf(\"%012x\", timestamp)\n\t\t\t\treturn tmp[0:fmtnum]\n\t\t\t}\n\t\t}\n\t} else if ok1 {\n\t\treturn reqTime.Add(prt.duration).Format(prt.format)\n\t} else if declaration == \"{%MD5SUM}\" {\n\t\ttestMd5 := Md5Inputs[command]\n\t\tfor _, macro := range Md5Macros[command] {\n\t\t\ttestMd5 = strings.Replace(testMd5, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\t\treturn strings.ToUpper(fmt.Sprintf(\"%x\", md5.Sum([]byte(testMd5))))\n\t} else if declaration == \"{%PKSENC}\" {\n\t\tpksInput := PksInputs[command]\n\t\tfor _, macro := range PksMacros[command] {\n\t\t\tpksInput = strings.Replace(pksInput, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\n\t\t\/\/ that's dirty, waiting for proper func management\n\t\tinputs := strings.Split(pksInput, \",\")\n\t\tif len(inputs) != 3 {\n\t\t\treturn \"invalid PKSInput format. Must be pwd,key,keyexp\"\n\t\t}\n\t\tencryptor, err := NewPKSEncryptor(inputs[1], inputs[2], inputs[0])\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tres, err := encryptor.Encrypt()\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\treturn hex.EncodeToString(res)\n\t} else if declaration == \"{%BASE64ENC}\" {\n\t\tbase64In := Base64Inputs[command]\n\t\tfor _, macro := range Base64Macros[command] {\n\t\t\tbase64In = strings.Replace(base64In, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t\t}\n\t\treturn base64.StdEncoding.EncodeToString([]byte(base64In))\n\t} else if strings.HasPrefix(declaration, \"{$\") {\n\t\t\/\/ an env var macro like {$SECRET}\n\t\treturn os.Getenv(declaration[2 : len(declaration)-1])\n\t} else {\n\t\t\/\/ Check if it match {%ARGS[X]}\n\t\targsIndex := reArgs.FindStringSubmatch(declaration) \/\/ regexp.MustCompile(\"{%ARGS\\\\[(\\\\d+)\\\\]}\")\n\t\tif len(argsIndex) > 0 {\n\t\t\ti, _ := strconv.Atoi(argsIndex[1])\n\t\t\tarr := strings.Split(inputData, delimeter)\n\t\t\tif i >= len(arr) {\n\t\t\t\t\/\/ TODO : print error ?\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn arr[i]\n\t\t}\n\t\t\/\/ Check if it match a session var\n\t\tif declaration[1] == '%' {\n\t\t\tsession_var := declaration[2 : len(declaration)-1]\n\t\t\tval, ok := sessionVars[session_var]\n\t\t\tif ok {\n\t\t\t\treturn val\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n} \/\/_runnerMacro replaces the variable reference like {%X} or {$X} with the value stored in the hash table\n\nfunc runnerMacro(command string, declaration string, inputData string, sessionVars map[string]string, reqTime time.Time) string {\n\tif !(strings.HasPrefix(declaration, \"{%\") || strings.HasPrefix(declaration, \"{$\")) || !strings.HasSuffix(declaration, \"}\") {\n\t\treturn \"\"\n\t} \/\/This functions gets passed in a {%X} and {$X} variable reference, looks it up the hash table and returns the string value\n\n\tssrx, _ := regexp.Compile(\"\\\\[(\\\\d+):(\\\\d+)\\\\]}\")\n\tdeclSubstr := ssrx.FindStringSubmatch(declaration)\n\tif len(declSubstr) == 0 {\n\t\treturn _runnerMacro(command, declaration, inputData, sessionVars, reqTime)\n\t} else {\n\t\tdeclaration = strings.Replace(declaration, declSubstr[0], \"}\", 1)\n\t\tresult := _runnerMacro(command, declaration, inputData, sessionVars, reqTime)\n\t\tss0, _ := strconv.Atoi(declSubstr[1])\n\t\tss1, _ := strconv.Atoi(declSubstr[2])\n\t\treturn result[ss0:ss1]\n\t}\n}\n\nfunc RunnerMacros(command string, inputData string, sessionVars map[string]string, reqTime time.Time, field string) string {\n\tfor _, macro := range CommandMacros[command] {\n\t\tfield = strings.Replace(field, macro, runnerMacro(command, macro, inputData, sessionVars, reqTime), -1)\n\t}\n\treturn field\n}\n\nfunc RunnerMacrosRegexp(command string, inputData string, sessionVars map[string]string, reqTime time.Time, field string) string {\n\tfor _, macro := range CommandMacros[command] {\n\t\treplacement := regexp.QuoteMeta(runnerMacro(command, macro, inputData, sessionVars, reqTime))\n\t\tfield = strings.Replace(field, macro, replacement, -1)\n\t}\n\treturn field\n}\n\nfunc SessionLogMacros(inputData string, sessionVars map[string]string, logTime time.Time, initial string) string {\n\treturn RunnerMacros(\"\\nSessionLog\", inputData, sessionVars, logTime, initial)\n}\n<|endoftext|>"}
{"text":"<commit_before>package jwtauth_test\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/goware\/jwtauth\"\n\t\"github.com\/pressly\/chi\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\tTokenAuth   *jwtauth.JwtAuth\n\tTokenSecret = []byte(\"secretpass\")\n)\n\nfunc init() {\n\tTokenAuth = jwtauth.New(\"HS256\", []byte(\"secretpass\"), nil)\n}\n\n\/\/\n\/\/ Tests\n\/\/\n\nfunc TestSimple(t *testing.T) {\n\tr := chi.NewRouter()\n\n\tr.Use(TokenAuth.Verifier)\n\tr.Use(jwtauth.Authenticator)\n\n\tr.Get(\"\/\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"welcome\"))\n\t})\n\n\tts := httptest.NewServer(r)\n\tdefer ts.Close()\n\n\t\/\/ sending unauthorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", nil, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken([]byte(\"wrong\"), map[string]interface{}{}))\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\th.Set(\"Authorization\", \"BEARER asdf\")\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\t\/\/ sending authorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", newAuthHeader(), nil); resp != \"welcome\" {\n\t\tt.Fatalf(resp)\n\t}\n}\n\nfunc TestMore(t *testing.T) {\n\tr := chi.NewRouter()\n\n\t\/\/ Protected routes\n\tr.Group(func(r chi.Router) {\n\t\tr.Use(TokenAuth.Verifier)\n\n\t\tauthenticator := func(next chi.Handler) chi.Handler {\n\t\t\treturn chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif jwtErr, ok := ctx.Value(\"jwt.err\").(error); ok {\n\t\t\t\t\tswitch jwtErr {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlog.Println(\"...we're expired... I think..:\", jwtErr)\n\t\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase jwtauth.ErrExpired:\n\t\t\t\t\t\thttp.Error(w, \"expired\", 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase jwtauth.ErrUnauthorized:\n\t\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase nil:\n\t\t\t\t\t\t\/\/ no error\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tjwtToken, ok := ctx.Value(\"jwt\").(*jwt.Token)\n\t\t\t\tif !ok || jwtToken == nil || !jwtToken.Valid {\n\t\t\t\t\tlog.Println(\"jwt token..........?\", jwtToken)\n\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Token is authenticated, pass it through\n\t\t\t\tnext.ServeHTTPC(ctx, w, r)\n\t\t\t})\n\t\t}\n\t\tr.Use(authenticator)\n\n\t\tr.Get(\"\/admin\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Write([]byte(\"protected\"))\n\t\t})\n\t})\n\n\t\/\/ Public routes\n\tr.Group(func(r chi.Router) {\n\t\tr.Get(\"\/\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Write([]byte(\"welcome\"))\n\t\t})\n\t})\n\n\tts := httptest.NewServer(r)\n\tdefer ts.Close()\n\n\t\/\/ sending unauthorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", nil, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken([]byte(\"wrong\"), map[string]interface{}{}))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\th.Set(\"Authorization\", \"BEARER asdf\")\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th = newAuthHeader((jwtauth.Claims{}).Set(\"exp\", jwtauth.EpochNow()-1000))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"expired\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\t\/\/ sending authorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", nil, nil); resp != \"welcome\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th = newAuthHeader((jwtauth.Claims{}).SetExpiryIn(5 * time.Minute))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"protected\" {\n\t\tt.Fatalf(resp)\n\t}\n}\n\n\/\/\n\/\/ Test helper functions\n\/\/\n\nfunc testRequest(t *testing.T, ts *httptest.Server, method, path string, header http.Header, body io.Reader) string {\n\treq, err := http.NewRequest(method, ts.URL+path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Set(k, v[0])\n\t\t}\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\tdefer resp.Body.Close()\n\n\treturn string(respBody)\n}\n\nfunc newJwtToken(secret []byte, claims ...jwtauth.Claims) string {\n\ttoken := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\tif len(claims) > 0 {\n\t\tfor k, v := range claims[0] {\n\t\t\ttoken.Claims[k] = v\n\t\t}\n\t}\n\ttokenStr, err := token.SignedString(secret)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn tokenStr\n}\n\nfunc newAuthHeader(claims ...jwtauth.Claims) http.Header {\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken(TokenSecret, claims...))\n\treturn h\n}\n<commit_msg>Remove debug statements<commit_after>package jwtauth_test\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/goware\/jwtauth\"\n\t\"github.com\/pressly\/chi\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\tTokenAuth   *jwtauth.JwtAuth\n\tTokenSecret = []byte(\"secretpass\")\n)\n\nfunc init() {\n\tTokenAuth = jwtauth.New(\"HS256\", []byte(\"secretpass\"), nil)\n}\n\n\/\/\n\/\/ Tests\n\/\/\n\nfunc TestSimple(t *testing.T) {\n\tr := chi.NewRouter()\n\n\tr.Use(TokenAuth.Verifier)\n\tr.Use(jwtauth.Authenticator)\n\n\tr.Get(\"\/\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"welcome\"))\n\t})\n\n\tts := httptest.NewServer(r)\n\tdefer ts.Close()\n\n\t\/\/ sending unauthorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", nil, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken([]byte(\"wrong\"), map[string]interface{}{}))\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\th.Set(\"Authorization\", \"BEARER asdf\")\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\t\/\/ sending authorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", newAuthHeader(), nil); resp != \"welcome\" {\n\t\tt.Fatalf(resp)\n\t}\n}\n\nfunc TestMore(t *testing.T) {\n\tr := chi.NewRouter()\n\n\t\/\/ Protected routes\n\tr.Group(func(r chi.Router) {\n\t\tr.Use(TokenAuth.Verifier)\n\n\t\tauthenticator := func(next chi.Handler) chi.Handler {\n\t\t\treturn chi.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tif jwtErr, ok := ctx.Value(\"jwt.err\").(error); ok {\n\t\t\t\t\tswitch jwtErr {\n\t\t\t\t\tdefault:\n\t\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase jwtauth.ErrExpired:\n\t\t\t\t\t\thttp.Error(w, \"expired\", 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase jwtauth.ErrUnauthorized:\n\t\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\t\treturn\n\t\t\t\t\tcase nil:\n\t\t\t\t\t\t\/\/ no error\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tjwtToken, ok := ctx.Value(\"jwt\").(*jwt.Token)\n\t\t\t\tif !ok || jwtToken == nil || !jwtToken.Valid {\n\t\t\t\t\thttp.Error(w, http.StatusText(401), 401)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Token is authenticated, pass it through\n\t\t\t\tnext.ServeHTTPC(ctx, w, r)\n\t\t\t})\n\t\t}\n\t\tr.Use(authenticator)\n\n\t\tr.Get(\"\/admin\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Write([]byte(\"protected\"))\n\t\t})\n\t})\n\n\t\/\/ Public routes\n\tr.Group(func(r chi.Router) {\n\t\tr.Get(\"\/\", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Write([]byte(\"welcome\"))\n\t\t})\n\t})\n\n\tts := httptest.NewServer(r)\n\tdefer ts.Close()\n\n\t\/\/ sending unauthorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", nil, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken([]byte(\"wrong\"), map[string]interface{}{}))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\th.Set(\"Authorization\", \"BEARER asdf\")\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"Unauthorized\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th = newAuthHeader((jwtauth.Claims{}).Set(\"exp\", jwtauth.EpochNow()-1000))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"expired\\n\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\t\/\/ sending authorized requests\n\tif resp := testRequest(t, ts, \"GET\", \"\/\", nil, nil); resp != \"welcome\" {\n\t\tt.Fatalf(resp)\n\t}\n\n\th = newAuthHeader((jwtauth.Claims{}).SetExpiryIn(5 * time.Minute))\n\tif resp := testRequest(t, ts, \"GET\", \"\/admin\", h, nil); resp != \"protected\" {\n\t\tt.Fatalf(resp)\n\t}\n}\n\n\/\/\n\/\/ Test helper functions\n\/\/\n\nfunc testRequest(t *testing.T, ts *httptest.Server, method, path string, header http.Header, body io.Reader) string {\n\treq, err := http.NewRequest(method, ts.URL+path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Set(k, v[0])\n\t\t}\n\t}\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\n\trespBody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn \"\"\n\t}\n\tdefer resp.Body.Close()\n\n\treturn string(respBody)\n}\n\nfunc newJwtToken(secret []byte, claims ...jwtauth.Claims) string {\n\ttoken := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\tif len(claims) > 0 {\n\t\tfor k, v := range claims[0] {\n\t\t\ttoken.Claims[k] = v\n\t\t}\n\t}\n\ttokenStr, err := token.SignedString(secret)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn tokenStr\n}\n\nfunc newAuthHeader(claims ...jwtauth.Claims) http.Header {\n\th := http.Header{}\n\th.Set(\"Authorization\", \"BEARER \"+newJwtToken(TokenSecret, claims...))\n\treturn h\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\n\/\/ Package app implements a server that runs a set of active\n\/\/ components.  This includes replication controllers, service endpoints and\n\/\/ nodes.\npackage app\n\nimport (\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/resource\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/cloudprovider\"\n\tnodeControllerPkg \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/cloudprovider\/controller\"\n\treplicationControllerPkg \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/controller\"\n\t_ \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/healthz\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/master\/ports\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/resourcequota\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/service\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/util\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/\/ CMServer is the mail context object for the controller manager.\ntype CMServer struct {\n\tPort                    int\n\tAddress                 util.IP\n\tClientConfig            client.Config\n\tCloudProvider           string\n\tCloudConfigFile         string\n\tMinionRegexp            string\n\tNodeSyncPeriod          time.Duration\n\tResourceQuotaSyncPeriod time.Duration\n\tRegisterRetryCount      int\n\tMachineList             util.StringList\n\tSyncNodeList            bool\n\tPodEvictionTimeout      time.Duration\n\n\t\/\/ TODO: Discover these by pinging the host machines, and rip out these params.\n\tNodeMilliCPU int64\n\tNodeMemory   resource.Quantity\n\n\tKubeletConfig client.KubeletConfig\n}\n\n\/\/ NewCMServer creates a new CMServer with a default config.\nfunc NewCMServer() *CMServer {\n\ts := CMServer{\n\t\tPort:                    ports.ControllerManagerPort,\n\t\tAddress:                 util.IP(net.ParseIP(\"127.0.0.1\")),\n\t\tNodeSyncPeriod:          10 * time.Second,\n\t\tResourceQuotaSyncPeriod: 10 * time.Second,\n\t\tRegisterRetryCount:      10,\n\t\tPodEvictionTimeout:      5 * time.Minute,\n\t\tNodeMilliCPU:            1000,\n\t\tNodeMemory:              resource.MustParse(\"3Gi\"),\n\t\tSyncNodeList:            true,\n\t\tKubeletConfig: client.KubeletConfig{\n\t\t\tPort:        ports.KubeletPort,\n\t\t\tEnableHttps: false,\n\t\t},\n\t}\n\treturn &s\n}\n\n\/\/ AddFlags adds flags for a specific CMServer to the specified FlagSet\nfunc (s *CMServer) AddFlags(fs *pflag.FlagSet) {\n\tfs.IntVar(&s.Port, \"port\", s.Port, \"The port that the controller-manager's http service runs on\")\n\tfs.Var(&s.Address, \"address\", \"The IP address to serve on (set to 0.0.0.0 for all interfaces)\")\n\tclient.BindClientConfigFlags(fs, &s.ClientConfig)\n\tfs.StringVar(&s.CloudProvider, \"cloud_provider\", s.CloudProvider, \"The provider for cloud services.  Empty string for no provider.\")\n\tfs.StringVar(&s.CloudConfigFile, \"cloud_config\", s.CloudConfigFile, \"The path to the cloud provider configuration file.  Empty string for no configuration file.\")\n\tfs.StringVar(&s.MinionRegexp, \"minion_regexp\", s.MinionRegexp, \"If non empty, and --cloud_provider is specified, a regular expression for matching minion VMs.\")\n\tfs.DurationVar(&s.NodeSyncPeriod, \"node_sync_period\", s.NodeSyncPeriod, \"\"+\n\t\t\"The period for syncing nodes from cloudprovider. Longer periods will result in \"+\n\t\t\"fewer calls to cloud provider, but may delay addition of new nodes to cluster.\")\n\tfs.DurationVar(&s.ResourceQuotaSyncPeriod, \"resource_quota_sync_period\", s.ResourceQuotaSyncPeriod, \"The period for syncing quota usage status in the system\")\n\tfs.DurationVar(&s.PodEvictionTimeout, \"pod_eviction_timeout\", s.PodEvictionTimeout, \"The grace peroid for deleting pods on failed nodes.\")\n\tfs.IntVar(&s.RegisterRetryCount, \"register_retry_count\", s.RegisterRetryCount, \"\"+\n\t\t\"The number of retries for initial node registration.  Retry interval equals node_sync_period.\")\n\tfs.Var(&s.MachineList, \"machines\", \"List of machines to schedule onto, comma separated.\")\n\tfs.BoolVar(&s.SyncNodeList, \"sync_nodes\", s.SyncNodeList, \"If true, and --cloud_provider is specified, sync nodes from the cloud provider. Default true.\")\n\t\/\/ TODO: Discover these by pinging the host machines, and rip out these flags.\n\t\/\/ TODO: in the meantime, use resource.QuantityFlag() instead of these\n\tfs.Int64Var(&s.NodeMilliCPU, \"node_milli_cpu\", s.NodeMilliCPU, \"The amount of MilliCPU provisioned on each node\")\n\tfs.Var(resource.NewQuantityFlagValue(&s.NodeMemory), \"node_memory\", \"The amount of memory (in bytes) provisioned on each node\")\n\tclient.BindKubeletClientConfigFlags(fs, &s.KubeletConfig)\n}\n\nfunc (s *CMServer) verifyMinionFlags() {\n\tif !s.SyncNodeList && s.MinionRegexp != \"\" {\n\t\tglog.Info(\"--minion_regexp is ignored by --sync_nodes=false\")\n\t}\n\tif s.CloudProvider == \"\" || s.MinionRegexp == \"\" {\n\t\tif len(s.MachineList) == 0 {\n\t\t\tglog.Info(\"No machines specified!\")\n\t\t}\n\t\treturn\n\t}\n\tif len(s.MachineList) != 0 {\n\t\tglog.Info(\"--machines is overwritten by --minion_regexp\")\n\t}\n}\n\n\/\/ Run runs the CMServer.  This should never exit.\nfunc (s *CMServer) Run(_ []string) error {\n\ts.verifyMinionFlags()\n\n\tif len(s.ClientConfig.Host) == 0 {\n\t\tglog.Fatal(\"usage: controller-manager --master <master>\")\n\t}\n\n\tkubeClient, err := client.New(&s.ClientConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid API configuration: %v\", err)\n\t}\n\n\tgo http.ListenAndServe(net.JoinHostPort(s.Address.String(), strconv.Itoa(s.Port)), nil)\n\n\tendpoints := service.NewEndpointController(kubeClient)\n\tgo util.Forever(func() { endpoints.SyncServiceEndpoints() }, time.Second*10)\n\n\tcontrollerManager := replicationControllerPkg.NewReplicationManager(kubeClient)\n\tcontrollerManager.Run(10 * time.Second)\n\n\tkubeletClient, err := client.NewKubeletClient(&s.KubeletConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failure to start kubelet client: %v\", err)\n\t}\n\n\tcloud := cloudprovider.InitCloudProvider(s.CloudProvider, s.CloudConfigFile)\n\tnodeResources := &api.NodeResources{\n\t\tCapacity: api.ResourceList{\n\t\t\tapi.ResourceCPU:    *resource.NewMilliQuantity(s.NodeMilliCPU, resource.DecimalSI),\n\t\t\tapi.ResourceMemory: s.NodeMemory,\n\t\t},\n\t}\n\n\tnodeController := nodeControllerPkg.NewNodeController(cloud, s.MinionRegexp, s.MachineList, nodeResources,\n\t\tkubeClient, kubeletClient, s.RegisterRetryCount, s.PodEvictionTimeout)\n\tnodeController.Run(s.NodeSyncPeriod, s.SyncNodeList)\n\n\tresourceQuotaManager := resourcequota.NewResourceQuotaManager(kubeClient)\n\tresourceQuotaManager.Run(s.ResourceQuotaSyncPeriod)\n\n\tselect {}\n\treturn nil\n}\n<commit_msg>Fix typo in comment: mail -> main<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\n\/\/ Package app implements a server that runs a set of active\n\/\/ components.  This includes replication controllers, service endpoints and\n\/\/ nodes.\npackage app\n\nimport (\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/resource\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/cloudprovider\"\n\tnodeControllerPkg \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/cloudprovider\/controller\"\n\treplicationControllerPkg \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/controller\"\n\t_ \"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/healthz\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/master\/ports\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/resourcequota\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/service\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/util\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/\/ CMServer is the main context object for the controller manager.\ntype CMServer struct {\n\tPort                    int\n\tAddress                 util.IP\n\tClientConfig            client.Config\n\tCloudProvider           string\n\tCloudConfigFile         string\n\tMinionRegexp            string\n\tNodeSyncPeriod          time.Duration\n\tResourceQuotaSyncPeriod time.Duration\n\tRegisterRetryCount      int\n\tMachineList             util.StringList\n\tSyncNodeList            bool\n\tPodEvictionTimeout      time.Duration\n\n\t\/\/ TODO: Discover these by pinging the host machines, and rip out these params.\n\tNodeMilliCPU int64\n\tNodeMemory   resource.Quantity\n\n\tKubeletConfig client.KubeletConfig\n}\n\n\/\/ NewCMServer creates a new CMServer with a default config.\nfunc NewCMServer() *CMServer {\n\ts := CMServer{\n\t\tPort:                    ports.ControllerManagerPort,\n\t\tAddress:                 util.IP(net.ParseIP(\"127.0.0.1\")),\n\t\tNodeSyncPeriod:          10 * time.Second,\n\t\tResourceQuotaSyncPeriod: 10 * time.Second,\n\t\tRegisterRetryCount:      10,\n\t\tPodEvictionTimeout:      5 * time.Minute,\n\t\tNodeMilliCPU:            1000,\n\t\tNodeMemory:              resource.MustParse(\"3Gi\"),\n\t\tSyncNodeList:            true,\n\t\tKubeletConfig: client.KubeletConfig{\n\t\t\tPort:        ports.KubeletPort,\n\t\t\tEnableHttps: false,\n\t\t},\n\t}\n\treturn &s\n}\n\n\/\/ AddFlags adds flags for a specific CMServer to the specified FlagSet\nfunc (s *CMServer) AddFlags(fs *pflag.FlagSet) {\n\tfs.IntVar(&s.Port, \"port\", s.Port, \"The port that the controller-manager's http service runs on\")\n\tfs.Var(&s.Address, \"address\", \"The IP address to serve on (set to 0.0.0.0 for all interfaces)\")\n\tclient.BindClientConfigFlags(fs, &s.ClientConfig)\n\tfs.StringVar(&s.CloudProvider, \"cloud_provider\", s.CloudProvider, \"The provider for cloud services.  Empty string for no provider.\")\n\tfs.StringVar(&s.CloudConfigFile, \"cloud_config\", s.CloudConfigFile, \"The path to the cloud provider configuration file.  Empty string for no configuration file.\")\n\tfs.StringVar(&s.MinionRegexp, \"minion_regexp\", s.MinionRegexp, \"If non empty, and --cloud_provider is specified, a regular expression for matching minion VMs.\")\n\tfs.DurationVar(&s.NodeSyncPeriod, \"node_sync_period\", s.NodeSyncPeriod, \"\"+\n\t\t\"The period for syncing nodes from cloudprovider. Longer periods will result in \"+\n\t\t\"fewer calls to cloud provider, but may delay addition of new nodes to cluster.\")\n\tfs.DurationVar(&s.ResourceQuotaSyncPeriod, \"resource_quota_sync_period\", s.ResourceQuotaSyncPeriod, \"The period for syncing quota usage status in the system\")\n\tfs.DurationVar(&s.PodEvictionTimeout, \"pod_eviction_timeout\", s.PodEvictionTimeout, \"The grace peroid for deleting pods on failed nodes.\")\n\tfs.IntVar(&s.RegisterRetryCount, \"register_retry_count\", s.RegisterRetryCount, \"\"+\n\t\t\"The number of retries for initial node registration.  Retry interval equals node_sync_period.\")\n\tfs.Var(&s.MachineList, \"machines\", \"List of machines to schedule onto, comma separated.\")\n\tfs.BoolVar(&s.SyncNodeList, \"sync_nodes\", s.SyncNodeList, \"If true, and --cloud_provider is specified, sync nodes from the cloud provider. Default true.\")\n\t\/\/ TODO: Discover these by pinging the host machines, and rip out these flags.\n\t\/\/ TODO: in the meantime, use resource.QuantityFlag() instead of these\n\tfs.Int64Var(&s.NodeMilliCPU, \"node_milli_cpu\", s.NodeMilliCPU, \"The amount of MilliCPU provisioned on each node\")\n\tfs.Var(resource.NewQuantityFlagValue(&s.NodeMemory), \"node_memory\", \"The amount of memory (in bytes) provisioned on each node\")\n\tclient.BindKubeletClientConfigFlags(fs, &s.KubeletConfig)\n}\n\nfunc (s *CMServer) verifyMinionFlags() {\n\tif !s.SyncNodeList && s.MinionRegexp != \"\" {\n\t\tglog.Info(\"--minion_regexp is ignored by --sync_nodes=false\")\n\t}\n\tif s.CloudProvider == \"\" || s.MinionRegexp == \"\" {\n\t\tif len(s.MachineList) == 0 {\n\t\t\tglog.Info(\"No machines specified!\")\n\t\t}\n\t\treturn\n\t}\n\tif len(s.MachineList) != 0 {\n\t\tglog.Info(\"--machines is overwritten by --minion_regexp\")\n\t}\n}\n\n\/\/ Run runs the CMServer.  This should never exit.\nfunc (s *CMServer) Run(_ []string) error {\n\ts.verifyMinionFlags()\n\n\tif len(s.ClientConfig.Host) == 0 {\n\t\tglog.Fatal(\"usage: controller-manager --master <master>\")\n\t}\n\n\tkubeClient, err := client.New(&s.ClientConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Invalid API configuration: %v\", err)\n\t}\n\n\tgo http.ListenAndServe(net.JoinHostPort(s.Address.String(), strconv.Itoa(s.Port)), nil)\n\n\tendpoints := service.NewEndpointController(kubeClient)\n\tgo util.Forever(func() { endpoints.SyncServiceEndpoints() }, time.Second*10)\n\n\tcontrollerManager := replicationControllerPkg.NewReplicationManager(kubeClient)\n\tcontrollerManager.Run(10 * time.Second)\n\n\tkubeletClient, err := client.NewKubeletClient(&s.KubeletConfig)\n\tif err != nil {\n\t\tglog.Fatalf(\"Failure to start kubelet client: %v\", err)\n\t}\n\n\tcloud := cloudprovider.InitCloudProvider(s.CloudProvider, s.CloudConfigFile)\n\tnodeResources := &api.NodeResources{\n\t\tCapacity: api.ResourceList{\n\t\t\tapi.ResourceCPU:    *resource.NewMilliQuantity(s.NodeMilliCPU, resource.DecimalSI),\n\t\t\tapi.ResourceMemory: s.NodeMemory,\n\t\t},\n\t}\n\n\tnodeController := nodeControllerPkg.NewNodeController(cloud, s.MinionRegexp, s.MachineList, nodeResources,\n\t\tkubeClient, kubeletClient, s.RegisterRetryCount, s.PodEvictionTimeout)\n\tnodeController.Run(s.NodeSyncPeriod, s.SyncNodeList)\n\n\tresourceQuotaManager := resourcequota.NewResourceQuotaManager(kubeClient)\n\tresourceQuotaManager.Run(s.ResourceQuotaSyncPeriod)\n\n\tselect {}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package defaults\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/goreleaser\/goreleaser\/config\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/testlib\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDescription(t *testing.T) {\n\tassert.NotEmpty(t, Pipe{}.String())\n}\n\nfunc TestFillBasicData(t *testing.T) {\n\t_, back := testlib.Mktmp(t)\n\tdefer back()\n\ttestlib.GitInit(t)\n\ttestlib.GitRemoteAdd(t, \"git@github.com:goreleaser\/goreleaser.git\")\n\n\tvar ctx = &context.Context{\n\t\tConfig: config.Project{},\n\t}\n\n\tassert.NoError(t, Pipe{}.Run(ctx))\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Release.GitHub.Owner)\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Release.GitHub.Name)\n\tassert.NotEmpty(t, ctx.Config.Builds)\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Builds[0].Binary)\n\tassert.Equal(t, \".\", ctx.Config.Builds[0].Main)\n\tassert.Contains(t, ctx.Config.Builds[0].Goos, \"darwin\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goos, \"linux\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goarch, \"386\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goarch, \"amd64\")\n\tassert.Equal(t, \"tar.gz\", ctx.Config.Archive.Format)\n\tassert.Contains(t, ctx.Config.Brew.Install, \"bin.install \\\"goreleaser\\\"\")\n\tassert.Empty(t, ctx.Config.Dockers)\n\tassert.Equal(t, \"https:\/\/github.com\", ctx.Config.GitHubURLs.Download)\n\tassert.NotEmpty(\n\t\tt,\n\t\tctx.Config.Archive.NameTemplate,\n\t\tctx.Config.Builds[0].Ldflags,\n\t\tctx.Config.Archive.Files,\n\t\tctx.Config.Dist,\n\t)\n}\n\nfunc TestFillPartial(t *testing.T) {\n\t_, back := testlib.Mktmp(t)\n\tdefer back()\n\ttestlib.GitInit(t)\n\ttestlib.GitRemoteAdd(t, \"git@github.com:goreleaser\/goreleaser.git\")\n\n\tvar ctx = &context.Context{\n\t\tConfig: config.Project{\n\t\t\tGitHubURLs: config.GitHubURLs{\n\t\t\t\tDownload: \"https:\/\/github.company.com\",\n\t\t\t},\n\t\t\tDist: \"disttt\",\n\t\t\tRelease: config.Release{\n\t\t\t\tGitHub: config.Repo{\n\t\t\t\t\tOwner: \"goreleaser\",\n\t\t\t\t\tName:  \"test\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tArchive: config.Archive{\n\t\t\t\tFiles: []string{\n\t\t\t\t\t\"glob\/*\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tBuilds: []config.Build{\n\t\t\t\t{Binary: \"testreleaser\"},\n\t\t\t\t{Goos: []string{\"linux\"}},\n\t\t\t\t{\n\t\t\t\t\tBinary: \"another\",\n\t\t\t\t\tIgnore: []config.IgnoredBuild{\n\t\t\t\t\t\t{Goos: \"darwin\", Goarch: \"amd64\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDockers: []config.Docker{\n\t\t\t\t{Image: \"a\/b\"},\n\t\t\t},\n\t\t},\n\t}\n\tassert.NoError(t, Pipe{}.Run(ctx))\n\tassert.Len(t, ctx.Config.Archive.Files, 1)\n\tassert.Equal(t, `bin.install \"testreleaser\"`, ctx.Config.Brew.Install)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Binary)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Goos)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Goarch)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Dockerfile)\n\tassert.Empty(t, ctx.Config.Dockers[0].Goarm)\n\tassert.Equal(t, \"disttt\", ctx.Config.Dist)\n\tassert.NotEqual(t, \"https:\/\/github.com\", ctx.Config.GitHubURLs.Download)\n}\n<commit_msg>test: Use multiple calls to assert.NotEmpty()<commit_after>package defaults\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/goreleaser\/goreleaser\/config\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/testlib\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDescription(t *testing.T) {\n\tassert.NotEmpty(t, Pipe{}.String())\n}\n\nfunc TestFillBasicData(t *testing.T) {\n\t_, back := testlib.Mktmp(t)\n\tdefer back()\n\ttestlib.GitInit(t)\n\ttestlib.GitRemoteAdd(t, \"git@github.com:goreleaser\/goreleaser.git\")\n\n\tvar ctx = &context.Context{\n\t\tConfig: config.Project{},\n\t}\n\n\tassert.NoError(t, Pipe{}.Run(ctx))\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Release.GitHub.Owner)\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Release.GitHub.Name)\n\tassert.NotEmpty(t, ctx.Config.Builds)\n\tassert.Equal(t, \"goreleaser\", ctx.Config.Builds[0].Binary)\n\tassert.Equal(t, \".\", ctx.Config.Builds[0].Main)\n\tassert.Contains(t, ctx.Config.Builds[0].Goos, \"darwin\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goos, \"linux\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goarch, \"386\")\n\tassert.Contains(t, ctx.Config.Builds[0].Goarch, \"amd64\")\n\tassert.Equal(t, \"tar.gz\", ctx.Config.Archive.Format)\n\tassert.Contains(t, ctx.Config.Brew.Install, \"bin.install \\\"goreleaser\\\"\")\n\tassert.Empty(t, ctx.Config.Dockers)\n\tassert.Equal(t, \"https:\/\/github.com\", ctx.Config.GitHubURLs.Download)\n\tassert.NotEmpty(t, ctx.Config.Archive.NameTemplate)\n\tassert.NotEmpty(t, ctx.Config.Builds[0].Ldflags)\n\tassert.NotEmpty(t, ctx.Config.Archive.Files)\n\tassert.NotEmpty(t, ctx.Config.Dist)\n}\n\nfunc TestFillPartial(t *testing.T) {\n\t_, back := testlib.Mktmp(t)\n\tdefer back()\n\ttestlib.GitInit(t)\n\ttestlib.GitRemoteAdd(t, \"git@github.com:goreleaser\/goreleaser.git\")\n\n\tvar ctx = &context.Context{\n\t\tConfig: config.Project{\n\t\t\tGitHubURLs: config.GitHubURLs{\n\t\t\t\tDownload: \"https:\/\/github.company.com\",\n\t\t\t},\n\t\t\tDist: \"disttt\",\n\t\t\tRelease: config.Release{\n\t\t\t\tGitHub: config.Repo{\n\t\t\t\t\tOwner: \"goreleaser\",\n\t\t\t\t\tName:  \"test\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tArchive: config.Archive{\n\t\t\t\tFiles: []string{\n\t\t\t\t\t\"glob\/*\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tBuilds: []config.Build{\n\t\t\t\t{Binary: \"testreleaser\"},\n\t\t\t\t{Goos: []string{\"linux\"}},\n\t\t\t\t{\n\t\t\t\t\tBinary: \"another\",\n\t\t\t\t\tIgnore: []config.IgnoredBuild{\n\t\t\t\t\t\t{Goos: \"darwin\", Goarch: \"amd64\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tDockers: []config.Docker{\n\t\t\t\t{Image: \"a\/b\"},\n\t\t\t},\n\t\t},\n\t}\n\tassert.NoError(t, Pipe{}.Run(ctx))\n\tassert.Len(t, ctx.Config.Archive.Files, 1)\n\tassert.Equal(t, `bin.install \"testreleaser\"`, ctx.Config.Brew.Install)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Binary)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Goos)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Goarch)\n\tassert.NotEmpty(t, ctx.Config.Dockers[0].Dockerfile)\n\tassert.Empty(t, ctx.Config.Dockers[0].Goarm)\n\tassert.Equal(t, \"disttt\", ctx.Config.Dist)\n\tassert.NotEqual(t, \"https:\/\/github.com\", ctx.Config.GitHubURLs.Download)\n}\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"archive\/zip\"\n\t\"fmt\"\n\t\"github.com\/viant\/toolbox\"\n\t\"io\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype CopyHandler func(sourceObject Object, source io.Reader, destinationService Service, destinationURL string) error\ntype ModificationHandler func(reader io.ReadCloser) (io.ReadCloser, error)\n\nfunc urlPath(URL string) string {\n\tvar result = URL\n\tschemaPosition := strings.Index(URL, \":\/\/\")\n\tif schemaPosition != -1 {\n\t\tresult = string(URL[schemaPosition+3:])\n\t}\n\tpathRoot := strings.Index(result, \"\/\")\n\tif pathRoot > 0 {\n\t\tresult = string(result[pathRoot:])\n\t}\n\tif strings.HasSuffix(result, \"\/\") {\n\t\tresult = string(result[:len(result)-1])\n\t}\n\n\treturn result\n}\n\n\n\nfunc copyData(sourceService Service, sourceURL string, destinationService Service, destinationURL string, modifyContentHandler ModificationHandler, subPath string, copyHandler CopyHandler) error {\n\tsourceListURL := sourceURL\n\tif subPath != \"\" {\n\t\tsourceListURL = toolbox.URLPathJoin(sourceURL, subPath)\n\t}\n\tobjects, err := sourceService.List(sourceListURL)\n\tvar objectRelativePath string\n\tsourceURLPath := urlPath(sourceURL)\n\tfor _, object := range objects {\n\t\tvar objectURLPath = urlPath(object.URL())\n\t\tif object.IsFolder() {\n\n\t\t\tif sourceURLPath == objectURLPath {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif subPath != \"\" && objectURLPath == toolbox.URLPathJoin(sourceURLPath, subPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif len(objectURLPath) > len(sourceURLPath) {\n\t\t\tobjectRelativePath = objectURLPath[len(sourceURLPath):]\n\t\t\tif strings.HasPrefix(objectRelativePath, \"\/\") {\n\t\t\t\tobjectRelativePath = string(objectRelativePath[1:])\n\t\t\t}\n\t\t}\n\t\tvar destinationObjectURL = destinationURL\n\t\tif objectRelativePath != \"\" {\n\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationURL, objectRelativePath)\n\t\t}\n\t\tif object.IsContent() {\n\t\t\treader, err := sourceService.Download(object)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"unable download, %v -> %v, %v\", object.URL(), destinationObjectURL, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer reader.Close()\n\t\t\tif modifyContentHandler != nil {\n\t\t\t\treader, err = modifyContentHandler(reader)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"unable modify content, %v %v %v\", object.URL(), destinationObjectURL, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subPath == \"\" {\n\t\t\t\t_, sourceName := path.Split(object.URL())\n\t\t\t\t_, destinationName := path.Split(destinationURL)\n\t\t\t\tif strings.HasSuffix(destinationObjectURL, \"\/\") {\n\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationObjectURL, sourceName)\n\t\t\t\t} else {\n\t\t\t\t\tdestinationObject, _ := destinationService.StorageObject(destinationObjectURL)\n\t\t\t\t\tif destinationObject != nil && destinationObject.IsFolder() {\n\t\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationObjectURL, sourceName)\n\t\t\t\t\t} else if destinationName != sourceName {\n\t\t\t\t\t\tif !strings.Contains(destinationName, \".\") {\n\t\t\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationURL, sourceName)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = copyHandler(object, reader, destinationService, destinationObjectURL)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t} else {\n\t\t\terr = copyData(sourceService, sourceURL, destinationService, destinationURL, modifyContentHandler, objectRelativePath, copyHandler)\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 copySourceToDestination(sourceObject Object, reader io.Reader, destinationService Service, destinationURL string) error {\n\terr := destinationService.Upload(destinationURL, reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable upload, %v %v %v\", sourceObject.URL(), destinationURL, err)\n\t}\n\treturn err\n}\n\nfunc addPathIfNeeded(directories map[string]bool, path string, archive zip.Writer) {\n\tif path == \"\" {\n\t\treturn\n\t}\n\tif _, has := directories[path]; has {\n\t\treturn\n\t}\n\n}\n\nfunc getArchiveCopyHandler(archive zip.Writer, parentURL string) CopyHandler {\n\tvar directories = make(map[string]bool)\n\treturn func(sourceObject Object, reader io.Reader, destinationService Service, destinationURL string) error {\n\t\tvar _, relativePath = toolbox.URLSplit(destinationURL)\n\t\tif destinationURL != parentURL {\n\t\t\trelativePath = strings.Replace(destinationURL, parentURL, \"\", 1)\n\t\t\tvar parent, _ = path.Split(relativePath)\n\t\t\taddPathIfNeeded(directories, parent, archive)\n\t\t}\n\t\theader, err := zip.FileInfoHeader(sourceObject.FileInfo())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\theader.Method = zip.Deflate\n\t\theader.Name = relativePath\n\t\twriter, err := archive.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(writer, reader)\n\t\treturn err\n\t}\n}\n\n\/\/Copy downloads objects from source URL to upload them to destination URL.\nfunc Copy(sourceService Service, sourceURL string, destinationService Service, destinationURL string, modifyContentHandler ModificationHandler, copyHandler CopyHandler) (err error) {\n\tif copyHandler == nil {\n\t\tcopyHandler = copySourceToDestination\n\t}\n\terr = copyData(sourceService, sourceURL, destinationService, destinationURL, modifyContentHandler, \"\", copyHandler)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to copy %v -> %v: %v\", sourceURL, destinationURL, err)\n\t}\n\treturn err\n}\n<commit_msg>change name<commit_after>package storage\n\nimport (\n\t\"archive\/zip\"\n\t\"fmt\"\n\t\"github.com\/viant\/toolbox\"\n\t\"io\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype CopyHandler func(sourceObject Object, source io.Reader, destinationService Service, destinationURL string) error\ntype ModificationHandler func(reader io.ReadCloser) (io.ReadCloser, error)\n\nfunc urlPath(URL string) string {\n\tvar result = URL\n\tschemaPosition := strings.Index(URL, \":\/\/\")\n\tif schemaPosition != -1 {\n\t\tresult = string(URL[schemaPosition+3:])\n\t}\n\tpathRoot := strings.Index(result, \"\/\")\n\tif pathRoot > 0 {\n\t\tresult = string(result[pathRoot:])\n\t}\n\tif strings.HasSuffix(result, \"\/\") {\n\t\tresult = string(result[:len(result)-1])\n\t}\n\n\treturn result\n}\n\n\n\nfunc copyStorageContent(sourceService Service, sourceURL string, destinationService Service, destinationURL string, modifyContentHandler ModificationHandler, subPath string, copyHandler CopyHandler) error {\n\tsourceListURL := sourceURL\n\tif subPath != \"\" {\n\t\tsourceListURL = toolbox.URLPathJoin(sourceURL, subPath)\n\t}\n\tobjects, err := sourceService.List(sourceListURL)\n\tvar objectRelativePath string\n\tsourceURLPath := urlPath(sourceURL)\n\tfor _, object := range objects {\n\t\tvar objectURLPath = urlPath(object.URL())\n\t\tif object.IsFolder() {\n\n\t\t\tif sourceURLPath == objectURLPath {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif subPath != \"\" && objectURLPath == toolbox.URLPathJoin(sourceURLPath, subPath) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif len(objectURLPath) > len(sourceURLPath) {\n\t\t\tobjectRelativePath = objectURLPath[len(sourceURLPath):]\n\t\t\tif strings.HasPrefix(objectRelativePath, \"\/\") {\n\t\t\t\tobjectRelativePath = string(objectRelativePath[1:])\n\t\t\t}\n\t\t}\n\t\tvar destinationObjectURL = destinationURL\n\t\tif objectRelativePath != \"\" {\n\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationURL, objectRelativePath)\n\t\t}\n\t\tif object.IsContent() {\n\t\t\treader, err := sourceService.Download(object)\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"unable download, %v -> %v, %v\", object.URL(), destinationObjectURL, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer reader.Close()\n\t\t\tif modifyContentHandler != nil {\n\t\t\t\treader, err = modifyContentHandler(reader)\n\t\t\t\tif err != nil {\n\t\t\t\t\terr = fmt.Errorf(\"unable modify content, %v %v %v\", object.URL(), destinationObjectURL, err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subPath == \"\" {\n\t\t\t\t_, sourceName := path.Split(object.URL())\n\t\t\t\t_, destinationName := path.Split(destinationURL)\n\t\t\t\tif strings.HasSuffix(destinationObjectURL, \"\/\") {\n\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationObjectURL, sourceName)\n\t\t\t\t} else {\n\t\t\t\t\tdestinationObject, _ := destinationService.StorageObject(destinationObjectURL)\n\t\t\t\t\tif destinationObject != nil && destinationObject.IsFolder() {\n\t\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationObjectURL, sourceName)\n\t\t\t\t\t} else if destinationName != sourceName {\n\t\t\t\t\t\tif !strings.Contains(destinationName, \".\") {\n\t\t\t\t\t\t\tdestinationObjectURL = toolbox.URLPathJoin(destinationURL, sourceName)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = copyHandler(object, reader, destinationService, destinationObjectURL)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t} else {\n\t\t\terr = copyStorageContent(sourceService, sourceURL, destinationService, destinationURL, modifyContentHandler, objectRelativePath, copyHandler)\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 copySourceToDestination(sourceObject Object, reader io.Reader, destinationService Service, destinationURL string) error {\n\terr := destinationService.Upload(destinationURL, reader)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable upload, %v %v %v\", sourceObject.URL(), destinationURL, err)\n\t}\n\treturn err\n}\n\nfunc addPathIfNeeded(directories map[string]bool, path string, archive zip.Writer) {\n\tif path == \"\" {\n\t\treturn\n\t}\n\tif _, has := directories[path]; has {\n\t\treturn\n\t}\n\n}\n\nfunc getArchiveCopyHandler(archive zip.Writer, parentURL string) CopyHandler {\n\tvar directories = make(map[string]bool)\n\treturn func(sourceObject Object, reader io.Reader, destinationService Service, destinationURL string) error {\n\t\tvar _, relativePath = toolbox.URLSplit(destinationURL)\n\t\tif destinationURL != parentURL {\n\t\t\trelativePath = strings.Replace(destinationURL, parentURL, \"\", 1)\n\t\t\tvar parent, _ = path.Split(relativePath)\n\t\t\taddPathIfNeeded(directories, parent, archive)\n\t\t}\n\t\theader, err := zip.FileInfoHeader(sourceObject.FileInfo())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\theader.Method = zip.Deflate\n\t\theader.Name = relativePath\n\t\twriter, err := archive.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(writer, reader)\n\t\treturn err\n\t}\n}\n\n\/\/Copy downloads objects from source URL to upload them to destination URL.\nfunc Copy(sourceService Service, sourceURL string, destinationService Service, destinationURL string, modifyContentHandler ModificationHandler, copyHandler CopyHandler) (err error) {\n\tif copyHandler == nil {\n\t\tcopyHandler = copySourceToDestination\n\t}\n\terr = copyStorageContent(sourceService, sourceURL, destinationService, destinationURL, modifyContentHandler, \"\", copyHandler)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to copy %v -> %v: %v\", sourceURL, destinationURL, err)\n\t}\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2016 Confluent 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\n\/\/ kafka client.\n\/\/ This package implements high-level Apache Kafka producer and consumers\n\/\/ using bindings on-top of the C librdkafka library.\npackage kafka\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\n\/*\n#include <librdkafka\/rdkafka.h>\n#include <stdlib.h>\n*\/\nimport \"C\"\n\ntype Handle interface {\n\tget_handle() *handle\n}\n\n\/\/ Common instance handle for both Producer and Consumer\ntype handle struct {\n\trk  *C.rd_kafka_t\n\trkq *C.rd_kafka_queue_t\n\n\t\/\/ Termination of background go-routines\n\tterminated_chan chan string \/\/ string is go-routine name\n\n\t\/\/ Topic <-> rkt caches\n\trkt_cache_lock sync.Mutex\n\t\/\/ topic name -> rkt cache\n\trkt_cache map[string]*C.rd_kafka_topic_t\n\t\/\/ rkt -> topic name cache\n\trkt_name_cache map[*C.rd_kafka_topic_t]string\n\n\t\/\/\n\t\/\/ cgo map\n\t\/\/ Maps C callbacks based on cgoid back to its Go object\n\tcgo_lock   sync.Mutex\n\tcgoid_next uintptr\n\tcgomap     map[uintptr]cgoif\n\n\t\/\/\n\t\/\/ producer\n\t\/\/\n\tp *Producer\n\n\t\/\/ Forward delivery reports on Producer.Events channel\n\tfwd_dr bool\n\n\t\/\/\n\t\/\/ consumer\n\t\/\/\n\tc *Consumer\n\n\t\/\/ Forward rebalancing ack responsibility to application (current setting)\n\tcurr_app_rebalance_enable bool\n}\n\nfunc (h *handle) String() string {\n\treturn C.GoString(C.rd_kafka_name(h.rk))\n}\n\nfunc (h *handle) setup() {\n\th.rkt_cache = make(map[string]*C.rd_kafka_topic_t)\n\th.rkt_name_cache = make(map[*C.rd_kafka_topic_t]string)\n\n\th.terminated_chan = make(chan string, 10)\n}\n\nfunc (h *handle) cleanup() {\n\tfor _, c_rkt := range h.rkt_cache {\n\t\tC.rd_kafka_topic_destroy(c_rkt)\n\t}\n\n\tif h.rkq != nil {\n\t\tC.rd_kafka_queue_destroy(h.rkq)\n\t}\n}\n\n\/\/ wait_terminated waits termination of background go-routines.\n\/\/ term_cnt is the number of goroutines expected to signal termination completion\n\/\/ on h.terminated_chan\nfunc (h *handle) wait_terminated(term_cnt int) {\n\t\/\/ Wait for term_cnt termination-done events from goroutines\n\tfor ; term_cnt > 0; term_cnt -= 1 {\n\t\t_ = <-h.terminated_chan\n\t}\n}\n\n\/\/ get_rkt0 finds or creates and returns a C topic_t object from the local cache.\nfunc (h *handle) get_rkt0(topic string, c_topic *C.char, do_lock bool) (c_rkt *C.rd_kafka_topic_t) {\n\tif do_lock {\n\t\th.rkt_cache_lock.Lock()\n\t}\n\tc_rkt, ok := h.rkt_cache[topic]\n\tif ok {\n\t\tif do_lock {\n\t\t\th.rkt_cache_lock.Unlock()\n\t\t}\n\t\treturn c_rkt\n\t}\n\n\tif c_topic == nil {\n\t\tc_topic = C.CString(topic)\n\t\tdefer C.free(unsafe.Pointer(c_topic))\n\t}\n\n\tc_rkt = C.rd_kafka_topic_new(h.rk, c_topic, nil)\n\tif c_rkt == nil {\n\t\tpanic(fmt.Sprintf(\"Unable to create now C topic \\\"%s\\\": %s\",\n\t\t\ttopic, C.GoString(C.rd_kafka_err2str(C.rd_kafka_last_error()))))\n\t}\n\n\th.rkt_cache[topic] = c_rkt\n\th.rkt_name_cache[c_rkt] = topic\n\n\tif do_lock {\n\t\th.rkt_cache_lock.Unlock()\n\t}\n\n\treturn c_rkt\n}\n\n\/\/ get_rkt finds or creates and returns a C topic_t object from the local cache.\nfunc (h *handle) get_rkt(topic string) (c_rkt *C.rd_kafka_topic_t) {\n\treturn h.get_rkt0(topic, nil, true)\n}\n\n\/\/ get_topic_name_from_rkt returns the topic name for a C topic_t object, preferably\n\/\/ using the local cache to avoid a cgo call.\nfunc (h *handle) get_topic_name_from_rkt(c_rkt *C.rd_kafka_topic_t) (topic string) {\n\th.rkt_cache_lock.Lock()\n\ttopic, ok := h.rkt_name_cache[c_rkt]\n\tif ok {\n\t\th.rkt_cache_lock.Unlock()\n\t\treturn topic\n\t}\n\n\t\/\/ we need our own copy\/refcount of the c_rkt\n\tc_topic := C.rd_kafka_topic_name(c_rkt)\n\ttopic = C.GoString(c_topic)\n\n\tc_rkt = h.get_rkt0(topic, c_topic, false \/* dont lock *\/)\n\th.rkt_cache_lock.Unlock()\n\n\treturn topic\n}\n\n\/\/ cgoif is a generic interface for holding Go state passed as opaque\n\/\/ value to the C code.\n\/\/ Since pointers to complex Go types cannot be passed to C we instead create\n\/\/ a cgoif object, generate a unique id that is added to the cgomap,\n\/\/ and then pass that id to the C code. When the C code callback is called we\n\/\/ use the id to look up the cgoif object in the cgomap.\ntype cgoif interface{}\n\n\/\/ delivery report cgoif container\ntype cgo_dr struct {\n\tdelivery_chan chan Event\n\topaque        *interface{}\n}\n\n\/\/ cgo_put adds object cg to the handle's cgo map and returns a\n\/\/ unique id for the added entry.\n\/\/ Thread-safe.\n\/\/ FIXME: the uniquity of the id is questionable over time.\nfunc (h *handle) cgo_put(cg cgoif) (cgoid uintptr) {\n\th.cgo_lock.Lock()\n\th.cgoid_next += 1\n\tif h.cgoid_next == 0 {\n\t\th.cgoid_next += 1\n\t}\n\tcgoid = h.cgoid_next\n\th.cgomap[cgoid] = cg\n\th.cgo_lock.Unlock()\n\treturn cgoid\n}\n\n\/\/ cgo_get looks up cgoid in the cgo map, deletes the reference from the map\n\/\/ and returns the object, if found. Else returns nil, false.\n\/\/ Thread-safe.\nfunc (h *handle) cgo_get(cgoid uintptr) (cg cgoif, found bool) {\n\tif cgoid == 0 {\n\t\treturn nil, false\n\t}\n\n\th.cgo_lock.Lock()\n\tcg, found = h.cgomap[cgoid]\n\tif found {\n\t\tdelete(h.cgomap, cgoid)\n\t}\n\th.cgo_lock.Unlock()\n\treturn cg, found\n}\n<commit_msg>Use defer to Unlock<commit_after>\/**\n * Copyright 2016 Confluent 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\n\/\/ kafka client.\n\/\/ This package implements high-level Apache Kafka producer and consumers\n\/\/ using bindings on-top of the C librdkafka library.\npackage kafka\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\n\/*\n#include <librdkafka\/rdkafka.h>\n#include <stdlib.h>\n*\/\nimport \"C\"\n\ntype Handle interface {\n\tget_handle() *handle\n}\n\n\/\/ Common instance handle for both Producer and Consumer\ntype handle struct {\n\trk  *C.rd_kafka_t\n\trkq *C.rd_kafka_queue_t\n\n\t\/\/ Termination of background go-routines\n\tterminated_chan chan string \/\/ string is go-routine name\n\n\t\/\/ Topic <-> rkt caches\n\trkt_cache_lock sync.Mutex\n\t\/\/ topic name -> rkt cache\n\trkt_cache map[string]*C.rd_kafka_topic_t\n\t\/\/ rkt -> topic name cache\n\trkt_name_cache map[*C.rd_kafka_topic_t]string\n\n\t\/\/\n\t\/\/ cgo map\n\t\/\/ Maps C callbacks based on cgoid back to its Go object\n\tcgo_lock   sync.Mutex\n\tcgoid_next uintptr\n\tcgomap     map[uintptr]cgoif\n\n\t\/\/\n\t\/\/ producer\n\t\/\/\n\tp *Producer\n\n\t\/\/ Forward delivery reports on Producer.Events channel\n\tfwd_dr bool\n\n\t\/\/\n\t\/\/ consumer\n\t\/\/\n\tc *Consumer\n\n\t\/\/ Forward rebalancing ack responsibility to application (current setting)\n\tcurr_app_rebalance_enable bool\n}\n\nfunc (h *handle) String() string {\n\treturn C.GoString(C.rd_kafka_name(h.rk))\n}\n\nfunc (h *handle) setup() {\n\th.rkt_cache = make(map[string]*C.rd_kafka_topic_t)\n\th.rkt_name_cache = make(map[*C.rd_kafka_topic_t]string)\n\n\th.terminated_chan = make(chan string, 10)\n}\n\nfunc (h *handle) cleanup() {\n\tfor _, c_rkt := range h.rkt_cache {\n\t\tC.rd_kafka_topic_destroy(c_rkt)\n\t}\n\n\tif h.rkq != nil {\n\t\tC.rd_kafka_queue_destroy(h.rkq)\n\t}\n}\n\n\/\/ wait_terminated waits termination of background go-routines.\n\/\/ term_cnt is the number of goroutines expected to signal termination completion\n\/\/ on h.terminated_chan\nfunc (h *handle) wait_terminated(term_cnt int) {\n\t\/\/ Wait for term_cnt termination-done events from goroutines\n\tfor ; term_cnt > 0; term_cnt -= 1 {\n\t\t_ = <-h.terminated_chan\n\t}\n}\n\n\/\/ get_rkt0 finds or creates and returns a C topic_t object from the local cache.\nfunc (h *handle) get_rkt0(topic string, c_topic *C.char, do_lock bool) (c_rkt *C.rd_kafka_topic_t) {\n\tif do_lock {\n\t\th.rkt_cache_lock.Lock()\n\t\tdefer h.rkt_cache_lock.Unlock()\n\t}\n\tc_rkt, ok := h.rkt_cache[topic]\n\tif ok {\n\t\treturn c_rkt\n\t}\n\n\tif c_topic == nil {\n\t\tc_topic = C.CString(topic)\n\t\tdefer C.free(unsafe.Pointer(c_topic))\n\t}\n\n\tc_rkt = C.rd_kafka_topic_new(h.rk, c_topic, nil)\n\tif c_rkt == nil {\n\t\tpanic(fmt.Sprintf(\"Unable to create now C topic \\\"%s\\\": %s\",\n\t\t\ttopic, C.GoString(C.rd_kafka_err2str(C.rd_kafka_last_error()))))\n\t}\n\n\th.rkt_cache[topic] = c_rkt\n\th.rkt_name_cache[c_rkt] = topic\n\n\treturn c_rkt\n}\n\n\/\/ get_rkt finds or creates and returns a C topic_t object from the local cache.\nfunc (h *handle) get_rkt(topic string) (c_rkt *C.rd_kafka_topic_t) {\n\treturn h.get_rkt0(topic, nil, true)\n}\n\n\/\/ get_topic_name_from_rkt returns the topic name for a C topic_t object, preferably\n\/\/ using the local cache to avoid a cgo call.\nfunc (h *handle) get_topic_name_from_rkt(c_rkt *C.rd_kafka_topic_t) (topic string) {\n\th.rkt_cache_lock.Lock()\n\tdefer h.rkt_cache_lock.Unlock()\n\n\ttopic, ok := h.rkt_name_cache[c_rkt]\n\tif ok {\n\t\treturn topic\n\t}\n\n\t\/\/ we need our own copy\/refcount of the c_rkt\n\tc_topic := C.rd_kafka_topic_name(c_rkt)\n\ttopic = C.GoString(c_topic)\n\n\tc_rkt = h.get_rkt0(topic, c_topic, false \/* dont lock *\/)\n\n\treturn topic\n}\n\n\/\/ cgoif is a generic interface for holding Go state passed as opaque\n\/\/ value to the C code.\n\/\/ Since pointers to complex Go types cannot be passed to C we instead create\n\/\/ a cgoif object, generate a unique id that is added to the cgomap,\n\/\/ and then pass that id to the C code. When the C code callback is called we\n\/\/ use the id to look up the cgoif object in the cgomap.\ntype cgoif interface{}\n\n\/\/ delivery report cgoif container\ntype cgo_dr struct {\n\tdelivery_chan chan Event\n\topaque        *interface{}\n}\n\n\/\/ cgo_put adds object cg to the handle's cgo map and returns a\n\/\/ unique id for the added entry.\n\/\/ Thread-safe.\n\/\/ FIXME: the uniquity of the id is questionable over time.\nfunc (h *handle) cgo_put(cg cgoif) (cgoid uintptr) {\n\th.cgo_lock.Lock()\n\tdefer h.cgo_lock.Unlock()\n\n\th.cgoid_next += 1\n\tif h.cgoid_next == 0 {\n\t\th.cgoid_next += 1\n\t}\n\tcgoid = h.cgoid_next\n\th.cgomap[cgoid] = cg\n\treturn cgoid\n}\n\n\/\/ cgo_get looks up cgoid in the cgo map, deletes the reference from the map\n\/\/ and returns the object, if found. Else returns nil, false.\n\/\/ Thread-safe.\nfunc (h *handle) cgo_get(cgoid uintptr) (cg cgoif, found bool) {\n\tif cgoid == 0 {\n\t\treturn nil, false\n\t}\n\n\th.cgo_lock.Lock()\n\tdefer h.cgo_lock.Unlock()\n\tcg, found = h.cgomap[cgoid]\n\tif found {\n\t\tdelete(h.cgomap, cgoid)\n\t}\n\n\treturn cg, found\n}\n<|endoftext|>"}
{"text":"<commit_before>package operation\n\ntype Manifest struct {\n\tApplications []AppManifest `yaml:\"applications\"`\n}\n\ntype AppManifest struct {\n\tName                    string              `yaml:\"name\"`\n\tBuildpacks              []string            `yaml:\"buildpacks,omitempty\"`\n\tCommand                 string              `yaml:\"command,omitempty\"`\n\tDiskQuota               string              `yaml:\"disk_quota,omitempty\"`\n\tDocker                  *AppManifestDocker  `yaml:\"docker,omitempty\"`\n\tEnv                     map[string]string   `yaml:\"env,omitempty\"`\n\tHealthCheckType         string              `yaml:\"health-check-type,omitempty\"`\n\tHealthCheckHTTPEndpoint string              `yaml:\"health-check-http-endpoint,omitempty\"`\n\tInstances               int                 `yaml:\"instances,omitempty\"`\n\tLogRateLimit            string              `yaml:\"log-rate-limit,omitempty\"`\n\tMemory                  string              `yaml:\"memory,omitempty\"`\n\tNoRoute                 bool                `yaml:\"no-route,omitempty\"`\n\tRoutes                  []AppManifestRoutes `yaml:\"routes,omitempty\"`\n\tServices                []string            `yaml:\"services,omitempty\"`\n\tStack                   string              `yaml:\"stack,omitempty\"`\n\tTimeout                 int                 `yaml:\"timeout,omitempty\"`\n}\n\ntype AppManifestDocker struct {\n\tImage    string `yaml:\"image,omitempty\"`\n\tUsername string `yaml:\"username,omitempty\"`\n}\n\ntype AppManifestRoutes struct {\n\tRoute string `yaml:\"route,omitempty\"`\n}\n<commit_msg>Add pointer type ot apps array<commit_after>package operation\n\ntype Manifest struct {\n\tApplications []*AppManifest `yaml:\"applications\"`\n}\n\ntype AppManifest struct {\n\tName                    string              `yaml:\"name\"`\n\tBuildpacks              []string            `yaml:\"buildpacks,omitempty\"`\n\tCommand                 string              `yaml:\"command,omitempty\"`\n\tDiskQuota               string              `yaml:\"disk_quota,omitempty\"`\n\tDocker                  *AppManifestDocker  `yaml:\"docker,omitempty\"`\n\tEnv                     map[string]string   `yaml:\"env,omitempty\"`\n\tHealthCheckType         string              `yaml:\"health-check-type,omitempty\"`\n\tHealthCheckHTTPEndpoint string              `yaml:\"health-check-http-endpoint,omitempty\"`\n\tInstances               int                 `yaml:\"instances,omitempty\"`\n\tLogRateLimit            string              `yaml:\"log-rate-limit,omitempty\"`\n\tMemory                  string              `yaml:\"memory,omitempty\"`\n\tNoRoute                 bool                `yaml:\"no-route,omitempty\"`\n\tRoutes                  []AppManifestRoutes `yaml:\"routes,omitempty\"`\n\tServices                []string            `yaml:\"services,omitempty\"`\n\tStack                   string              `yaml:\"stack,omitempty\"`\n\tTimeout                 int                 `yaml:\"timeout,omitempty\"`\n}\n\ntype AppManifestDocker struct {\n\tImage    string `yaml:\"image,omitempty\"`\n\tUsername string `yaml:\"username,omitempty\"`\n}\n\ntype AppManifestRoutes struct {\n\tRoute string `yaml:\"route,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Add ZEROXDEL constant<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nfunc homepath(p string) string {\n\tif runtime.GOOS == \"windows\" {\n\t\treturn filepath.Join(os.Getenv(\"USERPROFILE\"), p)\n\t}\n\treturn filepath.Join(os.Getenv(\"HOME\"), p)\n}\n\nfunc getDiscovery(c *cli.Context) string {\n\tif len(c.Args()) == 1 {\n\t\treturn c.Args()[0]\n\t}\n\treturn os.Getenv(\"SWARM_DISCOVERY\")\n}\n\nvar (\n\tflStore = cli.StringFlag{\n\t\tName:  \"rootdir\",\n\t\tValue: homepath(\".swarm\"),\n\t\tUsage: \"\",\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\tflHosts = cli.StringSliceFlag{\n\t\tName:   \"host, H\",\n\t\tValue:  &cli.StringSlice{\"tcp:\/\/127.0.0.1:2375\"},\n\t\tUsage:  \"ip\/socket to listen on\",\n\t\tEnvVar: \"SWARM_HOST\",\n\t}\n\tflHeartBeat = cli.IntFlag{\n\t\tName:  \"heartbeat, hb\",\n\t\tValue: 25,\n\t\tUsage: \"time in second between each heartbeat\",\n\t}\n\tflEnableCors = cli.BoolFlag{\n\t\tName:  \"api-enable-cors, cors\",\n\t\tUsage: \"enable CORS headers in the remote API\",\n\t}\n\tflTls = cli.BoolFlag{\n\t\tName:  \"tls\",\n\t\tUsage: \"use TLS; implied by --tlsverify=true\",\n\t}\n\tflTlsCaCert = cli.StringFlag{\n\t\tName:  \"tlscacert\",\n\t\tUsage: \"trust only remotes providing a certificate signed by the CA given here\",\n\t}\n\tflTlsCert = cli.StringFlag{\n\t\tName:  \"tlscert\",\n\t\tUsage: \"path to TLS certificate file\",\n\t}\n\tflTlsKey = cli.StringFlag{\n\t\tName:  \"tlskey\",\n\t\tUsage: \"path to TLS key file\",\n\t}\n\tflTlsVerify = cli.BoolFlag{\n\t\tName:  \"tlsverify\",\n\t\tUsage: \"use TLS and verify the remote\",\n\t}\n\tflOverCommit = cli.Float64Flag{\n\t\tName:  \"overcommit, oc\",\n\t\tUsage: \"overcommit to apply on resources\",\n\t\tValue: 0.05,\n\t}\n\tflStrategy = cli.StringFlag{\n\t\tName:  \"strategy\",\n\t\tUsage: \"placement strategy to use [binpacking, random]\",\n\t\tValue: \"binpacking\",\n\t}\n\tflFilter = cli.StringSliceFlag{\n\t\tName:  \"filter, f\",\n\t\tUsage: \"filter to use [constraint, affinity, health, port]\",\n\t\tValue: &cli.StringSlice{\"constraint\", \"affinity\", \"health\", \"port\"},\n\t}\n)\n<commit_msg>flags: Cleanup the homepath() function.<commit_after>package main\n\nimport (\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nfunc homepath(p string) string {\n\thome := os.Getenv(\"HOME\")\n\tif runtime.GOOS == \"windows\" {\n\t\thome = os.Getenv(\"USERPROFILE\")\n\t}\n\treturn filepath.Join(home, p)\n}\n\nfunc getDiscovery(c *cli.Context) string {\n\tif len(c.Args()) == 1 {\n\t\treturn c.Args()[0]\n\t}\n\treturn os.Getenv(\"SWARM_DISCOVERY\")\n}\n\nvar (\n\tflStore = cli.StringFlag{\n\t\tName:  \"rootdir\",\n\t\tValue: homepath(\".swarm\"),\n\t\tUsage: \"\",\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\tflHosts = cli.StringSliceFlag{\n\t\tName:   \"host, H\",\n\t\tValue:  &cli.StringSlice{\"tcp:\/\/127.0.0.1:2375\"},\n\t\tUsage:  \"ip\/socket to listen on\",\n\t\tEnvVar: \"SWARM_HOST\",\n\t}\n\tflHeartBeat = cli.IntFlag{\n\t\tName:  \"heartbeat, hb\",\n\t\tValue: 25,\n\t\tUsage: \"time in second between each heartbeat\",\n\t}\n\tflEnableCors = cli.BoolFlag{\n\t\tName:  \"api-enable-cors, cors\",\n\t\tUsage: \"enable CORS headers in the remote API\",\n\t}\n\tflTls = cli.BoolFlag{\n\t\tName:  \"tls\",\n\t\tUsage: \"use TLS; implied by --tlsverify=true\",\n\t}\n\tflTlsCaCert = cli.StringFlag{\n\t\tName:  \"tlscacert\",\n\t\tUsage: \"trust only remotes providing a certificate signed by the CA given here\",\n\t}\n\tflTlsCert = cli.StringFlag{\n\t\tName:  \"tlscert\",\n\t\tUsage: \"path to TLS certificate file\",\n\t}\n\tflTlsKey = cli.StringFlag{\n\t\tName:  \"tlskey\",\n\t\tUsage: \"path to TLS key file\",\n\t}\n\tflTlsVerify = cli.BoolFlag{\n\t\tName:  \"tlsverify\",\n\t\tUsage: \"use TLS and verify the remote\",\n\t}\n\tflOverCommit = cli.Float64Flag{\n\t\tName:  \"overcommit, oc\",\n\t\tUsage: \"overcommit to apply on resources\",\n\t\tValue: 0.05,\n\t}\n\tflStrategy = cli.StringFlag{\n\t\tName:  \"strategy\",\n\t\tUsage: \"placement strategy to use [binpacking, random]\",\n\t\tValue: \"binpacking\",\n\t}\n\tflFilter = cli.StringSliceFlag{\n\t\tName:  \"filter, f\",\n\t\tUsage: \"filter to use [constraint, affinity, health, port]\",\n\t\tValue: &cli.StringSlice{\"constraint\", \"affinity\", \"health\", \"port\"},\n\t}\n)\n<|endoftext|>"}
{"text":"<commit_before>package mount \/\/ import \"github.com\/docker\/docker\/pkg\/mount\"\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar flags = map[string]struct {\n\tclear bool\n\tflag  int\n}{\n\t\"defaults\":      {false, 0},\n\t\"ro\":            {false, RDONLY},\n\t\"rw\":            {true, RDONLY},\n\t\"suid\":          {true, NOSUID},\n\t\"nosuid\":        {false, NOSUID},\n\t\"dev\":           {true, NODEV},\n\t\"nodev\":         {false, NODEV},\n\t\"exec\":          {true, NOEXEC},\n\t\"noexec\":        {false, NOEXEC},\n\t\"sync\":          {false, SYNCHRONOUS},\n\t\"async\":         {true, SYNCHRONOUS},\n\t\"dirsync\":       {false, DIRSYNC},\n\t\"remount\":       {false, REMOUNT},\n\t\"mand\":          {false, MANDLOCK},\n\t\"nomand\":        {true, MANDLOCK},\n\t\"atime\":         {true, NOATIME},\n\t\"noatime\":       {false, NOATIME},\n\t\"diratime\":      {true, NODIRATIME},\n\t\"nodiratime\":    {false, NODIRATIME},\n\t\"bind\":          {false, BIND},\n\t\"rbind\":         {false, RBIND},\n\t\"unbindable\":    {false, UNBINDABLE},\n\t\"runbindable\":   {false, RUNBINDABLE},\n\t\"private\":       {false, PRIVATE},\n\t\"rprivate\":      {false, RPRIVATE},\n\t\"shared\":        {false, SHARED},\n\t\"rshared\":       {false, RSHARED},\n\t\"slave\":         {false, SLAVE},\n\t\"rslave\":        {false, RSLAVE},\n\t\"relatime\":      {false, RELATIME},\n\t\"norelatime\":    {true, RELATIME},\n\t\"strictatime\":   {false, STRICTATIME},\n\t\"nostrictatime\": {true, STRICTATIME},\n}\n\nvar validFlags = map[string]bool{\n\t\"\":          true,\n\t\"size\":      true,\n\t\"mode\":      true,\n\t\"uid\":       true,\n\t\"gid\":       true,\n\t\"nr_inodes\": true,\n\t\"nr_blocks\": true,\n\t\"mpol\":      true,\n}\n\nvar propagationFlags = map[string]bool{\n\t\"bind\":        true,\n\t\"rbind\":       true,\n\t\"unbindable\":  true,\n\t\"runbindable\": true,\n\t\"private\":     true,\n\t\"rprivate\":    true,\n\t\"shared\":      true,\n\t\"rshared\":     true,\n\t\"slave\":       true,\n\t\"rslave\":      true,\n}\n\n\/\/ MergeTmpfsOptions merge mount options to make sure there is no duplicate.\nfunc MergeTmpfsOptions(options []string) ([]string, error) {\n\t\/\/ We use collisions maps to remove duplicates.\n\t\/\/ For flag, the key is the flag value (the key for propagation flag is -1)\n\t\/\/ For data=value, the key is the data\n\tflagCollisions := map[int]bool{}\n\tdataCollisions := map[string]bool{}\n\n\tvar newOptions []string\n\t\/\/ We process in reverse order\n\tfor i := len(options) - 1; i >= 0; i-- {\n\t\toption := options[i]\n\t\tif option == \"defaults\" {\n\t\t\tcontinue\n\t\t}\n\t\tif f, ok := flags[option]; ok && f.flag != 0 {\n\t\t\t\/\/ There is only one propagation mode\n\t\t\tkey := f.flag\n\t\t\tif propagationFlags[option] {\n\t\t\t\tkey = -1\n\t\t\t}\n\t\t\t\/\/ Check to see if there is collision for flag\n\t\t\tif !flagCollisions[key] {\n\t\t\t\t\/\/ We prepend the option and add to collision map\n\t\t\t\tnewOptions = append([]string{option}, newOptions...)\n\t\t\t\tflagCollisions[key] = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\topt := strings.SplitN(option, \"=\", 2)\n\t\tif len(opt) != 2 || !validFlags[opt[0]] {\n\t\t\treturn nil, fmt.Errorf(\"Invalid tmpfs option %q\", opt)\n\t\t}\n\t\tif !dataCollisions[opt[0]] {\n\t\t\t\/\/ We prepend the option and add to collision map\n\t\t\tnewOptions = append([]string{option}, newOptions...)\n\t\t\tdataCollisions[opt[0]] = true\n\t\t}\n\t}\n\n\treturn newOptions, nil\n}\n\n\/\/ Parse fstab type mount options into mount() flags\n\/\/ and device specific data\nfunc parseOptions(options string) (int, string) {\n\tvar (\n\t\tflag int\n\t\tdata []string\n\t)\n\n\tfor _, o := range strings.Split(options, \",\") {\n\t\t\/\/ If the option does not exist in the flags table or the flag\n\t\t\/\/ is not supported on the platform,\n\t\t\/\/ then it is a data value for a specific fs type\n\t\tif f, exists := flags[o]; exists && f.flag != 0 {\n\t\t\tif f.clear {\n\t\t\t\tflag &= ^f.flag\n\t\t\t} else {\n\t\t\t\tflag |= f.flag\n\t\t\t}\n\t\t} else {\n\t\t\tdata = append(data, o)\n\t\t}\n\t}\n\treturn flag, strings.Join(data, \",\")\n}\n\n\/\/ ParseTmpfsOptions parse fstab type mount options into flags and data\nfunc ParseTmpfsOptions(options string) (int, string, error) {\n\tflags, data := parseOptions(options)\n\tfor _, o := range strings.Split(data, \",\") {\n\t\topt := strings.SplitN(o, \"=\", 2)\n\t\tif !validFlags[opt[0]] {\n\t\t\treturn 0, \"\", fmt.Errorf(\"Invalid tmpfs option %q\", opt)\n\t\t}\n\t}\n\treturn flags, data, nil\n}\n<commit_msg>pkg\/mount: remove unused ParseTmpfsOptions<commit_after>package mount \/\/ import \"github.com\/docker\/docker\/pkg\/mount\"\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nvar flags = map[string]struct {\n\tclear bool\n\tflag  int\n}{\n\t\"defaults\":      {false, 0},\n\t\"ro\":            {false, RDONLY},\n\t\"rw\":            {true, RDONLY},\n\t\"suid\":          {true, NOSUID},\n\t\"nosuid\":        {false, NOSUID},\n\t\"dev\":           {true, NODEV},\n\t\"nodev\":         {false, NODEV},\n\t\"exec\":          {true, NOEXEC},\n\t\"noexec\":        {false, NOEXEC},\n\t\"sync\":          {false, SYNCHRONOUS},\n\t\"async\":         {true, SYNCHRONOUS},\n\t\"dirsync\":       {false, DIRSYNC},\n\t\"remount\":       {false, REMOUNT},\n\t\"mand\":          {false, MANDLOCK},\n\t\"nomand\":        {true, MANDLOCK},\n\t\"atime\":         {true, NOATIME},\n\t\"noatime\":       {false, NOATIME},\n\t\"diratime\":      {true, NODIRATIME},\n\t\"nodiratime\":    {false, NODIRATIME},\n\t\"bind\":          {false, BIND},\n\t\"rbind\":         {false, RBIND},\n\t\"unbindable\":    {false, UNBINDABLE},\n\t\"runbindable\":   {false, RUNBINDABLE},\n\t\"private\":       {false, PRIVATE},\n\t\"rprivate\":      {false, RPRIVATE},\n\t\"shared\":        {false, SHARED},\n\t\"rshared\":       {false, RSHARED},\n\t\"slave\":         {false, SLAVE},\n\t\"rslave\":        {false, RSLAVE},\n\t\"relatime\":      {false, RELATIME},\n\t\"norelatime\":    {true, RELATIME},\n\t\"strictatime\":   {false, STRICTATIME},\n\t\"nostrictatime\": {true, STRICTATIME},\n}\n\nvar validFlags = map[string]bool{\n\t\"\":          true,\n\t\"size\":      true,\n\t\"mode\":      true,\n\t\"uid\":       true,\n\t\"gid\":       true,\n\t\"nr_inodes\": true,\n\t\"nr_blocks\": true,\n\t\"mpol\":      true,\n}\n\nvar propagationFlags = map[string]bool{\n\t\"bind\":        true,\n\t\"rbind\":       true,\n\t\"unbindable\":  true,\n\t\"runbindable\": true,\n\t\"private\":     true,\n\t\"rprivate\":    true,\n\t\"shared\":      true,\n\t\"rshared\":     true,\n\t\"slave\":       true,\n\t\"rslave\":      true,\n}\n\n\/\/ MergeTmpfsOptions merge mount options to make sure there is no duplicate.\nfunc MergeTmpfsOptions(options []string) ([]string, error) {\n\t\/\/ We use collisions maps to remove duplicates.\n\t\/\/ For flag, the key is the flag value (the key for propagation flag is -1)\n\t\/\/ For data=value, the key is the data\n\tflagCollisions := map[int]bool{}\n\tdataCollisions := map[string]bool{}\n\n\tvar newOptions []string\n\t\/\/ We process in reverse order\n\tfor i := len(options) - 1; i >= 0; i-- {\n\t\toption := options[i]\n\t\tif option == \"defaults\" {\n\t\t\tcontinue\n\t\t}\n\t\tif f, ok := flags[option]; ok && f.flag != 0 {\n\t\t\t\/\/ There is only one propagation mode\n\t\t\tkey := f.flag\n\t\t\tif propagationFlags[option] {\n\t\t\t\tkey = -1\n\t\t\t}\n\t\t\t\/\/ Check to see if there is collision for flag\n\t\t\tif !flagCollisions[key] {\n\t\t\t\t\/\/ We prepend the option and add to collision map\n\t\t\t\tnewOptions = append([]string{option}, newOptions...)\n\t\t\t\tflagCollisions[key] = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\topt := strings.SplitN(option, \"=\", 2)\n\t\tif len(opt) != 2 || !validFlags[opt[0]] {\n\t\t\treturn nil, fmt.Errorf(\"Invalid tmpfs option %q\", opt)\n\t\t}\n\t\tif !dataCollisions[opt[0]] {\n\t\t\t\/\/ We prepend the option and add to collision map\n\t\t\tnewOptions = append([]string{option}, newOptions...)\n\t\t\tdataCollisions[opt[0]] = true\n\t\t}\n\t}\n\n\treturn newOptions, nil\n}\n\n\/\/ Parse fstab type mount options into mount() flags\n\/\/ and device specific data\nfunc parseOptions(options string) (int, string) {\n\tvar (\n\t\tflag int\n\t\tdata []string\n\t)\n\n\tfor _, o := range strings.Split(options, \",\") {\n\t\t\/\/ If the option does not exist in the flags table or the flag\n\t\t\/\/ is not supported on the platform,\n\t\t\/\/ then it is a data value for a specific fs type\n\t\tif f, exists := flags[o]; exists && f.flag != 0 {\n\t\t\tif f.clear {\n\t\t\t\tflag &= ^f.flag\n\t\t\t} else {\n\t\t\t\tflag |= f.flag\n\t\t\t}\n\t\t} else {\n\t\t\tdata = append(data, o)\n\t\t}\n\t}\n\treturn flag, strings.Join(data, \",\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package flenv\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"net\/url\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar ErrNotStruct = errors.New(\"Attempted to decode into a value that was not a pointer to struct\")\nvar ErrUnsupportedFlagType = errors.New(\"Unsupported flag type\")\n\nfunc DecodeArgs(result interface{}) (*flag.FlagSet, error) {\n\treturn Decode(result, os.Args)\n}\n\nfunc Decode(result interface{}, args []string) (*flag.FlagSet, error) {\n\tflagSet := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\n\tval := reflect.ValueOf(result)\n\tif val.Kind() != reflect.Ptr {\n\t\treturn nil, ErrNotStruct\n\t}\n\n\tst := val.Elem()\n\tif st.Kind() != reflect.Struct {\n\t\treturn nil, ErrNotStruct\n\t}\n\n\ttyp := val.Elem().Type()\n\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield := st.Field(i)\n\t\ttypeField := typ.Field(i)\n\n\t\t\/\/ Get env tag.\n\t\tenvName := typeField.Tag.Get(\"env\")\n\t\tdefaultValue := typeField.Tag.Get(\"default\")\n\n\t\t\/\/ Set the value to the default value\n\t\tif err := setValue(field, envName, defaultValue); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ If there's a flag associated, we need to set that up, possibly with a default.\n\t\tflagNames := decodeFlagTag(typeField.Tag.Get(\"flag\"))\n\t\tflagHelp := typeField.Tag.Get(\"help\")\n\t\tif len(flagNames) > 0 {\n\t\t\taddFlag(flagSet, field, flagNames, flagHelp)\n\t\t}\n\t}\n\n\treturn flagSet, flagSet.Parse(args)\n}\n\nfunc decodeFlagTag(tag string) (names []string) {\n\tbits := strings.Split(tag, \",\")\n\tout := make([]string, 0, len(bits))\n\tfor _, bit := range bits {\n\t\ttrimmed := strings.TrimLeft(bit, \"-\")\n\t\tif len(trimmed) > 0 {\n\t\t\tout = append(out, trimmed)\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc addFlag(flagSet *flag.FlagSet, field reflect.Value, names []string, help string) error {\n\tfor _, name := range names {\n\t\tswitch field.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tflagSet.BoolVar(field.Addr().Interface().(*bool), name, field.Bool(), help)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tflagSet.Float64Var(field.Addr().Interface().(*float64), name, field.Float(), help)\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:\n\t\t\tflagSet.IntVar(field.Addr().Interface().(*int), name, int(field.Int()), help)\n\t\tcase reflect.Int64:\n\t\t\tif t := field.Type(); t.PkgPath() == \"time\" && t.Name() == \"Duration\" {\n\t\t\t\tflagSet.DurationVar(field.Addr().Interface().(*time.Duration), name, time.Duration(field.Int()), help)\n\t\t\t} else {\n\t\t\t\tflagSet.Int64Var(field.Addr().Interface().(*int64), name, field.Int(), help)\n\t\t\t}\n\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\tflagSet.Uint64Var(field.Addr().Interface().(*uint64), name, field.Uint(), help)\n\t\tcase reflect.String:\n\t\t\tflagSet.StringVar(field.Addr().Interface().(*string), name, field.String(), help)\n\t\tdefault:\n\t\t\t\/\/ TODO: We can make a URL parser, but not right now.\n\t\t\treturn ErrUnsupportedFlagType\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc setValue(field reflect.Value, name, def string) error {\n\ttmp := os.Getenv(name)\n\tif tmp == \"\" {\n\t\ttmp = def\n\t}\n\n\tif tmp == \"\" {\n\t\treturn nil\n\t}\n\n\tswitch field.Kind() {\n\tcase reflect.Bool:\n\t\tv, err := strconv.ParseBool(tmp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetBool(v)\n\n\tcase reflect.Float32, reflect.Float64:\n\t\tbits := field.Type().Bits()\n\t\tv, err := strconv.ParseFloat(tmp, bits)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetFloat(v)\n\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tif t := field.Type(); t.PkgPath() == \"time\" && t.Name() == \"Duration\" {\n\t\t\tv, err := time.ParseDuration(tmp)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfield.SetInt(int64(v))\n\n\t\t} else {\n\t\t\tbits := field.Type().Bits()\n\t\t\tv, err := strconv.ParseInt(tmp, 0, bits)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfield.SetInt(v)\n\t\t}\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tbits := field.Type().Bits()\n\t\tv, err := strconv.ParseUint(tmp, 0, bits)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetUint(v)\n\n\tcase reflect.String:\n\t\tfield.SetString(tmp)\n\n\tcase reflect.Ptr:\n\t\tif t := field.Type().Elem(); t.Kind() == reflect.Struct && t.PkgPath() == \"net\/url\" && t.Name() == \"URL\" {\n\t\t\tv, err := url.Parse(tmp)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfield.Set(reflect.ValueOf(v))\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Add documentation to Decode<commit_after>package flenv\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"net\/url\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ ErrNotStruct is an error\nvar ErrNotStruct = errors.New(\"Attempted to decode into a value that was not a pointer to struct\")\n\n\/\/ ErrNotStruct is an error\nvar ErrUnsupportedFlagType = errors.New(\"Unsupported flag type\")\n\n\/\/ DecodeArgs runs decode with os.Args\nfunc DecodeArgs(result interface{}) (*flag.FlagSet, error) {\n\treturn Decode(result, os.Args)\n}\n\n\/\/ Decode attempts to populate result, based on struct tags from args and the environment\n\/\/\n\/\/ `result` should be a struct with at least one of the following tags\n\/\/\n\/\/    env:\"ENVIRONMENT_VARIABLE\"\n\/\/    flag:\"--environment-variable\"\n\/\/\n\/\/ Additionally, the following tags are also allowed\n\/\/\n\/\/    help:\"help text for flag parsing\"\n\/\/    default:\"default value\"\nfunc Decode(result interface{}, args []string) (*flag.FlagSet, error) {\n\tflagSet := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\n\tval := reflect.ValueOf(result)\n\tif val.Kind() != reflect.Ptr {\n\t\treturn nil, ErrNotStruct\n\t}\n\n\tst := val.Elem()\n\tif st.Kind() != reflect.Struct {\n\t\treturn nil, ErrNotStruct\n\t}\n\n\ttyp := val.Elem().Type()\n\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield := st.Field(i)\n\t\ttypeField := typ.Field(i)\n\n\t\t\/\/ Get env tag.\n\t\tenvName := typeField.Tag.Get(\"env\")\n\t\tdefaultValue := typeField.Tag.Get(\"default\")\n\n\t\t\/\/ Set the value to the default value\n\t\tif err := setValue(field, envName, defaultValue); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ If there's a flag associated, we need to set that up, possibly with a default.\n\t\tflagNames := decodeFlagTag(typeField.Tag.Get(\"flag\"))\n\t\tflagHelp := typeField.Tag.Get(\"help\")\n\t\tif len(flagNames) > 0 {\n\t\t\taddFlag(flagSet, field, flagNames, flagHelp)\n\t\t}\n\t}\n\n\treturn flagSet, flagSet.Parse(args)\n}\n\nfunc decodeFlagTag(tag string) (names []string) {\n\tbits := strings.Split(tag, \",\")\n\tout := make([]string, 0, len(bits))\n\tfor _, bit := range bits {\n\t\ttrimmed := strings.TrimLeft(bit, \"-\")\n\t\tif len(trimmed) > 0 {\n\t\t\tout = append(out, trimmed)\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc addFlag(flagSet *flag.FlagSet, field reflect.Value, names []string, help string) error {\n\tfor _, name := range names {\n\t\tswitch field.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tflagSet.BoolVar(field.Addr().Interface().(*bool), name, field.Bool(), help)\n\t\tcase reflect.Float32, reflect.Float64:\n\t\t\tflagSet.Float64Var(field.Addr().Interface().(*float64), name, field.Float(), help)\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:\n\t\t\tflagSet.IntVar(field.Addr().Interface().(*int), name, int(field.Int()), help)\n\t\tcase reflect.Int64:\n\t\t\tif t := field.Type(); t.PkgPath() == \"time\" && t.Name() == \"Duration\" {\n\t\t\t\tflagSet.DurationVar(field.Addr().Interface().(*time.Duration), name, time.Duration(field.Int()), help)\n\t\t\t} else {\n\t\t\t\tflagSet.Int64Var(field.Addr().Interface().(*int64), name, field.Int(), help)\n\t\t\t}\n\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\tflagSet.Uint64Var(field.Addr().Interface().(*uint64), name, field.Uint(), help)\n\t\tcase reflect.String:\n\t\t\tflagSet.StringVar(field.Addr().Interface().(*string), name, field.String(), help)\n\t\tdefault:\n\t\t\t\/\/ TODO: We can make a URL parser, but not right now.\n\t\t\treturn ErrUnsupportedFlagType\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc setValue(field reflect.Value, name, def string) error {\n\ttmp := os.Getenv(name)\n\tif tmp == \"\" {\n\t\ttmp = def\n\t}\n\n\tif tmp == \"\" {\n\t\treturn nil\n\t}\n\n\tswitch field.Kind() {\n\tcase reflect.Bool:\n\t\tv, err := strconv.ParseBool(tmp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetBool(v)\n\n\tcase reflect.Float32, reflect.Float64:\n\t\tbits := field.Type().Bits()\n\t\tv, err := strconv.ParseFloat(tmp, bits)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetFloat(v)\n\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tif t := field.Type(); t.PkgPath() == \"time\" && t.Name() == \"Duration\" {\n\t\t\tv, err := time.ParseDuration(tmp)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfield.SetInt(int64(v))\n\n\t\t} else {\n\t\t\tbits := field.Type().Bits()\n\t\t\tv, err := strconv.ParseInt(tmp, 0, bits)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfield.SetInt(v)\n\t\t}\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tbits := field.Type().Bits()\n\t\tv, err := strconv.ParseUint(tmp, 0, bits)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.SetUint(v)\n\n\tcase reflect.String:\n\t\tfield.SetString(tmp)\n\n\tcase reflect.Ptr:\n\t\tif t := field.Type().Elem(); t.Kind() == reflect.Struct && t.PkgPath() == \"net\/url\" && t.Name() == \"URL\" {\n\t\t\tv, err := url.Parse(tmp)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfield.Set(reflect.ValueOf(v))\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Copyright 2015 Cloudbase Solutions SRL\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage containerinit_test\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\tstdtesting \"testing\"\n\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/juju\/juju\/cloudconfig\/cloudinit\"\n\t\"github.com\/juju\/juju\/cloudconfig\/containerinit\"\n\t\"github.com\/juju\/juju\/container\"\n\tcontainertesting \"github.com\/juju\/juju\/container\/testing\"\n\t\"github.com\/juju\/juju\/network\"\n\t\"github.com\/juju\/juju\/testing\"\n)\n\nfunc Test(t *stdtesting.T) {\n\tgc.TestingT(t)\n}\n\ntype UserDataSuite struct {\n\ttesting.BaseSuite\n\n\tnetworkInterfacesFile       string\n\tsystemNetworkInterfacesFile string\n\n\tfakeInterfaces []network.InterfaceInfo\n\n\texpectedSampleConfig     string\n\texpectedSampleUserData   string\n\texpectedFallbackConfig   string\n\texpectedFallbackUserData string\n}\n\nvar _ = gc.Suite(&UserDataSuite{})\n\nfunc (s *UserDataSuite) SetUpTest(c *gc.C) {\n\ts.BaseSuite.SetUpTest(c)\n\ts.networkInterfacesFile = filepath.Join(c.MkDir(), \"juju-interfaces\")\n\ts.systemNetworkInterfacesFile = filepath.Join(c.MkDir(), \"system-interfaces\")\n\ts.fakeInterfaces = []network.InterfaceInfo{{\n\t\tInterfaceName:    \"any0\",\n\t\tCIDR:             \"0.1.2.0\/24\",\n\t\tConfigType:       network.ConfigStatic,\n\t\tNoAutoStart:      false,\n\t\tAddress:          network.NewAddress(\"0.1.2.3\"),\n\t\tDNSServers:       network.NewAddresses(\"ns1.invalid\", \"ns2.invalid\"),\n\t\tDNSSearchDomains: []string{\"foo\", \"bar\"},\n\t\tGatewayAddress:   network.NewAddress(\"0.1.2.1\"),\n\t\tMACAddress:       \"aa:bb:cc:dd:ee:f0\",\n\t}, {\n\t\tInterfaceName:    \"any1\",\n\t\tCIDR:             \"0.2.2.0\/24\",\n\t\tConfigType:       network.ConfigStatic,\n\t\tNoAutoStart:      false,\n\t\tAddress:          network.NewAddress(\"0.2.2.4\"),\n\t\tDNSServers:       network.NewAddresses(\"ns1.invalid\", \"ns2.invalid\"),\n\t\tDNSSearchDomains: []string{\"foo\", \"bar\"},\n\t\tGatewayAddress:   network.NewAddress(\"0.2.2.1\"),\n\t\tMACAddress:       \"aa:bb:cc:dd:ee:f1\",\n\t\tRoutes: []network.Route{{\n\t\t\tDestinationCIDR: \"0.5.6.0\/24\",\n\t\t\tGatewayIP:       \"0.2.2.1\",\n\t\t\tMetric:          50,\n\t\t}},\n\t}, {\n\t\tInterfaceName: \"any2\",\n\t\tConfigType:    network.ConfigDHCP,\n\t\tNoAutoStart:   true,\n\t}, {\n\t\tInterfaceName: \"any3\",\n\t\tConfigType:    network.ConfigDHCP,\n\t\tNoAutoStart:   false,\n\t}, {\n\t\tInterfaceName: \"any4\",\n\t\tConfigType:    network.ConfigManual,\n\t\tNoAutoStart:   true,\n\t}}\n\ts.expectedSampleConfig = `\nauto any0 any1 any3 lo\n\niface lo inet loopback\n  dns-nameservers ns1.invalid ns2.invalid\n  dns-search bar foo\n\niface any0 inet static\n  address 0.1.2.3\/24\n  gateway 0.1.2.1\n\niface any1 inet static\n  address 0.2.2.4\/24\n  post-up ip route add 0.5.6.0\/24 via 0.2.2.1 metric 50\n  pre-down ip route del 0.5.6.0\/24 via 0.2.2.1 metric 50\n\niface any2 inet dhcp\n\niface any3 inet dhcp\n\niface any4 inet manual\n`\n\ts.expectedSampleUserData = `\n#cloud-config\nbootcmd:\n- install -D -m 644 \/dev\/null '%[1]s'\n- |-\n  printf '%%s\\n' '\n  auto any0 any1 any3 lo\n\n  iface lo inet loopback\n    dns-nameservers ns1.invalid ns2.invalid\n    dns-search bar foo\n\n  iface any0 inet static\n    address 0.1.2.3\/24\n    gateway 0.1.2.1\n\n  iface any1 inet static\n    address 0.2.2.4\/24\n    post-up ip route add 0.5.6.0\/24 via 0.2.2.1 metric 50\n    pre-down ip route del 0.5.6.0\/24 via 0.2.2.1 metric 50\n\n  iface any2 inet dhcp\n\n  iface any3 inet dhcp\n\n  iface any4 inet manual\n  ' > '%[1]s'\nruncmd:\n- |-\n  if [ -f %[1]s ]; then\n      ifdown -a\n      sleep 1.5\n      if ifup -a --interfaces=%[1]s; then\n          cp %[2]s %[2]s-orig\n          cp %[1]s %[2]s\n      else\n          ifup -a\n      fi\n  fi\n`[1:]\n\n\ts.expectedFallbackConfig = `\nauto eth0 lo\n\niface lo inet loopback\n\niface eth0 inet dhcp\n`\n\ts.expectedFallbackUserData = `\n#cloud-config\nbootcmd:\n- install -D -m 644 \/dev\/null '%[1]s'\n- |-\n  printf '%%s\\n' '\n  auto eth0 lo\n\n  iface lo inet loopback\n\n  iface eth0 inet dhcp\n  ' > '%[1]s'\nruncmd:\n- |-\n  if [ -f %[1]s ]; then\n      ifdown -a\n      sleep 1.5\n      if ifup -a --interfaces=%[1]s; then\n          cp %[2]s %[2]s-orig\n          cp %[1]s %[2]s\n      else\n          ifup -a\n      fi\n  fi\n`[1:]\n\n\ts.PatchValue(containerinit.NetworkInterfacesFile, s.networkInterfacesFile)\n\ts.PatchValue(containerinit.SystemNetworkInterfacesFile, s.systemNetworkInterfacesFile)\n}\n\nfunc (s *UserDataSuite) TestGenerateNetworkConfig(c *gc.C) {\n\tdata, err := containerinit.GenerateNetworkConfig(nil)\n\tc.Assert(err, gc.ErrorMatches, \"missing container network config\")\n\tc.Assert(data, gc.Equals, \"\")\n\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err = containerinit.GenerateNetworkConfig(netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.Equals, s.expectedFallbackConfig)\n\n\t\/\/ Test with all interface types.\n\tnetConfig = container.BridgeNetworkConfig(\"foo\", 0, s.fakeInterfaces)\n\tdata, err = containerinit.GenerateNetworkConfig(netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.Equals, s.expectedSampleConfig)\n}\n\nfunc (s *UserDataSuite) TestNewCloudInitConfigWithNetworksSampleConfig(c *gc.C) {\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, s.fakeInterfaces)\n\tcloudConf, err := containerinit.NewCloudInitConfigWithNetworks(\"quantal\", netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(cloudConf, gc.NotNil)\n\n\texpected := fmt.Sprintf(s.expectedSampleUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tassertUserData(c, cloudConf, expected)\n}\n\nfunc (s *UserDataSuite) TestNewCloudInitConfigWithNetworksFallbackConfig(c *gc.C) {\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tcloudConf, err := containerinit.NewCloudInitConfigWithNetworks(\"quantal\", netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(cloudConf, gc.NotNil)\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tassertUserData(c, cloudConf, expected)\n}\n\nfunc CloudInitDataExcludingOutputSection(data string) []string {\n\t\/\/ Extract the \"#cloud-config\" header and all lines between\n\t\/\/ from the \"bootcmd\" section up to (but not including) the\n\t\/\/ \"output\" sections to match against expected. But we cannot\n\t\/\/ possibly handle all the \/other\/ output that may be added by\n\t\/\/ CloudInitUserData() in the future, so we also truncate at\n\t\/\/ the first runcmd which now happens to include the runcmd's\n\t\/\/ added for raising the network interfaces captured in\n\t\/\/ expectedFallbackUserData. However, the other tests above do\n\t\/\/ check for that output.\n\n\tvar linesToMatch []string\n\tseenBootcmd := false\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\tif strings.HasPrefix(line, \"#cloud-config\") {\n\t\t\tlinesToMatch = append(linesToMatch, line)\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"bootcmd:\") {\n\t\t\tseenBootcmd = true\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"output:\") && seenBootcmd {\n\t\t\tbreak\n\t\t}\n\n\t\tif seenBootcmd {\n\t\t\tlinesToMatch = append(linesToMatch, line)\n\t\t}\n\t}\n\n\treturn linesToMatch\n}\n\n\/\/ TestCloudInitUserDataNoNetworkConfig tests that no network-interfaces, or\n\/\/ related data, appear in user-data when no networkConfig is passed to\n\/\/ CloudInitUserData.\nfunc (s *UserDataSuite) TestCloudInitUserDataNoNetworkConfig(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, nil)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\"), gc.Equals, \"#cloud-config\")\n}\n\nfunc (s *UserDataSuite) TestCloudInitUserDataFallbackConfig(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tnetworkConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tvar expectedLinesToMatch []string\n\n\tfor _, line := range strings.Split(expected, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"runcmd:\") {\n\t\t\tbreak\n\t\t}\n\t\texpectedLinesToMatch = append(expectedLinesToMatch, line)\n\t}\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\")+\"\\n\", gc.Equals, strings.Join(expectedLinesToMatch, \"\\n\")+\"\\n\")\n}\n\nfunc (s *UserDataSuite) TestCloudInitUserDataFallbackConfigWithContainerHostname(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tinstanceConfig.MachineContainerHostname = \"lxdhostname\"\n\tc.Assert(err, jc.ErrorIsNil)\n\tnetworkConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tvar expectedLinesToMatch []string\n\n\tfor _, line := range strings.Split(expected, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"runcmd:\") {\n\t\t\tbreak\n\t\t}\n\t\texpectedLinesToMatch = append(expectedLinesToMatch, line)\n\t}\n\n\texpectedLinesToMatch = append(expectedLinesToMatch, \"hostname: lxdhostname\")\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\")+\"\\n\", gc.Equals, strings.Join(expectedLinesToMatch, \"\\n\")+\"\\n\")\n}\n\nfunc assertUserData(c *gc.C, cloudConf cloudinit.CloudConfig, expected string) {\n\tdata, err := cloudConf.RenderYAML()\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(string(data), gc.Equals, expected)\n\n\t\/\/ Make sure it's valid YAML as well.\n\tout := make(map[string]interface{})\n\terr = yaml.Unmarshal(data, &out)\n\tc.Assert(err, jc.ErrorIsNil)\n\tif len(cloudConf.BootCmds()) > 0 {\n\t\toutcmds := out[\"bootcmd\"].([]interface{})\n\t\tconfcmds := cloudConf.BootCmds()\n\t\tc.Assert(len(outcmds), gc.Equals, len(confcmds))\n\t\tfor i, _ := range outcmds {\n\t\t\tc.Assert(outcmds[i].(string), gc.Equals, confcmds[i])\n\t\t}\n\t} else {\n\t\tc.Assert(out[\"bootcmd\"], gc.IsNil)\n\t}\n}\n<commit_msg>update the test to handle the new debug messages<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Copyright 2015 Cloudbase Solutions SRL\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage containerinit_test\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\tstdtesting \"testing\"\n\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/juju\/juju\/cloudconfig\/cloudinit\"\n\t\"github.com\/juju\/juju\/cloudconfig\/containerinit\"\n\t\"github.com\/juju\/juju\/container\"\n\tcontainertesting \"github.com\/juju\/juju\/container\/testing\"\n\t\"github.com\/juju\/juju\/network\"\n\t\"github.com\/juju\/juju\/testing\"\n)\n\nfunc Test(t *stdtesting.T) {\n\tgc.TestingT(t)\n}\n\ntype UserDataSuite struct {\n\ttesting.BaseSuite\n\n\tnetworkInterfacesFile       string\n\tsystemNetworkInterfacesFile string\n\n\tfakeInterfaces []network.InterfaceInfo\n\n\texpectedSampleConfig     string\n\texpectedSampleUserData   string\n\texpectedFallbackConfig   string\n\texpectedFallbackUserData string\n}\n\nvar _ = gc.Suite(&UserDataSuite{})\n\nfunc (s *UserDataSuite) SetUpTest(c *gc.C) {\n\ts.BaseSuite.SetUpTest(c)\n\ts.networkInterfacesFile = filepath.Join(c.MkDir(), \"juju-interfaces\")\n\ts.systemNetworkInterfacesFile = filepath.Join(c.MkDir(), \"system-interfaces\")\n\ts.fakeInterfaces = []network.InterfaceInfo{{\n\t\tInterfaceName:    \"any0\",\n\t\tCIDR:             \"0.1.2.0\/24\",\n\t\tConfigType:       network.ConfigStatic,\n\t\tNoAutoStart:      false,\n\t\tAddress:          network.NewAddress(\"0.1.2.3\"),\n\t\tDNSServers:       network.NewAddresses(\"ns1.invalid\", \"ns2.invalid\"),\n\t\tDNSSearchDomains: []string{\"foo\", \"bar\"},\n\t\tGatewayAddress:   network.NewAddress(\"0.1.2.1\"),\n\t\tMACAddress:       \"aa:bb:cc:dd:ee:f0\",\n\t}, {\n\t\tInterfaceName:    \"any1\",\n\t\tCIDR:             \"0.2.2.0\/24\",\n\t\tConfigType:       network.ConfigStatic,\n\t\tNoAutoStart:      false,\n\t\tAddress:          network.NewAddress(\"0.2.2.4\"),\n\t\tDNSServers:       network.NewAddresses(\"ns1.invalid\", \"ns2.invalid\"),\n\t\tDNSSearchDomains: []string{\"foo\", \"bar\"},\n\t\tGatewayAddress:   network.NewAddress(\"0.2.2.1\"),\n\t\tMACAddress:       \"aa:bb:cc:dd:ee:f1\",\n\t\tRoutes: []network.Route{{\n\t\t\tDestinationCIDR: \"0.5.6.0\/24\",\n\t\t\tGatewayIP:       \"0.2.2.1\",\n\t\t\tMetric:          50,\n\t\t}},\n\t}, {\n\t\tInterfaceName: \"any2\",\n\t\tConfigType:    network.ConfigDHCP,\n\t\tNoAutoStart:   true,\n\t}, {\n\t\tInterfaceName: \"any3\",\n\t\tConfigType:    network.ConfigDHCP,\n\t\tNoAutoStart:   false,\n\t}, {\n\t\tInterfaceName: \"any4\",\n\t\tConfigType:    network.ConfigManual,\n\t\tNoAutoStart:   true,\n\t}}\n\ts.expectedSampleConfig = `\nauto any0 any1 any3 lo\n\niface lo inet loopback\n  dns-nameservers ns1.invalid ns2.invalid\n  dns-search bar foo\n\niface any0 inet static\n  address 0.1.2.3\/24\n  gateway 0.1.2.1\n\niface any1 inet static\n  address 0.2.2.4\/24\n  post-up ip route add 0.5.6.0\/24 via 0.2.2.1 metric 50\n  pre-down ip route del 0.5.6.0\/24 via 0.2.2.1 metric 50\n\niface any2 inet dhcp\n\niface any3 inet dhcp\n\niface any4 inet manual\n`\n\ts.expectedSampleUserData = `\n#cloud-config\nbootcmd:\n- install -D -m 644 \/dev\/null '%[1]s'\n- |-\n  printf '%%s\\n' '\n  auto any0 any1 any3 lo\n\n  iface lo inet loopback\n    dns-nameservers ns1.invalid ns2.invalid\n    dns-search bar foo\n\n  iface any0 inet static\n    address 0.1.2.3\/24\n    gateway 0.1.2.1\n\n  iface any1 inet static\n    address 0.2.2.4\/24\n    post-up ip route add 0.5.6.0\/24 via 0.2.2.1 metric 50\n    pre-down ip route del 0.5.6.0\/24 via 0.2.2.1 metric 50\n\n  iface any2 inet dhcp\n\n  iface any3 inet dhcp\n\n  iface any4 inet manual\n  ' > '%[1]s'\nruncmd:\n- |-\n  if [ -f %[1]s ]; then\n      echo \"stopping all interfaces\"\n      ifdown -a\n      sleep 1.5\n      if ifup -a --interfaces=%[1]s; then\n          echo \"ifup with %[1]s succeeded, renaming to %[2]s\"\n          cp %[2]s %[2]s-orig\n          cp %[1]s %[2]s\n      else\n          echo \"ifup with %[1]s failed, leaving old %[2]s alone\"\n          ifup -a\n      fi\n  else\n      echo \"did not find %[1]s, not reconfiguring networking\"\n  fi\n`[1:]\n\n\ts.expectedFallbackConfig = `\nauto eth0 lo\n\niface lo inet loopback\n\niface eth0 inet dhcp\n`\n\ts.expectedFallbackUserData = `\n#cloud-config\nbootcmd:\n- install -D -m 644 \/dev\/null '%[1]s'\n- |-\n  printf '%%s\\n' '\n  auto eth0 lo\n\n  iface lo inet loopback\n\n  iface eth0 inet dhcp\n  ' > '%[1]s'\nruncmd:\n- |-\n  if [ -f %[1]s ]; then\n      echo \"stopping all interfaces\"\n      ifdown -a\n      sleep 1.5\n      if ifup -a --interfaces=%[1]s; then\n          echo \"ifup with %[1]s succeeded, renaming to %[2]s\"\n          cp %[2]s %[2]s-orig\n          cp %[1]s %[2]s\n      else\n          echo \"ifup with %[1]s failed, leaving old %[2]s alone\"\n          ifup -a\n      fi\n  else\n      echo \"did not find %[1]s, not reconfiguring networking\"\n  fi\n`[1:]\n\n\ts.PatchValue(containerinit.NetworkInterfacesFile, s.networkInterfacesFile)\n\ts.PatchValue(containerinit.SystemNetworkInterfacesFile, s.systemNetworkInterfacesFile)\n}\n\nfunc (s *UserDataSuite) TestGenerateNetworkConfig(c *gc.C) {\n\tdata, err := containerinit.GenerateNetworkConfig(nil)\n\tc.Assert(err, gc.ErrorMatches, \"missing container network config\")\n\tc.Assert(data, gc.Equals, \"\")\n\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err = containerinit.GenerateNetworkConfig(netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.Equals, s.expectedFallbackConfig)\n\n\t\/\/ Test with all interface types.\n\tnetConfig = container.BridgeNetworkConfig(\"foo\", 0, s.fakeInterfaces)\n\tdata, err = containerinit.GenerateNetworkConfig(netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.Equals, s.expectedSampleConfig)\n}\n\nfunc (s *UserDataSuite) TestNewCloudInitConfigWithNetworksSampleConfig(c *gc.C) {\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, s.fakeInterfaces)\n\tcloudConf, err := containerinit.NewCloudInitConfigWithNetworks(\"quantal\", netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(cloudConf, gc.NotNil)\n\n\texpected := fmt.Sprintf(s.expectedSampleUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tassertUserData(c, cloudConf, expected)\n}\n\nfunc (s *UserDataSuite) TestNewCloudInitConfigWithNetworksFallbackConfig(c *gc.C) {\n\tnetConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tcloudConf, err := containerinit.NewCloudInitConfigWithNetworks(\"quantal\", netConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(cloudConf, gc.NotNil)\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tassertUserData(c, cloudConf, expected)\n}\n\nfunc CloudInitDataExcludingOutputSection(data string) []string {\n\t\/\/ Extract the \"#cloud-config\" header and all lines between\n\t\/\/ from the \"bootcmd\" section up to (but not including) the\n\t\/\/ \"output\" sections to match against expected. But we cannot\n\t\/\/ possibly handle all the \/other\/ output that may be added by\n\t\/\/ CloudInitUserData() in the future, so we also truncate at\n\t\/\/ the first runcmd which now happens to include the runcmd's\n\t\/\/ added for raising the network interfaces captured in\n\t\/\/ expectedFallbackUserData. However, the other tests above do\n\t\/\/ check for that output.\n\n\tvar linesToMatch []string\n\tseenBootcmd := false\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\tif strings.HasPrefix(line, \"#cloud-config\") {\n\t\t\tlinesToMatch = append(linesToMatch, line)\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"bootcmd:\") {\n\t\t\tseenBootcmd = true\n\t\t}\n\n\t\tif strings.HasPrefix(line, \"output:\") && seenBootcmd {\n\t\t\tbreak\n\t\t}\n\n\t\tif seenBootcmd {\n\t\t\tlinesToMatch = append(linesToMatch, line)\n\t\t}\n\t}\n\n\treturn linesToMatch\n}\n\n\/\/ TestCloudInitUserDataNoNetworkConfig tests that no network-interfaces, or\n\/\/ related data, appear in user-data when no networkConfig is passed to\n\/\/ CloudInitUserData.\nfunc (s *UserDataSuite) TestCloudInitUserDataNoNetworkConfig(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, nil)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\"), gc.Equals, \"#cloud-config\")\n}\n\nfunc (s *UserDataSuite) TestCloudInitUserDataFallbackConfig(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tnetworkConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tvar expectedLinesToMatch []string\n\n\tfor _, line := range strings.Split(expected, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"runcmd:\") {\n\t\t\tbreak\n\t\t}\n\t\texpectedLinesToMatch = append(expectedLinesToMatch, line)\n\t}\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\")+\"\\n\", gc.Equals, strings.Join(expectedLinesToMatch, \"\\n\")+\"\\n\")\n}\n\nfunc (s *UserDataSuite) TestCloudInitUserDataFallbackConfigWithContainerHostname(c *gc.C) {\n\tinstanceConfig, err := containertesting.MockMachineConfig(\"1\/lxd\/0\")\n\tinstanceConfig.MachineContainerHostname = \"lxdhostname\"\n\tc.Assert(err, jc.ErrorIsNil)\n\tnetworkConfig := container.BridgeNetworkConfig(\"foo\", 0, nil)\n\tdata, err := containerinit.CloudInitUserData(instanceConfig, networkConfig)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(data, gc.NotNil)\n\n\tlinesToMatch := CloudInitDataExcludingOutputSection(string(data))\n\n\texpected := fmt.Sprintf(s.expectedFallbackUserData, s.networkInterfacesFile, s.systemNetworkInterfacesFile)\n\tvar expectedLinesToMatch []string\n\n\tfor _, line := range strings.Split(expected, \"\\n\") {\n\t\tif strings.HasPrefix(line, \"runcmd:\") {\n\t\t\tbreak\n\t\t}\n\t\texpectedLinesToMatch = append(expectedLinesToMatch, line)\n\t}\n\n\texpectedLinesToMatch = append(expectedLinesToMatch, \"hostname: lxdhostname\")\n\n\tc.Assert(strings.Join(linesToMatch, \"\\n\")+\"\\n\", gc.Equals, strings.Join(expectedLinesToMatch, \"\\n\")+\"\\n\")\n}\n\nfunc assertUserData(c *gc.C, cloudConf cloudinit.CloudConfig, expected string) {\n\tdata, err := cloudConf.RenderYAML()\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(string(data), gc.Equals, expected)\n\n\t\/\/ Make sure it's valid YAML as well.\n\tout := make(map[string]interface{})\n\terr = yaml.Unmarshal(data, &out)\n\tc.Assert(err, jc.ErrorIsNil)\n\tif len(cloudConf.BootCmds()) > 0 {\n\t\toutcmds := out[\"bootcmd\"].([]interface{})\n\t\tconfcmds := cloudConf.BootCmds()\n\t\tc.Assert(len(outcmds), gc.Equals, len(confcmds))\n\t\tfor i, _ := range outcmds {\n\t\t\tc.Assert(outcmds[i].(string), gc.Equals, confcmds[i])\n\t\t}\n\t} else {\n\t\tc.Assert(out[\"bootcmd\"], gc.IsNil)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitbucketapi\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/estafette\/estafette-ci-api\/pkg\/api\"\n\tcrypt \"github.com\/estafette\/estafette-ci-crypt\"\n\t\"github.com\/opentracing-contrib\/go-stdlib\/nethttp\"\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/rs\/zerolog\/log\"\n\t\"github.com\/sethgrid\/pester\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\n\/\/ Client is the interface for communicating with the bitbucket api\n\/\/go:generate mockgen -package=bitbucketapi -destination .\/mock.go -source=client.go\ntype Client interface {\n\tGetAccessToken(ctx context.Context) (accesstoken AccessToken, err error)\n\tGetEstafetteManifest(ctx context.Context, accesstoken AccessToken, event RepositoryPushEvent) (valid bool, manifest string, err error)\n\tJobVarsFunc(ctx context.Context) func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error)\n\tGenerateJWT() (tokenString string, err error)\n\tGetInstallations(ctx context.Context) (installations []*BitbucketAppInstallation, err error)\n\tAddInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error)\n\tRemoveInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error)\n}\n\n\/\/ NewClient returns a new bitbucket.Client\nfunc NewClient(config *api.APIConfig, kubeClientset *kubernetes.Clientset, secretHelper crypt.SecretHelper) Client {\n\treturn &client{\n\t\tenabled:       config != nil && config.Integrations != nil && config.Integrations.Bitbucket != nil && config.Integrations.Bitbucket.Enable,\n\t\tconfig:        config,\n\t\tkubeClientset: kubeClientset,\n\t\tsecretHelper:  secretHelper,\n\t}\n}\n\ntype client struct {\n\tenabled       bool\n\tconfig        *api.APIConfig\n\tkubeClientset *kubernetes.Clientset\n\tsecretHelper  crypt.SecretHelper\n}\n\n\/\/ GetAccessToken returns an access token to access the Bitbucket api\nfunc (c *client) GetAccessToken(ctx context.Context) (accesstoken AccessToken, err error) {\n\n\tjtwToken, err := c.GenerateJWT()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ form values\n\tdata := url.Values{}\n\tdata.Set(\"grant_type\", \"urn:bitbucket:oauth2:jwt\")\n\n\t\/\/ create client, in order to add headers\n\tclient := pester.NewExtendedClient(&http.Client{Transport: &nethttp.Transport{}})\n\tclient.MaxRetries = 3\n\tclient.Backoff = pester.ExponentialJitterBackoff\n\tclient.KeepLog = true\n\tclient.Timeout = time.Second * 10\n\trequest, err := http.NewRequest(\"POST\", \"https:\/\/bitbucket.org\/site\/oauth2\/access_token\", bytes.NewBufferString(data.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspan := opentracing.SpanFromContext(ctx)\n\tvar ht *nethttp.Tracer\n\tif span != nil {\n\t\t\/\/ add tracing context\n\t\trequest = request.WithContext(opentracing.ContextWithSpan(request.Context(), span))\n\n\t\t\/\/ collect additional information on setting up connections\n\t\trequest, ht = nethttp.TraceRequest(span.Tracer(), request)\n\t}\n\n\t\/\/ add headers\n\trequest.Header.Add(\"Authorization\", fmt.Sprintf(\"%v %v\", \"JWT\", jtwToken))\n\trequest.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\t\/\/ perform actual request\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer response.Body.Close()\n\tif ht != nil {\n\t\tht.Finish()\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ unmarshal json body\n\terr = json.Unmarshal(body, &accesstoken)\n\tif err != nil {\n\t\tlog.Warn().Str(\"body\", string(body)).Msg(\"Failed unmarshalling access token\")\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) GetEstafetteManifest(ctx context.Context, accesstoken AccessToken, pushEvent RepositoryPushEvent) (exists bool, manifest string, err error) {\n\n\t\/\/ create client, in order to add headers\n\tclient := pester.NewExtendedClient(&http.Client{Transport: &nethttp.Transport{}})\n\tclient.MaxRetries = 3\n\tclient.Backoff = pester.ExponentialJitterBackoff\n\tclient.KeepLog = true\n\tclient.Timeout = time.Second * 10\n\n\tmanifestSourceAPIUrl := fmt.Sprintf(\"https:\/\/api.bitbucket.org\/2.0\/repositories\/%v\/src\/%v\/.estafette.yaml\", pushEvent.Repository.FullName, pushEvent.Push.Changes[0].New.Target.Hash)\n\n\trequest, err := http.NewRequest(\"GET\", manifestSourceAPIUrl, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspan := opentracing.SpanFromContext(ctx)\n\tvar ht *nethttp.Tracer\n\tif span != nil {\n\t\t\/\/ add tracing context\n\t\trequest = request.WithContext(opentracing.ContextWithSpan(request.Context(), span))\n\n\t\t\/\/ collect additional information on setting up connections\n\t\trequest, ht = nethttp.TraceRequest(span.Tracer(), request)\n\t}\n\n\t\/\/ add headers\n\trequest.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %v\", accesstoken.AccessToken))\n\n\t\/\/ perform actual request\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer response.Body.Close()\n\tif ht != nil {\n\t\tht.Finish()\n\t}\n\n\tif response.StatusCode == http.StatusNotFound {\n\t\treturn\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\terr = fmt.Errorf(\"Retrieving estafette manifest from %v failed with status code %v\", manifestSourceAPIUrl, response.StatusCode)\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\texists = true\n\tmanifest = string(body)\n\n\treturn\n}\n\n\/\/ JobVarsFunc returns a function that can get an access token and authenticated url for a repository\nfunc (c *client) JobVarsFunc(ctx context.Context) func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error) {\n\treturn func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error) {\n\t\t\/\/ get access token\n\t\taccessToken, err := c.GetAccessToken(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn accessToken.AccessToken, nil\n\t}\n}\n\nfunc (c *client) GenerateJWT() (tokenString string, err error) {\n\n\t\/\/ Create the token\n\ttoken := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\tclaims := token.Claims.(jwt.MapClaims)\n\n\tnow := time.Now().UTC()\n\texpiry := now.Add(time.Duration(180) * time.Second)\n\n\t\/\/ set required claims\n\tclaims[\"iss\"] = c.config.Integrations.Bitbucket.Key\n\tclaims[\"iat\"] = now.Unix()\n\tclaims[\"exp\"] = expiry.Unix()\n\tclaims[\"sub\"] = c.config.Integrations.Bitbucket.ClientKey\n\n\t\/\/ sign the token\n\treturn token.SignedString([]byte(c.config.Integrations.Bitbucket.SharedSecret))\n}\n\nvar installationsCache []*BitbucketAppInstallation\n\nconst bitbucketConfigmapName = \"estafette-ci-api.bitbucket\"\n\nfunc (c *client) GetInstallations(ctx context.Context) (installations []*BitbucketAppInstallation, err error) {\n\t\/\/ get from cache\n\tif installationsCache != nil {\n\t\treturn installationsCache, nil\n\t}\n\n\tinstallations = make([]*BitbucketAppInstallation, 0)\n\n\tconfigMap, err := c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Get(ctx, bitbucketConfigmapName, metav1.GetOptions{})\n\tif err != nil || configMap == nil {\n\t\treturn installations, nil\n\t}\n\n\tif data, ok := configMap.Data[\"installations\"]; ok {\n\t\terr = json.Unmarshal([]byte(data), &installations)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tc.decryptSharedSecrets(ctx, installations)\n\n\t\t\/\/ add to cache\n\t\tinstallationsCache = installations\n\t}\n\n\treturn\n}\n\nfunc (c *client) AddInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error) {\n\tinstallations, err := c.GetInstallations(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif installations == nil {\n\t\tinstallations = make([]*BitbucketAppInstallation, 0)\n\t}\n\n\t\/\/ check if installation(s) with key and clientKey exists, if not add, otherwise update\n\tinstallationExists := false\n\tfor _, inst := range installations {\n\t\tif inst.Key == installation.Key && inst.ClientKey == installation.ClientKey {\n\t\t\tinstallationExists = true\n\n\t\t\tinst.BaseApiURL = installation.BaseApiURL\n\t\t\tinst.SharedSecret = installation.SharedSecret\n\t\t}\n\t}\n\n\tif !installationExists {\n\t\tinstallations = append(installations, &installation)\n\t}\n\n\terr = c.upsertConfigmap(ctx, installations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) RemoveInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error) {\n\tinstallations, err := c.GetInstallations(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif installations == nil {\n\t\tinstallations = make([]*BitbucketAppInstallation, 0)\n\t}\n\n\t\/\/ check if installation(s) with key and clientKey exists, then remove\n\tfor i, inst := range installations {\n\t\tif inst.Key == installation.Key && inst.ClientKey == installation.ClientKey {\n\t\t\tinstallations = append(installations[:i], installations[i+1:]...)\n\t\t}\n\t}\n\n\terr = c.upsertConfigmap(ctx, installations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) upsertConfigmap(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\n\tc.encryptSharedSecrets(ctx, installations)\n\n\t\/\/ marshal to json\n\tdata, err := json.Marshal(installations)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ store in configmap\n\tconfigMap, err := c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Get(ctx, bitbucketConfigmapName, metav1.GetOptions{})\n\tif err != nil || configMap == nil {\n\t\t\/\/ create configmap\n\t\tconfigMap = &v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName:      bitbucketConfigmapName,\n\t\t\t\tNamespace: c.getCurrentNamespace(),\n\t\t\t},\n\t\t\tData: map[string]string{\n\t\t\t\t\"installations\": string(data),\n\t\t\t},\n\t\t}\n\t\t_, err = c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Create(ctx, configMap, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ update configmap\n\t\tconfigMap.Data[\"installations\"] = string(data)\n\t\t_, err = c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Update(ctx, configMap, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ update cache\n\tinstallationsCache = installations\n\n\treturn\n}\n\nfunc (c *client) getCurrentNamespace() string {\n\tnamespace, err := ioutil.ReadFile(\"\/var\/run\/secrets\/kubernetes.io\/serviceaccount\/namespace\")\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading namespace\")\n\t}\n\n\treturn string(namespace)\n}\n\nfunc (c *client) encryptSharedSecrets(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\tfor _, installation := range installations {\n\t\tencryptedSharedSecret, encryptErr := c.secretHelper.EncryptEnvelope(installation.SharedSecret, crypt.DefaultPipelineAllowList)\n\t\tif encryptErr != nil {\n\t\t\treturn encryptErr\n\t\t}\n\t\tinstallation.SharedSecret = encryptedSharedSecret\n\t}\n\n\treturn nil\n}\n\nfunc (c *client) decryptSharedSecrets(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\tfor _, installation := range installations {\n\t\tdecryptedSharedSecret, _, decryptErr := c.secretHelper.DecryptEnvelope(installation.SharedSecret, \"\")\n\t\tif decryptErr != nil {\n\t\t\treturn decryptErr\n\t\t}\n\t\tinstallation.SharedSecret = decryptedSharedSecret\n\t}\n\n\treturn nil\n}\n<commit_msg>errcheck encrypt\/decrypt shared secrets for bitbucket installations<commit_after>package bitbucketapi\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/estafette\/estafette-ci-api\/pkg\/api\"\n\tcrypt \"github.com\/estafette\/estafette-ci-crypt\"\n\t\"github.com\/opentracing-contrib\/go-stdlib\/nethttp\"\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/rs\/zerolog\/log\"\n\t\"github.com\/sethgrid\/pester\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\n\/\/ Client is the interface for communicating with the bitbucket api\n\/\/go:generate mockgen -package=bitbucketapi -destination .\/mock.go -source=client.go\ntype Client interface {\n\tGetAccessToken(ctx context.Context) (accesstoken AccessToken, err error)\n\tGetEstafetteManifest(ctx context.Context, accesstoken AccessToken, event RepositoryPushEvent) (valid bool, manifest string, err error)\n\tJobVarsFunc(ctx context.Context) func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error)\n\tGenerateJWT() (tokenString string, err error)\n\tGetInstallations(ctx context.Context) (installations []*BitbucketAppInstallation, err error)\n\tAddInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error)\n\tRemoveInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error)\n}\n\n\/\/ NewClient returns a new bitbucket.Client\nfunc NewClient(config *api.APIConfig, kubeClientset *kubernetes.Clientset, secretHelper crypt.SecretHelper) Client {\n\treturn &client{\n\t\tenabled:       config != nil && config.Integrations != nil && config.Integrations.Bitbucket != nil && config.Integrations.Bitbucket.Enable,\n\t\tconfig:        config,\n\t\tkubeClientset: kubeClientset,\n\t\tsecretHelper:  secretHelper,\n\t}\n}\n\ntype client struct {\n\tenabled       bool\n\tconfig        *api.APIConfig\n\tkubeClientset *kubernetes.Clientset\n\tsecretHelper  crypt.SecretHelper\n}\n\n\/\/ GetAccessToken returns an access token to access the Bitbucket api\nfunc (c *client) GetAccessToken(ctx context.Context) (accesstoken AccessToken, err error) {\n\n\tjtwToken, err := c.GenerateJWT()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ form values\n\tdata := url.Values{}\n\tdata.Set(\"grant_type\", \"urn:bitbucket:oauth2:jwt\")\n\n\t\/\/ create client, in order to add headers\n\tclient := pester.NewExtendedClient(&http.Client{Transport: &nethttp.Transport{}})\n\tclient.MaxRetries = 3\n\tclient.Backoff = pester.ExponentialJitterBackoff\n\tclient.KeepLog = true\n\tclient.Timeout = time.Second * 10\n\trequest, err := http.NewRequest(\"POST\", \"https:\/\/bitbucket.org\/site\/oauth2\/access_token\", bytes.NewBufferString(data.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspan := opentracing.SpanFromContext(ctx)\n\tvar ht *nethttp.Tracer\n\tif span != nil {\n\t\t\/\/ add tracing context\n\t\trequest = request.WithContext(opentracing.ContextWithSpan(request.Context(), span))\n\n\t\t\/\/ collect additional information on setting up connections\n\t\trequest, ht = nethttp.TraceRequest(span.Tracer(), request)\n\t}\n\n\t\/\/ add headers\n\trequest.Header.Add(\"Authorization\", fmt.Sprintf(\"%v %v\", \"JWT\", jtwToken))\n\trequest.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\t\/\/ perform actual request\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer response.Body.Close()\n\tif ht != nil {\n\t\tht.Finish()\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ unmarshal json body\n\terr = json.Unmarshal(body, &accesstoken)\n\tif err != nil {\n\t\tlog.Warn().Str(\"body\", string(body)).Msg(\"Failed unmarshalling access token\")\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) GetEstafetteManifest(ctx context.Context, accesstoken AccessToken, pushEvent RepositoryPushEvent) (exists bool, manifest string, err error) {\n\n\t\/\/ create client, in order to add headers\n\tclient := pester.NewExtendedClient(&http.Client{Transport: &nethttp.Transport{}})\n\tclient.MaxRetries = 3\n\tclient.Backoff = pester.ExponentialJitterBackoff\n\tclient.KeepLog = true\n\tclient.Timeout = time.Second * 10\n\n\tmanifestSourceAPIUrl := fmt.Sprintf(\"https:\/\/api.bitbucket.org\/2.0\/repositories\/%v\/src\/%v\/.estafette.yaml\", pushEvent.Repository.FullName, pushEvent.Push.Changes[0].New.Target.Hash)\n\n\trequest, err := http.NewRequest(\"GET\", manifestSourceAPIUrl, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspan := opentracing.SpanFromContext(ctx)\n\tvar ht *nethttp.Tracer\n\tif span != nil {\n\t\t\/\/ add tracing context\n\t\trequest = request.WithContext(opentracing.ContextWithSpan(request.Context(), span))\n\n\t\t\/\/ collect additional information on setting up connections\n\t\trequest, ht = nethttp.TraceRequest(span.Tracer(), request)\n\t}\n\n\t\/\/ add headers\n\trequest.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %v\", accesstoken.AccessToken))\n\n\t\/\/ perform actual request\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer response.Body.Close()\n\tif ht != nil {\n\t\tht.Finish()\n\t}\n\n\tif response.StatusCode == http.StatusNotFound {\n\t\treturn\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\terr = fmt.Errorf(\"Retrieving estafette manifest from %v failed with status code %v\", manifestSourceAPIUrl, response.StatusCode)\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\texists = true\n\tmanifest = string(body)\n\n\treturn\n}\n\n\/\/ JobVarsFunc returns a function that can get an access token and authenticated url for a repository\nfunc (c *client) JobVarsFunc(ctx context.Context) func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error) {\n\treturn func(ctx context.Context, repoSource, repoOwner, repoName string) (token string, err error) {\n\t\t\/\/ get access token\n\t\taccessToken, err := c.GetAccessToken(ctx)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn accessToken.AccessToken, nil\n\t}\n}\n\nfunc (c *client) GenerateJWT() (tokenString string, err error) {\n\n\t\/\/ Create the token\n\ttoken := jwt.New(jwt.GetSigningMethod(\"HS256\"))\n\tclaims := token.Claims.(jwt.MapClaims)\n\n\tnow := time.Now().UTC()\n\texpiry := now.Add(time.Duration(180) * time.Second)\n\n\t\/\/ set required claims\n\tclaims[\"iss\"] = c.config.Integrations.Bitbucket.Key\n\tclaims[\"iat\"] = now.Unix()\n\tclaims[\"exp\"] = expiry.Unix()\n\tclaims[\"sub\"] = c.config.Integrations.Bitbucket.ClientKey\n\n\t\/\/ sign the token\n\treturn token.SignedString([]byte(c.config.Integrations.Bitbucket.SharedSecret))\n}\n\nvar installationsCache []*BitbucketAppInstallation\n\nconst bitbucketConfigmapName = \"estafette-ci-api.bitbucket\"\n\nfunc (c *client) GetInstallations(ctx context.Context) (installations []*BitbucketAppInstallation, err error) {\n\t\/\/ get from cache\n\tif installationsCache != nil {\n\t\treturn installationsCache, nil\n\t}\n\n\tinstallations = make([]*BitbucketAppInstallation, 0)\n\n\tconfigMap, err := c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Get(ctx, bitbucketConfigmapName, metav1.GetOptions{})\n\tif err != nil || configMap == nil {\n\t\treturn installations, nil\n\t}\n\n\tif data, ok := configMap.Data[\"installations\"]; ok {\n\t\terr = json.Unmarshal([]byte(data), &installations)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = c.decryptSharedSecrets(ctx, installations)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ add to cache\n\t\tinstallationsCache = installations\n\t}\n\n\treturn\n}\n\nfunc (c *client) AddInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error) {\n\tinstallations, err := c.GetInstallations(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif installations == nil {\n\t\tinstallations = make([]*BitbucketAppInstallation, 0)\n\t}\n\n\t\/\/ check if installation(s) with key and clientKey exists, if not add, otherwise update\n\tinstallationExists := false\n\tfor _, inst := range installations {\n\t\tif inst.Key == installation.Key && inst.ClientKey == installation.ClientKey {\n\t\t\tinstallationExists = true\n\n\t\t\tinst.BaseApiURL = installation.BaseApiURL\n\t\t\tinst.SharedSecret = installation.SharedSecret\n\t\t}\n\t}\n\n\tif !installationExists {\n\t\tinstallations = append(installations, &installation)\n\t}\n\n\terr = c.upsertConfigmap(ctx, installations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) RemoveInstallation(ctx context.Context, installation BitbucketAppInstallation) (err error) {\n\tinstallations, err := c.GetInstallations(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif installations == nil {\n\t\tinstallations = make([]*BitbucketAppInstallation, 0)\n\t}\n\n\t\/\/ check if installation(s) with key and clientKey exists, then remove\n\tfor i, inst := range installations {\n\t\tif inst.Key == installation.Key && inst.ClientKey == installation.ClientKey {\n\t\t\tinstallations = append(installations[:i], installations[i+1:]...)\n\t\t}\n\t}\n\n\terr = c.upsertConfigmap(ctx, installations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (c *client) upsertConfigmap(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\n\terr = c.encryptSharedSecrets(ctx, installations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ marshal to json\n\tdata, err := json.Marshal(installations)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ store in configmap\n\tconfigMap, err := c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Get(ctx, bitbucketConfigmapName, metav1.GetOptions{})\n\tif err != nil || configMap == nil {\n\t\t\/\/ create configmap\n\t\tconfigMap = &v1.ConfigMap{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName:      bitbucketConfigmapName,\n\t\t\t\tNamespace: c.getCurrentNamespace(),\n\t\t\t},\n\t\t\tData: map[string]string{\n\t\t\t\t\"installations\": string(data),\n\t\t\t},\n\t\t}\n\t\t_, err = c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Create(ctx, configMap, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ update configmap\n\t\tconfigMap.Data[\"installations\"] = string(data)\n\t\t_, err = c.kubeClientset.CoreV1().ConfigMaps(c.getCurrentNamespace()).Update(ctx, configMap, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ update cache\n\tinstallationsCache = installations\n\n\treturn\n}\n\nfunc (c *client) getCurrentNamespace() string {\n\tnamespace, err := ioutil.ReadFile(\"\/var\/run\/secrets\/kubernetes.io\/serviceaccount\/namespace\")\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading namespace\")\n\t}\n\n\treturn string(namespace)\n}\n\nfunc (c *client) encryptSharedSecrets(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\tfor _, installation := range installations {\n\t\tencryptedSharedSecret, encryptErr := c.secretHelper.EncryptEnvelope(installation.SharedSecret, crypt.DefaultPipelineAllowList)\n\t\tif encryptErr != nil {\n\t\t\treturn encryptErr\n\t\t}\n\t\tinstallation.SharedSecret = encryptedSharedSecret\n\t}\n\n\treturn nil\n}\n\nfunc (c *client) decryptSharedSecrets(ctx context.Context, installations []*BitbucketAppInstallation) (err error) {\n\tfor _, installation := range installations {\n\t\tdecryptedSharedSecret, _, decryptErr := c.secretHelper.DecryptEnvelope(installation.SharedSecret, \"\")\n\t\tif decryptErr != nil {\n\t\t\treturn decryptErr\n\t\t}\n\t\tinstallation.SharedSecret = decryptedSharedSecret\n\t}\n\n\treturn nil\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 offlinevm\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n\tk8smetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/pkg\/virtctl\/templates\"\n)\n\nconst (\n\tCOMMAND_START = \"start\"\n\tCOMMAND_STOP  = \"stop\"\n)\n\nfunc NewStartCommand(clientConfig clientcmd.ClientConfig) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:     \"start (vm)\",\n\t\tShort:   \"Start a virtual machine which is managed by an offline virtual machine.\",\n\t\tExample: usage(COMMAND_START),\n\t\tArgs:    cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc := Command{command: COMMAND_START, clientConfig: clientConfig}\n\t\t\treturn c.Run(cmd, args)\n\t\t},\n\t}\n\tcmd.SetUsageTemplate(templates.UsageTemplate())\n\treturn cmd\n}\n\nfunc NewStopCommand(clientConfig clientcmd.ClientConfig) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse:     \"stop (vm)\",\n\t\tShort:   \"Stop a virtual machine which is managed by an offline virtual machine.\",\n\t\tExample: usage(COMMAND_STOP),\n\t\tArgs:    cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc := Command{command: COMMAND_STOP, clientConfig: clientConfig}\n\t\t\treturn c.Run(cmd, args)\n\t\t},\n\t}\n}\n\ntype Command struct {\n\tclientConfig clientcmd.ClientConfig\n\tcommand      string\n}\n\nfunc NewCommand(command string) *Command {\n\treturn &Command{command: command}\n}\n\nfunc usage(cmd string) string {\n\tusage := \"#Start a virtual machine called 'myvm':\\n\"\n\tusage += fmt.Sprintf(\"virtctl %s myvm\", cmd)\n\treturn usage\n}\n\nfunc (o *Command) Run(cmd *cobra.Command, args []string) error {\n\n\tvmName := args[0]\n\n\tnamespace, _, err := o.clientConfig.Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar running bool\n\tif o.command == COMMAND_START {\n\t\trunning = true\n\t} else if o.command == COMMAND_STOP {\n\t\trunning = false\n\t}\n\n\tvirtClient, err := kubecli.GetKubevirtClientFromClientConfig(o.clientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot obtain KubeVirt client: %v\", err)\n\t}\n\n\toptions := &k8smetav1.GetOptions{}\n\tovm, err := virtClient.OfflineVirtualMachine(namespace).Get(vmName, options)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error fetching OfflineVirtualMachine: %v\", err)\n\t}\n\n\tif ovm.Spec.Running != running {\n\t\tovm.Spec.Running = running\n\t\t_, err := virtClient.OfflineVirtualMachine(namespace).Patch(ovm.Name, types.MergePatchType,\n\t\t\t[]byte(\"{\\\"spec\\\":{\\\"running\\\":true}}\"))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating OfflineVirtualMachine: %v\", err)\n\t\t}\n\t} else {\n\t\tstateMsg := \"stopped\"\n\t\tif running {\n\t\t\tstateMsg = \"running\"\n\t\t}\n\t\treturn fmt.Errorf(\"Error: VirtualMachine '%s' is already %s\", vmName, stateMsg)\n\t}\n\n\treturn nil\n}\n<commit_msg>changing code according feedbacks<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 offlinevm\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n\tk8smetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/pkg\/virtctl\/templates\"\n)\n\nconst (\n\tCOMMAND_START = \"start\"\n\tCOMMAND_STOP  = \"stop\"\n)\n\nfunc NewStartCommand(clientConfig clientcmd.ClientConfig) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:     \"start (vm)\",\n\t\tShort:   \"Start a virtual machine which is managed by an offline virtual machine.\",\n\t\tExample: usage(COMMAND_START),\n\t\tArgs:    cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc := Command{command: COMMAND_START, clientConfig: clientConfig}\n\t\t\treturn c.Run(cmd, args)\n\t\t},\n\t}\n\tcmd.SetUsageTemplate(templates.UsageTemplate())\n\treturn cmd\n}\n\nfunc NewStopCommand(clientConfig clientcmd.ClientConfig) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse:     \"stop (vm)\",\n\t\tShort:   \"Stop a virtual machine which is managed by an offline virtual machine.\",\n\t\tExample: usage(COMMAND_STOP),\n\t\tArgs:    cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc := Command{command: COMMAND_STOP, clientConfig: clientConfig}\n\t\t\treturn c.Run(cmd, args)\n\t\t},\n\t}\n}\n\ntype Command struct {\n\tclientConfig clientcmd.ClientConfig\n\tcommand      string\n}\n\nfunc NewCommand(command string) *Command {\n\treturn &Command{command: command}\n}\n\nfunc usage(cmd string) string {\n\tusage := \"#Start a virtual machine called 'myvm':\\n\"\n\tusage += fmt.Sprintf(\"virtctl %s myvm\", cmd)\n\treturn usage\n}\n\nfunc (o *Command) Run(cmd *cobra.Command, args []string) error {\n\n\tvmName := args[0]\n\n\tnamespace, _, err := o.clientConfig.Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvirtClient, err := kubecli.GetKubevirtClientFromClientConfig(o.clientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot obtain KubeVirt client: %v\", err)\n\t}\n\n\toptions := &k8smetav1.GetOptions{}\n\tovm, err := virtClient.OfflineVirtualMachine(namespace).Get(vmName, options)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error fetching OfflineVirtualMachine: %v\", err)\n\t}\n\n\tvar running bool\n\tif o.command == COMMAND_START {\n\t\trunning = true\n\t} else if o.command == COMMAND_STOP {\n\t\trunning = false\n\t}\n\n\tif ovm.Spec.Running != running {\n\t\tbodyStr := fmt.Sprintf(\"{\\\"spec\\\":{\\\"running\\\":%t}}\", running)\n\n\t\t_, err := virtClient.OfflineVirtualMachine(namespace).Patch(ovm.Name, types.MergePatchType,\n\t\t\t[]byte(bodyStr))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating OfflineVirtualMachine: %v\", err)\n\t\t}\n\n\t} else {\n\t\tstateMsg := \"stopped\"\n\t\tif running {\n\t\t\tstateMsg = \"running\"\n\t\t}\n\t\treturn fmt.Errorf(\"Error: VirtualMachine '%s' is already %s\", vmName, stateMsg)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/boltdb\/bolt\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\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\ntype BoltDbNeedleMap struct {\n\tdbFileName string\n\tdb         *bolt.DB\n\tbaseNeedleMapper\n}\n\nvar boltdbBucket = []byte(\"weed\")\n\n\/\/ TODO avoid using btree to count deletions.\nfunc NewBoltDbNeedleMap(dbFileName string, indexFile *os.File) (m *BoltDbNeedleMap, err error) {\n\tm = &BoltDbNeedleMap{dbFileName: dbFileName}\n\tm.indexFile = indexFile\n\tif !isBoltDbFresh(dbFileName, indexFile) {\n\t\tglog.V(1).Infof(\"Start to Generate %s from %s\", dbFileName, indexFile.Name())\n\t\tgenerateBoltDbFile(dbFileName, indexFile)\n\t\tglog.V(1).Infof(\"Finished Generating %s from %s\", dbFileName, indexFile.Name())\n\t}\n\tglog.V(1).Infof(\"Opening %s...\", dbFileName)\n\tif m.db, err = bolt.Open(dbFileName, 0644, nil); err != nil {\n\t\treturn\n\t}\n\tglog.V(1).Infof(\"Loading %s...\", indexFile.Name())\n\tmm, indexLoadError := newNeedleMapMetricFromIndexFile(indexFile)\n\tif indexLoadError != nil {\n\t\treturn nil, indexLoadError\n\t}\n\tm.mapMetric = *mm\n\treturn\n}\n\nfunc isBoltDbFresh(dbFileName string, indexFile *os.File) bool {\n\t\/\/ normally we always write to index file first\n\tdbLogFile, err := os.Open(dbFileName)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer dbLogFile.Close()\n\tdbStat, dbStatErr := dbLogFile.Stat()\n\tindexStat, indexStatErr := indexFile.Stat()\n\tif dbStatErr != nil || indexStatErr != nil {\n\t\tglog.V(0).Infof(\"Can not stat file: %v and %v\", dbStatErr, indexStatErr)\n\t\treturn false\n\t}\n\n\treturn dbStat.ModTime().After(indexStat.ModTime())\n}\n\nfunc generateBoltDbFile(dbFileName string, indexFile *os.File) error {\n\tdb, err := bolt.Open(dbFileName, 0644, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\treturn WalkIndexFile(indexFile, func(key NeedleId, offset Offset, size uint32) error {\n\t\tif offset > 0 && size != TombstoneFileSize {\n\t\t\tboltDbWrite(db, key, offset, size)\n\t\t} else {\n\t\t\tboltDbDelete(db, key)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (m *BoltDbNeedleMap) Get(key NeedleId) (element *needle.NeedleValue, ok bool) {\n\tvar offset Offset\n\tvar size uint32\n\tbytes := make([]byte, NeedleIdSize)\n\tNeedleIdToBytes(bytes, key)\n\terr := m.db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(boltdbBucket)\n\t\tif bucket == nil {\n\t\t\treturn fmt.Errorf(\"Bucket %q not found!\", boltdbBucket)\n\t\t}\n\n\t\tdata := bucket.Get(bytes)\n\n\t\tif len(data) != OffsetSize+SizeSize {\n\t\t\tglog.V(0).Infof(\"wrong data length: %d\", len(data))\n\t\t\treturn fmt.Errorf(\"wrong data length: %d\", len(data))\n\t\t}\n\n\t\toffset = BytesToOffset(data[0:OffsetSize])\n\t\tsize = util.BytesToUint32(data[OffsetSize:OffsetSize+SizeSize])\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\treturn &needle.NeedleValue{Key: NeedleId(key), Offset: offset, Size: size}, true\n}\n\nfunc (m *BoltDbNeedleMap) Put(key NeedleId, offset Offset, size uint32) error {\n\tvar oldSize uint32\n\tif oldNeedle, ok := m.Get(key); ok {\n\t\toldSize = oldNeedle.Size\n\t}\n\tm.logPut(key, oldSize, size)\n\t\/\/ write to index file first\n\tif err := m.appendToIndexFile(key, offset, size); err != nil {\n\t\treturn fmt.Errorf(\"cannot write to indexfile %s: %v\", m.indexFile.Name(), err)\n\t}\n\treturn boltDbWrite(m.db, key, offset, size)\n}\n\nfunc boltDbWrite(db *bolt.DB,\n\tkey NeedleId, offset Offset, size uint32) error {\n\n\tbytes := make([]byte, NeedleIdSize+OffsetSize+SizeSize)\n\tNeedleIdToBytes(bytes[0:NeedleIdSize], key)\n\tOffsetToBytes(bytes[NeedleIdSize:NeedleIdSize+OffsetSize], offset)\n\tutil.Uint32toBytes(bytes[NeedleIdSize+OffsetSize:NeedleIdSize+OffsetSize+SizeSize], size)\n\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(boltdbBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = bucket.Put(bytes[0:NeedleIdSize], bytes[NeedleIdSize:NeedleIdSize+OffsetSize+SizeSize])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\nfunc boltDbDelete(db *bolt.DB, key NeedleId) error {\n\tbytes := make([]byte, NeedleIdSize)\n\tNeedleIdToBytes(bytes, key)\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(boltdbBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = bucket.Delete(bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (m *BoltDbNeedleMap) Delete(key NeedleId, offset Offset) error {\n\tif oldNeedle, ok := m.Get(key); ok {\n\t\tm.logDelete(oldNeedle.Size)\n\t}\n\t\/\/ write to index file first\n\tif err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {\n\t\treturn err\n\t}\n\treturn boltDbDelete(m.db, key)\n}\n\nfunc (m *BoltDbNeedleMap) Close() {\n\tm.indexFile.Close()\n\tm.db.Close()\n}\n\nfunc (m *BoltDbNeedleMap) Destroy() error {\n\tm.Close()\n\tos.Remove(m.indexFile.Name())\n\treturn os.Remove(m.dbFileName)\n}\n<commit_msg>avoid extra log messages<commit_after>package storage\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/boltdb\/bolt\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\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\t\"errors\"\n)\n\ntype BoltDbNeedleMap struct {\n\tdbFileName string\n\tdb         *bolt.DB\n\tbaseNeedleMapper\n}\n\nvar boltdbBucket = []byte(\"weed\")\n\nvar NotFound = errors.New(\"not found\")\n\n\/\/ TODO avoid using btree to count deletions.\nfunc NewBoltDbNeedleMap(dbFileName string, indexFile *os.File) (m *BoltDbNeedleMap, err error) {\n\tm = &BoltDbNeedleMap{dbFileName: dbFileName}\n\tm.indexFile = indexFile\n\tif !isBoltDbFresh(dbFileName, indexFile) {\n\t\tglog.V(1).Infof(\"Start to Generate %s from %s\", dbFileName, indexFile.Name())\n\t\tgenerateBoltDbFile(dbFileName, indexFile)\n\t\tglog.V(1).Infof(\"Finished Generating %s from %s\", dbFileName, indexFile.Name())\n\t}\n\tglog.V(1).Infof(\"Opening %s...\", dbFileName)\n\tif m.db, err = bolt.Open(dbFileName, 0644, nil); err != nil {\n\t\treturn\n\t}\n\tglog.V(1).Infof(\"Loading %s...\", indexFile.Name())\n\tmm, indexLoadError := newNeedleMapMetricFromIndexFile(indexFile)\n\tif indexLoadError != nil {\n\t\treturn nil, indexLoadError\n\t}\n\tm.mapMetric = *mm\n\treturn\n}\n\nfunc isBoltDbFresh(dbFileName string, indexFile *os.File) bool {\n\t\/\/ normally we always write to index file first\n\tdbLogFile, err := os.Open(dbFileName)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer dbLogFile.Close()\n\tdbStat, dbStatErr := dbLogFile.Stat()\n\tindexStat, indexStatErr := indexFile.Stat()\n\tif dbStatErr != nil || indexStatErr != nil {\n\t\tglog.V(0).Infof(\"Can not stat file: %v and %v\", dbStatErr, indexStatErr)\n\t\treturn false\n\t}\n\n\treturn dbStat.ModTime().After(indexStat.ModTime())\n}\n\nfunc generateBoltDbFile(dbFileName string, indexFile *os.File) error {\n\tdb, err := bolt.Open(dbFileName, 0644, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\treturn WalkIndexFile(indexFile, func(key NeedleId, offset Offset, size uint32) error {\n\t\tif offset > 0 && size != TombstoneFileSize {\n\t\t\tboltDbWrite(db, key, offset, size)\n\t\t} else {\n\t\t\tboltDbDelete(db, key)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (m *BoltDbNeedleMap) Get(key NeedleId) (element *needle.NeedleValue, ok bool) {\n\tvar offset Offset\n\tvar size uint32\n\tbytes := make([]byte, NeedleIdSize)\n\tNeedleIdToBytes(bytes, key)\n\terr := m.db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(boltdbBucket)\n\t\tif bucket == nil {\n\t\t\treturn fmt.Errorf(\"Bucket %q not found!\", boltdbBucket)\n\t\t}\n\n\t\tdata := bucket.Get(bytes)\n\n\t\tif len(data) == 0 {\n\t\t\treturn NotFound\n\t\t}\n\n\t\tif len(data) != OffsetSize+SizeSize {\n\t\t\tglog.V(0).Infof(\"key:%v has wrong data length: %d\", key, len(data))\n\t\t\treturn fmt.Errorf(\"key:%v has wrong data length: %d\", key, len(data))\n\t\t}\n\n\t\toffset = BytesToOffset(data[0:OffsetSize])\n\t\tsize = util.BytesToUint32(data[OffsetSize:OffsetSize+SizeSize])\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\treturn &needle.NeedleValue{Key: key, Offset: offset, Size: size}, true\n}\n\nfunc (m *BoltDbNeedleMap) Put(key NeedleId, offset Offset, size uint32) error {\n\tvar oldSize uint32\n\tif oldNeedle, ok := m.Get(key); ok {\n\t\toldSize = oldNeedle.Size\n\t}\n\tm.logPut(key, oldSize, size)\n\t\/\/ write to index file first\n\tif err := m.appendToIndexFile(key, offset, size); err != nil {\n\t\treturn fmt.Errorf(\"cannot write to indexfile %s: %v\", m.indexFile.Name(), err)\n\t}\n\treturn boltDbWrite(m.db, key, offset, size)\n}\n\nfunc boltDbWrite(db *bolt.DB,\n\tkey NeedleId, offset Offset, size uint32) error {\n\n\tbytes := make([]byte, NeedleIdSize+OffsetSize+SizeSize)\n\tNeedleIdToBytes(bytes[0:NeedleIdSize], key)\n\tOffsetToBytes(bytes[NeedleIdSize:NeedleIdSize+OffsetSize], offset)\n\tutil.Uint32toBytes(bytes[NeedleIdSize+OffsetSize:NeedleIdSize+OffsetSize+SizeSize], size)\n\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(boltdbBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = bucket.Put(bytes[0:NeedleIdSize], bytes[NeedleIdSize:NeedleIdSize+OffsetSize+SizeSize])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\nfunc boltDbDelete(db *bolt.DB, key NeedleId) error {\n\tbytes := make([]byte, NeedleIdSize)\n\tNeedleIdToBytes(bytes, key)\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tbucket, err := tx.CreateBucketIfNotExists(boltdbBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = bucket.Delete(bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (m *BoltDbNeedleMap) Delete(key NeedleId, offset Offset) error {\n\tif oldNeedle, ok := m.Get(key); ok {\n\t\tm.logDelete(oldNeedle.Size)\n\t}\n\t\/\/ write to index file first\n\tif err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {\n\t\treturn err\n\t}\n\treturn boltDbDelete(m.db, key)\n}\n\nfunc (m *BoltDbNeedleMap) Close() {\n\tm.indexFile.Close()\n\tm.db.Close()\n}\n\nfunc (m *BoltDbNeedleMap) Destroy() error {\n\tm.Close()\n\tos.Remove(m.indexFile.Name())\n\treturn os.Remove(m.dbFileName)\n}\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/memory_map\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t. \"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n)\n\nvar ErrorNotFound = errors.New(\"not found\")\n\n\/\/ isFileUnchanged checks whether this needle to write is same as last one.\n\/\/ It requires serialized access in the same volume.\nfunc (v *Volume) isFileUnchanged(n *needle.Needle) bool {\n\tif v.Ttl.String() != \"\" {\n\t\treturn false\n\t}\n\n\tnv, ok := v.nm.Get(n.Id)\n\tif ok && !nv.Offset.IsZero() && nv.Size != TombstoneFileSize {\n\t\toldNeedle := new(needle.Needle)\n\t\terr := oldNeedle.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"Failed to check updated file at offset %d size %d: %v\", nv.Offset.ToAcutalOffset(), nv.Size, err)\n\t\t\treturn false\n\t\t}\n\t\tif oldNeedle.Cookie == n.Cookie && oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {\n\t\t\tn.DataSize = oldNeedle.DataSize\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Destroy removes everything related to this volume\nfunc (v *Volume) Destroy() (err error) {\n\tif v.isCompacting {\n\t\terr = fmt.Errorf(\"volume %d is compacting\", v.Id)\n\t\treturn\n\t}\n\tmMap, exists := memory_map.FileMemoryMap[v.dataFile.Name()]\n\tif exists {\n\t\tmMap.DeleteFileAndMemoryMap()\n\t\tdelete(memory_map.FileMemoryMap, v.dataFile.Name())\n\t}\n\n\tv.Close()\n\tos.Remove(v.FileName() + \".dat\")\n\tos.Remove(v.FileName() + \".idx\")\n\tos.Remove(v.FileName() + \".cpd\")\n\tos.Remove(v.FileName() + \".cpx\")\n\tos.Remove(v.FileName() + \".ldb\")\n\tos.Remove(v.FileName() + \".bdb\")\n\treturn\n}\n\nfunc (v *Volume) writeNeedle(n *needle.Needle) (offset uint64, size uint32, isUnchanged bool, err error) {\n\tglog.V(4).Infof(\"writing needle %s\", needle.NewFileIdFromNeedle(v.Id, n).String())\n\tif v.readOnly {\n\t\terr = fmt.Errorf(\"%s is read-only\", v.dataFile.Name())\n\t\treturn\n\t}\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\tif v.isFileUnchanged(n) {\n\t\tsize = n.DataSize\n\t\tisUnchanged = true\n\t\treturn\n\t}\n\n\tif n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {\n\t\tn.SetHasTtl()\n\t\tn.Ttl = v.Ttl\n\t}\n\n\t\/\/ check whether existing needle cookie matches\n\tnv, ok := v.nm.Get(n.Id)\n\tif ok {\n\t\texistingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.dataFile, v.Version(), nv.Offset.ToAcutalOffset())\n\t\tif existingNeedleReadErr != nil {\n\t\t\terr = fmt.Errorf(\"reading existing needle: %v\", existingNeedleReadErr)\n\t\t\treturn\n\t\t}\n\t\tif existingNeedle.Cookie != n.Cookie {\n\t\t\tglog.V(0).Infof(\"write cookie mismatch: existing %x, new %x\", existingNeedle.Cookie, n.Cookie)\n\t\t\terr = fmt.Errorf(\"mismatching cookie %x\", n.Cookie)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ append to dat file\n\tn.AppendAtNs = uint64(time.Now().UnixNano())\n\tif offset, size, _, err = n.Append(v.dataFile, v.Version()); err != nil {\n\t\treturn\n\t}\n\tv.lastAppendAtNs = n.AppendAtNs\n\n\t\/\/ add to needle map\n\tif !ok || uint64(nv.Offset.ToAcutalOffset()) < offset {\n\t\tif err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {\n\t\t\tglog.V(4).Infof(\"failed to save in needle map %d: %v\", n.Id, err)\n\t\t}\n\t}\n\tif v.lastModifiedTsSeconds < n.LastModified {\n\t\tv.lastModifiedTsSeconds = n.LastModified\n\t}\n\treturn\n}\n\nfunc (v *Volume) deleteNeedle(n *needle.Needle) (uint32, error) {\n\tglog.V(4).Infof(\"delete needle %s\", needle.NewFileIdFromNeedle(v.Id, n).String())\n\tif v.readOnly {\n\t\treturn 0, fmt.Errorf(\"%s is read-only\", v.dataFile.Name())\n\t}\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\tnv, ok := v.nm.Get(n.Id)\n\t\/\/fmt.Println(\"key\", n.Id, \"volume offset\", nv.Offset, \"data_size\", n.Size, \"cached size\", nv.Size)\n\tif ok && nv.Size != TombstoneFileSize {\n\t\tsize := nv.Size\n\t\tn.Data = nil\n\t\tn.AppendAtNs = uint64(time.Now().UnixNano())\n\t\toffset, _, _, err := n.Append(v.dataFile, v.Version())\n\t\tif err != nil {\n\t\t\treturn size, err\n\t\t}\n\t\tv.lastAppendAtNs = n.AppendAtNs\n\t\tif err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {\n\t\t\treturn size, err\n\t\t}\n\t\treturn size, err\n\t}\n\treturn 0, nil\n}\n\n\/\/ read fills in Needle content by looking up n.Id from NeedleMapper\nfunc (v *Volume) readNeedle(n *needle.Needle) (int, error) {\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\n\tnv, ok := v.nm.Get(n.Id)\n\tif !ok || nv.Offset.IsZero() {\n\t\treturn -1, ErrorNotFound\n\t}\n\tif nv.Size == TombstoneFileSize {\n\t\treturn -1, errors.New(\"already deleted\")\n\t}\n\tif nv.Size == 0 {\n\t\treturn 0, nil\n\t}\n\terr := n.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbytesRead := len(n.Data)\n\tif !n.HasTtl() {\n\t\treturn bytesRead, nil\n\t}\n\tttlMinutes := n.Ttl.Minutes()\n\tif ttlMinutes == 0 {\n\t\treturn bytesRead, nil\n\t}\n\tif !n.HasLastModifiedDate() {\n\t\treturn bytesRead, nil\n\t}\n\tif uint64(time.Now().Unix()) < n.LastModified+uint64(ttlMinutes*60) {\n\t\treturn bytesRead, nil\n\t}\n\treturn -1, ErrorNotFound\n}\n\ntype VolumeFileScanner interface {\n\tVisitSuperBlock(SuperBlock) error\n\tReadNeedleBody() bool\n\tVisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error\n}\n\nfunc ScanVolumeFile(dirname string, collection string, id needle.VolumeId,\n\tneedleMapKind NeedleMapType,\n\tvolumeFileScanner VolumeFileScanner) (err error) {\n\tvar v *Volume\n\tif v, err = loadVolumeWithoutIndex(dirname, collection, id, needleMapKind); err != nil {\n\t\treturn fmt.Errorf(\"failed to load volume %d: %v\", id, err)\n\t}\n\tif err = volumeFileScanner.VisitSuperBlock(v.SuperBlock); err != nil {\n\t\treturn fmt.Errorf(\"failed to process volume %d super block: %v\", id, err)\n\t}\n\tdefer v.Close()\n\n\tversion := v.Version()\n\n\toffset := int64(v.SuperBlock.BlockSize())\n\n\treturn ScanVolumeFileFrom(version, v.dataFile, offset, volumeFileScanner)\n}\n\nfunc ScanVolumeFileFrom(version needle.Version, dataFile *os.File, offset int64, volumeFileScanner VolumeFileScanner) (err error) {\n\tn, nh, rest, e := needle.ReadNeedleHeader(dataFile, version, offset)\n\tif e != nil {\n\t\tif e == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"cannot read %s at offset %d: %v\", dataFile.Name(), offset, e)\n\t}\n\tfor n != nil {\n\t\tvar needleBody []byte\n\t\tif volumeFileScanner.ReadNeedleBody() {\n\t\t\tif needleBody, err = n.ReadNeedleBody(dataFile, version, offset+NeedleHeaderSize, rest); err != nil {\n\t\t\t\tglog.V(0).Infof(\"cannot read needle body: %v\", err)\n\t\t\t\t\/\/err = fmt.Errorf(\"cannot read needle body: %v\", err)\n\t\t\t\t\/\/return\n\t\t\t}\n\t\t}\n\t\terr := volumeFileScanner.VisitNeedle(n, offset, nh, needleBody)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"visit needle error: %v\", err)\n\t\t\treturn fmt.Errorf(\"visit needle error: %v\", err)\n\t\t}\n\t\toffset += NeedleHeaderSize + rest\n\t\tglog.V(4).Infof(\"==> new entry offset %d\", offset)\n\t\tif n, _, rest, err = needle.ReadNeedleHeader(dataFile, version, offset); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"cannot read needle header at offset %d: %v\", offset, err)\n\t\t}\n\t\tglog.V(4).Infof(\"new entry needle size:%d rest:%d\", n.Size, rest)\n\t}\n\treturn nil\n}\n<commit_msg>fix missing needle header read<commit_after>package storage\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/memory_map\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t. \"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n)\n\nvar ErrorNotFound = errors.New(\"not found\")\n\n\/\/ isFileUnchanged checks whether this needle to write is same as last one.\n\/\/ It requires serialized access in the same volume.\nfunc (v *Volume) isFileUnchanged(n *needle.Needle) bool {\n\tif v.Ttl.String() != \"\" {\n\t\treturn false\n\t}\n\n\tnv, ok := v.nm.Get(n.Id)\n\tif ok && !nv.Offset.IsZero() && nv.Size != TombstoneFileSize {\n\t\toldNeedle := new(needle.Needle)\n\t\terr := oldNeedle.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"Failed to check updated file at offset %d size %d: %v\", nv.Offset.ToAcutalOffset(), nv.Size, err)\n\t\t\treturn false\n\t\t}\n\t\tif oldNeedle.Cookie == n.Cookie && oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {\n\t\t\tn.DataSize = oldNeedle.DataSize\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Destroy removes everything related to this volume\nfunc (v *Volume) Destroy() (err error) {\n\tif v.isCompacting {\n\t\terr = fmt.Errorf(\"volume %d is compacting\", v.Id)\n\t\treturn\n\t}\n\tmMap, exists := memory_map.FileMemoryMap[v.dataFile.Name()]\n\tif exists {\n\t\tmMap.DeleteFileAndMemoryMap()\n\t\tdelete(memory_map.FileMemoryMap, v.dataFile.Name())\n\t}\n\n\tv.Close()\n\tos.Remove(v.FileName() + \".dat\")\n\tos.Remove(v.FileName() + \".idx\")\n\tos.Remove(v.FileName() + \".cpd\")\n\tos.Remove(v.FileName() + \".cpx\")\n\tos.Remove(v.FileName() + \".ldb\")\n\tos.Remove(v.FileName() + \".bdb\")\n\treturn\n}\n\nfunc (v *Volume) writeNeedle(n *needle.Needle) (offset uint64, size uint32, isUnchanged bool, err error) {\n\tglog.V(4).Infof(\"writing needle %s\", needle.NewFileIdFromNeedle(v.Id, n).String())\n\tif v.readOnly {\n\t\terr = fmt.Errorf(\"%s is read-only\", v.dataFile.Name())\n\t\treturn\n\t}\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\tif v.isFileUnchanged(n) {\n\t\tsize = n.DataSize\n\t\tisUnchanged = true\n\t\treturn\n\t}\n\n\tif n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {\n\t\tn.SetHasTtl()\n\t\tn.Ttl = v.Ttl\n\t}\n\n\t\/\/ check whether existing needle cookie matches\n\tnv, ok := v.nm.Get(n.Id)\n\tif ok {\n\t\texistingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.dataFile, v.Version(), nv.Offset.ToAcutalOffset())\n\t\tif existingNeedleReadErr != nil {\n\t\t\terr = fmt.Errorf(\"reading existing needle: %v\", existingNeedleReadErr)\n\t\t\treturn\n\t\t}\n\t\tif existingNeedle.Cookie != n.Cookie {\n\t\t\tglog.V(0).Infof(\"write cookie mismatch: existing %x, new %x\", existingNeedle.Cookie, n.Cookie)\n\t\t\terr = fmt.Errorf(\"mismatching cookie %x\", n.Cookie)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ append to dat file\n\tn.AppendAtNs = uint64(time.Now().UnixNano())\n\tif offset, size, _, err = n.Append(v.dataFile, v.Version()); err != nil {\n\t\treturn\n\t}\n\tv.lastAppendAtNs = n.AppendAtNs\n\n\t\/\/ add to needle map\n\tif !ok || uint64(nv.Offset.ToAcutalOffset()) < offset {\n\t\tif err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {\n\t\t\tglog.V(4).Infof(\"failed to save in needle map %d: %v\", n.Id, err)\n\t\t}\n\t}\n\tif v.lastModifiedTsSeconds < n.LastModified {\n\t\tv.lastModifiedTsSeconds = n.LastModified\n\t}\n\treturn\n}\n\nfunc (v *Volume) deleteNeedle(n *needle.Needle) (uint32, error) {\n\tglog.V(4).Infof(\"delete needle %s\", needle.NewFileIdFromNeedle(v.Id, n).String())\n\tif v.readOnly {\n\t\treturn 0, fmt.Errorf(\"%s is read-only\", v.dataFile.Name())\n\t}\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\tnv, ok := v.nm.Get(n.Id)\n\t\/\/fmt.Println(\"key\", n.Id, \"volume offset\", nv.Offset, \"data_size\", n.Size, \"cached size\", nv.Size)\n\tif ok && nv.Size != TombstoneFileSize {\n\t\tsize := nv.Size\n\t\tn.Data = nil\n\t\tn.AppendAtNs = uint64(time.Now().UnixNano())\n\t\toffset, _, _, err := n.Append(v.dataFile, v.Version())\n\t\tif err != nil {\n\t\t\treturn size, err\n\t\t}\n\t\tv.lastAppendAtNs = n.AppendAtNs\n\t\tif err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {\n\t\t\treturn size, err\n\t\t}\n\t\treturn size, err\n\t}\n\treturn 0, nil\n}\n\n\/\/ read fills in Needle content by looking up n.Id from NeedleMapper\nfunc (v *Volume) readNeedle(n *needle.Needle) (int, error) {\n\tv.dataFileAccessLock.Lock()\n\tdefer v.dataFileAccessLock.Unlock()\n\n\tnv, ok := v.nm.Get(n.Id)\n\tif !ok || nv.Offset.IsZero() {\n\t\treturn -1, ErrorNotFound\n\t}\n\tif nv.Size == TombstoneFileSize {\n\t\treturn -1, errors.New(\"already deleted\")\n\t}\n\tif nv.Size == 0 {\n\t\treturn 0, nil\n\t}\n\terr := n.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbytesRead := len(n.Data)\n\tif !n.HasTtl() {\n\t\treturn bytesRead, nil\n\t}\n\tttlMinutes := n.Ttl.Minutes()\n\tif ttlMinutes == 0 {\n\t\treturn bytesRead, nil\n\t}\n\tif !n.HasLastModifiedDate() {\n\t\treturn bytesRead, nil\n\t}\n\tif uint64(time.Now().Unix()) < n.LastModified+uint64(ttlMinutes*60) {\n\t\treturn bytesRead, nil\n\t}\n\treturn -1, ErrorNotFound\n}\n\ntype VolumeFileScanner interface {\n\tVisitSuperBlock(SuperBlock) error\n\tReadNeedleBody() bool\n\tVisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error\n}\n\nfunc ScanVolumeFile(dirname string, collection string, id needle.VolumeId,\n\tneedleMapKind NeedleMapType,\n\tvolumeFileScanner VolumeFileScanner) (err error) {\n\tvar v *Volume\n\tif v, err = loadVolumeWithoutIndex(dirname, collection, id, needleMapKind); err != nil {\n\t\treturn fmt.Errorf(\"failed to load volume %d: %v\", id, err)\n\t}\n\tif err = volumeFileScanner.VisitSuperBlock(v.SuperBlock); err != nil {\n\t\treturn fmt.Errorf(\"failed to process volume %d super block: %v\", id, err)\n\t}\n\tdefer v.Close()\n\n\tversion := v.Version()\n\n\toffset := int64(v.SuperBlock.BlockSize())\n\n\treturn ScanVolumeFileFrom(version, v.dataFile, offset, volumeFileScanner)\n}\n\nfunc ScanVolumeFileFrom(version needle.Version, dataFile *os.File, offset int64, volumeFileScanner VolumeFileScanner) (err error) {\n\tn, nh, rest, e := needle.ReadNeedleHeader(dataFile, version, offset)\n\tif e != nil {\n\t\tif e == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"cannot read %s at offset %d: %v\", dataFile.Name(), offset, e)\n\t}\n\tfor n != nil {\n\t\tvar needleBody []byte\n\t\tif volumeFileScanner.ReadNeedleBody() {\n\t\t\tif needleBody, err = n.ReadNeedleBody(dataFile, version, offset+NeedleHeaderSize, rest); err != nil {\n\t\t\t\tglog.V(0).Infof(\"cannot read needle body: %v\", err)\n\t\t\t\t\/\/err = fmt.Errorf(\"cannot read needle body: %v\", err)\n\t\t\t\t\/\/return\n\t\t\t}\n\t\t}\n\t\terr := volumeFileScanner.VisitNeedle(n, offset, nh, needleBody)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"visit needle error: %v\", err)\n\t\t\treturn fmt.Errorf(\"visit needle error: %v\", err)\n\t\t}\n\t\toffset += NeedleHeaderSize + rest\n\t\tglog.V(4).Infof(\"==> new entry offset %d\", offset)\n\t\tif n, nh, rest, err = needle.ReadNeedleHeader(dataFile, version, offset); err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"cannot read needle header at offset %d: %v\", offset, err)\n\t\t}\n\t\tglog.V(4).Infof(\"new entry needle size:%d rest:%d\", n.Size, rest)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package fs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/op\/go-logging\"\n\t\"github.com\/subgraph\/oz\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n)\n\ntype Filesystem struct {\n\tlog    *logging.Logger\n\tbase   string\n\tchroot bool\n}\n\nfunc NewFilesystem(config *oz.Config, log *logging.Logger) *Filesystem {\n\tif log == nil {\n\t\tlog = logging.MustGetLogger(\"oz\")\n\t}\n\treturn &Filesystem{\n\t\tbase: config.SandboxPath,\n\t\tlog:  log,\n\t}\n}\n\nfunc (fs *Filesystem) Root() string {\n\treturn path.Join(fs.base, \"rootfs\")\n}\n\nfunc (fs *Filesystem) CreateEmptyDir(target string) error {\n\tfi, err := os.Stat(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !fs.chroot {\n\t\ttarget = path.Join(fs.Root(), target)\n\t}\n\tif err := os.MkdirAll(target, fi.Mode().Perm()); err != nil {\n\t\treturn err\n\t}\n\treturn copyFileInfo(fi, target)\n}\n\nfunc (fs *Filesystem) CreateDevice(devpath string, dev int, mode, perm uint32) error {\n\tp := path.Join(fs.Root(), devpath)\n\tif err := syscall.Mknod(p, mode, dev); err != nil {\n\t\treturn fmt.Errorf(\"failed to mknod device '%s': %v\", p, err)\n\t}\n\tif err := os.Chmod(p, os.FileMode(perm)); err != nil {\n\t\treturn fmt.Errorf(\"unable to set file permissions on device '%s': %v\", p, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) CreateSymlink(oldpath, newpath string) error {\n\tif !fs.chroot {\n\t\tnewpath = path.Join(fs.Root(), newpath)\n\t}\n\tif err := syscall.Symlink(oldpath, newpath); err != nil {\n\t\treturn fmt.Errorf(\"failed to symlink %s to %s: %v\", newpath, oldpath, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) BindPath(target string, flags int, u *user.User) error {\n\treturn fs.bindResolve(target, \"\", flags, u)\n}\n\nfunc (fs *Filesystem) BindTo(from string, to string, flags int, u *user.User) error {\n\treturn fs.bindResolve(from, to, flags, u)\n}\n\nconst (\n\tBindReadOnly = 1 << iota\n\tBindCanCreate\n)\n\nfunc (fs *Filesystem) bindResolve(from string, to string, flags int, u *user.User) error {\n\tif (to == \"\") || (from == to) {\n\t\treturn fs.bindSame(from, flags, u)\n\t}\n\tif isGlobbed(to) {\n\t\treturn fmt.Errorf(\"bind target (%s) cannot have globbed path\", to)\n\t}\n\tt, err := resolveVars(to, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isGlobbed(from) {\n\t\treturn fmt.Errorf(\"bind src (%s) cannot have globbed path with separate target path (%s)\", from, to)\n\t}\n\tf, err := resolveVars(from, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn fs.bind(f, t, flags, u)\n}\n\nfunc (fs *Filesystem) bindSame(p string, flags int, u *user.User) error {\n\tps, err := resolvePath(p, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range ps {\n\t\tif err := fs.bind(p, p, flags, u); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) bind(from string, to string, flags int, u *user.User) error {\n\tsrc, err := filepath.EvalSymlinks(from)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resolving symlinks for path (%s): %v\", from, err)\n\t}\n\tcc := flags&BindCanCreate != 0\n\tsinfo, err := readSourceInfo(src, cc, u)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to bind path (%s): %v\", src, err)\n\t}\n\n\tif to == \"\" {\n\t\tto = from\n\t}\n\tto = path.Join(fs.Root(), to)\n\n\t_, err = os.Stat(to)\n\tif err == nil || !os.IsNotExist(err) {\n\t\tfs.log.Warning(\"Target (%s > %s) already exists, ignoring\", src, to)\n\t\treturn nil\n\t}\n\n\tif sinfo.IsDir() {\n\t\tif err := os.MkdirAll(to, sinfo.Mode().Perm()); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := createEmptyFile(to, 0750); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := copyPathPermissions(fs.Root(), src); err != nil {\n\t\treturn fmt.Errorf(\"failed to copy path permissions for (%s): %v\", src, err)\n\t}\n\tfs.log.Info(\"bind mounting %s -> %s\", src, to)\n\tmntflags := syscall.MS_NOSUID | syscall.MS_NODEV\n\tif flags&BindReadOnly != 0 {\n\t\tmntflags |= syscall.MS_RDONLY\n\t} else {\n\t\tflags |= syscall.MS_NOEXEC\n\t}\n\treturn bindMount(src, to, mntflags)\n}\n\nfunc readSourceInfo(src string, cancreate bool, u *user.User) (os.FileInfo, error) {\n\tif fi, err := os.Stat(src); err == nil {\n\t\treturn fi, nil\n\t} else if !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif u == nil || !cancreate {\n\t\treturn nil, fmt.Errorf(\"source path (%s) does not exist\", src)\n\t}\n\n\thome := u.HomeDir\n\tif !strings.HasPrefix(src, home) {\n\t\treturn nil, fmt.Errorf(\"mount item (%s) has flag MountCreateIfAbsent, but is not child of home directory (%s)\", src, home)\n\t}\n\n\tif err := os.MkdirAll(src, 0750); err != nil {\n\t\treturn nil, err\n\t}\n\n\tpinfo, err := os.Stat(path.Dir(src))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := copyFileInfo(pinfo, src); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.Stat(src)\n}\n\nfunc (fs *Filesystem) BlacklistPath(target string, u *user.User) error {\n\tps, err := resolvePath(target, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range ps {\n\t\tif err := fs.blacklist(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) blacklist(target string) error {\n\tt, err := filepath.EvalSymlinks(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"symlink evaluation failed while blacklisting path %s: %v\", target, err)\n\t}\n\tfi, err := os.Stat(t)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tfs.log.Info(\"Blacklist path (%s) does not exist\", t)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tsrc := emptyFilePath\n\tif fi.IsDir() {\n\t\tsrc = emptyDirPath\n\t}\n\tif !fs.chroot {\n\t\tsrc = path.Join(fs.Root(), src)\n\t\tt = path.Join(fs.Root(), t)\n\t}\n\tif err := syscall.Mount(src, t, \"\", syscall.MS_BIND, \"mode=400,gid=0\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to bind %s -> %s for blacklist: %v\", src, t, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) Chroot() error {\n\tif fs.chroot {\n\t\treturn fmt.Errorf(\"filesystem is already in chroot()\")\n\t}\n\tfs.log.Debug(\"chroot to %s\", fs.Root())\n\tif err := syscall.Chroot(fs.Root()); err != nil {\n\t\treturn fmt.Errorf(\"chroot to %s failed: %v\", fs.Root(), err)\n\t}\n\tif err := os.Chdir(\"\/\"); err != nil {\n\t\treturn fmt.Errorf(\"chdir to \/ after chroot() failed: %v\", err)\n\t}\n\tfs.chroot = true\n\treturn nil\n}\n\nfunc (fs *Filesystem) MountProc() error {\n\terr := fs.mountSpecial(\"\/proc\", \"proc\", 0, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\troMounts := []string{\n\t\t\"sysrq-trigger\",\n\t\t\"bus\",\n\t\t\"irq\",\n\t\t\"sys\/kernel\/hotplug\",\n\t}\n\tfor _, rom := range roMounts {\n\t\tif _, err := os.Stat(rom); err == nil {\n\t\t\tif err := bindMount(rom, rom, syscall.MS_RDONLY); err != nil {\n\t\t\t\treturn fmt.Errorf(\"remount RO of %s failed: %v\", rom, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) MountFullDev() error {\n\treturn fs.mountSpecial(\"\/dev\", \"devtmpfs\", 0, \"\")\n}\n\nfunc (fs *Filesystem) MountSys() error {\n\treturn fs.mountSpecial(\"\/sys\", \"sysfs\", syscall.MS_RDONLY, \"\")\n}\n\nfunc (fs *Filesystem) MountTmp() error {\n\treturn fs.mountSpecial(\"\/tmp\", \"tmpfs\", syscall.MS_NODEV, \"\")\n}\n\nfunc (fs *Filesystem) MountPts() error {\n\treturn fs.mountSpecial(\"\/dev\/pts\", \"devpts\", 0, \"newinstance,ptmxmode=0666\")\n}\n\nfunc (fs *Filesystem) MountShm() error {\n\treturn fs.mountSpecial(\"\/dev\/shm\", \"tmpfs\", syscall.MS_NODEV, \"\")\n}\n\nfunc (fs *Filesystem) mountSpecial(path, mtype string, flags int, args string) error {\n\tif !fs.chroot {\n\t\treturn fmt.Errorf(\"cannot mount %s (%s) until Chroot() is called.\", path, mtype)\n\t}\n\tfs.log.Debug(\"Mounting %s [%s]\", path, mtype)\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create mount point (%s): %v\", path, err)\n\t}\n\tmountFlags := uintptr(flags | syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_REC)\n\treturn syscall.Mount(\"\", path, mtype, mountFlags, args)\n}\n\nfunc bindMount(source, target string, flags int) error {\n\tif err := syscall.Mount(source, target, \"\", syscall.MS_BIND, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"bind mount of %s -> %s failed: %v\", source, target, err)\n\t}\n\tif flags != 0 {\n\t\treturn remount(target, flags)\n\t}\n\treturn nil\n}\n\nfunc remount(target string, flags int) error {\n\tfl := uintptr(flags | syscall.MS_BIND | syscall.MS_REMOUNT)\n\tif err := syscall.Mount(\"\", target, \"\", fl, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to remount %s with flags %x: %v\", target, flags, err)\n\t}\n\treturn nil\n}\n\nconst emptyFilePath = \"\/oz.ro.file\"\nconst emptyDirPath = \"\/oz.ro.dir\"\n\nfunc (fs *Filesystem) CreateBlacklistPaths() error {\n\tp := emptyDirPath\n\tif !fs.chroot {\n\t\tp = path.Join(fs.Root(), emptyDirPath)\n\t}\n\tif err := createBlacklistDir(p); err != nil {\n\t\treturn err\n\t}\n\tp = emptyFilePath\n\tif !fs.chroot {\n\t\tp = path.Join(fs.Root(), emptyFilePath)\n\t}\n\tif err := createBlacklistFile(p); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc createBlacklistDir(p string) error {\n\tif err := os.MkdirAll(p, 0000); err != nil {\n\t\treturn err\n\t}\n\treturn setBlacklistPerms(p, 0500)\n}\n\nfunc createBlacklistFile(path string) error {\n\tfd, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := fd.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn setBlacklistPerms(path, 0400)\n}\n\nfunc setBlacklistPerms(path string, mode os.FileMode) error {\n\tif err := os.Chown(path, 0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chmod(path, mode); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc createEmptyFile(name string, mode os.FileMode) error {\n\tif err := os.MkdirAll(path.Dir(name), 0750); err != nil {\n\t\treturn err\n\t}\n\tfd, err := os.Create(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := fd.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chmod(name, mode); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc copyPathPermissions(root, src string) error {\n\tcurrent := \"\/\"\n\tfor _, part := range strings.Split(src, \"\/\") {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcurrent = path.Join(current, part)\n\t\ttarget := path.Join(root, current)\n\t\tif err := copyFilePermissions(current, target); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc copyFilePermissions(src, target string) error {\n\tfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn copyFileInfo(fi, target)\n}\n\nfunc copyFileInfo(info os.FileInfo, target string) error {\n\tst := info.Sys().(*syscall.Stat_t)\n\tos.Chown(target, int(st.Uid), int(st.Gid))\n\tos.Chmod(target, info.Mode().Perm())\n\treturn nil\n}\n<commit_msg>added helper function to resolve paths correctly both inside and outside of chroot<commit_after>package fs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/op\/go-logging\"\n\t\"github.com\/subgraph\/oz\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n)\n\ntype Filesystem struct {\n\tlog    *logging.Logger\n\tbase   string\n\tchroot bool\n}\n\nfunc NewFilesystem(config *oz.Config, log *logging.Logger) *Filesystem {\n\tif log == nil {\n\t\tlog = logging.MustGetLogger(\"oz\")\n\t}\n\treturn &Filesystem{\n\t\tbase: config.SandboxPath,\n\t\tlog:  log,\n\t}\n}\n\nfunc (fs *Filesystem) Root() string {\n\treturn path.Join(fs.base, \"rootfs\")\n}\n\nfunc (fs *Filesystem) absPath(p string) string {\n\tif fs.chroot {\n\t\treturn p\n\t}\n\treturn path.Join(fs.Root(), p)\n}\n\nfunc (fs *Filesystem) CreateEmptyDir(target string) error {\n\tfi, err := os.Stat(target)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(fs.absPath(target), fi.Mode().Perm()); err != nil {\n\t\treturn err\n\t}\n\treturn copyFileInfo(fi, target)\n}\n\nfunc (fs *Filesystem) CreateDevice(devpath string, dev int, mode, perm uint32) error {\n\tp := fs.absPath(devpath)\n\tif err := syscall.Mknod(p, mode, dev); err != nil {\n\t\treturn fmt.Errorf(\"failed to mknod device '%s': %v\", p, err)\n\t}\n\tif err := os.Chmod(p, os.FileMode(perm)); err != nil {\n\t\treturn fmt.Errorf(\"unable to set file permissions on device '%s': %v\", p, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) CreateSymlink(oldpath, newpath string) error {\n\tif err := syscall.Symlink(oldpath, fs.absPath(newpath)); err != nil {\n\t\treturn fmt.Errorf(\"failed to symlink %s to %s: %v\", fs.absPath(newpath), oldpath, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) BindPath(target string, flags int, u *user.User) error {\n\treturn fs.bindResolve(target, \"\", flags, u)\n}\n\nfunc (fs *Filesystem) BindTo(from string, to string, flags int, u *user.User) error {\n\treturn fs.bindResolve(from, to, flags, u)\n}\n\nconst (\n\tBindReadOnly = 1 << iota\n\tBindCanCreate\n)\n\nfunc (fs *Filesystem) bindResolve(from string, to string, flags int, u *user.User) error {\n\tif (to == \"\") || (from == to) {\n\t\treturn fs.bindSame(from, flags, u)\n\t}\n\tif isGlobbed(to) {\n\t\treturn fmt.Errorf(\"bind target (%s) cannot have globbed path\", to)\n\t}\n\tt, err := resolveVars(to, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isGlobbed(from) {\n\t\treturn fmt.Errorf(\"bind src (%s) cannot have globbed path with separate target path (%s)\", from, to)\n\t}\n\tf, err := resolveVars(from, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn fs.bind(f, t, flags, u)\n}\n\nfunc (fs *Filesystem) bindSame(p string, flags int, u *user.User) error {\n\tps, err := resolvePath(p, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range ps {\n\t\tif err := fs.bind(p, p, flags, u); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) bind(from string, to string, flags int, u *user.User) error {\n\tsrc, err := filepath.EvalSymlinks(from)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resolving symlinks for path (%s): %v\", from, err)\n\t}\n\tcc := flags&BindCanCreate != 0\n\tsinfo, err := readSourceInfo(src, cc, u)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to bind path (%s): %v\", src, err)\n\t}\n\n\tif to == \"\" {\n\t\tto = from\n\t}\n\tto = path.Join(fs.Root(), to)\n\n\t_, err = os.Stat(to)\n\tif err == nil || !os.IsNotExist(err) {\n\t\tfs.log.Warning(\"Target (%s > %s) already exists, ignoring\", src, to)\n\t\treturn nil\n\t}\n\n\tif sinfo.IsDir() {\n\t\tif err := os.MkdirAll(to, sinfo.Mode().Perm()); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := createEmptyFile(to, 0750); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := copyPathPermissions(fs.Root(), src); err != nil {\n\t\treturn fmt.Errorf(\"failed to copy path permissions for (%s): %v\", src, err)\n\t}\n\tfs.log.Info(\"bind mounting %s -> %s\", src, to)\n\tmntflags := syscall.MS_NOSUID | syscall.MS_NODEV\n\tif flags&BindReadOnly != 0 {\n\t\tmntflags |= syscall.MS_RDONLY\n\t} else {\n\t\tflags |= syscall.MS_NOEXEC\n\t}\n\treturn bindMount(src, to, mntflags)\n}\n\nfunc readSourceInfo(src string, cancreate bool, u *user.User) (os.FileInfo, error) {\n\tif fi, err := os.Stat(src); err == nil {\n\t\treturn fi, nil\n\t} else if !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif u == nil || !cancreate {\n\t\treturn nil, fmt.Errorf(\"source path (%s) does not exist\", src)\n\t}\n\n\thome := u.HomeDir\n\tif !strings.HasPrefix(src, home) {\n\t\treturn nil, fmt.Errorf(\"mount item (%s) has flag MountCreateIfAbsent, but is not child of home directory (%s)\", src, home)\n\t}\n\n\tif err := os.MkdirAll(src, 0750); err != nil {\n\t\treturn nil, err\n\t}\n\n\tpinfo, err := os.Stat(path.Dir(src))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := copyFileInfo(pinfo, src); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.Stat(src)\n}\n\nfunc (fs *Filesystem) BlacklistPath(target string, u *user.User) error {\n\tps, err := resolvePath(target, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range ps {\n\t\tif err := fs.blacklist(p); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) blacklist(target string) error {\n\tt, err := filepath.EvalSymlinks(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"symlink evaluation failed while blacklisting path %s: %v\", target, err)\n\t}\n\tfi, err := os.Stat(t)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tfs.log.Info(\"Blacklist path (%s) does not exist\", t)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tsrc := emptyFilePath\n\tif fi.IsDir() {\n\t\tsrc = emptyDirPath\n\t}\n\n\tif err := syscall.Mount(fs.absPath(src), fs.absPath(t), \"\", syscall.MS_BIND, \"mode=400,gid=0\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to bind %s -> %s for blacklist: %v\", src, t, err)\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) Chroot() error {\n\tif fs.chroot {\n\t\treturn fmt.Errorf(\"filesystem is already in chroot()\")\n\t}\n\tfs.log.Debug(\"chroot to %s\", fs.Root())\n\tif err := syscall.Chroot(fs.Root()); err != nil {\n\t\treturn fmt.Errorf(\"chroot to %s failed: %v\", fs.Root(), err)\n\t}\n\tif err := os.Chdir(\"\/\"); err != nil {\n\t\treturn fmt.Errorf(\"chdir to \/ after chroot() failed: %v\", err)\n\t}\n\tfs.chroot = true\n\treturn nil\n}\n\nfunc (fs *Filesystem) MountProc() error {\n\terr := fs.mountSpecial(\"\/proc\", \"proc\", 0, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\troMounts := []string{\n\t\t\"sysrq-trigger\",\n\t\t\"bus\",\n\t\t\"irq\",\n\t\t\"sys\/kernel\/hotplug\",\n\t}\n\tfor _, rom := range roMounts {\n\t\tif _, err := os.Stat(rom); err == nil {\n\t\t\tif err := bindMount(rom, rom, syscall.MS_RDONLY); err != nil {\n\t\t\t\treturn fmt.Errorf(\"remount RO of %s failed: %v\", rom, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (fs *Filesystem) MountFullDev() error {\n\treturn fs.mountSpecial(\"\/dev\", \"devtmpfs\", 0, \"\")\n}\n\nfunc (fs *Filesystem) MountSys() error {\n\treturn fs.mountSpecial(\"\/sys\", \"sysfs\", syscall.MS_RDONLY, \"\")\n}\n\nfunc (fs *Filesystem) MountTmp() error {\n\treturn fs.mountSpecial(\"\/tmp\", \"tmpfs\", syscall.MS_NODEV, \"\")\n}\n\nfunc (fs *Filesystem) MountPts() error {\n\treturn fs.mountSpecial(\"\/dev\/pts\", \"devpts\", 0, \"newinstance,ptmxmode=0666\")\n}\n\nfunc (fs *Filesystem) MountShm() error {\n\treturn fs.mountSpecial(\"\/dev\/shm\", \"tmpfs\", syscall.MS_NODEV, \"\")\n}\n\nfunc (fs *Filesystem) mountSpecial(path, mtype string, flags int, args string) error {\n\tif !fs.chroot {\n\t\treturn fmt.Errorf(\"cannot mount %s (%s) until Chroot() is called.\", path, mtype)\n\t}\n\tfs.log.Debug(\"Mounting %s [%s]\", path, mtype)\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\treturn fmt.Errorf(\"failed to create mount point (%s): %v\", path, err)\n\t}\n\tmountFlags := uintptr(flags | syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_REC)\n\treturn syscall.Mount(\"\", path, mtype, mountFlags, args)\n}\n\nfunc bindMount(source, target string, flags int) error {\n\tif err := syscall.Mount(source, target, \"\", syscall.MS_BIND, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"bind mount of %s -> %s failed: %v\", source, target, err)\n\t}\n\tif flags != 0 {\n\t\treturn remount(target, flags)\n\t}\n\treturn nil\n}\n\nfunc remount(target string, flags int) error {\n\tfl := uintptr(flags | syscall.MS_BIND | syscall.MS_REMOUNT)\n\tif err := syscall.Mount(\"\", target, \"\", fl, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to remount %s with flags %x: %v\", target, flags, err)\n\t}\n\treturn nil\n}\n\nconst emptyFilePath = \"\/oz.ro.file\"\nconst emptyDirPath = \"\/oz.ro.dir\"\n\nfunc (fs *Filesystem) CreateBlacklistPaths() error {\n\tif err := createBlacklistDir(fs.absPath(emptyDirPath)); err != nil {\n\t\treturn err\n\t}\n\tif err := createBlacklistFile(fs.absPath(emptyFilePath)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc createBlacklistDir(p string) error {\n\tif err := os.MkdirAll(p, 0000); err != nil {\n\t\treturn err\n\t}\n\treturn setBlacklistPerms(p, 0500)\n}\n\nfunc createBlacklistFile(path string) error {\n\tfd, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := fd.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn setBlacklistPerms(path, 0400)\n}\n\nfunc setBlacklistPerms(path string, mode os.FileMode) error {\n\tif err := os.Chown(path, 0, 0); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chmod(path, mode); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc createEmptyFile(name string, mode os.FileMode) error {\n\tif err := os.MkdirAll(path.Dir(name), 0750); err != nil {\n\t\treturn err\n\t}\n\tfd, err := os.Create(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := fd.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chmod(name, mode); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc copyPathPermissions(root, src string) error {\n\tcurrent := \"\/\"\n\tfor _, part := range strings.Split(src, \"\/\") {\n\t\tif part == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcurrent = path.Join(current, part)\n\t\ttarget := path.Join(root, current)\n\t\tif err := copyFilePermissions(current, target); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc copyFilePermissions(src, target string) error {\n\tfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn copyFileInfo(fi, target)\n}\n\nfunc copyFileInfo(info os.FileInfo, target string) error {\n\tst := info.Sys().(*syscall.Stat_t)\n\tos.Chown(target, int(st.Uid), int(st.Gid))\n\tos.Chmod(target, info.Mode().Perm())\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Accounting and limiting reader\n\npackage fs\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/VividCortex\/ewma\"\n\t\"github.com\/tsenart\/tb\"\n)\n\n\/\/ Globals\nvar (\n\tStats       = NewStats()\n\ttokenBucket *tb.Bucket\n)\n\n\/\/ Start the token bucket if necessary\nfunc startTokenBucket() {\n\tif bwLimit > 0 {\n\t\ttokenBucket = tb.NewBucket(int64(bwLimit), 100*time.Millisecond)\n\t\tLog(nil, \"Starting bandwidth limiter at %vBytes\/s\", &bwLimit)\n\t}\n}\n\n\/\/ stringSet holds a set of strings\ntype stringSet map[string]struct{}\n\n\/\/ inProgress holds a synchronizes map of in progress transfers\ntype inProgress struct {\n\tmu sync.Mutex\n\tm  map[string]*Account\n}\n\n\/\/ newInProgress makes a new inProgress object\nfunc newInProgress() *inProgress {\n\treturn &inProgress{\n\t\tm: make(map[string]*Account, Config.Transfers),\n\t}\n}\n\n\/\/ set marks the name as in progress\nfunc (ip *inProgress) set(name string, acc *Account) {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\tip.m[name] = acc\n}\n\n\/\/ clear marks the name as no longer in progress\nfunc (ip *inProgress) clear(name string) {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\tdelete(ip.m, name)\n}\n\n\/\/ get gets the account for name, of nil if not found\nfunc (ip *inProgress) get(name string) *Account {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\treturn ip.m[name]\n}\n\n\/\/ Strings returns all the strings in the stringSet\nfunc (ss stringSet) Strings() []string {\n\tstrings := make([]string, 0, len(ss))\n\tfor name := range ss {\n\t\tvar out string\n\t\tif acc := Stats.inProgress.get(name); acc != nil {\n\t\t\tout = acc.String()\n\t\t} else {\n\t\t\tout = name\n\t\t}\n\t\tstrings = append(strings, \" * \"+out)\n\t}\n\tsorted := sort.StringSlice(strings)\n\tsorted.Sort()\n\treturn sorted\n}\n\n\/\/ String returns all the file names in the stringSet joined by newline\nfunc (ss stringSet) String() string {\n\treturn strings.Join(ss.Strings(), \"\\n\")\n}\n\n\/\/ StatsInfo limits and accounts all transfers\ntype StatsInfo struct {\n\tlock         sync.RWMutex\n\tbytes        int64\n\terrors       int64\n\tchecks       int64\n\tchecking     stringSet\n\ttransfers    int64\n\ttransferring stringSet\n\tstart        time.Time\n\tinProgress   *inProgress\n}\n\n\/\/ NewStats cretates an initialised StatsInfo\nfunc NewStats() *StatsInfo {\n\treturn &StatsInfo{\n\t\tchecking:     make(stringSet, Config.Checkers),\n\t\ttransferring: make(stringSet, Config.Transfers),\n\t\tstart:        time.Now(),\n\t\tinProgress:   newInProgress(),\n\t}\n}\n\n\/\/ String convert the StatsInfo to a string for printing\nfunc (s *StatsInfo) String() string {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\tdt := time.Now().Sub(s.start)\n\tdtSeconds := dt.Seconds()\n\tspeed := 0.0\n\tif dt > 0 {\n\t\tspeed = float64(s.bytes) \/ 1024 \/ dtSeconds\n\t}\n\tdtRounded := dt - (dt % (time.Second \/ 10))\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, `\nTransferred:   %10d Bytes (%7.2f kByte\/s)\nErrors:        %10d\nChecks:        %10d\nTransferred:   %10d\nElapsed time:  %10v\n`,\n\t\ts.bytes, speed,\n\t\ts.errors,\n\t\ts.checks,\n\t\ts.transfers,\n\t\tdtRounded)\n\tif len(s.checking) > 0 {\n\t\tfmt.Fprintf(buf, \"Checking:\\n%s\\n\", s.checking)\n\t}\n\tif len(s.transferring) > 0 {\n\t\tfmt.Fprintf(buf, \"Transferring:\\n%s\\n\", s.transferring)\n\t}\n\treturn buf.String()\n}\n\n\/\/ Log outputs the StatsInfo to the log\nfunc (s *StatsInfo) Log() {\n\tlog.Printf(\"%v\\n\", s)\n}\n\n\/\/ Bytes updates the stats for bytes bytes\nfunc (s *StatsInfo) Bytes(bytes int64) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.bytes += bytes\n}\n\n\/\/ Errors updates the stats for errors\nfunc (s *StatsInfo) Errors(errors int64) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.errors += errors\n}\n\n\/\/ GetErrors reads the number of errors\nfunc (s *StatsInfo) GetErrors() int64 {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.errors\n}\n\n\/\/ ResetCounters sets the counters (bytes, checks, errors, transfers) to 0\nfunc (s *StatsInfo) ResetCounters() {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\ts.bytes = 0\n\ts.errors = 0\n\ts.checks = 0\n\ts.transfers = 0\n}\n\n\/\/ ResetErrors sets the errors count to 0\nfunc (s *StatsInfo) ResetErrors() {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\ts.errors = 0\n}\n\n\/\/ Errored returns whether there have been any errors\nfunc (s *StatsInfo) Errored() bool {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.errors != 0\n}\n\n\/\/ Error adds a single error into the stats\nfunc (s *StatsInfo) Error() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.errors++\n}\n\n\/\/ Checking adds a check into the stats\nfunc (s *StatsInfo) Checking(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.checking[o.Remote()] = struct{}{}\n}\n\n\/\/ DoneChecking removes a check from the stats\nfunc (s *StatsInfo) DoneChecking(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tdelete(s.checking, o.Remote())\n\ts.checks++\n}\n\n\/\/ GetTransfers reads the number of transfers\nfunc (s *StatsInfo) GetTransfers() int64 {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.transfers\n}\n\n\/\/ Transferring adds a transfer into the stats\nfunc (s *StatsInfo) Transferring(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.transferring[o.Remote()] = struct{}{}\n}\n\n\/\/ DoneTransferring removes a transfer from the stats\nfunc (s *StatsInfo) DoneTransferring(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tdelete(s.transferring, o.Remote())\n\ts.transfers++\n}\n\n\/\/ Account limits and accounts for one transfer\ntype Account struct {\n\t\/\/ The mutex is to make sure Read() and Close() aren't called\n\t\/\/ concurrently.  Unfortunately the persistent connection loop\n\t\/\/ in http transport calls Read() after Do() returns on\n\t\/\/ CancelRequest so this race can happen when it apparently\n\t\/\/ shouldn't.\n\tmu      sync.Mutex\n\tin      io.ReadCloser\n\tsize    int64\n\tname    string\n\tstatmu  sync.Mutex         \/\/ Separate mutex for stat values.\n\tbytes   int64              \/\/ Total number of bytes read\n\tstart   time.Time          \/\/ Start time of first read\n\tlpTime  time.Time          \/\/ Time of last average measurement\n\tlpBytes int                \/\/ Number of bytes read since last measurement\n\tavg     ewma.MovingAverage \/\/ Moving average of last few measurements\n\tclosed  bool               \/\/ set if the file is closed\n\texit    chan struct{}      \/\/ channel that will be closed when transfer is finished\n}\n\n\/\/ NewAccount makes a Account reader for an object\nfunc NewAccount(in io.ReadCloser, obj Object) *Account {\n\tacc := &Account{\n\t\tin:     in,\n\t\tsize:   obj.Size(),\n\t\tname:   obj.Remote(),\n\t\texit:   make(chan struct{}),\n\t\tavg:    ewma.NewMovingAverage(),\n\t\tlpTime: time.Now(),\n\t}\n\tgo acc.averageLoop()\n\tStats.inProgress.set(acc.name, acc)\n\treturn acc\n}\n\nfunc (file *Account) averageLoop() {\n\ttick := time.NewTicker(time.Second)\n\tdefer tick.Stop()\n\tfor {\n\t\tselect {\n\t\tcase now := <-tick.C:\n\t\t\tfile.statmu.Lock()\n\t\t\t\/\/ Add average of last second.\n\t\t\telapsed := now.Sub(file.lpTime).Seconds()\n\t\t\tavg := float64(file.lpBytes) \/ elapsed\n\t\t\tfile.avg.Add(avg)\n\t\t\tfile.lpBytes = 0\n\t\t\tfile.lpTime = now\n\t\t\t\/\/ Unlock stats\n\t\t\tfile.statmu.Unlock()\n\t\tcase <-file.exit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Read bytes from the object - see io.Reader\nfunc (file *Account) Read(p []byte) (n int, err error) {\n\tfile.mu.Lock()\n\tdefer file.mu.Unlock()\n\n\t\/\/ Set start time.\n\tfile.statmu.Lock()\n\tif file.start.IsZero() {\n\t\tfile.start = time.Now()\n\t}\n\tfile.statmu.Unlock()\n\n\tn, err = file.in.Read(p)\n\n\t\/\/ Update Stats\n\tfile.statmu.Lock()\n\tfile.lpBytes += n\n\tfile.bytes += int64(n)\n\tfile.statmu.Unlock()\n\n\tStats.Bytes(int64(n))\n\n\t\/\/ Limit the transfer speed if required\n\tif tokenBucket != nil {\n\t\ttokenBucket.Wait(int64(n))\n\t}\n\treturn\n}\n\n\/\/ Progress returns bytes read as well as the size.\n\/\/ Size can be <= 0 if the size is unknown.\nfunc (file *Account) Progress() (bytes, size int64) {\n\tif file == nil {\n\t\treturn 0, 0\n\t}\n\tfile.statmu.Lock()\n\tif bytes > size {\n\t\tsize = 0\n\t}\n\tdefer file.statmu.Unlock()\n\treturn file.bytes, file.size\n}\n\n\/\/ Speed returns the speed of the current file transfer\n\/\/ in bytes per second, as well a an exponentially weighted moving average\n\/\/ If no read has completed yet, 0 is returned for both values.\nfunc (file *Account) Speed() (bps, current float64) {\n\tif file == nil {\n\t\treturn 0, 0\n\t}\n\tfile.statmu.Lock()\n\tdefer file.statmu.Unlock()\n\tif file.bytes == 0 {\n\t\treturn 0, 0\n\t}\n\t\/\/ Calculate speed from first read.\n\ttotal := float64(time.Now().Sub(file.start)) \/ float64(time.Second)\n\tbps = float64(file.bytes) \/ total\n\tcurrent = file.avg.Value()\n\treturn\n}\n\n\/\/ ETA returns the ETA of the current operation,\n\/\/ rounded to full seconds.\n\/\/ If the ETA cannot be determined 'ok' returns false.\nfunc (file *Account) ETA() (eta time.Duration, ok bool) {\n\tif file == nil || file.size <= 0 {\n\t\treturn 0, false\n\t}\n\tfile.statmu.Lock()\n\tdefer file.statmu.Unlock()\n\tif file.bytes == 0 {\n\t\treturn 0, false\n\t}\n\tleft := file.size - file.bytes\n\tif left <= 0 {\n\t\treturn 0, true\n\t}\n\tavg := file.avg.Value()\n\tif avg <= 0 {\n\t\treturn 0, false\n\t}\n\tseconds := float64(left) \/ file.avg.Value()\n\n\treturn time.Duration(time.Second * time.Duration(int(seconds))), true\n}\n\n\/\/ String produces stats for this file\nfunc (file *Account) String() string {\n\ta, b := file.Progress()\n\tavg, cur := file.Speed()\n\teta, etaok := file.ETA()\n\tetas := \"-\"\n\tif etaok {\n\t\tif eta > 0 {\n\t\t\tetas = fmt.Sprintf(\"%v\", eta)\n\t\t} else {\n\t\t\tetas = \"0s\"\n\t\t}\n\t}\n\tname := []rune(file.name)\n\tif len(name) > 45 {\n\t\twhere := len(name) - 42\n\t\tname = append([]rune{'.', '.', '.'}, name[where:]...)\n\t}\n\tif b <= 0 {\n\t\treturn fmt.Sprintf(\"%45s: avg:%7.1f, cur: %6.1f kByte\/s. ETA: %s\", string(name), avg\/1024, cur\/1024, etas)\n\t}\n\treturn fmt.Sprintf(\"%45s: %2d%% done. avg: %6.1f, cur: %6.1f kByte\/s. ETA: %s\", string(name), int(100*float64(a)\/float64(b)), avg\/1024, cur\/1024, etas)\n}\n\n\/\/ Close the object\nfunc (file *Account) Close() error {\n\tfile.mu.Lock()\n\tdefer file.mu.Unlock()\n\tif file.closed {\n\t\treturn nil\n\t}\n\tfile.closed = true\n\tclose(file.exit)\n\tStats.inProgress.clear(file.name)\n\treturn file.in.Close()\n}\n\n\/\/ Check it satisfies the interface\nvar _ io.ReadCloser = &Account{}\n<commit_msg>Display the transfer stats in more human readable form - fixes #428<commit_after>\/\/ Accounting and limiting reader\n\npackage fs\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/VividCortex\/ewma\"\n\t\"github.com\/tsenart\/tb\"\n)\n\n\/\/ Globals\nvar (\n\tStats       = NewStats()\n\ttokenBucket *tb.Bucket\n)\n\n\/\/ Start the token bucket if necessary\nfunc startTokenBucket() {\n\tif bwLimit > 0 {\n\t\ttokenBucket = tb.NewBucket(int64(bwLimit), 100*time.Millisecond)\n\t\tLog(nil, \"Starting bandwidth limiter at %vBytes\/s\", &bwLimit)\n\t}\n}\n\n\/\/ stringSet holds a set of strings\ntype stringSet map[string]struct{}\n\n\/\/ inProgress holds a synchronizes map of in progress transfers\ntype inProgress struct {\n\tmu sync.Mutex\n\tm  map[string]*Account\n}\n\n\/\/ newInProgress makes a new inProgress object\nfunc newInProgress() *inProgress {\n\treturn &inProgress{\n\t\tm: make(map[string]*Account, Config.Transfers),\n\t}\n}\n\n\/\/ set marks the name as in progress\nfunc (ip *inProgress) set(name string, acc *Account) {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\tip.m[name] = acc\n}\n\n\/\/ clear marks the name as no longer in progress\nfunc (ip *inProgress) clear(name string) {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\tdelete(ip.m, name)\n}\n\n\/\/ get gets the account for name, of nil if not found\nfunc (ip *inProgress) get(name string) *Account {\n\tip.mu.Lock()\n\tdefer ip.mu.Unlock()\n\treturn ip.m[name]\n}\n\n\/\/ Strings returns all the strings in the stringSet\nfunc (ss stringSet) Strings() []string {\n\tstrings := make([]string, 0, len(ss))\n\tfor name := range ss {\n\t\tvar out string\n\t\tif acc := Stats.inProgress.get(name); acc != nil {\n\t\t\tout = acc.String()\n\t\t} else {\n\t\t\tout = name\n\t\t}\n\t\tstrings = append(strings, \" * \"+out)\n\t}\n\tsorted := sort.StringSlice(strings)\n\tsorted.Sort()\n\treturn sorted\n}\n\n\/\/ String returns all the file names in the stringSet joined by newline\nfunc (ss stringSet) String() string {\n\treturn strings.Join(ss.Strings(), \"\\n\")\n}\n\n\/\/ StatsInfo limits and accounts all transfers\ntype StatsInfo struct {\n\tlock         sync.RWMutex\n\tbytes        int64\n\terrors       int64\n\tchecks       int64\n\tchecking     stringSet\n\ttransfers    int64\n\ttransferring stringSet\n\tstart        time.Time\n\tinProgress   *inProgress\n}\n\n\/\/ NewStats cretates an initialised StatsInfo\nfunc NewStats() *StatsInfo {\n\treturn &StatsInfo{\n\t\tchecking:     make(stringSet, Config.Checkers),\n\t\ttransferring: make(stringSet, Config.Transfers),\n\t\tstart:        time.Now(),\n\t\tinProgress:   newInProgress(),\n\t}\n}\n\n\/\/ String convert the StatsInfo to a string for printing\nfunc (s *StatsInfo) String() string {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\tdt := time.Now().Sub(s.start)\n\tdtSeconds := dt.Seconds()\n\tspeed := 0.0\n\tif dt > 0 {\n\t\tspeed = float64(s.bytes) \/ 1024 \/ dtSeconds\n\t}\n\tdtRounded := dt - (dt % (time.Second \/ 10))\n\tbuf := &bytes.Buffer{}\n\tfmt.Fprintf(buf, `\nTransferred:   %10vBytes (%vByte\/s)\nErrors:        %10d\nChecks:        %10d\nTransferred:   %10d\nElapsed time:  %10v\n`,\n\t\tSizeSuffix(s.bytes), SizeSuffix(speed),\n\t\ts.errors,\n\t\ts.checks,\n\t\ts.transfers,\n\t\tdtRounded)\n\tif len(s.checking) > 0 {\n\t\tfmt.Fprintf(buf, \"Checking:\\n%s\\n\", s.checking)\n\t}\n\tif len(s.transferring) > 0 {\n\t\tfmt.Fprintf(buf, \"Transferring:\\n%s\\n\", s.transferring)\n\t}\n\treturn buf.String()\n}\n\n\/\/ Log outputs the StatsInfo to the log\nfunc (s *StatsInfo) Log() {\n\tlog.Printf(\"%v\\n\", s)\n}\n\n\/\/ Bytes updates the stats for bytes bytes\nfunc (s *StatsInfo) Bytes(bytes int64) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.bytes += bytes\n}\n\n\/\/ Errors updates the stats for errors\nfunc (s *StatsInfo) Errors(errors int64) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.errors += errors\n}\n\n\/\/ GetErrors reads the number of errors\nfunc (s *StatsInfo) GetErrors() int64 {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.errors\n}\n\n\/\/ ResetCounters sets the counters (bytes, checks, errors, transfers) to 0\nfunc (s *StatsInfo) ResetCounters() {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\ts.bytes = 0\n\ts.errors = 0\n\ts.checks = 0\n\ts.transfers = 0\n}\n\n\/\/ ResetErrors sets the errors count to 0\nfunc (s *StatsInfo) ResetErrors() {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\ts.errors = 0\n}\n\n\/\/ Errored returns whether there have been any errors\nfunc (s *StatsInfo) Errored() bool {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.errors != 0\n}\n\n\/\/ Error adds a single error into the stats\nfunc (s *StatsInfo) Error() {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.errors++\n}\n\n\/\/ Checking adds a check into the stats\nfunc (s *StatsInfo) Checking(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.checking[o.Remote()] = struct{}{}\n}\n\n\/\/ DoneChecking removes a check from the stats\nfunc (s *StatsInfo) DoneChecking(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tdelete(s.checking, o.Remote())\n\ts.checks++\n}\n\n\/\/ GetTransfers reads the number of transfers\nfunc (s *StatsInfo) GetTransfers() int64 {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn s.transfers\n}\n\n\/\/ Transferring adds a transfer into the stats\nfunc (s *StatsInfo) Transferring(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\ts.transferring[o.Remote()] = struct{}{}\n}\n\n\/\/ DoneTransferring removes a transfer from the stats\nfunc (s *StatsInfo) DoneTransferring(o Object) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tdelete(s.transferring, o.Remote())\n\ts.transfers++\n}\n\n\/\/ Account limits and accounts for one transfer\ntype Account struct {\n\t\/\/ The mutex is to make sure Read() and Close() aren't called\n\t\/\/ concurrently.  Unfortunately the persistent connection loop\n\t\/\/ in http transport calls Read() after Do() returns on\n\t\/\/ CancelRequest so this race can happen when it apparently\n\t\/\/ shouldn't.\n\tmu      sync.Mutex\n\tin      io.ReadCloser\n\tsize    int64\n\tname    string\n\tstatmu  sync.Mutex         \/\/ Separate mutex for stat values.\n\tbytes   int64              \/\/ Total number of bytes read\n\tstart   time.Time          \/\/ Start time of first read\n\tlpTime  time.Time          \/\/ Time of last average measurement\n\tlpBytes int                \/\/ Number of bytes read since last measurement\n\tavg     ewma.MovingAverage \/\/ Moving average of last few measurements\n\tclosed  bool               \/\/ set if the file is closed\n\texit    chan struct{}      \/\/ channel that will be closed when transfer is finished\n}\n\n\/\/ NewAccount makes a Account reader for an object\nfunc NewAccount(in io.ReadCloser, obj Object) *Account {\n\tacc := &Account{\n\t\tin:     in,\n\t\tsize:   obj.Size(),\n\t\tname:   obj.Remote(),\n\t\texit:   make(chan struct{}),\n\t\tavg:    ewma.NewMovingAverage(),\n\t\tlpTime: time.Now(),\n\t}\n\tgo acc.averageLoop()\n\tStats.inProgress.set(acc.name, acc)\n\treturn acc\n}\n\nfunc (file *Account) averageLoop() {\n\ttick := time.NewTicker(time.Second)\n\tdefer tick.Stop()\n\tfor {\n\t\tselect {\n\t\tcase now := <-tick.C:\n\t\t\tfile.statmu.Lock()\n\t\t\t\/\/ Add average of last second.\n\t\t\telapsed := now.Sub(file.lpTime).Seconds()\n\t\t\tavg := float64(file.lpBytes) \/ elapsed\n\t\t\tfile.avg.Add(avg)\n\t\t\tfile.lpBytes = 0\n\t\t\tfile.lpTime = now\n\t\t\t\/\/ Unlock stats\n\t\t\tfile.statmu.Unlock()\n\t\tcase <-file.exit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Read bytes from the object - see io.Reader\nfunc (file *Account) Read(p []byte) (n int, err error) {\n\tfile.mu.Lock()\n\tdefer file.mu.Unlock()\n\n\t\/\/ Set start time.\n\tfile.statmu.Lock()\n\tif file.start.IsZero() {\n\t\tfile.start = time.Now()\n\t}\n\tfile.statmu.Unlock()\n\n\tn, err = file.in.Read(p)\n\n\t\/\/ Update Stats\n\tfile.statmu.Lock()\n\tfile.lpBytes += n\n\tfile.bytes += int64(n)\n\tfile.statmu.Unlock()\n\n\tStats.Bytes(int64(n))\n\n\t\/\/ Limit the transfer speed if required\n\tif tokenBucket != nil {\n\t\ttokenBucket.Wait(int64(n))\n\t}\n\treturn\n}\n\n\/\/ Progress returns bytes read as well as the size.\n\/\/ Size can be <= 0 if the size is unknown.\nfunc (file *Account) Progress() (bytes, size int64) {\n\tif file == nil {\n\t\treturn 0, 0\n\t}\n\tfile.statmu.Lock()\n\tif bytes > size {\n\t\tsize = 0\n\t}\n\tdefer file.statmu.Unlock()\n\treturn file.bytes, file.size\n}\n\n\/\/ Speed returns the speed of the current file transfer\n\/\/ in bytes per second, as well a an exponentially weighted moving average\n\/\/ If no read has completed yet, 0 is returned for both values.\nfunc (file *Account) Speed() (bps, current float64) {\n\tif file == nil {\n\t\treturn 0, 0\n\t}\n\tfile.statmu.Lock()\n\tdefer file.statmu.Unlock()\n\tif file.bytes == 0 {\n\t\treturn 0, 0\n\t}\n\t\/\/ Calculate speed from first read.\n\ttotal := float64(time.Now().Sub(file.start)) \/ float64(time.Second)\n\tbps = float64(file.bytes) \/ total\n\tcurrent = file.avg.Value()\n\treturn\n}\n\n\/\/ ETA returns the ETA of the current operation,\n\/\/ rounded to full seconds.\n\/\/ If the ETA cannot be determined 'ok' returns false.\nfunc (file *Account) ETA() (eta time.Duration, ok bool) {\n\tif file == nil || file.size <= 0 {\n\t\treturn 0, false\n\t}\n\tfile.statmu.Lock()\n\tdefer file.statmu.Unlock()\n\tif file.bytes == 0 {\n\t\treturn 0, false\n\t}\n\tleft := file.size - file.bytes\n\tif left <= 0 {\n\t\treturn 0, true\n\t}\n\tavg := file.avg.Value()\n\tif avg <= 0 {\n\t\treturn 0, false\n\t}\n\tseconds := float64(left) \/ file.avg.Value()\n\n\treturn time.Duration(time.Second * time.Duration(int(seconds))), true\n}\n\n\/\/ String produces stats for this file\nfunc (file *Account) String() string {\n\ta, b := file.Progress()\n\tavg, cur := file.Speed()\n\teta, etaok := file.ETA()\n\tetas := \"-\"\n\tif etaok {\n\t\tif eta > 0 {\n\t\t\tetas = fmt.Sprintf(\"%v\", eta)\n\t\t} else {\n\t\t\tetas = \"0s\"\n\t\t}\n\t}\n\tname := []rune(file.name)\n\tif len(name) > 45 {\n\t\twhere := len(name) - 42\n\t\tname = append([]rune{'.', '.', '.'}, name[where:]...)\n\t}\n\tif b <= 0 {\n\t\treturn fmt.Sprintf(\"%45s: avg:%7.1f, cur: %6.1f kByte\/s. ETA: %s\", string(name), avg\/1024, cur\/1024, etas)\n\t}\n\treturn fmt.Sprintf(\"%45s: %2d%% done. avg: %6.1f, cur: %6.1f kByte\/s. ETA: %s\", string(name), int(100*float64(a)\/float64(b)), avg\/1024, cur\/1024, etas)\n}\n\n\/\/ Close the object\nfunc (file *Account) Close() error {\n\tfile.mu.Lock()\n\tdefer file.mu.Unlock()\n\tif file.closed {\n\t\treturn nil\n\t}\n\tfile.closed = true\n\tclose(file.exit)\n\tStats.inProgress.clear(file.name)\n\treturn file.in.Close()\n}\n\n\/\/ Check it satisfies the interface\nvar _ io.ReadCloser = &Account{}\n<|endoftext|>"}
{"text":"<commit_before>package log\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/fatih\/camelcase\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tbucketFactor = 2.0\n\tbucketCount  = 20 \/\/ Which makes the max bucket 2^20 seconds or ~12 days in size\n)\n\n\/\/ This needs to be a global var, not a field on the logger, because multiple servers\n\/\/ create new loggers, and the prometheus registration uses a global namespace\nvar reportMetricGauge prometheus.Gauge\nvar reportMetricsOnce sync.Once\n\n\/\/ Logger is a helper for emitting our grpc API logs\ntype Logger interface {\n\tLog(request interface{}, response interface{}, err error, duration time.Duration)\n\tLogAtLevelFromDepth(request interface{}, response interface{}, err error, duration time.Duration, level logrus.Level, depth int)\n}\n\ntype logger struct {\n\t*logrus.Entry\n\thistogram   map[string]*prometheus.HistogramVec\n\tcounter     map[string]prometheus.Counter\n\tmutex       *sync.Mutex\n\texportStats bool\n}\n\n\/\/ NewLogger creates a new logger\nfunc NewLogger(service string) Logger {\n\treturn newLogger(service, true)\n}\n\n\/\/ NewLogger creates a new logger for local testing (which does not report prometheus metrics)\nfunc NewLocalLogger(service string) Logger {\n\treturn newLogger(service, false)\n}\n\nfunc newLogger(service string, exportStats bool) Logger {\n\tl := logrus.New()\n\tl.Formatter = new(prettyFormatter)\n\tnewLogger := &logger{\n\t\tl.WithFields(logrus.Fields{\"service\": service}),\n\t\tmake(map[string]*prometheus.HistogramVec),\n\t\tmake(map[string]prometheus.Counter),\n\t\t&sync.Mutex{},\n\t\texportStats,\n\t}\n\tif exportStats {\n\t\treportMetricsOnce.Do(func() {\n\t\t\tnewReportMetricGauge := prometheus.NewGauge(\n\t\t\t\tprometheus.GaugeOpts{\n\t\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\t\tName:      \"report_metric\",\n\t\t\t\t\tHelp:      \"gauge of number of calls to ReportMetric()\",\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err := prometheus.Register(newReportMetricGauge); err != nil {\n\t\t\t\tentry := newLogger.WithFields(logrus.Fields{\"method\": \"NewLogger\"})\n\t\t\t\tnewLogger.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t\t} else {\n\t\t\t\treportMetricGauge = newReportMetricGauge\n\t\t\t}\n\t\t})\n\t}\n\treturn newLogger\n}\n\n\/\/ Helper function used to log requests and responses from our GRPC method\n\/\/ implementations\nfunc (l *logger) Log(request interface{}, response interface{}, err error, duration time.Duration) {\n\tif err != nil {\n\t\tl.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)\n\t} else {\n\t\tl.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)\n\t}\n\t\/\/ We have to grab the method's name here before we\n\t\/\/ enter the goro's stack\n\tgo l.ReportMetric(getMethodName(), duration, err)\n}\n\nfunc getMethodName() string {\n\tdepth := 4\n\tpc := make([]uintptr, depth)\n\truntime.Callers(depth, pc)\n\tsplit := strings.Split(runtime.FuncForPC(pc[0]).Name(), \".\")\n\treturn split[len(split)-1]\n}\n\nfunc (l *logger) ReportMetric(method string, duration time.Duration, err error) {\n\tif !l.exportStats {\n\t\treturn\n\t}\n\t\/\/ Count the number of ReportMetric() goros in case we start to leak them\n\tif reportMetricGauge != nil {\n\t\treportMetricGauge.Inc()\n\t}\n\tdefer func() {\n\t\tif reportMetricGauge != nil {\n\t\t\treportMetricGauge.Dec()\n\t\t}\n\t}()\n\tl.mutex.Lock() \/\/ for conccurent map access (histogram,counter)\n\tdefer l.mutex.Unlock()\n\tstate := \"started\"\n\tif err != nil {\n\t\tstate = \"errored\"\n\t} else {\n\t\tif duration.Seconds() > 0 {\n\t\t\tstate = \"finished\"\n\t\t}\n\t}\n\tentry := l.WithFields(logrus.Fields{\"method\": method})\n\n\tvar tokens []string\n\tfor _, token := range camelcase.Split(method) {\n\t\ttokens = append(tokens, strings.ToLower(token))\n\t}\n\trootStatName := strings.Join(tokens, \"_\")\n\n\t\/\/ Recording the distribution of started times is meaningless\n\tif state != \"started\" {\n\t\trunTimeName := fmt.Sprintf(\"%v_time\", rootStatName)\n\t\trunTime, ok := l.histogram[runTimeName]\n\t\tif !ok {\n\t\t\trunTime = prometheus.NewHistogramVec(\n\t\t\t\tprometheus.HistogramOpts{\n\t\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\t\tName:      runTimeName,\n\t\t\t\t\tHelp:      fmt.Sprintf(\"Run time of %v\", method),\n\t\t\t\t\tBuckets:   prometheus.ExponentialBuckets(1.0, bucketFactor, bucketCount),\n\t\t\t\t},\n\t\t\t\t[]string{\n\t\t\t\t\t\"state\", \/\/ Since both finished and errored API calls can have run times\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err := prometheus.Register(runTime); err != nil {\n\t\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t\t} else {\n\t\t\t\tl.histogram[runTimeName] = runTime\n\t\t\t}\n\t\t}\n\t\tif hist, err := runTime.GetMetricWithLabelValues(state); err != nil {\n\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"failed to get histogram w labels: state (%v) with error %v\", state, err)\n\t\t} else {\n\t\t\thist.Observe(duration.Seconds())\n\t\t}\n\t}\n\n\tsecondsCountName := fmt.Sprintf(\"%v_seconds_count\", rootStatName)\n\tsecondsCount, ok := l.counter[secondsCountName]\n\tif !ok {\n\t\tsecondsCount = prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\tName:      secondsCountName,\n\t\t\t\tHelp:      fmt.Sprintf(\"cumulative number of seconds spent in %v\", method),\n\t\t\t},\n\t\t)\n\t\tif err := prometheus.Register(secondsCount); err != nil {\n\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t} else {\n\t\t\tl.counter[secondsCountName] = secondsCount\n\t\t}\n\t}\n\tsecondsCount.Add(duration.Seconds())\n\n}\n\nfunc (l *logger) LogAtLevel(entry *logrus.Entry, level logrus.Level, args ...interface{}) {\n\tswitch level {\n\tcase logrus.PanicLevel:\n\t\tentry.Panic(args)\n\tcase logrus.FatalLevel:\n\t\tentry.Fatal(args)\n\tcase logrus.ErrorLevel:\n\t\tentry.Error(args)\n\tcase logrus.WarnLevel:\n\t\tentry.Warn(args)\n\tcase logrus.InfoLevel:\n\t\tentry.Info(args)\n\tcase logrus.DebugLevel:\n\t\tentry.Debug(args)\n\t}\n}\n\nfunc (l *logger) LogAtLevelFromDepth(request interface{}, response interface{}, err error, duration time.Duration, level logrus.Level, depth int) {\n\tpc := make([]uintptr, depth)\n\truntime.Callers(depth, pc)\n\tsplit := strings.Split(runtime.FuncForPC(pc[0]).Name(), \".\")\n\tmethod := split[len(split)-1]\n\n\tfields := logrus.Fields{\n\t\t\"method\":  method,\n\t\t\"request\": request,\n\t}\n\tif response != nil {\n\t\tfields[\"response\"] = response\n\t}\n\tif err != nil {\n\t\t\/\/ \"err\" itself might be a code or even an empty struct\n\t\tfields[\"error\"] = err.Error()\n\t}\n\tif duration > 0 {\n\t\tfields[\"duration\"] = duration\n\t}\n\tl.LogAtLevel(l.WithFields(fields), level)\n}\n\ntype prettyFormatter struct{}\n\nfunc (f *prettyFormatter) Format(entry *logrus.Entry) ([]byte, error) {\n\tserialized := []byte(\n\t\tfmt.Sprintf(\n\t\t\t\"%v %v \",\n\t\t\tentry.Time.Format(logrus.DefaultTimestampFormat),\n\t\t\tstrings.ToUpper(entry.Level.String()),\n\t\t),\n\t)\n\tif entry.Data[\"service\"] != nil {\n\t\tserialized = append(serialized, []byte(fmt.Sprintf(\"%v.%v \", entry.Data[\"service\"], entry.Data[\"method\"]))...)\n\t}\n\tif len(entry.Data) > 2 {\n\t\tdelete(entry.Data, \"service\")\n\t\tdelete(entry.Data, \"method\")\n\t\tif entry.Data[\"duration\"] != nil {\n\t\t\tentry.Data[\"duration\"] = entry.Data[\"duration\"].(time.Duration).Seconds()\n\t\t}\n\t\tdata, err := json.Marshal(entry.Data)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to marshal fields to JSON, %v\", err)\n\t\t}\n\t\tserialized = append(serialized, []byte(string(data))...)\n\t\tserialized = append(serialized, ' ')\n\t}\n\n\tserialized = append(serialized, []byte(entry.Message)...)\n\tserialized = append(serialized, '\\n')\n\treturn serialized, nil\n}\n<commit_msg>Make linter happy<commit_after>package log\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/fatih\/camelcase\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tbucketFactor = 2.0\n\tbucketCount  = 20 \/\/ Which makes the max bucket 2^20 seconds or ~12 days in size\n)\n\n\/\/ This needs to be a global var, not a field on the logger, because multiple servers\n\/\/ create new loggers, and the prometheus registration uses a global namespace\nvar reportMetricGauge prometheus.Gauge\nvar reportMetricsOnce sync.Once\n\n\/\/ Logger is a helper for emitting our grpc API logs\ntype Logger interface {\n\tLog(request interface{}, response interface{}, err error, duration time.Duration)\n\tLogAtLevelFromDepth(request interface{}, response interface{}, err error, duration time.Duration, level logrus.Level, depth int)\n}\n\ntype logger struct {\n\t*logrus.Entry\n\thistogram   map[string]*prometheus.HistogramVec\n\tcounter     map[string]prometheus.Counter\n\tmutex       *sync.Mutex\n\texportStats bool\n}\n\n\/\/ NewLogger creates a new logger\nfunc NewLogger(service string) Logger {\n\treturn newLogger(service, true)\n}\n\n\/\/ NewLocalLogger creates a new logger for local testing (which does not report prometheus metrics)\nfunc NewLocalLogger(service string) Logger {\n\treturn newLogger(service, false)\n}\n\nfunc newLogger(service string, exportStats bool) Logger {\n\tl := logrus.New()\n\tl.Formatter = new(prettyFormatter)\n\tnewLogger := &logger{\n\t\tl.WithFields(logrus.Fields{\"service\": service}),\n\t\tmake(map[string]*prometheus.HistogramVec),\n\t\tmake(map[string]prometheus.Counter),\n\t\t&sync.Mutex{},\n\t\texportStats,\n\t}\n\tif exportStats {\n\t\treportMetricsOnce.Do(func() {\n\t\t\tnewReportMetricGauge := prometheus.NewGauge(\n\t\t\t\tprometheus.GaugeOpts{\n\t\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\t\tName:      \"report_metric\",\n\t\t\t\t\tHelp:      \"gauge of number of calls to ReportMetric()\",\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err := prometheus.Register(newReportMetricGauge); err != nil {\n\t\t\t\tentry := newLogger.WithFields(logrus.Fields{\"method\": \"NewLogger\"})\n\t\t\t\tnewLogger.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t\t} else {\n\t\t\t\treportMetricGauge = newReportMetricGauge\n\t\t\t}\n\t\t})\n\t}\n\treturn newLogger\n}\n\n\/\/ Helper function used to log requests and responses from our GRPC method\n\/\/ implementations\nfunc (l *logger) Log(request interface{}, response interface{}, err error, duration time.Duration) {\n\tif err != nil {\n\t\tl.LogAtLevelFromDepth(request, response, err, duration, logrus.ErrorLevel, 4)\n\t} else {\n\t\tl.LogAtLevelFromDepth(request, response, err, duration, logrus.InfoLevel, 4)\n\t}\n\t\/\/ We have to grab the method's name here before we\n\t\/\/ enter the goro's stack\n\tgo l.ReportMetric(getMethodName(), duration, err)\n}\n\nfunc getMethodName() string {\n\tdepth := 4\n\tpc := make([]uintptr, depth)\n\truntime.Callers(depth, pc)\n\tsplit := strings.Split(runtime.FuncForPC(pc[0]).Name(), \".\")\n\treturn split[len(split)-1]\n}\n\nfunc (l *logger) ReportMetric(method string, duration time.Duration, err error) {\n\tif !l.exportStats {\n\t\treturn\n\t}\n\t\/\/ Count the number of ReportMetric() goros in case we start to leak them\n\tif reportMetricGauge != nil {\n\t\treportMetricGauge.Inc()\n\t}\n\tdefer func() {\n\t\tif reportMetricGauge != nil {\n\t\t\treportMetricGauge.Dec()\n\t\t}\n\t}()\n\tl.mutex.Lock() \/\/ for conccurent map access (histogram,counter)\n\tdefer l.mutex.Unlock()\n\tstate := \"started\"\n\tif err != nil {\n\t\tstate = \"errored\"\n\t} else {\n\t\tif duration.Seconds() > 0 {\n\t\t\tstate = \"finished\"\n\t\t}\n\t}\n\tentry := l.WithFields(logrus.Fields{\"method\": method})\n\n\tvar tokens []string\n\tfor _, token := range camelcase.Split(method) {\n\t\ttokens = append(tokens, strings.ToLower(token))\n\t}\n\trootStatName := strings.Join(tokens, \"_\")\n\n\t\/\/ Recording the distribution of started times is meaningless\n\tif state != \"started\" {\n\t\trunTimeName := fmt.Sprintf(\"%v_time\", rootStatName)\n\t\trunTime, ok := l.histogram[runTimeName]\n\t\tif !ok {\n\t\t\trunTime = prometheus.NewHistogramVec(\n\t\t\t\tprometheus.HistogramOpts{\n\t\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\t\tName:      runTimeName,\n\t\t\t\t\tHelp:      fmt.Sprintf(\"Run time of %v\", method),\n\t\t\t\t\tBuckets:   prometheus.ExponentialBuckets(1.0, bucketFactor, bucketCount),\n\t\t\t\t},\n\t\t\t\t[]string{\n\t\t\t\t\t\"state\", \/\/ Since both finished and errored API calls can have run times\n\t\t\t\t},\n\t\t\t)\n\t\t\tif err := prometheus.Register(runTime); err != nil {\n\t\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t\t} else {\n\t\t\t\tl.histogram[runTimeName] = runTime\n\t\t\t}\n\t\t}\n\t\tif hist, err := runTime.GetMetricWithLabelValues(state); err != nil {\n\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"failed to get histogram w labels: state (%v) with error %v\", state, err)\n\t\t} else {\n\t\t\thist.Observe(duration.Seconds())\n\t\t}\n\t}\n\n\tsecondsCountName := fmt.Sprintf(\"%v_seconds_count\", rootStatName)\n\tsecondsCount, ok := l.counter[secondsCountName]\n\tif !ok {\n\t\tsecondsCount = prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tNamespace: \"pachyderm\",\n\t\t\t\tSubsystem: \"pachd\",\n\t\t\t\tName:      secondsCountName,\n\t\t\t\tHelp:      fmt.Sprintf(\"cumulative number of seconds spent in %v\", method),\n\t\t\t},\n\t\t)\n\t\tif err := prometheus.Register(secondsCount); err != nil {\n\t\t\tl.LogAtLevel(entry, logrus.WarnLevel, \"error registering prometheus metric: %v\", err)\n\t\t} else {\n\t\t\tl.counter[secondsCountName] = secondsCount\n\t\t}\n\t}\n\tsecondsCount.Add(duration.Seconds())\n\n}\n\nfunc (l *logger) LogAtLevel(entry *logrus.Entry, level logrus.Level, args ...interface{}) {\n\tswitch level {\n\tcase logrus.PanicLevel:\n\t\tentry.Panic(args)\n\tcase logrus.FatalLevel:\n\t\tentry.Fatal(args)\n\tcase logrus.ErrorLevel:\n\t\tentry.Error(args)\n\tcase logrus.WarnLevel:\n\t\tentry.Warn(args)\n\tcase logrus.InfoLevel:\n\t\tentry.Info(args)\n\tcase logrus.DebugLevel:\n\t\tentry.Debug(args)\n\t}\n}\n\nfunc (l *logger) LogAtLevelFromDepth(request interface{}, response interface{}, err error, duration time.Duration, level logrus.Level, depth int) {\n\tpc := make([]uintptr, depth)\n\truntime.Callers(depth, pc)\n\tsplit := strings.Split(runtime.FuncForPC(pc[0]).Name(), \".\")\n\tmethod := split[len(split)-1]\n\n\tfields := logrus.Fields{\n\t\t\"method\":  method,\n\t\t\"request\": request,\n\t}\n\tif response != nil {\n\t\tfields[\"response\"] = response\n\t}\n\tif err != nil {\n\t\t\/\/ \"err\" itself might be a code or even an empty struct\n\t\tfields[\"error\"] = err.Error()\n\t}\n\tif duration > 0 {\n\t\tfields[\"duration\"] = duration\n\t}\n\tl.LogAtLevel(l.WithFields(fields), level)\n}\n\ntype prettyFormatter struct{}\n\nfunc (f *prettyFormatter) Format(entry *logrus.Entry) ([]byte, error) {\n\tserialized := []byte(\n\t\tfmt.Sprintf(\n\t\t\t\"%v %v \",\n\t\t\tentry.Time.Format(logrus.DefaultTimestampFormat),\n\t\t\tstrings.ToUpper(entry.Level.String()),\n\t\t),\n\t)\n\tif entry.Data[\"service\"] != nil {\n\t\tserialized = append(serialized, []byte(fmt.Sprintf(\"%v.%v \", entry.Data[\"service\"], entry.Data[\"method\"]))...)\n\t}\n\tif len(entry.Data) > 2 {\n\t\tdelete(entry.Data, \"service\")\n\t\tdelete(entry.Data, \"method\")\n\t\tif entry.Data[\"duration\"] != nil {\n\t\t\tentry.Data[\"duration\"] = entry.Data[\"duration\"].(time.Duration).Seconds()\n\t\t}\n\t\tdata, err := json.Marshal(entry.Data)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed to marshal fields to JSON, %v\", err)\n\t\t}\n\t\tserialized = append(serialized, []byte(string(data))...)\n\t\tserialized = append(serialized, ' ')\n\t}\n\n\tserialized = append(serialized, []byte(entry.Message)...)\n\tserialized = append(serialized, '\\n')\n\treturn serialized, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bridge\n\nimport (\n\t\"sync\"\n\n\t\"github.com\/x-cray\/marathon-service-registrator\/consul\"\n\t\"github.com\/x-cray\/marathon-service-registrator\/marathon\"\n\t\"github.com\/x-cray\/marathon-service-registrator\/types\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype serviceGroupPair struct {\n\tservice *types.Service\n\tgroup   *types.ServiceGroup\n}\n\ntype Bridge struct {\n\tsync.Mutex\n\n\tscheduler              types.SchedulerAdapter\n\tschedulerServiceGroups map[string]*types.ServiceGroup\n\tregistry               types.RegistryAdapter\n\tregistryAdvertizeAddr  string\n\tconfig                 *types.Config\n}\n\nfunc New(c *types.Config) (*Bridge, error) {\n\tmarathon, err := marathon.New(c.Marathon)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconsul, err := consul.New(c.Consul, c.DryRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Bridge{\n\t\tconfig:    c,\n\t\tscheduler: marathon,\n\t\tregistry:  consul,\n\t}, nil\n}\n\nfunc (b *Bridge) cachedServiceGroup(groupID, actionText string) *types.ServiceGroup {\n\tif group, ok := b.schedulerServiceGroups[groupID]; ok {\n\t\treturn group\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Warningf(\n\t\t\"Service group %s was not found in scheduler cache (has %d entries). Could not %s.\",\n\t\tgroupID,\n\t\tlen(b.schedulerServiceGroups),\n\t\tactionText,\n\t)\n\treturn nil\n}\n\nfunc logSkipMessage(ip string) {\n\tlog.WithFields(log.Fields{\n\t\t\"prefix\": \"bridge\",\n\t\t\"ip\":     ip,\n\t}).Debug(\"Skipping event due to unrelated service host\")\n}\n\nfunc (b *Bridge) processServiceEvent(event *types.ServiceEvent) error {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tswitch event.Action {\n\tcase types.ServiceStarted:\n\t\t\/\/ New service is started, we need to refresh service cache.\n\t\t_, err := b.refreshSchedulerServices()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase types.ServiceStopped:\n\t\t\/\/ Service stopped, deregister and remove it from cache.\n\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\tif event.IP == b.registryAdvertizeAddr {\n\t\t\tif group := b.cachedServiceGroup(event.ServiceID, \"deregister\"); group != nil {\n\t\t\t\tb.registry.Deregister(group)\n\t\t\t\tdelete(b.schedulerServiceGroups, event.ServiceID)\n\t\t\t}\n\t\t} else {\n\t\t\tlogSkipMessage(event.IP)\n\t\t}\n\tcase types.ServiceWentUp:\n\t\t\/\/ Service went up, register it.\n\t\tif group := b.cachedServiceGroup(event.ServiceID, \"register\"); group != nil {\n\t\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\t\tif group.IP == b.registryAdvertizeAddr {\n\t\t\t\tb.registry.Register(group)\n\t\t\t} else {\n\t\t\t\tlogSkipMessage(group.IP)\n\t\t\t}\n\t\t}\n\tcase types.ServiceWentDown:\n\t\t\/\/ Service went down, deregister it.\n\t\tif group := b.cachedServiceGroup(event.ServiceID, \"deregister\"); group != nil {\n\t\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\t\tif group.IP == b.registryAdvertizeAddr {\n\t\t\t\tb.registry.Deregister(group)\n\t\t\t} else {\n\t\t\t\tlogSkipMessage(group.IP)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (b *Bridge) ProcessSchedulerEvents() error {\n\tschedulerEvents := make(types.EventsChannel, 5)\n\terr := b.scheduler.ListenForEvents(schedulerEvents)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Info(\"Registered for scheduler event stream\")\n\tfor {\n\t\tevent := <-schedulerEvents\n\t\tif event.Action != types.ServiceUnchanged {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"prefix\":  \"bridge\",\n\t\t\t\t\"service\": event.ServiceID,\n\t\t\t\t\"action\":  event.Action,\n\t\t\t\t\"event\":   event.OriginalEvent,\n\t\t\t}).Debug(\"Received scheduler event\")\n\t\t\tb.processServiceEvent(event)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Sync performs full synchronization of scheduler tasks to service registry.\nfunc (b *Bridge) Sync() error {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tactionsPerformed := false\n\n\t\/\/ Get services from registry.\n\tregistryServiceGroups, err := b.registry.Services()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\"Received %d services from registry\", len(registryServiceGroups))\n\n\t\/\/ Build ip:port-indexed service map.\n\tregistryServicesMap := make(map[string]*serviceGroupPair)\n\tfor _, group := range registryServiceGroups {\n\t\tfor _, service := range group.Services {\n\t\t\tregistryServicesMap[group.ServiceKey(service)] = &serviceGroupPair{\n\t\t\t\tservice: service,\n\t\t\t\tgroup:   group,\n\t\t\t}\n\t\t}\n\t}\n\n\tschedulerServicesMap, err := b.refreshSchedulerServices()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Register scheduler services absent in registry.\n\tfor _, schedulerService := range schedulerServicesMap {\n\t\tgroup := schedulerService.group\n\t\tservice := schedulerService.service\n\n\t\t\/\/ If service is not yet registered we need to register it.\n\t\t\/\/ Only consider healthy services registered on current registry's advertized address.\n\t\tif group.IP == b.registryAdvertizeAddr && service.Healthy && registryServicesMap[group.ServiceKey(service)] == nil {\n\t\t\terr := b.registry.Register(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tactionsPerformed = true\n\t\t}\n\t}\n\n\t\/\/ Deregister dangling services (existing in registry and absent in scheduler).\n\tfor _, registryService := range registryServicesMap {\n\t\tgroup := registryService.group\n\t\tservice := registryService.service\n\n\t\t\/\/ If service is registered and we don't have it in scheduler we need to deregister it.\n\t\tif schedulerServicesMap[group.ServiceKey(service)] == nil {\n\t\t\terr := b.registry.Deregister(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tactionsPerformed = true\n\t\t}\n\t}\n\n\tif !actionsPerformed {\n\t\tlog.WithField(\"prefix\", \"bridge\").Info(\"All services are in sync, no actions performed\")\n\t}\n\n\treturn nil\n}\n\nfunc (b *Bridge) refreshSchedulerServices() (map[string]*serviceGroupPair, error) {\n\tlog.WithField(\"prefix\", \"bridge\").Info(\"Refreshing scheduler services\")\n\n\t\/\/ Get registry's advertize address.\n\taddr, err := b.registry.AdvertiseAddr()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.registryAdvertizeAddr = addr\n\n\t\/\/ Get services from scheduler.\n\tschedulerServiceGroups, err := b.scheduler.Services()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\"Registry advertize address is %s\", b.registryAdvertizeAddr)\n\n\t\/\/ Build 2 maps of services:\n\t\/\/ ServiceID-indexed and ip:port-indexed\n\tipPortServices := make(map[string]*serviceGroupPair)\n\tb.schedulerServiceGroups = make(map[string]*types.ServiceGroup)\n\tfor _, group := range schedulerServiceGroups {\n\t\tb.schedulerServiceGroups[group.ID] = group\n\t\tfor _, service := range group.Services {\n\t\t\tipPortServices[group.ServiceKey(service)] = &serviceGroupPair{\n\t\t\t\tservice: service,\n\t\t\t\tgroup:   group,\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\n\t\t\"Received %d services from scheduler\",\n\t\tlen(schedulerServiceGroups),\n\t)\n\n\treturn ipPortServices, nil\n}\n<commit_msg>Fix some English<commit_after>package bridge\n\nimport (\n\t\"sync\"\n\n\t\"github.com\/x-cray\/marathon-service-registrator\/consul\"\n\t\"github.com\/x-cray\/marathon-service-registrator\/marathon\"\n\t\"github.com\/x-cray\/marathon-service-registrator\/types\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype serviceGroupPair struct {\n\tservice *types.Service\n\tgroup   *types.ServiceGroup\n}\n\ntype Bridge struct {\n\tsync.Mutex\n\n\tscheduler              types.SchedulerAdapter\n\tschedulerServiceGroups map[string]*types.ServiceGroup\n\tregistry               types.RegistryAdapter\n\tregistryAdvertizeAddr  string\n\tconfig                 *types.Config\n}\n\nfunc New(c *types.Config) (*Bridge, error) {\n\tmarathon, err := marathon.New(c.Marathon)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconsul, err := consul.New(c.Consul, c.DryRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Bridge{\n\t\tconfig:    c,\n\t\tscheduler: marathon,\n\t\tregistry:  consul,\n\t}, nil\n}\n\nfunc (b *Bridge) cachedServiceGroup(groupID, actionText string) *types.ServiceGroup {\n\tif group, ok := b.schedulerServiceGroups[groupID]; ok {\n\t\treturn group\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Warningf(\n\t\t\"Service group %s was not found in scheduler cache (has %d entries). Could not %s.\",\n\t\tgroupID,\n\t\tlen(b.schedulerServiceGroups),\n\t\tactionText,\n\t)\n\treturn nil\n}\n\nfunc logSkipMessage(ip string) {\n\tlog.WithFields(log.Fields{\n\t\t\"prefix\": \"bridge\",\n\t\t\"ip\":     ip,\n\t}).Debug(\"Skipping event due to unrelated service host\")\n}\n\nfunc (b *Bridge) processServiceEvent(event *types.ServiceEvent) error {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tswitch event.Action {\n\tcase types.ServiceStarted:\n\t\t\/\/ New service is started, we need to refresh service cache.\n\t\t_, err := b.refreshSchedulerServices()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase types.ServiceStopped:\n\t\t\/\/ Service stopped, deregister and remove it from cache.\n\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\tif event.IP == b.registryAdvertizeAddr {\n\t\t\tif group := b.cachedServiceGroup(event.ServiceID, \"deregister\"); group != nil {\n\t\t\t\tb.registry.Deregister(group)\n\t\t\t\tdelete(b.schedulerServiceGroups, event.ServiceID)\n\t\t\t}\n\t\t} else {\n\t\t\tlogSkipMessage(event.IP)\n\t\t}\n\tcase types.ServiceWentUp:\n\t\t\/\/ Service went up, register it.\n\t\tif group := b.cachedServiceGroup(event.ServiceID, \"register\"); group != nil {\n\t\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\t\tif group.IP == b.registryAdvertizeAddr {\n\t\t\t\tb.registry.Register(group)\n\t\t\t} else {\n\t\t\t\tlogSkipMessage(group.IP)\n\t\t\t}\n\t\t}\n\tcase types.ServiceWentDown:\n\t\t\/\/ Service went down, deregister it.\n\t\tif group := b.cachedServiceGroup(event.ServiceID, \"deregister\"); group != nil {\n\t\t\t\/\/ Only consider services registered on current registry's advertized address.\n\t\t\tif group.IP == b.registryAdvertizeAddr {\n\t\t\t\tb.registry.Deregister(group)\n\t\t\t} else {\n\t\t\t\tlogSkipMessage(group.IP)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (b *Bridge) ProcessSchedulerEvents() error {\n\tschedulerEvents := make(types.EventsChannel, 5)\n\terr := b.scheduler.ListenForEvents(schedulerEvents)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Info(\"Registered for scheduler event stream\")\n\tfor {\n\t\tevent := <-schedulerEvents\n\t\tif event.Action != types.ServiceUnchanged {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"prefix\":  \"bridge\",\n\t\t\t\t\"service\": event.ServiceID,\n\t\t\t\t\"action\":  event.Action,\n\t\t\t\t\"event\":   event.OriginalEvent,\n\t\t\t}).Debug(\"Received scheduler event\")\n\t\t\tb.processServiceEvent(event)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Sync performs full synchronization of scheduler tasks to service registry.\nfunc (b *Bridge) Sync() error {\n\tb.Lock()\n\tdefer b.Unlock()\n\n\tactionsPerformed := false\n\n\t\/\/ Get services from registry.\n\tregistryServiceGroups, err := b.registry.Services()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\"Received %d services from registry\", len(registryServiceGroups))\n\n\t\/\/ Build ip:port-indexed service map.\n\tregistryServicesMap := make(map[string]*serviceGroupPair)\n\tfor _, group := range registryServiceGroups {\n\t\tfor _, service := range group.Services {\n\t\t\tregistryServicesMap[group.ServiceKey(service)] = &serviceGroupPair{\n\t\t\t\tservice: service,\n\t\t\t\tgroup:   group,\n\t\t\t}\n\t\t}\n\t}\n\n\tschedulerServicesMap, err := b.refreshSchedulerServices()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Register scheduler services absent from registry.\n\tfor _, schedulerService := range schedulerServicesMap {\n\t\tgroup := schedulerService.group\n\t\tservice := schedulerService.service\n\n\t\t\/\/ If service is not yet registered we need to register it.\n\t\t\/\/ Only consider healthy services registered on current registry's advertized address.\n\t\tif group.IP == b.registryAdvertizeAddr && service.Healthy && registryServicesMap[group.ServiceKey(service)] == nil {\n\t\t\terr := b.registry.Register(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tactionsPerformed = true\n\t\t}\n\t}\n\n\t\/\/ Deregister dangling services (existing in registry but absent from scheduler).\n\tfor _, registryService := range registryServicesMap {\n\t\tgroup := registryService.group\n\t\tservice := registryService.service\n\n\t\t\/\/ If service is registered and we don't have it in scheduler we need to deregister it.\n\t\tif schedulerServicesMap[group.ServiceKey(service)] == nil {\n\t\t\terr := b.registry.Deregister(group)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tactionsPerformed = true\n\t\t}\n\t}\n\n\tif !actionsPerformed {\n\t\tlog.WithField(\"prefix\", \"bridge\").Info(\"All services are in sync, no actions performed\")\n\t}\n\n\treturn nil\n}\n\nfunc (b *Bridge) refreshSchedulerServices() (map[string]*serviceGroupPair, error) {\n\tlog.WithField(\"prefix\", \"bridge\").Info(\"Refreshing scheduler services\")\n\n\t\/\/ Get registry's advertize address.\n\taddr, err := b.registry.AdvertiseAddr()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.registryAdvertizeAddr = addr\n\n\t\/\/ Get services from scheduler.\n\tschedulerServiceGroups, err := b.scheduler.Services()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\"Registry advertize address is %s\", b.registryAdvertizeAddr)\n\n\t\/\/ Build 2 maps of services:\n\t\/\/ ServiceID-indexed and ip:port-indexed\n\tipPortServices := make(map[string]*serviceGroupPair)\n\tb.schedulerServiceGroups = make(map[string]*types.ServiceGroup)\n\tfor _, group := range schedulerServiceGroups {\n\t\tb.schedulerServiceGroups[group.ID] = group\n\t\tfor _, service := range group.Services {\n\t\t\tipPortServices[group.ServiceKey(service)] = &serviceGroupPair{\n\t\t\t\tservice: service,\n\t\t\t\tgroup:   group,\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.WithField(\"prefix\", \"bridge\").Infof(\n\t\t\"Received %d services from scheduler\",\n\t\tlen(schedulerServiceGroups),\n\t)\n\n\treturn ipPortServices, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package http2\n\nimport (\n\t\"fmt\"\n\thpack \"github.com\/ami-GS\/GoHPACK\"\n)\n\ntype Frame interface {\n\tPack()\n\tParse(data []byte)\n\tGetWire() []byte\n}\n\ntype Http2Header struct {\n\tLength     uint32\n\tType, Flag byte\n\tStreamID   uint32\n\tHeadWire   []byte\n}\n\nfunc NewHttp2Header(length uint32, fType, flag byte, streamID uint32) *Http2Header {\n\th := Http2Header{length, fType, flag, streamID, []byte{}}\n\th.Pack()\n\treturn &h\n}\n\nfunc (self *Http2Header) Pack() {\n\tself.HeadWire = make([]byte, 9)\n\tfor i := 0; i < 3; i++ {\n\t\tself.HeadWire[i] = byte(self.Length >> byte((2-i)*8))\n\t}\n\tself.HeadWire[3], self.HeadWire[4] = self.Type, self.Flag\n\tfor i := 0; i < 4; i++ {\n\t\tself.HeadWire[i+5] = byte(self.StreamID >> byte((3-i)*8))\n\t}\n}\n\nfunc (self *Http2Header) Parse(data []byte) {\n\tself.Length = uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])\n\tself.Type = data[3]\n\tself.Flag = data[4]\n\tself.StreamID = uint32(data[5])<<24 | uint32(data[6])<<16 | uint32(data[7])<<8 | uint32(data[8])\n}\n\ntype Data struct {\n\tHeader *Http2Header\n\tData   string\n\tPadLen byte\n\tWire   []byte\n}\n\nfunc NewData(data string, streamID uint32, flag, padLen byte) *Data {\n\tvar length uint32 = uint32(len(data))\n\tif flag&FLAG_PADDED == FLAG_PADDED {\n\t\tlength += uint32(padLen + 1)\n\t}\n\n\theader := NewHttp2Header(length, TYPE_DATA, flag, streamID)\n\tframe := Data{header, data, padLen, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Data) Pack() {\n\tidx := 0\n\tif self.Header.Flag == FLAG_PADDED {\n\t\tself.Wire = make([]byte, len(self.Data)+int(self.PadLen+1))\n\t\tself.Wire[idx] = self.PadLen\n\t\tidx++\n\t} else {\n\t\tself.Wire = make([]byte, uint32(len(self.Data)))\n\t}\n\tfor i, d := range self.Data {\n\t\tself.Wire[idx+i] = byte(d)\n\t}\n}\n\nfunc (self *Data) Parse(data []byte) {\n\tif self.Header.Flag == FLAG_PADDED {\n\t\tself.PadLen = data[0]\n\t\tself.Data = string(data[1 : self.Header.Length-uint32(self.PadLen)])\n\t} else {\n\t\tself.Data = string(data)\n\t}\n}\n\nfunc (self *Data) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype Settings struct {\n\tHeader    *Http2Header\n\tSettingID uint16\n\tValue     uint32\n\tWire      []byte\n}\n\nfunc NewSettings(settingID uint16, value uint32, flag byte) *Settings {\n\theader := NewHttp2Header(uint32(6), TYPE_SETTINGS, flag, 0)\n\tframe := Settings{header, settingID, value, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Settings) Pack() {\n\tself.Wire = make([]byte, 6)\n\tfor i := 0; i < 2; i++ {\n\t\tself.Wire[i] = byte(self.SettingID >> byte((1-i)*8))\n\t}\n\tfor i := 0; i < 4; i++ {\n\t\tself.Wire[2+i] = byte(self.Value >> byte((3-i)*8))\n\t}\n}\n\nfunc (self *Settings) Parse(data []byte) {\n\tself.SettingID = uint16(data[0])<<8 | uint16(data[1])\n\tself.Value = uint32(data[2])<<24 | uint32(data[3])<<16 | uint32(data[4])<<8 | uint32(data[5])\n\t_ = self.Header.Flag \/\/temporally\n}\n\nfunc (self *Settings) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype Headers struct {\n\tHeader           *Http2Header\n\tHeaders          []hpack.Header\n\tblock            []byte\n\tPadLen, Weight   byte\n\tE                bool\n\tStreamDependency uint32\n\tWire             []byte\n}\n\nfunc NewHeaders(headers []hpack.Header, table *hpack.Table, streamID uint32, flag, padLen, weight byte, e bool, streamDependency uint32) *Headers {\n\tencHeaders := hpack.Encode(headers, false, false, false, table, -1)\n\tvar length uint32 = uint32(len(encHeaders))\n\tif flag&FLAG_PADDED == FLAG_PADDED {\n\t\tlength += uint32(padLen + 1)\n\t}\n\tif flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tlength += 5\n\t}\n\n\theader := NewHttp2Header(length, TYPE_HEADERS, flag, streamID)\n\n\tframe := Headers{header, headers, encHeaders, padLen, weight, e, streamDependency, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Headers) Pack() {\n\tidx := 0\n\tif self.Header.Flag&FLAG_PADDED == FLAG_PADDED {\n\t\tself.Wire = make([]byte, int(self.PadLen+1)+len(self.block))\n\t\tself.Wire[idx] = self.PadLen\n\t\tidx++\n\t}\n\tif self.Header.Flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tself.Wire = make([]byte, 5+len(self.block))\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tself.Wire[i] = byte(self.StreamDependency >> byte((3-i)*8))\n\t\t}\n\t\tif self.E {\n\t\t\tself.Wire[0] |= 0x80\n\t\t}\n\t\tself.Wire[4] = self.Weight\n\t\tidx = 5\n\t}\n\tif self.Header.Flag&FLAG_END_HEADERS == FLAG_END_HEADERS || self.Header.Flag&FLAG_END_STREAM == FLAG_END_STREAM {\n\t\tself.Wire = make([]byte, len(self.block))\n\t}\n\t\/*else {\n\t\tpanic(\"undefined flag\")\n\t}*\/\n\tfor i, h := range self.block {\n\t\tself.Wire[idx+i] = h\n\t}\n}\n\nfunc (self *Headers) Parse(data []byte) {\n\tidx := 0\n\tif self.Header.Flag&FLAG_PADDED == FLAG_PADDED {\n\t\tself.PadLen = data[idx]\n\t\tidx++\n\t}\n\tif self.Header.Flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tif data[0]&0x80 > 0 {\n\t\t\tself.E = true\n\t\t}\n\t\tself.StreamDependency = uint32(data[0]&0xef)<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])\n\t\tself.Weight = data[4]\n\t\tidx += 5\n\t}\n\tif self.Header.Flag&FLAG_END_HEADERS == FLAG_END_HEADERS || self.Header.Flag&FLAG_END_STREAM == FLAG_END_STREAM {\n\t\tfmt.Println(\"change stream state\")\n\t}\n\t\/*else {\n\t\tpanic(\"undefined flag\")\n\t}*\/\n}\n\nfunc (self *Headers) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype GoAway struct {\n\tHeader       *Http2Header\n\tLastStreamID uint32\n\tErrorCode    uint32\n\tDebug        string\n\tWire         []byte\n}\n\nfunc NewGoAway(lastStreamID, errorCode uint32, debug string) *GoAway {\n\tvar length uint32 = uint32(len(debug) + 8)\n\theader := NewHttp2Header(length, TYPE_GOAWAY, FLAG_NO, 0)\n\tframe := GoAway{header, lastStreamID, errorCode, debug, []byte{}}\n\tframe.Pack()\n\treturn &frame\n}\n\nfunc (self *GoAway) Pack() {\n\tself.Wire = make([]byte, 8+len(self.Debug))\n\tfor i := 0; i < 4; i++ {\n\t\tself.Wire[i] = byte(self.LastStreamID >> byte((3-i)*8))\n\t\tself.Wire[i+4] = byte(self.ErrorCode >> byte((3-i)*8))\n\t}\n\tfor i, d := range self.Debug {\n\t\tself.Wire[i+8] = byte(d)\n\t}\n}\n\nfunc (self *GoAway) Parse(data []byte) {\n\tself.LastStreamID = uint32(data[0]&0xef)<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])\n\tself.ErrorCode = uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])\n\tif len(data) >= 9 {\n\t\tself.Debug = string(data[8:])\n\t}\n}\n\nfunc (self *GoAway) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\nfunc main() {\n\ttable := hpack.InitTable()\n\theaders := []hpack.Header{hpack.Header{\":method\", \"GET\"}, hpack.Header{\":scheme\", \"http\"},\n\t\thpack.Header{\":authority\", \"127.0.0.1\"}, hpack.Header{\":path\", \"\/\"}}\n\n\thttp2Header := Http2Header{Length: 12, Type: TYPE_DATA, Flag: FLAG_PADDED, StreamID: 1}\n\thttp2Header.Pack()\n\tfmt.Printf(\"http2Header %v\\n\", http2Header)\n\tdata := Data{Data: \"Hello!\", PadLen: 5}\n\tdata.Pack(http2Header.Flag)\n\tdata2 := Data{}\n\tdata2.Parse(data.Wire, http2Header.Flag, http2Header.Length)\n\tfmt.Printf(\"data %v\\n\", data)\n\tfmt.Printf(\"data2 %v\\n\", data2)\n\tsettings := Settings{SettingID: 0xff00, Value: 0xff00ff00}\n\tsettings2 := Settings{}\n\tsettings.Pack()\n\tsettings2.Parse(settings.Wire, http2Header.Flag)\n\tfmt.Printf(\"settings %v\\n\", settings)\n\tfmt.Printf(\"settings2 %v\\n\", settings2)\n\th := Headers{Headers: headers, PadLen: 5, Weight: 0, E: false}\n\th2 := Headers{}\n\th.Pack(http2Header.Flag, &table)\n\th2.Parse(h.Wire, http2Header.Flag, &table)\n\tfmt.Printf(\"headers %v\\n\", h)\n\tfmt.Printf(\"headers2 %v\\n\", h2)\n\tgoaway := GoAway{LastStreamID: 0xef00ff00, ErrorCode: 0xff00ff00, Debug: \"DEBUG MESSAGE!!\"}\n\tgoaway2 := GoAway{}\n\tgoaway.Pack()\n\tgoaway2.Parse(goaway.Wire)\n\tfmt.Printf(\"goaway %v\\n\", goaway)\n\tfmt.Printf(\"goaway2 %v\\n\", goaway2)\n}\n<commit_msg>temporally remove<commit_after>package http2\n\nimport (\n\t\"fmt\"\n\thpack \"github.com\/ami-GS\/GoHPACK\"\n)\n\ntype Frame interface {\n\tPack()\n\tParse(data []byte)\n\tGetWire() []byte\n}\n\ntype Http2Header struct {\n\tLength     uint32\n\tType, Flag byte\n\tStreamID   uint32\n\tHeadWire   []byte\n}\n\nfunc NewHttp2Header(length uint32, fType, flag byte, streamID uint32) *Http2Header {\n\th := Http2Header{length, fType, flag, streamID, []byte{}}\n\th.Pack()\n\treturn &h\n}\n\nfunc (self *Http2Header) Pack() {\n\tself.HeadWire = make([]byte, 9)\n\tfor i := 0; i < 3; i++ {\n\t\tself.HeadWire[i] = byte(self.Length >> byte((2-i)*8))\n\t}\n\tself.HeadWire[3], self.HeadWire[4] = self.Type, self.Flag\n\tfor i := 0; i < 4; i++ {\n\t\tself.HeadWire[i+5] = byte(self.StreamID >> byte((3-i)*8))\n\t}\n}\n\nfunc (self *Http2Header) Parse(data []byte) {\n\tself.Length = uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])\n\tself.Type = data[3]\n\tself.Flag = data[4]\n\tself.StreamID = uint32(data[5])<<24 | uint32(data[6])<<16 | uint32(data[7])<<8 | uint32(data[8])\n}\n\ntype Data struct {\n\tHeader *Http2Header\n\tData   string\n\tPadLen byte\n\tWire   []byte\n}\n\nfunc NewData(data string, streamID uint32, flag, padLen byte) *Data {\n\tvar length uint32 = uint32(len(data))\n\tif flag&FLAG_PADDED == FLAG_PADDED {\n\t\tlength += uint32(padLen + 1)\n\t}\n\n\theader := NewHttp2Header(length, TYPE_DATA, flag, streamID)\n\tframe := Data{header, data, padLen, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Data) Pack() {\n\tidx := 0\n\tif self.Header.Flag == FLAG_PADDED {\n\t\tself.Wire = make([]byte, len(self.Data)+int(self.PadLen+1))\n\t\tself.Wire[idx] = self.PadLen\n\t\tidx++\n\t} else {\n\t\tself.Wire = make([]byte, uint32(len(self.Data)))\n\t}\n\tfor i, d := range self.Data {\n\t\tself.Wire[idx+i] = byte(d)\n\t}\n}\n\nfunc (self *Data) Parse(data []byte) {\n\tif self.Header.Flag == FLAG_PADDED {\n\t\tself.PadLen = data[0]\n\t\tself.Data = string(data[1 : self.Header.Length-uint32(self.PadLen)])\n\t} else {\n\t\tself.Data = string(data)\n\t}\n}\n\nfunc (self *Data) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype Settings struct {\n\tHeader    *Http2Header\n\tSettingID uint16\n\tValue     uint32\n\tWire      []byte\n}\n\nfunc NewSettings(settingID uint16, value uint32, flag byte) *Settings {\n\theader := NewHttp2Header(uint32(6), TYPE_SETTINGS, flag, 0)\n\tframe := Settings{header, settingID, value, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Settings) Pack() {\n\tself.Wire = make([]byte, 6)\n\tfor i := 0; i < 2; i++ {\n\t\tself.Wire[i] = byte(self.SettingID >> byte((1-i)*8))\n\t}\n\tfor i := 0; i < 4; i++ {\n\t\tself.Wire[2+i] = byte(self.Value >> byte((3-i)*8))\n\t}\n}\n\nfunc (self *Settings) Parse(data []byte) {\n\tself.SettingID = uint16(data[0])<<8 | uint16(data[1])\n\tself.Value = uint32(data[2])<<24 | uint32(data[3])<<16 | uint32(data[4])<<8 | uint32(data[5])\n\t_ = self.Header.Flag \/\/temporally\n}\n\nfunc (self *Settings) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype Headers struct {\n\tHeader           *Http2Header\n\tHeaders          []hpack.Header\n\tblock            []byte\n\tPadLen, Weight   byte\n\tE                bool\n\tStreamDependency uint32\n\tWire             []byte\n}\n\nfunc NewHeaders(headers []hpack.Header, table *hpack.Table, streamID uint32, flag, padLen, weight byte, e bool, streamDependency uint32) *Headers {\n\tencHeaders := hpack.Encode(headers, false, false, false, table, -1)\n\tvar length uint32 = uint32(len(encHeaders))\n\tif flag&FLAG_PADDED == FLAG_PADDED {\n\t\tlength += uint32(padLen + 1)\n\t}\n\tif flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tlength += 5\n\t}\n\n\theader := NewHttp2Header(length, TYPE_HEADERS, flag, streamID)\n\n\tframe := Headers{header, headers, encHeaders, padLen, weight, e, streamDependency, []byte{}}\n\tframe.Pack()\n\n\treturn &frame\n}\n\nfunc (self *Headers) Pack() {\n\tidx := 0\n\tif self.Header.Flag&FLAG_PADDED == FLAG_PADDED {\n\t\tself.Wire = make([]byte, int(self.PadLen+1)+len(self.block))\n\t\tself.Wire[idx] = self.PadLen\n\t\tidx++\n\t}\n\tif self.Header.Flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tself.Wire = make([]byte, 5+len(self.block))\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tself.Wire[i] = byte(self.StreamDependency >> byte((3-i)*8))\n\t\t}\n\t\tif self.E {\n\t\t\tself.Wire[0] |= 0x80\n\t\t}\n\t\tself.Wire[4] = self.Weight\n\t\tidx = 5\n\t}\n\tif self.Header.Flag&FLAG_END_HEADERS == FLAG_END_HEADERS || self.Header.Flag&FLAG_END_STREAM == FLAG_END_STREAM {\n\t\tself.Wire = make([]byte, len(self.block))\n\t}\n\t\/*else {\n\t\tpanic(\"undefined flag\")\n\t}*\/\n\tfor i, h := range self.block {\n\t\tself.Wire[idx+i] = h\n\t}\n}\n\nfunc (self *Headers) Parse(data []byte) {\n\tidx := 0\n\tif self.Header.Flag&FLAG_PADDED == FLAG_PADDED {\n\t\tself.PadLen = data[idx]\n\t\tidx++\n\t}\n\tif self.Header.Flag&FLAG_PRIORITY == FLAG_PRIORITY {\n\t\tif data[0]&0x80 > 0 {\n\t\t\tself.E = true\n\t\t}\n\t\tself.StreamDependency = uint32(data[0]&0xef)<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])\n\t\tself.Weight = data[4]\n\t\tidx += 5\n\t}\n\tif self.Header.Flag&FLAG_END_HEADERS == FLAG_END_HEADERS || self.Header.Flag&FLAG_END_STREAM == FLAG_END_STREAM {\n\t\tfmt.Println(\"change stream state\")\n\t}\n\t\/*else {\n\t\tpanic(\"undefined flag\")\n\t}*\/\n}\n\nfunc (self *Headers) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\ntype GoAway struct {\n\tHeader       *Http2Header\n\tLastStreamID uint32\n\tErrorCode    uint32\n\tDebug        string\n\tWire         []byte\n}\n\nfunc NewGoAway(lastStreamID, errorCode uint32, debug string) *GoAway {\n\tvar length uint32 = uint32(len(debug) + 8)\n\theader := NewHttp2Header(length, TYPE_GOAWAY, FLAG_NO, 0)\n\tframe := GoAway{header, lastStreamID, errorCode, debug, []byte{}}\n\tframe.Pack()\n\treturn &frame\n}\n\nfunc (self *GoAway) Pack() {\n\tself.Wire = make([]byte, 8+len(self.Debug))\n\tfor i := 0; i < 4; i++ {\n\t\tself.Wire[i] = byte(self.LastStreamID >> byte((3-i)*8))\n\t\tself.Wire[i+4] = byte(self.ErrorCode >> byte((3-i)*8))\n\t}\n\tfor i, d := range self.Debug {\n\t\tself.Wire[i+8] = byte(d)\n\t}\n}\n\nfunc (self *GoAway) Parse(data []byte) {\n\tself.LastStreamID = uint32(data[0]&0xef)<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])\n\tself.ErrorCode = uint32(data[4])<<24 | uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])\n\tif len(data) >= 9 {\n\t\tself.Debug = string(data[8:])\n\t}\n}\n\nfunc (self *GoAway) GetWire() []byte {\n\treturn append(self.Header.HeadWire, self.Wire...)\n}\n\n\/*\nfunc main() {\n\ttable := hpack.InitTable()\n\theaders := []hpack.Header{hpack.Header{\":method\", \"GET\"}, hpack.Header{\":scheme\", \"http\"},\n\t\thpack.Header{\":authority\", \"127.0.0.1\"}, hpack.Header{\":path\", \"\/\"}}\n\n\thttp2Header := Http2Header{Length: 12, Type: TYPE_DATA, Flag: FLAG_PADDED, StreamID: 1}\n\thttp2Header.Pack()\n\tfmt.Printf(\"http2Header %v\\n\", http2Header)\n\tdata := Data{Data: \"Hello!\", PadLen: 5}\n\tdata.Pack(http2Header.Flag)\n\tdata2 := Data{}\n\tdata2.Parse(data.Wire, http2Header.Flag, http2Header.Length)\n\tfmt.Printf(\"data %v\\n\", data)\n\tfmt.Printf(\"data2 %v\\n\", data2)\n\tsettings := Settings{SettingID: 0xff00, Value: 0xff00ff00}\n\tsettings2 := Settings{}\n\tsettings.Pack()\n\tsettings2.Parse(settings.Wire, http2Header.Flag)\n\tfmt.Printf(\"settings %v\\n\", settings)\n\tfmt.Printf(\"settings2 %v\\n\", settings2)\n\th := Headers{Headers: headers, PadLen: 5, Weight: 0, E: false}\n\th2 := Headers{}\n\th.Pack(http2Header.Flag, &table)\n\th2.Parse(h.Wire, http2Header.Flag, &table)\n\tfmt.Printf(\"headers %v\\n\", h)\n\tfmt.Printf(\"headers2 %v\\n\", h2)\n\tgoaway := GoAway{LastStreamID: 0xef00ff00, ErrorCode: 0xff00ff00, Debug: \"DEBUG MESSAGE!!\"}\n\tgoaway2 := GoAway{}\n\tgoaway.Pack()\n\tgoaway2.Parse(goaway.Wire)\n\tfmt.Printf(\"goaway %v\\n\", goaway)\n\tfmt.Printf(\"goaway2 %v\\n\", goaway2)\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package transport\n\nimport (\n\t\"bytes\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/Randomsock5\/tcptunnel\/constants\"\n)\n\ntype AESConn struct {\n\tconn net.Conn\n\tr    *cipher.StreamReader\n\tw    *cipher.StreamWriter\n}\n\nfunc (ac *AESConn) Read(dst []byte) (int, error) {\n\tn, err := ac.r.Read(dst)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Write(src []byte) (int, error) {\n\tn, err := ac.w.Write(src)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Close() error {\n\treturn ac.conn.Close()\n}\n\nfunc (ac *AESConn) LocalAddr() net.Addr {\n\treturn ac.conn.LocalAddr()\n}\n\nfunc (ac *AESConn) RemoteAddr() net.Addr {\n\treturn ac.conn.RemoteAddr()\n}\n\nfunc (ac *AESConn) SetDeadline(t time.Time) error {\n\treturn ac.conn.SetDeadline(t)\n}\n\nfunc (ac *AESConn) SetReadDeadline(t time.Time) error {\n\treturn ac.conn.SetReadDeadline(t)\n}\n\nfunc (ac *AESConn) SetWriteDeadline(t time.Time) error {\n\treturn ac.conn.SetWriteDeadline(t)\n}\n\nfunc NewAESConn(key string, iv [aes.BlockSize]byte, conn net.Conn) (*AESConn, error) {\n\tkeyBin := []byte(key)\n\tt := time.Now().UTC()\n\n\thashKey := sha256.Sum256(keyBin)\n\tsalt := sha256.Sum256(\n\t\t[]byte(fmt.Sprintf(\"%d-%02d-%02d\", t.Year(), t.Month(), t.Day())))\n\n\thashSalt := append(hashKey[:], salt[:]...)\n\n\taesKey := sha256.Sum256(hashSalt)\n\n\trBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trStream := cipher.NewOFB(rBlock, iv[:])\n\twStream := cipher.NewOFB(wBlock, iv[:])\n\n\taesConn := &AESConn{\n\t\tconn: conn,\n\t\tr:    &cipher.StreamReader{S: rStream, R: conn},\n\t\tw:    &cipher.StreamWriter{S: wStream, W: conn},\n\t}\n\treturn aesConn, err\n}\n\ntype Listener struct {\n\tlistener net.Listener\n\tkey      string\n}\n\nfunc (l *Listener) Accept() (net.Conn, error) {\n\tconn, err := l.listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = conn.SetReadDeadline(time.Now().Add(constants.ConnTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\tif _, err := io.ReadFull(conn, ivVector); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpassword := sha256.Sum256([]byte(l.key))\n\tlongIv := append(password[:], ivVector...)\n\n\thash := sha256.Sum256(longIv)\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(l.key, iv, conn)\n\terr = conn.SetReadDeadline(time.Time{})\n\n\treturn aesConn, err\n}\n\nfunc (l *Listener) Close() error {\n\treturn l.listener.Close()\n}\n\nfunc (l *Listener) Addr() net.Addr {\n\treturn l.listener.Addr()\n}\n\nfunc Listen(listenAddress string, key string) (*Listener, error) {\n\tlisten, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &Listener{\n\t\tlistener: listen,\n\t\tkey:      key,\n\t}\n\treturn l, nil\n}\n\nfunc Dial(address string, key string, timeout time.Duration) (net.Conn, error) {\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\t_, err = rand.Read(ivVector[:])\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpassword := sha256.Sum256([]byte(key))\n\tlongIv := append(password[:], ivVector...)\n\thash := sha256.Sum256(longIv)\n\n\tbuf := bytes.NewBuffer(ivVector)\n\tif _, err := io.CopyN(conn, buf, constants.IVLength); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(key, iv, conn)\n\treturn aesConn, err\n}\n<commit_msg>set tcp keep alive<commit_after>package transport\n\nimport (\n\t\"bytes\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/Randomsock5\/tcptunnel\/constants\"\n)\n\ntype AESConn struct {\n\tconn net.Conn\n\tr    *cipher.StreamReader\n\tw    *cipher.StreamWriter\n}\n\nfunc (ac *AESConn) Read(dst []byte) (int, error) {\n\tn, err := ac.r.Read(dst)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Write(src []byte) (int, error) {\n\tn, err := ac.w.Write(src)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Close() error {\n\treturn ac.conn.Close()\n}\n\nfunc (ac *AESConn) LocalAddr() net.Addr {\n\treturn ac.conn.LocalAddr()\n}\n\nfunc (ac *AESConn) RemoteAddr() net.Addr {\n\treturn ac.conn.RemoteAddr()\n}\n\nfunc (ac *AESConn) SetDeadline(t time.Time) error {\n\treturn ac.conn.SetDeadline(t)\n}\n\nfunc (ac *AESConn) SetReadDeadline(t time.Time) error {\n\treturn ac.conn.SetReadDeadline(t)\n}\n\nfunc (ac *AESConn) SetWriteDeadline(t time.Time) error {\n\treturn ac.conn.SetWriteDeadline(t)\n}\n\nfunc NewAESConn(key string, iv [aes.BlockSize]byte, conn net.Conn) (*AESConn, error) {\n\tkeyBin := []byte(key)\n\tt := time.Now().UTC()\n\n\thashKey := sha256.Sum256(keyBin)\n\tsalt := sha256.Sum256(\n\t\t[]byte(fmt.Sprintf(\"%d-%02d-%02d\", t.Year(), t.Month(), t.Day())))\n\n\thashSalt := append(hashKey[:], salt[:]...)\n\n\taesKey := sha256.Sum256(hashSalt)\n\n\trBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trStream := cipher.NewOFB(rBlock, iv[:])\n\twStream := cipher.NewOFB(wBlock, iv[:])\n\n\taesConn := &AESConn{\n\t\tconn: conn,\n\t\tr:    &cipher.StreamReader{S: rStream, R: conn},\n\t\tw:    &cipher.StreamWriter{S: wStream, W: conn},\n\t}\n\treturn aesConn, err\n}\n\ntype Listener struct {\n\tlistener net.Listener\n\tkey      string\n}\n\nfunc (l *Listener) Accept() (net.Conn, error) {\n\tconn, err := l.listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = conn.SetReadDeadline(time.Now().Add(constants.ConnTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\tif _, err := io.ReadFull(conn, ivVector); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpassword := sha256.Sum256([]byte(l.key))\n\tlongIv := append(password[:], ivVector...)\n\n\thash := sha256.Sum256(longIv)\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(l.key, iv, conn)\n\terr = conn.SetReadDeadline(time.Time{})\n\n\treturn aesConn, err\n}\n\nfunc (l *Listener) Close() error {\n\treturn l.listener.Close()\n}\n\nfunc (l *Listener) Addr() net.Addr {\n\treturn l.listener.Addr()\n}\n\nfunc Listen(listenAddress string, key string) (*Listener, error) {\n\tlisten, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &Listener{\n\t\tlistener: listen,\n\t\tkey:      key,\n\t}\n\treturn l, nil\n}\n\nfunc Dial(address string, key string, timeout time.Duration) (net.Conn, error) {\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = conn.(*net.TCPConn).SetKeepAlive(true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = conn.(*net.TCPConn).SetKeepAlivePeriod(2 * timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\t_, err = rand.Read(ivVector[:])\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpassword := sha256.Sum256([]byte(key))\n\tlongIv := append(password[:], ivVector...)\n\thash := sha256.Sum256(longIv)\n\n\tbuf := bytes.NewBuffer(ivVector)\n\tif _, err := io.CopyN(conn, buf, constants.IVLength); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(key, iv, conn)\n\treturn aesConn, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package transport\n\nimport (\n\t\"bytes\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/Randomsock5\/tcptunnel\/constants\"\n)\n\ntype AESConn struct {\n\tconn net.Conn\n\tr    *cipher.StreamReader\n\tw    *cipher.StreamWriter\n}\n\nfunc (ac *AESConn) Read(dst []byte) (int, error) {\n\tn, err := ac.r.Read(dst)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Write(src []byte) (int, error) {\n\tn, err := ac.w.Write(src)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Close() error {\n\treturn ac.conn.Close()\n}\n\nfunc (ac *AESConn) LocalAddr() net.Addr {\n\treturn ac.conn.LocalAddr()\n}\n\nfunc (ac *AESConn) RemoteAddr() net.Addr {\n\treturn ac.conn.RemoteAddr()\n}\n\nfunc (ac *AESConn) SetDeadline(t time.Time) error {\n\treturn ac.conn.SetDeadline(t)\n}\n\nfunc (ac *AESConn) SetReadDeadline(t time.Time) error {\n\treturn ac.conn.SetReadDeadline(t)\n}\n\nfunc (ac *AESConn) SetWriteDeadline(t time.Time) error {\n\treturn ac.conn.SetWriteDeadline(t)\n}\n\nfunc NewAESConn(key string, iv [aes.BlockSize]byte, conn net.Conn) (*AESConn, error) {\n\tkeyBin := []byte(key)\n\tt := time.Now().UTC()\n\n\thashKey := sha256.Sum256(keyBin)\n\tsalt := sha256.Sum256(\n\t\t[]byte(fmt.Sprintf(\"%d-%02d-%02d\", t.Year(), t.Month(), t.Day())))\n\n\thashSalt := append(hashKey[:], salt[:]...)\n\n\taesKey := sha256.Sum256(hashSalt)\n\n\trBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trStream := cipher.NewOFB(rBlock, iv[:])\n\twStream := cipher.NewOFB(wBlock, iv[:])\n\n\taesConn := &AESConn{\n\t\tconn: conn,\n\t\tr:    &cipher.StreamReader{S: rStream, R: conn},\n\t\tw:    &cipher.StreamWriter{S: wStream, W: conn},\n\t}\n\treturn aesConn, err\n}\n\ntype Listener struct {\n\tlistener net.Listener\n\tkey      string\n}\n\nfunc (l *Listener) Accept() (net.Conn, error) {\n\tconn, err := l.listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = conn.SetReadDeadline(time.Now().Add(constants.ConnTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\tif _, err := io.ReadFull(conn, ivVector); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpassword := sha256.Sum256([]byte(l.key))\n\tlongIv := append(password[:], ivVector...)\n\n\thash := sha256.Sum256(longIv)\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(l.key, iv, conn)\n\treturn aesConn, err\n}\n\nfunc (l *Listener) Close() error {\n\treturn l.listener.Close()\n}\n\nfunc (l *Listener) Addr() net.Addr {\n\treturn l.listener.Addr()\n}\n\nfunc Listen(listenAddress string, key string) (*Listener, error) {\n\tlisten, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &Listener{\n\t\tlistener: listen,\n\t\tkey:      key,\n\t}\n\treturn l, nil\n}\n\nfunc Dial(address string, key string, timeout time.Duration) (net.Conn, error) {\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\t_, err = rand.Read(ivVector[:])\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpassword := sha256.Sum256([]byte(key))\n\tlongIv := append(password[:], ivVector...)\n\thash := sha256.Sum256(longIv)\n\n\tbuf := bytes.NewBuffer(ivVector)\n\tif _, err := io.CopyN(conn, buf, constants.IVLength); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(key, iv, conn)\n\treturn aesConn, err\n}\n<commit_msg>cancel readtimeout<commit_after>package transport\n\nimport (\n\t\"bytes\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/Randomsock5\/tcptunnel\/constants\"\n)\n\ntype AESConn struct {\n\tconn net.Conn\n\tr    *cipher.StreamReader\n\tw    *cipher.StreamWriter\n}\n\nfunc (ac *AESConn) Read(dst []byte) (int, error) {\n\tn, err := ac.r.Read(dst)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Write(src []byte) (int, error) {\n\tn, err := ac.w.Write(src)\n\treturn n, err\n}\n\nfunc (ac *AESConn) Close() error {\n\treturn ac.conn.Close()\n}\n\nfunc (ac *AESConn) LocalAddr() net.Addr {\n\treturn ac.conn.LocalAddr()\n}\n\nfunc (ac *AESConn) RemoteAddr() net.Addr {\n\treturn ac.conn.RemoteAddr()\n}\n\nfunc (ac *AESConn) SetDeadline(t time.Time) error {\n\treturn ac.conn.SetDeadline(t)\n}\n\nfunc (ac *AESConn) SetReadDeadline(t time.Time) error {\n\treturn ac.conn.SetReadDeadline(t)\n}\n\nfunc (ac *AESConn) SetWriteDeadline(t time.Time) error {\n\treturn ac.conn.SetWriteDeadline(t)\n}\n\nfunc NewAESConn(key string, iv [aes.BlockSize]byte, conn net.Conn) (*AESConn, error) {\n\tkeyBin := []byte(key)\n\tt := time.Now().UTC()\n\n\thashKey := sha256.Sum256(keyBin)\n\tsalt := sha256.Sum256(\n\t\t[]byte(fmt.Sprintf(\"%d-%02d-%02d\", t.Year(), t.Month(), t.Day())))\n\n\thashSalt := append(hashKey[:], salt[:]...)\n\n\taesKey := sha256.Sum256(hashSalt)\n\n\trBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\twBlock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trStream := cipher.NewOFB(rBlock, iv[:])\n\twStream := cipher.NewOFB(wBlock, iv[:])\n\n\taesConn := &AESConn{\n\t\tconn: conn,\n\t\tr:    &cipher.StreamReader{S: rStream, R: conn},\n\t\tw:    &cipher.StreamWriter{S: wStream, W: conn},\n\t}\n\treturn aesConn, err\n}\n\ntype Listener struct {\n\tlistener net.Listener\n\tkey      string\n}\n\nfunc (l *Listener) Accept() (net.Conn, error) {\n\tconn, err := l.listener.Accept()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = conn.SetReadDeadline(time.Now().Add(constants.ConnTimeout))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\tif _, err := io.ReadFull(conn, ivVector); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpassword := sha256.Sum256([]byte(l.key))\n\tlongIv := append(password[:], ivVector...)\n\n\thash := sha256.Sum256(longIv)\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(l.key, iv, conn)\n\terr = conn.SetReadDeadline(time.Time{})\n\n\treturn aesConn, err\n}\n\nfunc (l *Listener) Close() error {\n\treturn l.listener.Close()\n}\n\nfunc (l *Listener) Addr() net.Addr {\n\treturn l.listener.Addr()\n}\n\nfunc Listen(listenAddress string, key string) (*Listener, error) {\n\tlisten, err := net.Listen(\"tcp\", listenAddress)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tl := &Listener{\n\t\tlistener: listen,\n\t\tkey:      key,\n\t}\n\treturn l, nil\n}\n\nfunc Dial(address string, key string, timeout time.Duration) (net.Conn, error) {\n\tconn, err := net.DialTimeout(\"tcp\", address, timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tivVector := make([]byte, constants.IVLength)\n\t_, err = rand.Read(ivVector[:])\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpassword := sha256.Sum256([]byte(key))\n\tlongIv := append(password[:], ivVector...)\n\thash := sha256.Sum256(longIv)\n\n\tbuf := bytes.NewBuffer(ivVector)\n\tif _, err := io.CopyN(conn, buf, constants.IVLength); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar iv [aes.BlockSize]byte\n\tcopy(iv[:], hash[:aes.BlockSize])\n\n\taesConn, err := NewAESConn(key, iv, conn)\n\treturn aesConn, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package routing\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/jsonerror\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/config\"\n\t\"github.com\/matrix-org\/util\"\n)\n\ntype rateLimits struct {\n\tlimits           map[string]chan struct{}\n\tlimitsMutex      sync.RWMutex\n\tenabled          bool\n\trequestThreshold int64\n\tcooloffDuration  time.Duration\n}\n\nfunc newRateLimits(cfg *config.RateLimiting) *rateLimits {\n\tl := &rateLimits{\n\t\tlimits:           make(map[string]chan struct{}),\n\t\tenabled:          cfg.Enabled,\n\t\trequestThreshold: cfg.Threshold,\n\t\tcooloffDuration:  time.Duration(cfg.CooloffMS) * time.Millisecond,\n\t}\n\tif l.enabled {\n\t\tgo l.clean()\n\t}\n\treturn l\n}\n\nfunc (l *rateLimits) clean() {\n\tfor {\n\t\t\/\/ On a 30 second interval, we'll take an exclusive write\n\t\t\/\/ lock of the entire map and see if any of the channels are\n\t\t\/\/ empty. If they are then we will close and delete them,\n\t\t\/\/ freeing up memory.\n\t\ttime.Sleep(time.Second * 30)\n\t\tl.limitsMutex.Lock()\n\t\tfor k, c := range l.limits {\n\t\t\tif len(c) == 0 {\n\t\t\t\tclose(c)\n\t\t\t\tdelete(l.limits, k)\n\t\t\t}\n\t\t}\n\t\tl.limitsMutex.Unlock()\n\t}\n}\n\nfunc (l *rateLimits) rateLimit(req *http.Request) *util.JSONResponse {\n\t\/\/ If rate limiting is disabled then do nothing.\n\tif !l.enabled {\n\t\treturn nil\n\t}\n\n\t\/\/ Lock the map long enough to check for rate limiting. We hold it\n\t\/\/ for longer here than we really need to but it makes sure that we\n\t\/\/ also don't conflict with the cleaner goroutine which might clean\n\t\/\/ up a channel after we have retrieved it otherwise.\n\tl.limitsMutex.RLock()\n\tdefer l.limitsMutex.RUnlock()\n\n\t\/\/ First of all, work out if X-Forwarded-For was sent to us. If not\n\t\/\/ then we'll just use the IP address of the caller.\n\tcaller := req.RemoteAddr\n\tif forwardedFor := req.Header.Get(\"X-Forwarded-For\"); forwardedFor != \"\" {\n\t\tcaller = forwardedFor\n\t}\n\n\t\/\/ Look up the caller's channel, if they have one. If they don't then\n\t\/\/ let's create one.\n\trateLimit, ok := l.limits[caller]\n\tif !ok {\n\t\tl.limits[caller] = make(chan struct{}, l.requestThreshold)\n\t\trateLimit = l.limits[caller]\n\t}\n\n\t\/\/ Check if the user has got free resource slots for this request.\n\t\/\/ If they don't then we'll return an error.\n\tselect {\n\tcase rateLimit <- struct{}{}:\n\tdefault:\n\t\t\/\/ We hit the rate limit. Tell the client to back off.\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusTooManyRequests,\n\t\t\tJSON: jsonerror.LimitExceeded(\"You are sending too many requests too quickly!\", l.cooloffDuration.Milliseconds()),\n\t\t}\n\t}\n\n\t\/\/ After the time interval, drain a resource from the rate limiting\n\t\/\/ channel. This will free up space in the channel for new requests.\n\tgo func() {\n\t\t<-time.After(l.cooloffDuration)\n\t\t<-rateLimit\n\t}()\n\treturn nil\n}\n<commit_msg>Take write lock for rate limit map (#1532)<commit_after>package routing\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/jsonerror\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/config\"\n\t\"github.com\/matrix-org\/util\"\n)\n\ntype rateLimits struct {\n\tlimits           map[string]chan struct{}\n\tlimitsMutex      sync.RWMutex\n\tcleanMutex       sync.RWMutex\n\tenabled          bool\n\trequestThreshold int64\n\tcooloffDuration  time.Duration\n}\n\nfunc newRateLimits(cfg *config.RateLimiting) *rateLimits {\n\tl := &rateLimits{\n\t\tlimits:           make(map[string]chan struct{}),\n\t\tenabled:          cfg.Enabled,\n\t\trequestThreshold: cfg.Threshold,\n\t\tcooloffDuration:  time.Duration(cfg.CooloffMS) * time.Millisecond,\n\t}\n\tif l.enabled {\n\t\tgo l.clean()\n\t}\n\treturn l\n}\n\nfunc (l *rateLimits) clean() {\n\tfor {\n\t\t\/\/ On a 30 second interval, we'll take an exclusive write\n\t\t\/\/ lock of the entire map and see if any of the channels are\n\t\t\/\/ empty. If they are then we will close and delete them,\n\t\t\/\/ freeing up memory.\n\t\ttime.Sleep(time.Second * 30)\n\t\tl.cleanMutex.Lock()\n\t\tl.limitsMutex.Lock()\n\t\tfor k, c := range l.limits {\n\t\t\tif len(c) == 0 {\n\t\t\t\tclose(c)\n\t\t\t\tdelete(l.limits, k)\n\t\t\t}\n\t\t}\n\t\tl.limitsMutex.Unlock()\n\t\tl.cleanMutex.Unlock()\n\t}\n}\n\nfunc (l *rateLimits) rateLimit(req *http.Request) *util.JSONResponse {\n\t\/\/ If rate limiting is disabled then do nothing.\n\tif !l.enabled {\n\t\treturn nil\n\t}\n\n\t\/\/ Take a read lock out on the cleaner mutex. The cleaner expects to\n\t\/\/ be able to take a write lock, which isn't possible while there are\n\t\/\/ readers, so this has the effect of blocking the cleaner goroutine\n\t\/\/ from doing its work until there are no requests in flight.\n\tl.cleanMutex.RLock()\n\tdefer l.cleanMutex.RUnlock()\n\n\t\/\/ First of all, work out if X-Forwarded-For was sent to us. If not\n\t\/\/ then we'll just use the IP address of the caller.\n\tcaller := req.RemoteAddr\n\tif forwardedFor := req.Header.Get(\"X-Forwarded-For\"); forwardedFor != \"\" {\n\t\tcaller = forwardedFor\n\t}\n\n\t\/\/ Look up the caller's channel, if they have one.\n\tl.limitsMutex.RLock()\n\trateLimit, ok := l.limits[caller]\n\tl.limitsMutex.RUnlock()\n\n\t\/\/ If the caller doesn't have a channel, create one and write it\n\t\/\/ back to the map.\n\tif !ok {\n\t\trateLimit = make(chan struct{}, l.requestThreshold)\n\n\t\tl.limitsMutex.Lock()\n\t\tl.limits[caller] = rateLimit\n\t\tl.limitsMutex.Unlock()\n\t}\n\n\t\/\/ Check if the user has got free resource slots for this request.\n\t\/\/ If they don't then we'll return an error.\n\tselect {\n\tcase rateLimit <- struct{}{}:\n\tdefault:\n\t\t\/\/ We hit the rate limit. Tell the client to back off.\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusTooManyRequests,\n\t\t\tJSON: jsonerror.LimitExceeded(\"You are sending too many requests too quickly!\", l.cooloffDuration.Milliseconds()),\n\t\t}\n\t}\n\n\t\/\/ After the time interval, drain a resource from the rate limiting\n\t\/\/ channel. This will free up space in the channel for new requests.\n\tgo func() {\n\t\t<-time.After(l.cooloffDuration)\n\t\t<-rateLimit\n\t}()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package media_library\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"image\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/disintegration\/imaging\"\n\t\"github.com\/jinzhu\/gorm\"\n)\n\nvar ErrNotImplemented = errors.New(\"not implemented\")\n\ntype CropOption struct {\n\tX, Y, Width, Height int\n}\n\ntype fileHeader interface {\n\tOpen() (multipart.File, error)\n}\n\ntype fileWrapper struct {\n\t*os.File\n}\n\nfunc (fileWrapper *fileWrapper) Open() (multipart.File, error) {\n\treturn fileWrapper.File, nil\n}\n\ntype Base struct {\n\tFileName    string\n\tUrl         string\n\tCropOptions map[string]*CropOption `json:\",omitempty\"`\n\tCrop        bool                   `json:\"-\"`\n\tValid       bool                   `json:\"-\"`\n\tFileHeader  fileHeader             `json:\"-\"`\n\tReader      io.Reader              `json:\"-\"`\n}\n\nfunc (b *Base) Scan(data interface{}) (err error) {\n\tswitch values := data.(type) {\n\tcase *os.File:\n\t\tb.FileHeader = &fileWrapper{values}\n\t\tb.FileName = path.Base(values.Name())\n\t\tb.Valid = true\n\tcase []*multipart.FileHeader:\n\t\tif len(values) > 0 {\n\t\t\tfile := values[0]\n\t\t\tb.FileHeader, b.FileName, b.Valid = file, file.Filename, true\n\t\t}\n\tcase []byte:\n\t\tif err = json.Unmarshal(values, b); err == nil {\n\t\t\tb.Valid = true\n\t\t}\n\t\tvar doCrop struct{ Crop bool }\n\t\tif err = json.Unmarshal(values, &doCrop); err == nil && doCrop.Crop {\n\t\t\tb.Crop = true\n\t\t}\n\tcase string:\n\t\tb.Scan([]byte(values))\n\tcase []string:\n\t\tfor _, str := range values {\n\t\t\tb.Scan(str)\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"unsupported driver -> Scan pair for MediaLibrary\")\n\t}\n\treturn\n}\n\nfunc (b Base) Value() (driver.Value, error) {\n\tif b.Valid {\n\t\tresult, err := json.Marshal(b)\n\t\treturn string(result), err\n\t}\n\treturn nil, nil\n}\n\nfunc (b Base) URL(styles ...string) string {\n\tif len(styles) > 0 {\n\t\text := path.Ext(b.Url)\n\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(b.Url, ext), styles[0], ext)\n\t}\n\treturn b.Url\n}\n\nfunc (b Base) String() string {\n\treturn b.URL()\n}\n\nfunc (b Base) GetFileName() string {\n\treturn b.FileName\n}\n\nfunc (b Base) GetFileHeader() fileHeader {\n\treturn b.FileHeader\n}\n\nfunc (b Base) GetURLTemplate(option *Option) (path string) {\n\tif path = option.Get(\"URL\"); path == \"\" {\n\t\tpath = \"\/system\/{{class}}\/{{primary_key}}\/{{column}}\/{{filename_with_hash}}\"\n\t}\n\treturn\n}\n\nfunc getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {\n\thash := func() string { return strings.Replace(time.Now().Format(\"20060102150506.000000000\"), \".\", \"\", -1) }\n\treturn template.FuncMap{\n\t\t\"class\":       scope.TableName,\n\t\t\"primary_key\": func() string { return fmt.Sprintf(\"%v\", scope.PrimaryKeyValue()) },\n\t\t\"column\":      func() string { return field.Name },\n\t\t\"filename\":    func() string { return filename },\n\t\t\"basename\":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },\n\t\t\"hash\":        hash,\n\t\t\"filename_with_hash\": func() string {\n\t\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename))\n\t\t},\n\t\t\"extension\": func() string { return strings.TrimPrefix(path.Ext(filename), \".\") },\n\t}\n}\n\nfunc (b Base) GetURL(option *Option, scope *gorm.Scope, field *gorm.Field, templater URLTemplater) string {\n\tif path := templater.GetURLTemplate(option); path != \"\" {\n\t\ttmpl := template.New(\"\").Funcs(getFuncMap(scope, field, b.GetFileName()))\n\t\tif tmpl, err := tmpl.Parse(path); err == nil {\n\t\t\tvar result = bytes.NewBufferString(\"\")\n\t\t\tif err := tmpl.Execute(result, scope.Value); err == nil {\n\t\t\t\treturn result.String()\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Base) NeedCrop() bool {\n\treturn b.Crop\n}\n\nfunc (b *Base) GetCropOption(name string) *image.Rectangle {\n\tif cropOption := b.CropOptions[name]; cropOption != nil {\n\t\treturn &image.Rectangle{\n\t\t\tMin: image.Point{X: cropOption.X, Y: cropOption.Y},\n\t\t\tMax: image.Point{X: cropOption.X + cropOption.Width, Y: cropOption.Y + cropOption.Height},\n\t\t}\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (b Base) Retrieve(url string) (*os.File, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (b Base) GetSizes() map[string]Size {\n\treturn map[string]Size{}\n}\n\nfunc (b Base) IsImage() bool {\n\t_, err := getImageFormat(b.URL())\n\treturn err == nil\n}\n\nfunc getImageFormat(url string) (*imaging.Format, error) {\n\tformats := map[string]imaging.Format{\n\t\t\".jpg\":  imaging.JPEG,\n\t\t\".jpeg\": imaging.JPEG,\n\t\t\".png\":  imaging.PNG,\n\t\t\".tif\":  imaging.TIFF,\n\t\t\".tiff\": imaging.TIFF,\n\t\t\".bmp\":  imaging.BMP,\n\t\t\".gif\":  imaging.GIF,\n\t}\n\n\text := strings.ToLower(filepath.Ext(url))\n\tif f, ok := formats[ext]; ok {\n\t\treturn &f, nil\n\t} else {\n\t\treturn nil, imaging.ErrUnsupportedFormat\n\t}\n}\n<commit_msg>Bigger size for media library option<commit_after>package media_library\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"image\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/disintegration\/imaging\"\n\t\"github.com\/jinzhu\/gorm\"\n)\n\nvar ErrNotImplemented = errors.New(\"not implemented\")\n\ntype CropOption struct {\n\tX, Y, Width, Height int\n}\n\ntype fileHeader interface {\n\tOpen() (multipart.File, error)\n}\n\ntype fileWrapper struct {\n\t*os.File\n}\n\nfunc (fileWrapper *fileWrapper) Open() (multipart.File, error) {\n\treturn fileWrapper.File, nil\n}\n\ntype Base struct {\n\tFileName    string `sql:\"size:10240\"`\n\tUrl         string\n\tCropOptions map[string]*CropOption `json:\",omitempty\"`\n\tCrop        bool                   `json:\"-\"`\n\tValid       bool                   `json:\"-\"`\n\tFileHeader  fileHeader             `json:\"-\"`\n\tReader      io.Reader              `json:\"-\"`\n}\n\nfunc (b *Base) Scan(data interface{}) (err error) {\n\tswitch values := data.(type) {\n\tcase *os.File:\n\t\tb.FileHeader = &fileWrapper{values}\n\t\tb.FileName = path.Base(values.Name())\n\t\tb.Valid = true\n\tcase []*multipart.FileHeader:\n\t\tif len(values) > 0 {\n\t\t\tfile := values[0]\n\t\t\tb.FileHeader, b.FileName, b.Valid = file, file.Filename, true\n\t\t}\n\tcase []byte:\n\t\tif err = json.Unmarshal(values, b); err == nil {\n\t\t\tb.Valid = true\n\t\t}\n\t\tvar doCrop struct{ Crop bool }\n\t\tif err = json.Unmarshal(values, &doCrop); err == nil && doCrop.Crop {\n\t\t\tb.Crop = true\n\t\t}\n\tcase string:\n\t\tb.Scan([]byte(values))\n\tcase []string:\n\t\tfor _, str := range values {\n\t\t\tb.Scan(str)\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"unsupported driver -> Scan pair for MediaLibrary\")\n\t}\n\treturn\n}\n\nfunc (b Base) Value() (driver.Value, error) {\n\tif b.Valid {\n\t\tresult, err := json.Marshal(b)\n\t\treturn string(result), err\n\t}\n\treturn nil, nil\n}\n\nfunc (b Base) URL(styles ...string) string {\n\tif len(styles) > 0 {\n\t\text := path.Ext(b.Url)\n\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(b.Url, ext), styles[0], ext)\n\t}\n\treturn b.Url\n}\n\nfunc (b Base) String() string {\n\treturn b.URL()\n}\n\nfunc (b Base) GetFileName() string {\n\treturn b.FileName\n}\n\nfunc (b Base) GetFileHeader() fileHeader {\n\treturn b.FileHeader\n}\n\nfunc (b Base) GetURLTemplate(option *Option) (path string) {\n\tif path = option.Get(\"URL\"); path == \"\" {\n\t\tpath = \"\/system\/{{class}}\/{{primary_key}}\/{{column}}\/{{filename_with_hash}}\"\n\t}\n\treturn\n}\n\nfunc getFuncMap(scope *gorm.Scope, field *gorm.Field, filename string) template.FuncMap {\n\thash := func() string { return strings.Replace(time.Now().Format(\"20060102150506.000000000\"), \".\", \"\", -1) }\n\treturn template.FuncMap{\n\t\t\"class\":       scope.TableName,\n\t\t\"primary_key\": func() string { return fmt.Sprintf(\"%v\", scope.PrimaryKeyValue()) },\n\t\t\"column\":      func() string { return field.Name },\n\t\t\"filename\":    func() string { return filename },\n\t\t\"basename\":    func() string { return strings.TrimSuffix(path.Base(filename), path.Ext(filename)) },\n\t\t\"hash\":        hash,\n\t\t\"filename_with_hash\": func() string {\n\t\t\treturn fmt.Sprintf(\"%v.%v%v\", strings.TrimSuffix(filename, path.Ext(filename)), hash(), path.Ext(filename))\n\t\t},\n\t\t\"extension\": func() string { return strings.TrimPrefix(path.Ext(filename), \".\") },\n\t}\n}\n\nfunc (b Base) GetURL(option *Option, scope *gorm.Scope, field *gorm.Field, templater URLTemplater) string {\n\tif path := templater.GetURLTemplate(option); path != \"\" {\n\t\ttmpl := template.New(\"\").Funcs(getFuncMap(scope, field, b.GetFileName()))\n\t\tif tmpl, err := tmpl.Parse(path); err == nil {\n\t\t\tvar result = bytes.NewBufferString(\"\")\n\t\t\tif err := tmpl.Execute(result, scope.Value); err == nil {\n\t\t\t\treturn result.String()\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Base) NeedCrop() bool {\n\treturn b.Crop\n}\n\nfunc (b *Base) GetCropOption(name string) *image.Rectangle {\n\tif cropOption := b.CropOptions[name]; cropOption != nil {\n\t\treturn &image.Rectangle{\n\t\t\tMin: image.Point{X: cropOption.X, Y: cropOption.Y},\n\t\t\tMax: image.Point{X: cropOption.X + cropOption.Width, Y: cropOption.Y + cropOption.Height},\n\t\t}\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (b Base) Retrieve(url string) (*os.File, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (b Base) GetSizes() map[string]Size {\n\treturn map[string]Size{}\n}\n\nfunc (b Base) IsImage() bool {\n\t_, err := getImageFormat(b.URL())\n\treturn err == nil\n}\n\nfunc getImageFormat(url string) (*imaging.Format, error) {\n\tformats := map[string]imaging.Format{\n\t\t\".jpg\":  imaging.JPEG,\n\t\t\".jpeg\": imaging.JPEG,\n\t\t\".png\":  imaging.PNG,\n\t\t\".tif\":  imaging.TIFF,\n\t\t\".tiff\": imaging.TIFF,\n\t\t\".bmp\":  imaging.BMP,\n\t\t\".gif\":  imaging.GIF,\n\t}\n\n\text := strings.ToLower(filepath.Ext(url))\n\tif f, ok := formats[ext]; ok {\n\t\treturn &f, nil\n\t} else {\n\t\treturn nil, imaging.ErrUnsupportedFormat\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package esmlt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/belogik\/goes\"\n)\n\n\/\/ Application Version\nconst AppVersion = \"0.1.0\"\n\n\/\/ SearchConnection is an interface that is satisfied by goes.Connection and\n\/\/ can be satisfied by mock index connections for testing\ntype SearchConnection interface {\n\tSearch(query map[string]interface{}, indexList []string, typeList []string, extraArgs url.Values) (goes.Response, error)\n}\n\n\/\/ ParseIndicesShift parses strings like `2,4,5` into an int slice and adds a `shift`\nfunc ParseIndicesShift(s string, shift int) ([]int, error) {\n\tparts := strings.Split(s, \",\")\n\tvar indices []int\n\tfor _, p := range parts {\n\t\tvalue := strings.TrimSpace(p)\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti, err := strconv.ParseInt(value, 10, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tindices = append(indices, int(i)+shift)\n\t}\n\treturn indices, nil\n}\n\n\/\/ ParseIndices parses strings like `2,4,5` into an int slice\nfunc ParseIndices(s string) ([]int, error) {\n\treturn ParseIndicesShift(s, -1)\n}\n\n\/\/ ConcatenateValuesNull extracts values according to indices slice and concatenates them.\n\/\/ Values that equal a given `nullValue` are ignored.\nfunc ConcatenateValuesNull(values []string, indices []int, nullValue string) (string, error) {\n\tvar buffer bytes.Buffer\n\tfor _, i := range indices {\n\t\tif i > len(values)-1 {\n\t\t\treturn \"\", fmt.Errorf(\"index %d exceeds array\", i)\n\t\t}\n\t\tif values[i] == nullValue {\n\t\t\tbuffer.WriteString(\"\")\n\t\t\tcontinue\n\t\t}\n\t\tbuffer.WriteString(values[i])\n\t\tbuffer.WriteString(\" \")\n\t}\n\treturn strings.TrimSpace(buffer.String()), nil\n}\n\n\/\/ ConcatenateValues extracts values according to indices slice and concatenates them,\n\/\/ uses a default `nullValue` of `<NULL>`\nfunc ConcatenateValues(values []string, indices []int) (string, error) {\n\treturn ConcatenateValuesNull(values, indices, \"<NULL>\")\n}\n\n\/\/ Value returns the value in a nested map according to a key in dot notation\nfunc Value(key string, doc map[string]interface{}) interface{} {\n\tkeys := strings.Split(key, \".\")\n\tfor _, k := range keys {\n\t\tvalue := doc[k]\n\t\tif value == nil {\n\t\t\treturn nil\n\t\t}\n\t\tswitch value.(type) {\n\t\tcase map[string]interface{}:\n\t\t\treturn Value(strings.Join(keys[1:], \".\"), value.(map[string]interface{}))\n\t\tcase []interface{}:\n\t\t\tif len(value.([]interface{})) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfirst := value.([]interface{})[0]\n\t\t\tswitch first.(type) {\n\t\t\tcase map[string]interface{}:\n\t\t\t\treturn Value(strings.Join(keys[1:], \".\"), first.(map[string]interface{}))\n\t\t\tcase string:\n\t\t\t\treturn first\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>updated doc<commit_after>package esmlt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/belogik\/goes\"\n)\n\n\/\/ Application Version\nconst AppVersion = \"0.1.0\"\n\n\/\/ SearchConnection is an interface that is satisfied by goes.Connection and\n\/\/ can be satisfied by mock index connections for testing\ntype SearchConnection interface {\n\tSearch(query map[string]interface{}, indexList []string, typeList []string, extraArgs url.Values) (goes.Response, error)\n}\n\n\/\/ ParseIndicesShift parses strings like `2,4,5` into an int slice and adds a `shift`\nfunc ParseIndicesShift(s string, shift int) ([]int, error) {\n\tparts := strings.Split(s, \",\")\n\tvar indices []int\n\tfor _, p := range parts {\n\t\tvalue := strings.TrimSpace(p)\n\t\tif value == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti, err := strconv.ParseInt(value, 10, 0)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tindices = append(indices, int(i)+shift)\n\t}\n\treturn indices, nil\n}\n\n\/\/ ParseIndices parses strings like `2,4,5` into an int slice\nfunc ParseIndices(s string) ([]int, error) {\n\treturn ParseIndicesShift(s, -1)\n}\n\n\/\/ ConcatenateValuesNull extracts values according to indices slice and concatenates them.\n\/\/ Values that equal a given `nullValue` are ignored.\nfunc ConcatenateValuesNull(values []string, indices []int, nullValue string) (string, error) {\n\tvar buffer bytes.Buffer\n\tfor _, i := range indices {\n\t\tif i > len(values)-1 {\n\t\t\treturn \"\", fmt.Errorf(\"index %d exceeds array\", i)\n\t\t}\n\t\tif values[i] == nullValue {\n\t\t\tbuffer.WriteString(\"\")\n\t\t\tcontinue\n\t\t}\n\t\tbuffer.WriteString(values[i])\n\t\tbuffer.WriteString(\" \")\n\t}\n\treturn strings.TrimSpace(buffer.String()), nil\n}\n\n\/\/ ConcatenateValues extracts values according to indices slice and concatenates them,\n\/\/ uses a default `nullValue` of `<NULL>`\nfunc ConcatenateValues(values []string, indices []int) (string, error) {\n\treturn ConcatenateValuesNull(values, indices, \"<NULL>\")\n}\n\n\/\/ Value returns the value in a (nested) map according to a key in dot notation.\n\/\/ If the value is a slice, only the first element is considered.\nfunc Value(key string, doc map[string]interface{}) interface{} {\n\tkeys := strings.Split(key, \".\")\n\tfor _, k := range keys {\n\t\tvalue := doc[k]\n\t\tif value == nil {\n\t\t\treturn nil\n\t\t}\n\t\tswitch value.(type) {\n\t\tcase map[string]interface{}:\n\t\t\treturn Value(strings.Join(keys[1:], \".\"), value.(map[string]interface{}))\n\t\tcase []interface{}:\n\t\t\tif len(value.([]interface{})) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfirst := value.([]interface{})[0]\n\t\t\tswitch first.(type) {\n\t\t\tcase map[string]interface{}:\n\t\t\t\treturn Value(strings.Join(keys[1:], \".\"), first.(map[string]interface{}))\n\t\t\tcase string:\n\t\t\t\treturn first\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package espsdk\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\tprefixed \"github.com\/x-cray\/logrus-prefixed-formatter\"\n)\n\nvar Log = logrus.New()\n\nfunc init() {\n\tLog.Formatter = &prefixed.TextFormatter{TimestampFormat: time.RFC3339}\n}\n\n\/\/ A Token is a string representation of an OAuth2 token. It grants a user\n\/\/ access to the ESP API for a limited time.\ntype Token string\n\n\/\/ A Serializable object can be serialized to a byte stream such as JSON.\ntype serializable interface {\n\tMarshal() ([]byte, error)\n}\n\nfunc indentedJSON(obj interface{}) ([]byte, error) {\n\treturn json.MarshalIndent(obj, \"\", \"\\t\")\n}\n<commit_msg>docs: obey the linter<commit_after>package espsdk\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\tprefixed \"github.com\/x-cray\/logrus-prefixed-formatter\"\n)\n\n\/\/ Log is an instance of logrus.(*Logger) that allows easy access to\n\/\/ nicely-formatted log output that includes properties of completed HTTP\n\/\/ requests such as the response time and status code.\nvar Log = logrus.New()\n\nfunc init() {\n\tLog.Formatter = &prefixed.TextFormatter{TimestampFormat: time.RFC3339}\n}\n\n\/\/ A Token is a string representation of an OAuth2 token. It grants a user\n\/\/ access to the ESP API for a limited time.\ntype Token string\n\n\/\/ A Serializable object can be serialized to a byte stream such as JSON.\ntype serializable interface {\n\tMarshal() ([]byte, error)\n}\n\nfunc indentedJSON(obj interface{}) ([]byte, error) {\n\treturn json.MarshalIndent(obj, \"\", \"\\t\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package gotest\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jstemmer\/go-junit-report\/v2\/gtr\"\n\t\"github.com\/jstemmer\/go-junit-report\/v2\/parser\/gotest\/internal\/collector\"\n)\n\nconst (\n\tglobalID = 0\n)\n\n\/\/ reportBuilder helps build a test Report from a collection of events.\n\/\/\n\/\/ The reportBuilder keeps track of the active context whenever a test or build\n\/\/ error is created. This is necessary because the test parser do not contain\n\/\/ any state themselves and simply just emit an event for every line that is\n\/\/ read. By tracking the active context, any output that is appended to the\n\/\/ reportBuilder gets attributed to the correct test or build error.\ntype reportBuilder struct {\n\tpackages    []gtr.Package\n\ttests       map[int]gtr.Test\n\tbuildErrors map[int]gtr.Error\n\n\t\/\/ state\n\tnextID    int               \/\/ next free unused id\n\tlastID    int               \/\/ most recently created id\n\toutput    *collector.Output \/\/ output collected for each id\n\tcoverage  float64           \/\/ coverage percentage\n\tparentIDs map[int]struct{}  \/\/ set of test id's that contain subtests\n\n\t\/\/ options\n\tpackageName   string\n\tsubtestMode   SubtestMode\n\ttimestampFunc func() time.Time\n}\n\n\/\/ newReportBuilder creates a new reportBuilder.\nfunc newReportBuilder() *reportBuilder {\n\treturn &reportBuilder{\n\t\ttests:         make(map[int]gtr.Test),\n\t\tbuildErrors:   make(map[int]gtr.Error),\n\t\tnextID:        1,\n\t\toutput:        collector.New(),\n\t\tparentIDs:     make(map[int]struct{}),\n\t\ttimestampFunc: time.Now,\n\t}\n}\n\n\/\/ ProcessEvent gives an event to this reportBuilder to be processed for this\n\/\/ report.\nfunc (b *reportBuilder) ProcessEvent(ev Event) {\n\tswitch ev.Type {\n\tcase \"run_test\":\n\t\tb.CreateTest(ev.Name)\n\tcase \"pause_test\":\n\t\tb.PauseTest(ev.Name)\n\tcase \"cont_test\":\n\t\tb.ContinueTest(ev.Name)\n\tcase \"end_test\":\n\t\tb.EndTest(ev.Name, ev.Result, ev.Duration, ev.Indent)\n\tcase \"run_benchmark\":\n\t\tb.CreateTest(ev.Name)\n\tcase \"benchmark\":\n\t\tb.BenchmarkResult(ev.Name, ev.Iterations, ev.NsPerOp, ev.MBPerSec, ev.BytesPerOp, ev.AllocsPerOp)\n\tcase \"end_benchmark\":\n\t\tb.EndTest(ev.Name, ev.Result, 0, 0)\n\tcase \"status\":\n\t\tb.End()\n\tcase \"summary\":\n\t\tb.CreatePackage(ev.Name, ev.Result, ev.Duration, ev.Data)\n\tcase \"coverage\":\n\t\tb.Coverage(ev.CovPct, ev.CovPackages)\n\tcase \"build_output\":\n\t\tb.CreateBuildError(ev.Name)\n\tcase \"output\":\n\t\tb.AppendOutput(ev.Data)\n\tdefault:\n\t\tfmt.Printf(\"reportBuilder: unhandled event type: %v\\n\", ev.Type)\n\t}\n}\n\n\/\/ newID returns a new unique id and sets the active context this id.\nfunc (b *reportBuilder) newID() int {\n\tid := b.nextID\n\tb.lastID = id\n\tb.nextID++\n\treturn id\n}\n\n\/\/ flush creates a new package in this report containing any tests we've\n\/\/ collected so far. This is necessary when a test did not end with a summary.\nfunc (b *reportBuilder) flush() {\n\tif len(b.tests) > 0 {\n\t\tb.CreatePackage(b.packageName, \"\", 0, \"\")\n\t}\n}\n\n\/\/ Build returns the new Report containing all the tests and output created so\n\/\/ far.\nfunc (b *reportBuilder) Build() gtr.Report {\n\tb.flush()\n\treturn gtr.Report{Packages: b.packages}\n}\n\n\/\/ CreateTest adds a test with the given name to the report, and marks it as\n\/\/ active.\nfunc (b *reportBuilder) CreateTest(name string) {\n\tif parentID, ok := b.findTestParentID(name); ok {\n\t\tb.parentIDs[parentID] = struct{}{}\n\t}\n\tid := b.newID()\n\tb.tests[id] = gtr.NewTest(id, name)\n}\n\n\/\/ PauseTest marks the active context as no longer active. Any results or\n\/\/ output added to the report after calling PauseTest will no longer be assumed\n\/\/ to belong to this test.\nfunc (b *reportBuilder) PauseTest(name string) {\n\tb.lastID = 0\n}\n\n\/\/ ContinueTest finds the test with the given name and marks it as active. If\n\/\/ more than one test exist with this name, the most recently created test will\n\/\/ be used.\nfunc (b *reportBuilder) ContinueTest(name string) {\n\tb.lastID, _ = b.findTest(name)\n}\n\n\/\/ EndTest finds the test with the given name, sets the result, duration and\n\/\/ level. If more than one test exists with this name, the most recently\n\/\/ created test will be used. If no test exists with this name, a new test is\n\/\/ created.\nfunc (b *reportBuilder) EndTest(name, result string, duration time.Duration, level int) {\n\tid, ok := b.findTest(name)\n\tif !ok {\n\t\t\/\/ test did not exist, create one\n\t\t\/\/ TODO: Likely reason is that the user ran go test without the -v\n\t\t\/\/ flag, should we report this somewhere?\n\t\tb.CreateTest(name)\n\t\tid = b.lastID\n\t}\n\n\tt := b.tests[id]\n\tt.Result = parseResult(result)\n\tt.Duration = duration\n\tt.Level = level\n\tb.tests[id] = t\n\tb.lastID = 0\n}\n\n\/\/ End marks the active context as no longer active.\nfunc (b *reportBuilder) End() {\n\tb.lastID = 0\n}\n\n\/\/ BenchmarkResult updates an existing or adds a new test with the given\n\/\/ results and marks it as active. If an existing test with this name exists\n\/\/ but without result, then that one is updated. Otherwise a new one is added\n\/\/ to the report.\nfunc (b *reportBuilder) BenchmarkResult(name string, iterations int64, nsPerOp, mbPerSec float64, bytesPerOp, allocsPerOp int64) {\n\tid, ok := b.findTest(name)\n\tif !ok || b.tests[id].Result != gtr.Unknown {\n\t\tb.CreateTest(name)\n\t\tid = b.lastID\n\t}\n\n\tbenchmark := Benchmark{iterations, nsPerOp, mbPerSec, bytesPerOp, allocsPerOp}\n\ttest := gtr.NewTest(id, name)\n\ttest.Result = gtr.Pass\n\ttest.Duration = benchmark.ApproximateDuration()\n\tSetBenchmarkData(&test, benchmark)\n\tb.tests[id] = test\n}\n\n\/\/ CreateBuildError creates a new build error and marks it as active.\nfunc (b *reportBuilder) CreateBuildError(packageName string) {\n\tid := b.newID()\n\tb.buildErrors[id] = gtr.Error{ID: id, Name: packageName}\n}\n\n\/\/ CreatePackage adds a new package with the given name to the Report. This\n\/\/ package contains all the build errors, output, tests and benchmarks created\n\/\/ so far. Afterwards all state is reset.\nfunc (b *reportBuilder) CreatePackage(name, result string, duration time.Duration, data string) {\n\tpkg := gtr.Package{\n\t\tName:     name,\n\t\tDuration: duration,\n\t}\n\n\tif b.timestampFunc != nil {\n\t\tpkg.Timestamp = b.timestampFunc()\n\t}\n\n\t\/\/ Build errors are treated somewhat differently. Rather than having a\n\t\/\/ single package with all build errors collected so far, we only care\n\t\/\/ about the build errors for this particular package.\n\tfor id, buildErr := range b.buildErrors {\n\t\tif buildErr.Name == name {\n\t\t\tif len(b.tests) > 0 {\n\t\t\t\tpanic(\"unexpected tests found in build error package\")\n\t\t\t}\n\t\t\tbuildErr.ID = id\n\t\t\tbuildErr.Duration = duration\n\t\t\tbuildErr.Cause = data\n\t\t\tbuildErr.Output = b.output.Get(id)\n\n\t\t\tpkg.BuildError = buildErr\n\t\t\tb.packages = append(b.packages, pkg)\n\n\t\t\tdelete(b.buildErrors, id)\n\t\t\t\/\/ TODO: reset state\n\t\t\t\/\/ TODO: buildErrors shouldn't reset\/use nextID\/lastID, they're more like a global cache\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ If we've collected output, but there were no tests then either there\n\t\/\/ actually were no tests, or there was some other non-build error.\n\tif b.output.Contains(globalID) && len(b.tests) == 0 {\n\t\tif parseResult(result) == gtr.Fail {\n\t\t\tpkg.RunError = gtr.Error{\n\t\t\t\tName:   name,\n\t\t\t\tOutput: b.output.Get(globalID),\n\t\t\t}\n\t\t} else if b.output.Contains(globalID) {\n\t\t\tpkg.Output = b.output.Get(globalID)\n\t\t}\n\t\tb.packages = append(b.packages, pkg)\n\t\tb.output.Clear(globalID)\n\t\treturn\n\t}\n\n\t\/\/ If the summary result says we failed, but there were no failing tests\n\t\/\/ then something else must have failed.\n\tif parseResult(result) == gtr.Fail && len(b.tests) > 0 && !b.containsFailures() {\n\t\tpkg.RunError = gtr.Error{\n\t\t\tName:   name,\n\t\t\tOutput: b.output.Get(globalID),\n\t\t}\n\t\tb.output.Clear(globalID)\n\t}\n\n\t\/\/ Collect tests for this package, maintaining insertion order.\n\tvar tests []gtr.Test\n\tfor id := 1; id < b.nextID; id++ {\n\t\tif t, ok := b.tests[id]; ok {\n\t\t\tif b.isParent(id) {\n\t\t\t\tif b.subtestMode == IgnoreParentResults {\n\t\t\t\t\tt.Result = gtr.Pass\n\t\t\t\t} else if b.subtestMode == ExcludeParents {\n\t\t\t\t\tb.output.Merge(id, globalID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Output = b.output.Get(id)\n\t\t\ttests = append(tests, t)\n\t\t\tcontinue\n\t\t}\n\t}\n\ttests = b.groupBenchmarksByName(tests)\n\n\tpkg.Coverage = b.coverage\n\tpkg.Output = b.output.Get(globalID)\n\tpkg.Tests = tests\n\tb.packages = append(b.packages, pkg)\n\n\t\/\/ reset state, except for nextID to ensure all id's are unique.\n\tb.lastID = 0\n\tb.output.Clear(globalID)\n\tb.coverage = 0\n\tb.tests = make(map[int]gtr.Test)\n\tb.parentIDs = make(map[int]struct{})\n}\n\n\/\/ Coverage sets the code coverage percentage.\nfunc (b *reportBuilder) Coverage(pct float64, packages []string) {\n\tb.coverage = pct\n}\n\n\/\/ AppendOutput appends the given text to the currently active context. If no\n\/\/ active context exists, the output is assumed to belong to the package.\nfunc (b *reportBuilder) AppendOutput(text string) {\n\tb.output.Append(b.lastID, text)\n}\n\n\/\/ findTest returns the id of the most recently created test with the given\n\/\/ name if it exists.\nfunc (b *reportBuilder) findTest(name string) (int, bool) {\n\t\/\/ check if this test was lastID\n\tif t, ok := b.tests[b.lastID]; ok && t.Name == name {\n\t\treturn b.lastID, true\n\t}\n\tfor i := b.nextID; i > 0; i-- {\n\t\tif test, ok := b.tests[i]; ok && test.Name == name {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc (b *reportBuilder) findTestParentID(name string) (int, bool) {\n\tparent := dropLastSegment(name)\n\tfor parent != \"\" {\n\t\tif id, ok := b.findTest(parent); ok {\n\t\t\treturn id, true\n\t\t}\n\t\tparent = dropLastSegment(parent)\n\t}\n\treturn 0, false\n}\n\nfunc (b *reportBuilder) isParent(id int) bool {\n\t_, ok := b.parentIDs[id]\n\treturn ok\n}\n\nfunc dropLastSegment(name string) string {\n\tif idx := strings.LastIndexByte(name, '\/'); idx >= 0 {\n\t\treturn name[:idx]\n\t}\n\treturn \"\"\n}\n\n\/\/ containsFailures return true if the current list of tests contains at least\n\/\/ one failing test or an unknown result.\nfunc (b *reportBuilder) containsFailures() bool {\n\tfor _, test := range b.tests {\n\t\tif test.Result == gtr.Fail || test.Result == gtr.Unknown {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ parseResult returns a Result for the given string r.\nfunc parseResult(r string) gtr.Result {\n\tswitch r {\n\tcase \"PASS\":\n\t\treturn gtr.Pass\n\tcase \"FAIL\":\n\t\treturn gtr.Fail\n\tcase \"SKIP\":\n\t\treturn gtr.Skip\n\tcase \"BENCH\":\n\t\treturn gtr.Pass\n\tdefault:\n\t\treturn gtr.Unknown\n\t}\n}\n\nfunc (b *reportBuilder) groupBenchmarksByName(tests []gtr.Test) []gtr.Test {\n\tif len(tests) == 0 {\n\t\treturn nil\n\t}\n\n\tvar grouped []gtr.Test\n\tbyName := make(map[string][]gtr.Test)\n\tfor _, test := range tests {\n\t\tif !strings.HasPrefix(test.Name, \"Benchmark\") {\n\t\t\t\/\/ If this test is not a benchmark, we won't group it by name but\n\t\t\t\/\/ just add it to the final result.\n\t\t\tgrouped = append(grouped, test)\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := byName[test.Name]; !ok {\n\t\t\tgrouped = append(grouped, gtr.NewTest(test.ID, test.Name))\n\t\t}\n\t\tbyName[test.Name] = append(byName[test.Name], test)\n\t}\n\n\tfor i, group := range grouped {\n\t\tif !strings.HasPrefix(group.Name, \"Benchmark\") {\n\t\t\tcontinue\n\t\t}\n\t\tvar (\n\t\t\tids   []int\n\t\t\ttotal Benchmark\n\t\t\tcount int\n\t\t)\n\t\tfor _, test := range byName[group.Name] {\n\t\t\tids = append(ids, test.ID)\n\t\t\tif test.Result != gtr.Pass {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif bench, ok := GetBenchmarkData(test); ok {\n\t\t\t\ttotal.Iterations += bench.Iterations\n\t\t\t\ttotal.NsPerOp += bench.NsPerOp\n\t\t\t\ttotal.MBPerSec += bench.MBPerSec\n\t\t\t\ttotal.BytesPerOp += bench.BytesPerOp\n\t\t\t\ttotal.AllocsPerOp += bench.AllocsPerOp\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\n\t\tgroup.Duration = combinedDuration(byName[group.Name])\n\t\tgroup.Result = groupResults(byName[group.Name])\n\t\tgroup.Output = b.output.GetAll(ids...)\n\t\tif count > 0 {\n\t\t\ttotal.Iterations \/= int64(count)\n\t\t\ttotal.NsPerOp \/= float64(count)\n\t\t\ttotal.MBPerSec \/= float64(count)\n\t\t\ttotal.BytesPerOp \/= int64(count)\n\t\t\ttotal.AllocsPerOp \/= int64(count)\n\t\t\tSetBenchmarkData(&group, total)\n\t\t}\n\t\tgrouped[i] = group\n\t}\n\treturn grouped\n}\n\nfunc combinedDuration(tests []gtr.Test) time.Duration {\n\tvar total time.Duration\n\tfor _, test := range tests {\n\t\ttotal += test.Duration\n\t}\n\treturn total\n}\n\nfunc groupResults(tests []gtr.Test) gtr.Result {\n\tvar result gtr.Result\n\tfor _, test := range tests {\n\t\tif test.Result == gtr.Fail {\n\t\t\treturn gtr.Fail\n\t\t}\n\t\tif result != gtr.Pass {\n\t\t\tresult = test.Result\n\t\t}\n\t}\n\treturn result\n}\n<commit_msg>parser\/gotest: Return created id from CreateTest method<commit_after>package gotest\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jstemmer\/go-junit-report\/v2\/gtr\"\n\t\"github.com\/jstemmer\/go-junit-report\/v2\/parser\/gotest\/internal\/collector\"\n)\n\nconst (\n\tglobalID = 0\n)\n\n\/\/ reportBuilder helps build a test Report from a collection of events.\n\/\/\n\/\/ The reportBuilder keeps track of the active context whenever a test or build\n\/\/ error is created. This is necessary because the test parser do not contain\n\/\/ any state themselves and simply just emit an event for every line that is\n\/\/ read. By tracking the active context, any output that is appended to the\n\/\/ reportBuilder gets attributed to the correct test or build error.\ntype reportBuilder struct {\n\tpackages    []gtr.Package\n\ttests       map[int]gtr.Test\n\tbuildErrors map[int]gtr.Error\n\n\t\/\/ state\n\tnextID    int               \/\/ next free unused id\n\tlastID    int               \/\/ most recently created id\n\toutput    *collector.Output \/\/ output collected for each id\n\tcoverage  float64           \/\/ coverage percentage\n\tparentIDs map[int]struct{}  \/\/ set of test id's that contain subtests\n\n\t\/\/ options\n\tpackageName   string\n\tsubtestMode   SubtestMode\n\ttimestampFunc func() time.Time\n}\n\n\/\/ newReportBuilder creates a new reportBuilder.\nfunc newReportBuilder() *reportBuilder {\n\treturn &reportBuilder{\n\t\ttests:         make(map[int]gtr.Test),\n\t\tbuildErrors:   make(map[int]gtr.Error),\n\t\tnextID:        1,\n\t\toutput:        collector.New(),\n\t\tparentIDs:     make(map[int]struct{}),\n\t\ttimestampFunc: time.Now,\n\t}\n}\n\n\/\/ ProcessEvent gives an event to this reportBuilder to be processed for this\n\/\/ report.\nfunc (b *reportBuilder) ProcessEvent(ev Event) {\n\tswitch ev.Type {\n\tcase \"run_test\":\n\t\tb.CreateTest(ev.Name)\n\tcase \"pause_test\":\n\t\tb.PauseTest(ev.Name)\n\tcase \"cont_test\":\n\t\tb.ContinueTest(ev.Name)\n\tcase \"end_test\":\n\t\tb.EndTest(ev.Name, ev.Result, ev.Duration, ev.Indent)\n\tcase \"run_benchmark\":\n\t\tb.CreateTest(ev.Name)\n\tcase \"benchmark\":\n\t\tb.BenchmarkResult(ev.Name, ev.Iterations, ev.NsPerOp, ev.MBPerSec, ev.BytesPerOp, ev.AllocsPerOp)\n\tcase \"end_benchmark\":\n\t\tb.EndTest(ev.Name, ev.Result, 0, 0)\n\tcase \"status\":\n\t\tb.End()\n\tcase \"summary\":\n\t\tb.CreatePackage(ev.Name, ev.Result, ev.Duration, ev.Data)\n\tcase \"coverage\":\n\t\tb.Coverage(ev.CovPct, ev.CovPackages)\n\tcase \"build_output\":\n\t\tb.CreateBuildError(ev.Name)\n\tcase \"output\":\n\t\tb.AppendOutput(ev.Data)\n\tdefault:\n\t\tfmt.Printf(\"reportBuilder: unhandled event type: %v\\n\", ev.Type)\n\t}\n}\n\n\/\/ newID returns a new unique id and sets the active context this id.\nfunc (b *reportBuilder) newID() int {\n\tid := b.nextID\n\tb.lastID = id\n\tb.nextID++\n\treturn id\n}\n\n\/\/ flush creates a new package in this report containing any tests we've\n\/\/ collected so far. This is necessary when a test did not end with a summary.\nfunc (b *reportBuilder) flush() {\n\tif len(b.tests) > 0 {\n\t\tb.CreatePackage(b.packageName, \"\", 0, \"\")\n\t}\n}\n\n\/\/ Build returns the new Report containing all the tests and output created so\n\/\/ far.\nfunc (b *reportBuilder) Build() gtr.Report {\n\tb.flush()\n\treturn gtr.Report{Packages: b.packages}\n}\n\n\/\/ CreateTest adds a test with the given name to the report, and marks it as\n\/\/ active.\nfunc (b *reportBuilder) CreateTest(name string) int {\n\tif parentID, ok := b.findTestParentID(name); ok {\n\t\tb.parentIDs[parentID] = struct{}{}\n\t}\n\tid := b.newID()\n\tb.tests[id] = gtr.NewTest(id, name)\n\treturn id\n}\n\n\/\/ PauseTest marks the active context as no longer active. Any results or\n\/\/ output added to the report after calling PauseTest will no longer be assumed\n\/\/ to belong to this test.\nfunc (b *reportBuilder) PauseTest(name string) {\n\tb.lastID = 0\n}\n\n\/\/ ContinueTest finds the test with the given name and marks it as active. If\n\/\/ more than one test exist with this name, the most recently created test will\n\/\/ be used.\nfunc (b *reportBuilder) ContinueTest(name string) {\n\tb.lastID, _ = b.findTest(name)\n}\n\n\/\/ EndTest finds the test with the given name, sets the result, duration and\n\/\/ level. If more than one test exists with this name, the most recently\n\/\/ created test will be used. If no test exists with this name, a new test is\n\/\/ created.\nfunc (b *reportBuilder) EndTest(name, result string, duration time.Duration, level int) {\n\tid, ok := b.findTest(name)\n\tif !ok {\n\t\t\/\/ test did not exist, create one\n\t\t\/\/ TODO: Likely reason is that the user ran go test without the -v\n\t\t\/\/ flag, should we report this somewhere?\n\t\tid = b.CreateTest(name)\n\t}\n\n\tt := b.tests[id]\n\tt.Result = parseResult(result)\n\tt.Duration = duration\n\tt.Level = level\n\tb.tests[id] = t\n\tb.lastID = 0\n}\n\n\/\/ End marks the active context as no longer active.\nfunc (b *reportBuilder) End() {\n\tb.lastID = 0\n}\n\n\/\/ BenchmarkResult updates an existing or adds a new test with the given\n\/\/ results and marks it as active. If an existing test with this name exists\n\/\/ but without result, then that one is updated. Otherwise a new one is added\n\/\/ to the report.\nfunc (b *reportBuilder) BenchmarkResult(name string, iterations int64, nsPerOp, mbPerSec float64, bytesPerOp, allocsPerOp int64) {\n\tid, ok := b.findTest(name)\n\tif !ok || b.tests[id].Result != gtr.Unknown {\n\t\tid = b.CreateTest(name)\n\t}\n\n\tbenchmark := Benchmark{iterations, nsPerOp, mbPerSec, bytesPerOp, allocsPerOp}\n\ttest := gtr.NewTest(id, name)\n\ttest.Result = gtr.Pass\n\ttest.Duration = benchmark.ApproximateDuration()\n\tSetBenchmarkData(&test, benchmark)\n\tb.tests[id] = test\n}\n\n\/\/ CreateBuildError creates a new build error and marks it as active.\nfunc (b *reportBuilder) CreateBuildError(packageName string) {\n\tid := b.newID()\n\tb.buildErrors[id] = gtr.Error{ID: id, Name: packageName}\n}\n\n\/\/ CreatePackage adds a new package with the given name to the Report. This\n\/\/ package contains all the build errors, output, tests and benchmarks created\n\/\/ so far. Afterwards all state is reset.\nfunc (b *reportBuilder) CreatePackage(name, result string, duration time.Duration, data string) {\n\tpkg := gtr.Package{\n\t\tName:     name,\n\t\tDuration: duration,\n\t}\n\n\tif b.timestampFunc != nil {\n\t\tpkg.Timestamp = b.timestampFunc()\n\t}\n\n\t\/\/ Build errors are treated somewhat differently. Rather than having a\n\t\/\/ single package with all build errors collected so far, we only care\n\t\/\/ about the build errors for this particular package.\n\tfor id, buildErr := range b.buildErrors {\n\t\tif buildErr.Name == name {\n\t\t\tif len(b.tests) > 0 {\n\t\t\t\tpanic(\"unexpected tests found in build error package\")\n\t\t\t}\n\t\t\tbuildErr.ID = id\n\t\t\tbuildErr.Duration = duration\n\t\t\tbuildErr.Cause = data\n\t\t\tbuildErr.Output = b.output.Get(id)\n\n\t\t\tpkg.BuildError = buildErr\n\t\t\tb.packages = append(b.packages, pkg)\n\n\t\t\tdelete(b.buildErrors, id)\n\t\t\t\/\/ TODO: reset state\n\t\t\t\/\/ TODO: buildErrors shouldn't reset\/use nextID\/lastID, they're more like a global cache\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ If we've collected output, but there were no tests then either there\n\t\/\/ actually were no tests, or there was some other non-build error.\n\tif b.output.Contains(globalID) && len(b.tests) == 0 {\n\t\tif parseResult(result) == gtr.Fail {\n\t\t\tpkg.RunError = gtr.Error{\n\t\t\t\tName:   name,\n\t\t\t\tOutput: b.output.Get(globalID),\n\t\t\t}\n\t\t} else if b.output.Contains(globalID) {\n\t\t\tpkg.Output = b.output.Get(globalID)\n\t\t}\n\t\tb.packages = append(b.packages, pkg)\n\t\tb.output.Clear(globalID)\n\t\treturn\n\t}\n\n\t\/\/ If the summary result says we failed, but there were no failing tests\n\t\/\/ then something else must have failed.\n\tif parseResult(result) == gtr.Fail && len(b.tests) > 0 && !b.containsFailures() {\n\t\tpkg.RunError = gtr.Error{\n\t\t\tName:   name,\n\t\t\tOutput: b.output.Get(globalID),\n\t\t}\n\t\tb.output.Clear(globalID)\n\t}\n\n\t\/\/ Collect tests for this package, maintaining insertion order.\n\tvar tests []gtr.Test\n\tfor id := 1; id < b.nextID; id++ {\n\t\tif t, ok := b.tests[id]; ok {\n\t\t\tif b.isParent(id) {\n\t\t\t\tif b.subtestMode == IgnoreParentResults {\n\t\t\t\t\tt.Result = gtr.Pass\n\t\t\t\t} else if b.subtestMode == ExcludeParents {\n\t\t\t\t\tb.output.Merge(id, globalID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.Output = b.output.Get(id)\n\t\t\ttests = append(tests, t)\n\t\t\tcontinue\n\t\t}\n\t}\n\ttests = b.groupBenchmarksByName(tests)\n\n\tpkg.Coverage = b.coverage\n\tpkg.Output = b.output.Get(globalID)\n\tpkg.Tests = tests\n\tb.packages = append(b.packages, pkg)\n\n\t\/\/ reset state, except for nextID to ensure all id's are unique.\n\tb.lastID = 0\n\tb.output.Clear(globalID)\n\tb.coverage = 0\n\tb.tests = make(map[int]gtr.Test)\n\tb.parentIDs = make(map[int]struct{})\n}\n\n\/\/ Coverage sets the code coverage percentage.\nfunc (b *reportBuilder) Coverage(pct float64, packages []string) {\n\tb.coverage = pct\n}\n\n\/\/ AppendOutput appends the given text to the currently active context. If no\n\/\/ active context exists, the output is assumed to belong to the package.\nfunc (b *reportBuilder) AppendOutput(text string) {\n\tb.output.Append(b.lastID, text)\n}\n\n\/\/ findTest returns the id of the most recently created test with the given\n\/\/ name if it exists.\nfunc (b *reportBuilder) findTest(name string) (int, bool) {\n\t\/\/ check if this test was lastID\n\tif t, ok := b.tests[b.lastID]; ok && t.Name == name {\n\t\treturn b.lastID, true\n\t}\n\tfor i := b.nextID; i > 0; i-- {\n\t\tif test, ok := b.tests[i]; ok && test.Name == name {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc (b *reportBuilder) findTestParentID(name string) (int, bool) {\n\tparent := dropLastSegment(name)\n\tfor parent != \"\" {\n\t\tif id, ok := b.findTest(parent); ok {\n\t\t\treturn id, true\n\t\t}\n\t\tparent = dropLastSegment(parent)\n\t}\n\treturn 0, false\n}\n\nfunc (b *reportBuilder) isParent(id int) bool {\n\t_, ok := b.parentIDs[id]\n\treturn ok\n}\n\nfunc dropLastSegment(name string) string {\n\tif idx := strings.LastIndexByte(name, '\/'); idx >= 0 {\n\t\treturn name[:idx]\n\t}\n\treturn \"\"\n}\n\n\/\/ containsFailures return true if the current list of tests contains at least\n\/\/ one failing test or an unknown result.\nfunc (b *reportBuilder) containsFailures() bool {\n\tfor _, test := range b.tests {\n\t\tif test.Result == gtr.Fail || test.Result == gtr.Unknown {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ parseResult returns a Result for the given string r.\nfunc parseResult(r string) gtr.Result {\n\tswitch r {\n\tcase \"PASS\":\n\t\treturn gtr.Pass\n\tcase \"FAIL\":\n\t\treturn gtr.Fail\n\tcase \"SKIP\":\n\t\treturn gtr.Skip\n\tcase \"BENCH\":\n\t\treturn gtr.Pass\n\tdefault:\n\t\treturn gtr.Unknown\n\t}\n}\n\nfunc (b *reportBuilder) groupBenchmarksByName(tests []gtr.Test) []gtr.Test {\n\tif len(tests) == 0 {\n\t\treturn nil\n\t}\n\n\tvar grouped []gtr.Test\n\tbyName := make(map[string][]gtr.Test)\n\tfor _, test := range tests {\n\t\tif !strings.HasPrefix(test.Name, \"Benchmark\") {\n\t\t\t\/\/ If this test is not a benchmark, we won't group it by name but\n\t\t\t\/\/ just add it to the final result.\n\t\t\tgrouped = append(grouped, test)\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := byName[test.Name]; !ok {\n\t\t\tgrouped = append(grouped, gtr.NewTest(test.ID, test.Name))\n\t\t}\n\t\tbyName[test.Name] = append(byName[test.Name], test)\n\t}\n\n\tfor i, group := range grouped {\n\t\tif !strings.HasPrefix(group.Name, \"Benchmark\") {\n\t\t\tcontinue\n\t\t}\n\t\tvar (\n\t\t\tids   []int\n\t\t\ttotal Benchmark\n\t\t\tcount int\n\t\t)\n\t\tfor _, test := range byName[group.Name] {\n\t\t\tids = append(ids, test.ID)\n\t\t\tif test.Result != gtr.Pass {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif bench, ok := GetBenchmarkData(test); ok {\n\t\t\t\ttotal.Iterations += bench.Iterations\n\t\t\t\ttotal.NsPerOp += bench.NsPerOp\n\t\t\t\ttotal.MBPerSec += bench.MBPerSec\n\t\t\t\ttotal.BytesPerOp += bench.BytesPerOp\n\t\t\t\ttotal.AllocsPerOp += bench.AllocsPerOp\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\n\t\tgroup.Duration = combinedDuration(byName[group.Name])\n\t\tgroup.Result = groupResults(byName[group.Name])\n\t\tgroup.Output = b.output.GetAll(ids...)\n\t\tif count > 0 {\n\t\t\ttotal.Iterations \/= int64(count)\n\t\t\ttotal.NsPerOp \/= float64(count)\n\t\t\ttotal.MBPerSec \/= float64(count)\n\t\t\ttotal.BytesPerOp \/= int64(count)\n\t\t\ttotal.AllocsPerOp \/= int64(count)\n\t\t\tSetBenchmarkData(&group, total)\n\t\t}\n\t\tgrouped[i] = group\n\t}\n\treturn grouped\n}\n\nfunc combinedDuration(tests []gtr.Test) time.Duration {\n\tvar total time.Duration\n\tfor _, test := range tests {\n\t\ttotal += test.Duration\n\t}\n\treturn total\n}\n\nfunc groupResults(tests []gtr.Test) gtr.Result {\n\tvar result gtr.Result\n\tfor _, test := range tests {\n\t\tif test.Result == gtr.Fail {\n\t\t\treturn gtr.Fail\n\t\t}\n\t\tif result != gtr.Pass {\n\t\t\tresult = test.Result\n\t\t}\n\t}\n\treturn result\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\/service\/ec2\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/terraform\"\n)\n\nfunc TestAccAWSRouteDataSource_basic(t *testing.T) {\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:  func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDataSourceAwsRouteGroupConfig(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_destination_cidr_block\"),\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_instance_id\"),\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_peering_connection_id\"),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSRouteDataSource_TransitGatewayID(t *testing.T) {\n\tvar route ec2.Route\n\tdataSourceName := \"data.aws_route.test\"\n\tresourceName := \"aws_route.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSRouteDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSRouteDataSourceConfigTransitGatewayID(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSRouteExists(resourceName, &route),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"destination_cidr_block\", dataSourceName, \"destination_cidr_block\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"route_table_id\", dataSourceName, \"route_table_id\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"transit_gateway_id\", dataSourceName, \"transit_gateway_id\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSRouteDataSource_LocalGatewayID(t *testing.T) {\n\tvar route ec2.Route\n\tdataSourceName := \"data.aws_route.by_local_gateway_id\"\n\tresourceName := \"aws_route.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSRouteDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSRouteDataSourceConfigLocalGatewayID(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSRouteExists(resourceName, &route),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"destination_cidr_block\", dataSourceName, \"destination_cidr_block\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"route_table_id\", dataSourceName, \"route_table_id\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"local_gateway_id\", dataSourceName, \"local_gateway_id\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccDataSourceAwsRouteCheck(name string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[name]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"root module has no resource called %s\", name)\n\t\t}\n\n\t\tr, ok := s.RootModule().Resources[\"aws_route.test\"]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"can't find aws_route.test in state\")\n\t\t}\n\t\trts, ok := s.RootModule().Resources[\"aws_route_table.test\"]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"can't find aws_route_table.test in state\")\n\t\t}\n\n\t\tattr := rs.Primary.Attributes\n\n\t\tif attr[\"route_table_id\"] != r.Primary.Attributes[\"route_table_id\"] {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"route_table_id is %s; want %s\",\n\t\t\t\tattr[\"route_table_id\"],\n\t\t\t\tr.Primary.Attributes[\"route_table_id\"],\n\t\t\t)\n\t\t}\n\n\t\tif attr[\"route_table_id\"] != rts.Primary.Attributes[\"id\"] {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"route_table_id is %s; want %s\",\n\t\t\t\tattr[\"route_table_id\"],\n\t\t\t\trts.Primary.Attributes[\"id\"],\n\t\t\t)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccDataSourceAwsRouteGroupConfig() string {\n\treturn testAccLatestAmazonLinuxHvmEbsAmiConfig() + `\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"172.16.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-route-table-data-source\"\n  }\n}\n\nresource \"aws_vpc\" \"dest\" {\n  cidr_block = \"172.17.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-route-table-data-source\"\n  }\n}\n\nresource \"aws_vpc_peering_connection\" \"test\" {\n  peer_vpc_id = aws_vpc.dest.id\n  vpc_id      = aws_vpc.test.id\n  auto_accept = true\n}\n\nresource \"aws_subnet\" \"test\" {\n  cidr_block = \"172.16.0.0\/24\"\n  vpc_id     = aws_vpc.test.id\n\n  tags = {\n    Name = \"tf-acc-route-table-data-source\"\n  }\n}\n\nresource \"aws_route_table\" \"test\" {\n  vpc_id = aws_vpc.test.id\n\n  tags = {\n    Name = \"terraform-testacc-routetable-data-source\"\n  }\n}\n\nresource \"aws_route\" \"pcx\" {\n  route_table_id            = aws_route_table.test.id\n  vpc_peering_connection_id = aws_vpc_peering_connection.test.id\n  destination_cidr_block    = \"10.0.2.0\/24\"\n}\n\nresource \"aws_route_table_association\" \"a\" {\n  subnet_id      = aws_subnet.test.id\n  route_table_id = aws_route_table.test.id\n}\n\nresource \"aws_instance\" \"web\" {\n  ami           = data.aws_ami.amzn-ami-minimal-hvm-ebs.id\n  instance_type = \"t2.micro\"\n  subnet_id     = aws_subnet.test.id\n\n  tags = {\n    Name = \"HelloWorld\"\n  }\n}\n\nresource \"aws_route\" \"test\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"10.0.1.0\/24\"\n  instance_id            = aws_instance.web.id\n\n  timeouts {\n    create = \"5m\"\n  }\n}\n\ndata \"aws_route\" \"by_peering_connection_id\" {\n  route_table_id            = aws_route_table.test.id\n  vpc_peering_connection_id = aws_route.pcx.vpc_peering_connection_id\n}\n\ndata \"aws_route\" \"by_destination_cidr_block\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"10.0.1.0\/24\"\n  depends_on             = [aws_route.test]\n}\n\ndata \"aws_route\" \"by_instance_id\" {\n  route_table_id = aws_route_table.test.id\n  instance_id    = aws_instance.web.id\n  depends_on     = [aws_route.test]\n}\n`\n}\n\nfunc testAccAWSRouteDataSourceConfigTransitGatewayID() string {\n\treturn testAccAvailableAZsNoOptInDefaultExcludeConfig() + `\n# IncorrectState: Transit Gateway is not available in some availability zones\n\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.0.0.0\/16\"\n\n  tags = {\n    Name = \"tf-acc-test-ec2-route-datasource-transit-gateway-id\"\n  }\n}\n\nresource \"aws_subnet\" \"test\" {\n  availability_zone = data.aws_availability_zones.available.names[0]\n  cidr_block        = \"10.0.0.0\/24\"\n  vpc_id            = aws_vpc.test.id\n\n  tags = {\n    Name = \"tf-acc-test-ec2-route-datasource-transit-gateway-id\"\n  }\n}\n\nresource \"aws_ec2_transit_gateway\" \"test\" {}\n\nresource \"aws_ec2_transit_gateway_vpc_attachment\" \"test\" {\n  subnet_ids         = [aws_subnet.test.id]\n  transit_gateway_id = aws_ec2_transit_gateway.test.id\n  vpc_id             = aws_vpc.test.id\n}\n\nresource \"aws_route\" \"test\" {\n  destination_cidr_block = \"0.0.0.0\/0\"\n  route_table_id         = aws_vpc.test.default_route_table_id\n  transit_gateway_id     = aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id\n}\n\ndata \"aws_route\" \"test\" {\n  route_table_id     = aws_route.test.route_table_id\n  transit_gateway_id = aws_route.test.transit_gateway_id\n}\n`\n}\n\nfunc testAccAWSRouteDataSourceConfigLocalGatewayID() string {\n\treturn fmt.Sprintf(`\ndata \"aws_ec2_local_gateways\" \"all\" {}\ndata \"aws_ec2_local_gateway\" \"first\" {\n  id = tolist(data.aws_ec2_local_gateways.all.ids)[0]\n}\n\ndata \"aws_ec2_local_gateway_route_tables\" \"all\" {}\ndata \"aws_ec2_local_gateway_route_table\" \"first\" {\n  local_gateway_route_table_id = tolist(data.aws_ec2_local_gateway_route_tables.all.ids)[0]\n}\n\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.0.0.0\/16\"\n}\n\nresource \"aws_ec2_local_gateway_route_table_vpc_association\" \"example\" {\n  local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.first.id\n  vpc_id                       = aws_vpc.test.id\n}\n\nresource \"aws_route_table\" \"test\" {\n  vpc_id = aws_vpc.test.id\n}\n\nresource \"aws_route\" \"test\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"172.16.1.0\/24\"\n  local_gateway_id       = data.aws_ec2_local_gateway.first.id\n  depends_on             = [aws_ec2_local_gateway_route_table_vpc_association.example]\n}\n\ndata \"aws_route\" \"by_local_gateway_id\" {\n  route_table_id   = aws_route_table.test.id\n  local_gateway_id = data.aws_ec2_local_gateway.first.id\n  depends_on       = [aws_route.test]\n}\n`)\n}\n<commit_msg>Restricts TestAccAWSRouteDataSource_basic to supported subnets<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/terraform\"\n)\n\nfunc TestAccAWSRouteDataSource_basic(t *testing.T) {\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:  func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDataSourceAwsRouteGroupConfig(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_destination_cidr_block\"),\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_instance_id\"),\n\t\t\t\t\ttestAccDataSourceAwsRouteCheck(\"data.aws_route.by_peering_connection_id\"),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSRouteDataSource_TransitGatewayID(t *testing.T) {\n\tvar route ec2.Route\n\tdataSourceName := \"data.aws_route.test\"\n\tresourceName := \"aws_route.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSRouteDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSRouteDataSourceConfigTransitGatewayID(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSRouteExists(resourceName, &route),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"destination_cidr_block\", dataSourceName, \"destination_cidr_block\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"route_table_id\", dataSourceName, \"route_table_id\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"transit_gateway_id\", dataSourceName, \"transit_gateway_id\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSRouteDataSource_LocalGatewayID(t *testing.T) {\n\tvar route ec2.Route\n\tdataSourceName := \"data.aws_route.by_local_gateway_id\"\n\tresourceName := \"aws_route.test\"\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t); testAccPreCheckAWSOutpostsOutposts(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSRouteDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSRouteDataSourceConfigLocalGatewayID(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSRouteExists(resourceName, &route),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"destination_cidr_block\", dataSourceName, \"destination_cidr_block\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"route_table_id\", dataSourceName, \"route_table_id\"),\n\t\t\t\t\tresource.TestCheckResourceAttrPair(resourceName, \"local_gateway_id\", dataSourceName, \"local_gateway_id\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccDataSourceAwsRouteCheck(name string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[name]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"root module has no resource called %s\", name)\n\t\t}\n\n\t\tr, ok := s.RootModule().Resources[\"aws_route.test\"]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"can't find aws_route.test in state\")\n\t\t}\n\t\trts, ok := s.RootModule().Resources[\"aws_route_table.test\"]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"can't find aws_route_table.test in state\")\n\t\t}\n\n\t\tattr := rs.Primary.Attributes\n\n\t\tif attr[\"route_table_id\"] != r.Primary.Attributes[\"route_table_id\"] {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"route_table_id is %s; want %s\",\n\t\t\t\tattr[\"route_table_id\"],\n\t\t\t\tr.Primary.Attributes[\"route_table_id\"],\n\t\t\t)\n\t\t}\n\n\t\tif attr[\"route_table_id\"] != rts.Primary.Attributes[\"id\"] {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"route_table_id is %s; want %s\",\n\t\t\t\tattr[\"route_table_id\"],\n\t\t\t\trts.Primary.Attributes[\"id\"],\n\t\t\t)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccDataSourceAwsRouteGroupConfig() string {\n\treturn composeConfig(\n\t\ttestAccLatestAmazonLinuxHvmEbsAmiConfig(),\n\t\ttestAccAvailableAZsNoOptInDefaultExcludeConfig(), `\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"172.16.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-route-table-data-source\"\n  }\n}\n\nresource \"aws_vpc\" \"dest\" {\n  cidr_block = \"172.17.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-route-table-data-source\"\n  }\n}\n\nresource \"aws_vpc_peering_connection\" \"test\" {\n  peer_vpc_id = aws_vpc.dest.id\n  vpc_id      = aws_vpc.test.id\n  auto_accept = true\n}\n\nresource \"aws_subnet\" \"test\" {\n  cidr_block        = \"172.16.0.0\/24\"\n  vpc_id            = aws_vpc.test.id\n  availability_zone = data.aws_availability_zones.available.names[0]\n\n  tags = {\n    Name = \"tf-acc-route-table-data-source\"\n  }\n}\n\nresource \"aws_route_table\" \"test\" {\n  vpc_id = aws_vpc.test.id\n\n  tags = {\n    Name = \"terraform-testacc-routetable-data-source\"\n  }\n}\n\nresource \"aws_route\" \"pcx\" {\n  route_table_id            = aws_route_table.test.id\n  vpc_peering_connection_id = aws_vpc_peering_connection.test.id\n  destination_cidr_block    = \"10.0.2.0\/24\"\n}\n\nresource \"aws_route_table_association\" \"a\" {\n  subnet_id      = aws_subnet.test.id\n  route_table_id = aws_route_table.test.id\n}\n\nresource \"aws_instance\" \"web\" {\n  ami           = data.aws_ami.amzn-ami-minimal-hvm-ebs.id\n  instance_type = \"t2.micro\"\n  subnet_id     = aws_subnet.test.id\n\n  tags = {\n    Name = \"HelloWorld\"\n  }\n}\n\nresource \"aws_route\" \"test\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"10.0.1.0\/24\"\n  instance_id            = aws_instance.web.id\n\n  timeouts {\n    create = \"5m\"\n  }\n}\n\ndata \"aws_route\" \"by_peering_connection_id\" {\n  route_table_id            = aws_route_table.test.id\n  vpc_peering_connection_id = aws_route.pcx.vpc_peering_connection_id\n}\n\ndata \"aws_route\" \"by_destination_cidr_block\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"10.0.1.0\/24\"\n  depends_on             = [aws_route.test]\n}\n\ndata \"aws_route\" \"by_instance_id\" {\n  route_table_id = aws_route_table.test.id\n  instance_id    = aws_instance.web.id\n  depends_on     = [aws_route.test]\n}\n`)\n}\n\nfunc testAccAWSRouteDataSourceConfigTransitGatewayID() string {\n\treturn testAccAvailableAZsNoOptInDefaultExcludeConfig() + `\n# IncorrectState: Transit Gateway is not available in some availability zones\n\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.0.0.0\/16\"\n\n  tags = {\n    Name = \"tf-acc-test-ec2-route-datasource-transit-gateway-id\"\n  }\n}\n\nresource \"aws_subnet\" \"test\" {\n  availability_zone = data.aws_availability_zones.available.names[0]\n  cidr_block        = \"10.0.0.0\/24\"\n  vpc_id            = aws_vpc.test.id\n\n  tags = {\n    Name = \"tf-acc-test-ec2-route-datasource-transit-gateway-id\"\n  }\n}\n\nresource \"aws_ec2_transit_gateway\" \"test\" {}\n\nresource \"aws_ec2_transit_gateway_vpc_attachment\" \"test\" {\n  subnet_ids         = [aws_subnet.test.id]\n  transit_gateway_id = aws_ec2_transit_gateway.test.id\n  vpc_id             = aws_vpc.test.id\n}\n\nresource \"aws_route\" \"test\" {\n  destination_cidr_block = \"0.0.0.0\/0\"\n  route_table_id         = aws_vpc.test.default_route_table_id\n  transit_gateway_id     = aws_ec2_transit_gateway_vpc_attachment.test.transit_gateway_id\n}\n\ndata \"aws_route\" \"test\" {\n  route_table_id     = aws_route.test.route_table_id\n  transit_gateway_id = aws_route.test.transit_gateway_id\n}\n`\n}\n\nfunc testAccAWSRouteDataSourceConfigLocalGatewayID() string {\n\treturn fmt.Sprintf(`\ndata \"aws_ec2_local_gateways\" \"all\" {}\ndata \"aws_ec2_local_gateway\" \"first\" {\n  id = tolist(data.aws_ec2_local_gateways.all.ids)[0]\n}\n\ndata \"aws_ec2_local_gateway_route_tables\" \"all\" {}\ndata \"aws_ec2_local_gateway_route_table\" \"first\" {\n  local_gateway_route_table_id = tolist(data.aws_ec2_local_gateway_route_tables.all.ids)[0]\n}\n\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.0.0.0\/16\"\n}\n\nresource \"aws_ec2_local_gateway_route_table_vpc_association\" \"example\" {\n  local_gateway_route_table_id = data.aws_ec2_local_gateway_route_table.first.id\n  vpc_id                       = aws_vpc.test.id\n}\n\nresource \"aws_route_table\" \"test\" {\n  vpc_id = aws_vpc.test.id\n}\n\nresource \"aws_route\" \"test\" {\n  route_table_id         = aws_route_table.test.id\n  destination_cidr_block = \"172.16.1.0\/24\"\n  local_gateway_id       = data.aws_ec2_local_gateway.first.id\n  depends_on             = [aws_ec2_local_gateway_route_table_vpc_association.example]\n}\n\ndata \"aws_route\" \"by_local_gateway_id\" {\n  route_table_id   = aws_route_table.test.id\n  local_gateway_id = data.aws_ec2_local_gateway.first.id\n  depends_on       = [aws_route.test]\n}\n`)\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/arn\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n)\n\nfunc resourceAwsSsmParameter() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSsmParameterPut,\n\t\tRead:   resourceAwsSsmParameterRead,\n\t\tUpdate: resourceAwsSsmParameterPut,\n\t\tDelete: resourceAwsSsmParameterDelete,\n\t\tExists: resourceAwsSmmParameterExists,\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\"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\"type\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tssm.ParameterTypeString,\n\t\t\t\t\tssm.ParameterTypeStringList,\n\t\t\t\t\tssm.ParameterTypeSecureString,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"value\": {\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tRequired:  true,\n\t\t\t\tSensitive: true,\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"key_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"overwrite\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"allowed_pattern\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsSmmParameterExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tssmconn := meta.(*AWSClient).ssmconn\n\t_, err := ssmconn.GetParameter(&ssm.GetParameterInput{\n\t\tName:           aws.String(d.Id()),\n\t\tWithDecryption: aws.Bool(false),\n\t})\n\tif err != nil {\n\t\tif isAWSErr(err, ssm.ErrCodeParameterNotFound, \"\") {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc resourceAwsSsmParameterRead(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[DEBUG] Reading SSM Parameter: %s\", d.Id())\n\n\tresp, err := ssmconn.GetParameter(&ssm.GetParameterInput{\n\t\tName:           aws.String(d.Id()),\n\t\tWithDecryption: aws.Bool(true),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting SSM parameter: %s\", err)\n\t}\n\n\tparam := resp.Parameter\n\td.Set(\"name\", param.Name)\n\td.Set(\"type\", param.Type)\n\td.Set(\"value\", param.Value)\n\n\tdescribeParamsInput := &ssm.DescribeParametersInput{\n\t\tParameterFilters: []*ssm.ParameterStringFilter{\n\t\t\t&ssm.ParameterStringFilter{\n\t\t\t\tKey:    aws.String(\"Name\"),\n\t\t\t\tOption: aws.String(\"Equals\"),\n\t\t\t\tValues: []*string{aws.String(d.Get(\"name\").(string))},\n\t\t\t},\n\t\t},\n\t}\n\tdescribeResp, err := ssmconn.DescribeParameters(describeParamsInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error describing SSM parameter: %s\", err)\n\t}\n\n\tdetail := describeResp.Parameters[0]\n\td.Set(\"key_id\", detail.KeyId)\n\td.Set(\"description\", detail.Description)\n\td.Set(\"allowed_pattern\", detail.AllowedPattern)\n\n\tif tagList, err := ssmconn.ListTagsForResource(&ssm.ListTagsForResourceInput{\n\t\tResourceId:   aws.String(d.Get(\"name\").(string)),\n\t\tResourceType: aws.String(\"Parameter\"),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"Failed to get SSM parameter tags for %s: %s\", d.Get(\"name\"), err)\n\t} else {\n\t\td.Set(\"tags\", tagsToMapSSM(tagList.TagList))\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: meta.(*AWSClient).partition,\n\t\tRegion:    meta.(*AWSClient).region,\n\t\tService:   \"ssm\",\n\t\tAccountID: meta.(*AWSClient).accountid,\n\t\tResource:  fmt.Sprintf(\"parameter\/%s\", strings.TrimPrefix(d.Id(), \"\/\")),\n\t}\n\td.Set(\"arn\", arn.String())\n\n\treturn nil\n}\n\nfunc resourceAwsSsmParameterDelete(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[INFO] Deleting SSM Parameter: %s\", d.Id())\n\n\t_, err := ssmconn.DeleteParameter(&ssm.DeleteParameterInput{\n\t\tName: aws.String(d.Get(\"name\").(string)),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSsmParameterPut(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[INFO] Creating SSM Parameter: %s\", d.Get(\"name\").(string))\n\n\tparamInput := &ssm.PutParameterInput{\n\t\tName:           aws.String(d.Get(\"name\").(string)),\n\t\tType:           aws.String(d.Get(\"type\").(string)),\n\t\tValue:          aws.String(d.Get(\"value\").(string)),\n\t\tOverwrite:      aws.Bool(shouldUpdateSsmParameter(d)),\n\t\tAllowedPattern: aws.String(d.Get(\"allowed_pattern\").(string)),\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\t_, n := d.GetChange(\"description\")\n\t\tparamInput.Description = aws.String(n.(string))\n\t}\n\n\tif keyID, ok := d.GetOk(\"key_id\"); ok {\n\t\tlog.Printf(\"[DEBUG] Setting key_id for SSM Parameter %v: %s\", d.Get(\"name\"), keyID)\n\t\tparamInput.SetKeyId(keyID.(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for SSM Parameter %v to be updated\", d.Get(\"name\"))\n\tif _, err := ssmconn.PutParameter(paramInput); err != nil {\n\t\treturn fmt.Errorf(\"error creating SSM parameter: %s\", err)\n\t}\n\n\tif err := setTagsSSM(ssmconn, d, d.Get(\"name\").(string), \"Parameter\"); err != nil {\n\t\treturn fmt.Errorf(\"error creating SSM parameter tags: %s\", err)\n\t}\n\n\td.SetId(d.Get(\"name\").(string))\n\n\treturn resourceAwsSsmParameterRead(d, meta)\n}\n\nfunc shouldUpdateSsmParameter(d *schema.ResourceData) bool {\n\t\/\/ If the user has specified a preference, return their preference\n\tif value, ok := d.GetOkExists(\"overwrite\"); ok {\n\t\treturn value.(bool)\n\t}\n\n\t\/\/ Since the user has not specified a preference, obey lifecycle rules\n\t\/\/ if it is not a new resource, otherwise overwrite should be set to false.\n\treturn !d.IsNewResource()\n}\n<commit_msg>Check that the SSM DescribeParameters call returned a correct response<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/arn\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n)\n\nfunc resourceAwsSsmParameter() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsSsmParameterPut,\n\t\tRead:   resourceAwsSsmParameterRead,\n\t\tUpdate: resourceAwsSsmParameterPut,\n\t\tDelete: resourceAwsSsmParameterDelete,\n\t\tExists: resourceAwsSmmParameterExists,\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\"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\"type\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tssm.ParameterTypeString,\n\t\t\t\t\tssm.ParameterTypeStringList,\n\t\t\t\t\tssm.ParameterTypeSecureString,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"value\": {\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tRequired:  true,\n\t\t\t\tSensitive: true,\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"key_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"overwrite\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"allowed_pattern\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsSmmParameterExists(d *schema.ResourceData, meta interface{}) (bool, error) {\n\tssmconn := meta.(*AWSClient).ssmconn\n\t_, err := ssmconn.GetParameter(&ssm.GetParameterInput{\n\t\tName:           aws.String(d.Id()),\n\t\tWithDecryption: aws.Bool(false),\n\t})\n\tif err != nil {\n\t\tif isAWSErr(err, ssm.ErrCodeParameterNotFound, \"\") {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc resourceAwsSsmParameterRead(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[DEBUG] Reading SSM Parameter: %s\", d.Id())\n\n\tresp, err := ssmconn.GetParameter(&ssm.GetParameterInput{\n\t\tName:           aws.String(d.Id()),\n\t\tWithDecryption: aws.Bool(true),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting SSM parameter: %s\", err)\n\t}\n\n\tparam := resp.Parameter\n\td.Set(\"name\", param.Name)\n\td.Set(\"type\", param.Type)\n\td.Set(\"value\", param.Value)\n\n\tdescribeParamsInput := &ssm.DescribeParametersInput{\n\t\tParameterFilters: []*ssm.ParameterStringFilter{\n\t\t\t&ssm.ParameterStringFilter{\n\t\t\t\tKey:    aws.String(\"Name\"),\n\t\t\t\tOption: aws.String(\"Equals\"),\n\t\t\t\tValues: []*string{aws.String(d.Get(\"name\").(string))},\n\t\t\t},\n\t\t},\n\t}\n\tdescribeResp, err := ssmconn.DescribeParameters(describeParamsInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error describing SSM parameter: %s\", err)\n\t}\n\n\tif describeResp == nil || len(describeResp.Parameters) == 0 || describeResp.Parameters[0] == nil {\n\t\tlog.Printf(\"[WARN] SSM Parameter %q not found, removing from state\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\tdetail := describeResp.Parameters[0]\n\td.Set(\"key_id\", detail.KeyId)\n\td.Set(\"description\", detail.Description)\n\td.Set(\"allowed_pattern\", detail.AllowedPattern)\n\n\tif tagList, err := ssmconn.ListTagsForResource(&ssm.ListTagsForResourceInput{\n\t\tResourceId:   aws.String(d.Get(\"name\").(string)),\n\t\tResourceType: aws.String(\"Parameter\"),\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"Failed to get SSM parameter tags for %s: %s\", d.Get(\"name\"), err)\n\t} else {\n\t\td.Set(\"tags\", tagsToMapSSM(tagList.TagList))\n\t}\n\n\tarn := arn.ARN{\n\t\tPartition: meta.(*AWSClient).partition,\n\t\tRegion:    meta.(*AWSClient).region,\n\t\tService:   \"ssm\",\n\t\tAccountID: meta.(*AWSClient).accountid,\n\t\tResource:  fmt.Sprintf(\"parameter\/%s\", strings.TrimPrefix(d.Id(), \"\/\")),\n\t}\n\td.Set(\"arn\", arn.String())\n\n\treturn nil\n}\n\nfunc resourceAwsSsmParameterDelete(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[INFO] Deleting SSM Parameter: %s\", d.Id())\n\n\t_, err := ssmconn.DeleteParameter(&ssm.DeleteParameterInput{\n\t\tName: aws.String(d.Get(\"name\").(string)),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsSsmParameterPut(d *schema.ResourceData, meta interface{}) error {\n\tssmconn := meta.(*AWSClient).ssmconn\n\n\tlog.Printf(\"[INFO] Creating SSM Parameter: %s\", d.Get(\"name\").(string))\n\n\tparamInput := &ssm.PutParameterInput{\n\t\tName:           aws.String(d.Get(\"name\").(string)),\n\t\tType:           aws.String(d.Get(\"type\").(string)),\n\t\tValue:          aws.String(d.Get(\"value\").(string)),\n\t\tOverwrite:      aws.Bool(shouldUpdateSsmParameter(d)),\n\t\tAllowedPattern: aws.String(d.Get(\"allowed_pattern\").(string)),\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\t_, n := d.GetChange(\"description\")\n\t\tparamInput.Description = aws.String(n.(string))\n\t}\n\n\tif keyID, ok := d.GetOk(\"key_id\"); ok {\n\t\tlog.Printf(\"[DEBUG] Setting key_id for SSM Parameter %v: %s\", d.Get(\"name\"), keyID)\n\t\tparamInput.SetKeyId(keyID.(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for SSM Parameter %v to be updated\", d.Get(\"name\"))\n\tif _, err := ssmconn.PutParameter(paramInput); err != nil {\n\t\treturn fmt.Errorf(\"error creating SSM parameter: %s\", err)\n\t}\n\n\tif err := setTagsSSM(ssmconn, d, d.Get(\"name\").(string), \"Parameter\"); err != nil {\n\t\treturn fmt.Errorf(\"error creating SSM parameter tags: %s\", err)\n\t}\n\n\td.SetId(d.Get(\"name\").(string))\n\n\treturn resourceAwsSsmParameterRead(d, meta)\n}\n\nfunc shouldUpdateSsmParameter(d *schema.ResourceData) bool {\n\t\/\/ If the user has specified a preference, return their preference\n\tif value, ok := d.GetOkExists(\"overwrite\"); ok {\n\t\treturn value.(bool)\n\t}\n\n\t\/\/ Since the user has not specified a preference, obey lifecycle rules\n\t\/\/ if it is not a new resource, otherwise overwrite should be set to false.\n\treturn !d.IsNewResource()\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Bring Windows behaviour more into line with ANSI<commit_after><|endoftext|>"}
{"text":"<commit_before>package actor\n\nimport (\n\t\"log\"\n)\n\ntype paniced struct {\n\tactor  Actor\n\treason interface{}\n}\n\ntype superviseMe struct {\n\tactor Actor\n}\n\ntype Supervisor interface {\n\tSupervise(Actor)\n\tChildren() []Actor\n}\n\ntype supervisor struct {\n\tActor\n\tonPanic  func(Supervisor, Actor)\n\tchildren []Actor\n}\n\nfunc (sv *supervisor) Supervise(target Actor) {\n\tsv.Send() <- superviseMe{target}\n}\n\nfunc (sv *supervisor) Children() []Actor {\n\treturn sv.children\n}\n\nfunc (sv *supervisor) Init() {\n}\n\nfunc (sv *supervisor) Receive(_ Actor, msg interface{}) {\n\tswitch msg := msg.(type) {\n\tcase paniced:\n\t\tlog.Println(msg.actor.Path(), \"paniced\")\n\t\tsv.onPanic(sv, msg.actor)\n\tcase superviseMe:\n\t\tsv.children = append(sv.children, msg.actor)\n\t\tsv.Monitor(msg.actor)\n\tdefault:\n\t\tpanic(\"Supervisor error: received unexpected message\")\n\t}\n}\n\nfunc NewSupervisor(name string, strategy SupervisorStrategy, sys ActorSystem) Supervisor {\n\tsv := &supervisor{\n\t\tonPanic: strategy.onPanic,\n\t}\n\tsv.Actor = sys.ActorOf(name, sv)\n\tsv.start()\n\treturn sv\n}\n<commit_msg>Fix bug on NewSupervisor<commit_after>package actor\n\nimport (\n\t\"log\"\n)\n\ntype paniced struct {\n\tactor  Actor\n\treason interface{}\n}\n\ntype superviseMe struct {\n\tactor Actor\n}\n\ntype Supervisor interface {\n\tSupervise(Actor)\n\tChildren() []Actor\n}\n\ntype supervisor struct {\n\tActor\n\tonPanic  func(Supervisor, Actor)\n\tchildren []Actor\n}\n\nfunc (sv *supervisor) Supervise(target Actor) {\n\tsv.Send() <- superviseMe{target}\n}\n\nfunc (sv *supervisor) Children() []Actor {\n\treturn sv.children\n}\n\nfunc (sv *supervisor) Init() {\n}\n\nfunc (sv *supervisor) Receive(_ Actor, msg interface{}) {\n\tswitch msg := msg.(type) {\n\tcase paniced:\n\t\tlog.Println(msg.actor.Path(), \"paniced\")\n\t\tsv.onPanic(sv, msg.actor)\n\tcase superviseMe:\n\t\tsv.children = append(sv.children, msg.actor)\n\t\tsv.Monitor(msg.actor)\n\tdefault:\n\t\tpanic(\"Supervisor error: received unexpected message\")\n\t}\n}\n\nfunc NewSupervisor(name string, strategy SupervisorStrategy, sys ActorSystem) Supervisor {\n\tsv := &supervisor{\n\t\tonPanic: strategy.onPanic,\n\t}\n\tsv.Actor = sys.ActorOf(name, sv)\n\treturn sv\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n(c) Copyright [2015] Hewlett Packard Enterprise Development LP\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 ov -\npackage ov\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/HewlettPackard\/oneview-golang\/rest\"\n\t\"github.com\/HewlettPackard\/oneview-golang\/utils\"\n\t\"github.com\/docker\/machine\/libmachine\/log\"\n)\n\n\/\/ HardwareState\ntype HardwareState int\n\nconst (\n\tH_UNKNOWN HardwareState = 1 + iota\n\tH_ADDING\n\tH_NOPROFILE_APPLIED\n\tH_MONITORED\n\tH_UNMANAGED\n\tH_REMOVING\n\tH_REMOVE_FAILED\n\tH_REMOVED\n\tH_APPLYING_PROFILE\n\tH_PROFILE_APPLIED\n\tH_REMOVING_PROFILE\n\tH_PROFILE_ERROR\n\tH_UNSUPPORTED\n\tH_UPATING_FIRMWARE\n)\n\nvar hardwarestates = [...]string{\n\t\"Unknown\",          \/\/ not initialized\n\t\"Adding\",           \/\/ server being added\n\t\"NoProfileApplied\", \/\/ server successfully added\n\t\"Monitored\",        \/\/ server being monitored\n\t\"Unmanaged\",        \/\/ discovered a supported server\n\t\"Removing\",         \/\/ server being removed\n\t\"RemoveFailed\",     \/\/ unsuccessful server removal\n\t\"Removed\",          \/\/ server successfully removed\n\t\"ApplyingProfile\",  \/\/ profile being applied to server\n\t\"ProfileApplied\",   \/\/ profile successfully applied\n\t\"RemovingProfile\",  \/\/ profile being removed\n\t\"ProfileError\",     \/\/ unsuccessful profile apply or removal\n\t\"Unsupported\",      \/\/ server model or version not currently supported by the appliance\n\t\"UpdatingFirmware\", \/\/ server firmware update in progress\n}\n\nfunc (h HardwareState) String() string { return hardwarestates[h-1] }\nfunc (h HardwareState) Equal(s string) bool {\n\treturn (strings.ToUpper(s) == strings.ToUpper(h.String()))\n}\n\n\/\/ ServerHardware get server hardware from ov\ntype ServerHardware struct {\n\tServerHardwarev200\n\tAssetTag              string        `json:\"assetTag,omitempty\"`              \/\/ \"assetTag\": \"[Unknown]\",\n\tCategory              string        `json:\"category,omitempty\"`              \/\/ \"category\": \"server-hardware\",\n\tCreated               string        `json:\"created,omitempty\"`               \/\/ \"created\": \"2015-08-14T21:02:01.537Z\",\n\tDescription           utils.Nstring `json:\"description,omitempty\"`           \/\/ \"description\": null,\n\tETAG                  string        `json:\"eTag,omitempty\"`                  \/\/ \"eTag\": \"1441147370086\",\n\tFormFactor            string        `json:\"formFactor,omitempty\"`            \/\/ \"formFactor\": \"HalfHeight\",\n\tLicensingIntent       string        `json:\"licensingIntent,omitempty\"`       \/\/ \"licensingIntent\": \"OneView\",\n\tLocationURI           utils.Nstring `json:\"locationUri,omitempty\"`           \/\/ \"locationUri\": \"\/rest\/enclosures\/092SN51207RR\",\n\tMemoryMb              int           `json:\"memoryMb,omitempty\"`              \/\/ \"memoryMb\": 262144,\n\tModel                 string        `json:\"model,omitempty\"`                 \/\/ \"model\": \"ProLiant BL460c Gen9\",\n\tModified              string        `json:\"modified,omitempty\"`              \/\/ \"modified\": \"2015-09-01T22:42:50.086Z\",\n\tMpFirwareVersion      string        `json:\"mpFirmwareVersion,omitempty\"`     \/\/ \"mpFirmwareVersion\": \"2.03 Nov 07 2014\",\n\tMpModel               string        `json:\"mpModel,omitempty\"`               \/\/ \"mpModel\": \"iLO4\",\n\tName                  string        `json:\"name,omitempty\"`                  \/\/ \"name\": \"se05, bay 16\",\n\tPartNumber            string        `json:\"partNumber,omitempty\"`            \/\/ \"partNumber\": \"727021-B21\",\n\tPosition              int           `json:\"position,omitempty\"`              \/\/ \"position\": 16,\n\tPowerLock             bool          `json:\"powerLock,omitempty\"`             \/\/ \"powerLock\": false,\n\tPowerState            string        `json:\"powerState,omitempty\"`            \/\/ \"powerState\": \"Off\",\n\tProcessorCoreCount    int           `json:\"processorCoreCount,omitempty\"`    \/\/ \"processorCoreCount\": 14,\n\tProcessorCount        int           `json:\"processorCount,omitempty\"`        \/\/ \"processorCount\": 2,\n\tProcessorSpeedMhz     int           `json:\"processorSpeedMhz,omitempty\"`     \/\/ \"processorSpeedMhz\": 2300,\n\tProcessorType         string        `json:\"processorType,omitempty\"`         \/\/ \"processorType\": \"Intel(R) Xeon(R) CPU E5-2695 v3 @ 2.30GHz\",\n\tRefreshState          string        `json:\"refreshState,omitempty\"`          \/\/ \"refreshState\": \"NotRefreshing\",\n\tRomVersion            string        `json:\"romVersion,omitempty\"`            \/\/ \"romVersion\": \"I36 11\/03\/2014\",\n\tSerialNumber          utils.Nstring `json:\"serialNumber,omitempty\"`          \/\/ \"serialNumber\": \"2M25090RMW\",\n\tServerGroupURI        utils.Nstring `json:\"serverGroupUri,omitempty\"`        \/\/ \"serverGroupUri\": \"\/rest\/enclosure-groups\/56ad0069-8362-42fd-b4e3-f5c5a69af039\",\n\tServerHardwareTypeURI utils.Nstring `json:\"serverHardwareTypeUri,omitempty\"` \/\/ \"serverHardwareTypeUri\": \"\/rest\/server-hardware-types\/DB7726F7-F601-4EA8-B4A6-D1EE1B32C07C\",\n\tServerProfileURI      utils.Nstring `json:\"serverProfileUri,omitempty\"`      \/\/ \"serverProfileUri\": \"\/rest\/server-profiles\/9979b3a4-646a-4c3e-bca6-80ca0b403a93\",\n\tShortModel            string        `json:\"shortModel,omitempty\"`            \/\/ \"shortModel\": \"BL460c Gen9\",\n\tState                 string        `json:\"state,omitempty\"`                 \/\/ \"state\": \"ProfileApplied\",\n\tStateReason           string        `json:\"stateReason,omitempty\"`           \/\/ \"stateReason\": \"NotApplicable\",\n\tStatus                string        `json:\"status,omitempty\"`                \/\/ \"status\": \"Warning\",\n\tType                  string        `json:\"type,omitempty\"`                  \/\/ \"type\": \"server-hardware-3\",\n\tURI                   utils.Nstring `json:\"uri,omitempty\"`                   \/\/ \"uri\": \"\/rest\/server-hardware\/30373237-3132-4D32-3235-303930524D57\",\n\tUUID                  utils.Nstring `json:\"uuid,omitempty\"`                  \/\/ \"uuid\": \"30373237-3132-4D32-3235-303930524D57\",\n\tVirtualSerialNumber   utils.Nstring `json:\"VirtualSerialNumber,omitempty\"`   \/\/ \"virtualSerialNumber\": \"\",\n\tVirtualUUID           string        `json:\"virtualUuid,omitempty\"`           \/\/ \"virtualUuid\": \"00000000-0000-0000-0000-000000000000\"\n\t\/\/ v1 properties\n\tMpDnsName   string `json:\"mpDnsName,omitempty\"`   \/\/ \"mpDnsName\": \"ILO2M25090RMW\",\n\tMpIpAddress string `json:\"mpIpAddress,omitempty\"` \/\/ make this private to force calls to GetIloIPAddress() \"mpIpAddress\": \"172.28.3.136\",\n\t\/\/ extra client struct\n\tClient *OVClient\n}\n\n\/\/ GetIloIPAddress - Use MpIpAddress for v1 and\n\/\/ For v2 check MpHostInfo is not nil , loop through MpHostInfo.MpIPAddress[],\n\/\/ and return the first nonzero address\nfunc (h ServerHardware) GetIloIPAddress() string {\n\tif h.Client.IsHardwareSchemaV2() {\n\t\tif h.MpHostInfo != nil {\n\t\t\tlog.Debug(\"working on getting IloIPAddress from MpHostInfo\")\n\t\t\tfor _, MpIpObj := range h.MpHostInfo.MpIPAddress {\n\t\t\t\tif len(MpIpObj.Address) > 0 &&\n\t\t\t\t\t(MpDHCP.Equal(MpIpObj.Type) || MpStatic.Equal(MpIpObj.Type)) {\n\t\t\t\t\treturn MpIpObj.Address\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn h.MpIpAddress\n\t}\n\treturn \"\"\n}\n\n\/\/ server hardware list, simillar to ServerProfileList with a TODO\ntype ServerHardwareList struct {\n\tType        string           `json:\"type,omitempty\"`        \/\/ \"type\": \"server-hardware-list-3\",\n\tCategory    string           `json:\"category,omitempty\"`    \/\/ \"category\": \"server-hardware\",\n\tCount       int              `json:\"count,omitempty\"`       \/\/ \"count\": 15,\n\tCreated     string           `json:\"created,omitempty\"`     \/\/ \"created\": \"2015-09-08T04:58:21.489Z\",\n\tETAG        string           `json:\"eTag,omitempty\"`        \/\/ \"eTag\": \"1441688301489\",\n\tModified    string           `json:\"modified,omitempty\"`    \/\/ \"modified\": \"2015-09-08T04:58:21.489Z\",\n\tNextPageURI utils.Nstring    `json:\"nextPageUri,omitempty\"` \/\/ \"nextPageUri\": null,\n\tPrevPageURI utils.Nstring    `json:\"prevPageUri,omitempty\"` \/\/ \"prevPageUri\": null,\n\tStart       int              `json:\"start,omitempty\"`       \/\/ \"start\": 0,\n\tTotal       int              `json:\"total,omitempty\"`       \/\/ \"total\": 15,\n\tURI         string           `json:\"uri,omitempty\"`         \/\/ \"uri\": \"\/rest\/server-hardware?sort=name:asc&filter=serverHardwareTypeUri=%27\/rest\/server-hardware-types\/DB7726F7-F601-4EA8-B4A6-D1EE1B32C07C%27&filter=serverGroupUri=%27\/rest\/enclosure-groups\/56ad0069-8362-42fd-b4e3-f5c5a69af039%27&start=0&count=100\"\n\tMembers     []ServerHardware `json:\"members,omitempty\"`     \/\/\"members\":[]\n}\n\n\/\/ server hardware power off\nfunc (s ServerHardware) PowerOff() error {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\treturn pt.PowerExecutor(P_OFF)\n}\n\n\/\/ server hardware power on\nfunc (s ServerHardware) PowerOn() error {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\treturn pt.PowerExecutor(P_ON)\n}\n\n\/\/ get the power state\nfunc (s ServerHardware) GetPowerState() (PowerState, error) {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\tif err := pt.GetCurrentPowerState(); err != nil {\n\t\treturn P_UKNOWN, err\n\t}\n\treturn pt.State, nil\n}\n\n\/\/ get a server hardware with uri\nfunc (c *OVClient) GetServerHardware(uri utils.Nstring) (ServerHardware, error) {\n\n\tvar hardware ServerHardware\n\t\/\/ refresh login\n\tc.RefreshLogin()\n\tc.SetAuthHeaderOptions(c.GetAuthHeaderMap())\n\n\t\/\/ rest call\n\tdata, err := c.RestAPICall(rest.GET, uri.String(), nil)\n\tif err != nil {\n\t\treturn hardware, err\n\t}\n\n\tlog.Debugf(\"GetServerHardware %s\", data)\n\tif err := json.Unmarshal([]byte(data), &hardware); err != nil {\n\t\treturn hardware, err\n\t}\n\thardware.Client = c\n\treturn hardware, nil\n}\n\n\/\/ get a server hardware with filters\nfunc (c *OVClient) GetServerHardwareList(filters []string, sort string) (ServerHardwareList, error) {\n\tvar (\n\t\turi        = \"\/rest\/server-hardware\"\n\t\tq          map[string]interface{}\n\t\tserverlist ServerHardwareList\n\t)\n\tq = make(map[string]interface{})\n\tif len(filters) > 0 {\n\t\tq[\"filter\"] = filters\n\t}\n\n\tif sort != \"\" {\n\t\tq[\"sort\"] = sort\n\t}\n\n\t\/\/ refresh login\n\tc.RefreshLogin()\n\tc.SetAuthHeaderOptions(c.GetAuthHeaderMap())\n\t\/\/ Setup query\n\tif len(q) > 0 {\n\t\tc.SetQueryString(q)\n\t}\n\tdata, err := c.RestAPICall(rest.GET, uri, nil)\n\n\t\/\/ parse the url and setup any query strings\n\tvar Url *url.URL\n\tUrl, err = url.Parse(utils.Sanatize(c.Endpoint))\n\tif err != nil {\n\t\treturn serverlist, err\n\t}\n\tUrl.Path += uri\n\tc.GetQueryString(Url)\n\n\tlog.Debugf(\"GetServerHardwareList %s\", data)\n\tif err := json.Unmarshal([]byte(data), &serverlist); err != nil {\n\t\treturn serverlist, err\n\t}\n\treturn serverlist, nil\n}\n\n\/\/ get available server\n\/\/ blades = rest_api(:oneview, :get, \"\/rest\/server-hardware?sort=name:asc&filter=serverHardwareTypeUri='#{server_hardware_type_uri}'&filter=serverGroupUri='#{enclosure_group_uri}'\")\nfunc (c *OVClient) GetAvailableHardware(hardwaretype_uri utils.Nstring, servergroup_uri utils.Nstring) (hw ServerHardware, err error) {\n\tvar (\n\t\thwlist ServerHardwareList\n\t\tf      = []string{\"serverHardwareTypeUri='\" + hardwaretype_uri.String() + \"'\",\n\t\t\t\"serverGroupUri='\" + servergroup_uri.String() + \"'\"}\n\t)\n\tif hwlist, err = c.GetServerHardwareList(f, \"name:desc\"); err != nil {\n\t\treturn hw, err\n\t}\n\tif !(len(hwlist.Members) > 0) {\n\t\treturn hw, errors.New(\"Error! No available blades that are compatible with the server profile!\")\n\t}\n\n\t\/\/ pick an available blade\n\tfor _, blade := range hwlist.Members {\n\t\tif H_NOPROFILE_APPLIED.Equal(blade.State) {\n\t\t\thw = blade\n\t\t\tbreak\n\t\t}\n\t}\n\tif hw.Name == \"\" {\n\t\treturn hw, errors.New(\"No more blades are available for provisioning!\")\n\t}\n\treturn hw, nil\n}\n<commit_msg>fixup iloip address for c7000 200<commit_after>\/*\n(c) Copyright [2015] Hewlett Packard Enterprise Development LP\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 ov -\npackage ov\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/HewlettPackard\/oneview-golang\/rest\"\n\t\"github.com\/HewlettPackard\/oneview-golang\/utils\"\n\t\"github.com\/docker\/machine\/libmachine\/log\"\n)\n\n\/\/ HardwareState\ntype HardwareState int\n\nconst (\n\tH_UNKNOWN HardwareState = 1 + iota\n\tH_ADDING\n\tH_NOPROFILE_APPLIED\n\tH_MONITORED\n\tH_UNMANAGED\n\tH_REMOVING\n\tH_REMOVE_FAILED\n\tH_REMOVED\n\tH_APPLYING_PROFILE\n\tH_PROFILE_APPLIED\n\tH_REMOVING_PROFILE\n\tH_PROFILE_ERROR\n\tH_UNSUPPORTED\n\tH_UPATING_FIRMWARE\n)\n\nvar hardwarestates = [...]string{\n\t\"Unknown\",          \/\/ not initialized\n\t\"Adding\",           \/\/ server being added\n\t\"NoProfileApplied\", \/\/ server successfully added\n\t\"Monitored\",        \/\/ server being monitored\n\t\"Unmanaged\",        \/\/ discovered a supported server\n\t\"Removing\",         \/\/ server being removed\n\t\"RemoveFailed\",     \/\/ unsuccessful server removal\n\t\"Removed\",          \/\/ server successfully removed\n\t\"ApplyingProfile\",  \/\/ profile being applied to server\n\t\"ProfileApplied\",   \/\/ profile successfully applied\n\t\"RemovingProfile\",  \/\/ profile being removed\n\t\"ProfileError\",     \/\/ unsuccessful profile apply or removal\n\t\"Unsupported\",      \/\/ server model or version not currently supported by the appliance\n\t\"UpdatingFirmware\", \/\/ server firmware update in progress\n}\n\nfunc (h HardwareState) String() string { return hardwarestates[h-1] }\nfunc (h HardwareState) Equal(s string) bool {\n\treturn (strings.ToUpper(s) == strings.ToUpper(h.String()))\n}\n\n\/\/ ServerHardware get server hardware from ov\ntype ServerHardware struct {\n\tServerHardwarev200\n\tAssetTag              string        `json:\"assetTag,omitempty\"`              \/\/ \"assetTag\": \"[Unknown]\",\n\tCategory              string        `json:\"category,omitempty\"`              \/\/ \"category\": \"server-hardware\",\n\tCreated               string        `json:\"created,omitempty\"`               \/\/ \"created\": \"2015-08-14T21:02:01.537Z\",\n\tDescription           utils.Nstring `json:\"description,omitempty\"`           \/\/ \"description\": null,\n\tETAG                  string        `json:\"eTag,omitempty\"`                  \/\/ \"eTag\": \"1441147370086\",\n\tFormFactor            string        `json:\"formFactor,omitempty\"`            \/\/ \"formFactor\": \"HalfHeight\",\n\tLicensingIntent       string        `json:\"licensingIntent,omitempty\"`       \/\/ \"licensingIntent\": \"OneView\",\n\tLocationURI           utils.Nstring `json:\"locationUri,omitempty\"`           \/\/ \"locationUri\": \"\/rest\/enclosures\/092SN51207RR\",\n\tMemoryMb              int           `json:\"memoryMb,omitempty\"`              \/\/ \"memoryMb\": 262144,\n\tModel                 string        `json:\"model,omitempty\"`                 \/\/ \"model\": \"ProLiant BL460c Gen9\",\n\tModified              string        `json:\"modified,omitempty\"`              \/\/ \"modified\": \"2015-09-01T22:42:50.086Z\",\n\tMpFirwareVersion      string        `json:\"mpFirmwareVersion,omitempty\"`     \/\/ \"mpFirmwareVersion\": \"2.03 Nov 07 2014\",\n\tMpModel               string        `json:\"mpModel,omitempty\"`               \/\/ \"mpModel\": \"iLO4\",\n\tName                  string        `json:\"name,omitempty\"`                  \/\/ \"name\": \"se05, bay 16\",\n\tPartNumber            string        `json:\"partNumber,omitempty\"`            \/\/ \"partNumber\": \"727021-B21\",\n\tPosition              int           `json:\"position,omitempty\"`              \/\/ \"position\": 16,\n\tPowerLock             bool          `json:\"powerLock,omitempty\"`             \/\/ \"powerLock\": false,\n\tPowerState            string        `json:\"powerState,omitempty\"`            \/\/ \"powerState\": \"Off\",\n\tProcessorCoreCount    int           `json:\"processorCoreCount,omitempty\"`    \/\/ \"processorCoreCount\": 14,\n\tProcessorCount        int           `json:\"processorCount,omitempty\"`        \/\/ \"processorCount\": 2,\n\tProcessorSpeedMhz     int           `json:\"processorSpeedMhz,omitempty\"`     \/\/ \"processorSpeedMhz\": 2300,\n\tProcessorType         string        `json:\"processorType,omitempty\"`         \/\/ \"processorType\": \"Intel(R) Xeon(R) CPU E5-2695 v3 @ 2.30GHz\",\n\tRefreshState          string        `json:\"refreshState,omitempty\"`          \/\/ \"refreshState\": \"NotRefreshing\",\n\tRomVersion            string        `json:\"romVersion,omitempty\"`            \/\/ \"romVersion\": \"I36 11\/03\/2014\",\n\tSerialNumber          utils.Nstring `json:\"serialNumber,omitempty\"`          \/\/ \"serialNumber\": \"2M25090RMW\",\n\tServerGroupURI        utils.Nstring `json:\"serverGroupUri,omitempty\"`        \/\/ \"serverGroupUri\": \"\/rest\/enclosure-groups\/56ad0069-8362-42fd-b4e3-f5c5a69af039\",\n\tServerHardwareTypeURI utils.Nstring `json:\"serverHardwareTypeUri,omitempty\"` \/\/ \"serverHardwareTypeUri\": \"\/rest\/server-hardware-types\/DB7726F7-F601-4EA8-B4A6-D1EE1B32C07C\",\n\tServerProfileURI      utils.Nstring `json:\"serverProfileUri,omitempty\"`      \/\/ \"serverProfileUri\": \"\/rest\/server-profiles\/9979b3a4-646a-4c3e-bca6-80ca0b403a93\",\n\tShortModel            string        `json:\"shortModel,omitempty\"`            \/\/ \"shortModel\": \"BL460c Gen9\",\n\tState                 string        `json:\"state,omitempty\"`                 \/\/ \"state\": \"ProfileApplied\",\n\tStateReason           string        `json:\"stateReason,omitempty\"`           \/\/ \"stateReason\": \"NotApplicable\",\n\tStatus                string        `json:\"status,omitempty\"`                \/\/ \"status\": \"Warning\",\n\tType                  string        `json:\"type,omitempty\"`                  \/\/ \"type\": \"server-hardware-3\",\n\tURI                   utils.Nstring `json:\"uri,omitempty\"`                   \/\/ \"uri\": \"\/rest\/server-hardware\/30373237-3132-4D32-3235-303930524D57\",\n\tUUID                  utils.Nstring `json:\"uuid,omitempty\"`                  \/\/ \"uuid\": \"30373237-3132-4D32-3235-303930524D57\",\n\tVirtualSerialNumber   utils.Nstring `json:\"VirtualSerialNumber,omitempty\"`   \/\/ \"virtualSerialNumber\": \"\",\n\tVirtualUUID           string        `json:\"virtualUuid,omitempty\"`           \/\/ \"virtualUuid\": \"00000000-0000-0000-0000-000000000000\"\n\t\/\/ v1 properties\n\tMpDnsName   string `json:\"mpDnsName,omitempty\"`   \/\/ \"mpDnsName\": \"ILO2M25090RMW\",\n\tMpIpAddress string `json:\"mpIpAddress,omitempty\"` \/\/ make this private to force calls to GetIloIPAddress() \"mpIpAddress\": \"172.28.3.136\",\n\t\/\/ extra client struct\n\tClient *OVClient\n}\n\n\/\/ GetIloIPAddress - Use MpIpAddress for v1 and\n\/\/ For v2 check MpHostInfo is not nil , loop through MpHostInfo.MpIPAddress[],\n\/\/ and return the first nonzero address\nfunc (h ServerHardware) GetIloIPAddress() string {\n\tif h.Client.IsHardwareSchemaV2() {\n\t\tif h.MpHostInfo != nil {\n\t\t\tlog.Debug(\"working on getting IloIPAddress from MpHostInfo\")\n\t\t\tfor _, MpIpObj := range h.MpHostInfo.MpIPAddress {\n\t\t\t\tif len(MpIpObj.Address) > 0 &&\n\t\t\t\t\t(MpDHCP.Equal(MpIpObj.Type) ||\n\t\t\t\t\t\tMpStatic.Equal(MpIpObj.Type) ||\n\t\t\t\t\t\tMpUndefined.Equal(MpIpObj.Type)) {\n\t\t\t\t\treturn MpIpObj.Address\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn h.MpIpAddress\n\t}\n\treturn \"\"\n}\n\n\/\/ server hardware list, simillar to ServerProfileList with a TODO\ntype ServerHardwareList struct {\n\tType        string           `json:\"type,omitempty\"`        \/\/ \"type\": \"server-hardware-list-3\",\n\tCategory    string           `json:\"category,omitempty\"`    \/\/ \"category\": \"server-hardware\",\n\tCount       int              `json:\"count,omitempty\"`       \/\/ \"count\": 15,\n\tCreated     string           `json:\"created,omitempty\"`     \/\/ \"created\": \"2015-09-08T04:58:21.489Z\",\n\tETAG        string           `json:\"eTag,omitempty\"`        \/\/ \"eTag\": \"1441688301489\",\n\tModified    string           `json:\"modified,omitempty\"`    \/\/ \"modified\": \"2015-09-08T04:58:21.489Z\",\n\tNextPageURI utils.Nstring    `json:\"nextPageUri,omitempty\"` \/\/ \"nextPageUri\": null,\n\tPrevPageURI utils.Nstring    `json:\"prevPageUri,omitempty\"` \/\/ \"prevPageUri\": null,\n\tStart       int              `json:\"start,omitempty\"`       \/\/ \"start\": 0,\n\tTotal       int              `json:\"total,omitempty\"`       \/\/ \"total\": 15,\n\tURI         string           `json:\"uri,omitempty\"`         \/\/ \"uri\": \"\/rest\/server-hardware?sort=name:asc&filter=serverHardwareTypeUri=%27\/rest\/server-hardware-types\/DB7726F7-F601-4EA8-B4A6-D1EE1B32C07C%27&filter=serverGroupUri=%27\/rest\/enclosure-groups\/56ad0069-8362-42fd-b4e3-f5c5a69af039%27&start=0&count=100\"\n\tMembers     []ServerHardware `json:\"members,omitempty\"`     \/\/\"members\":[]\n}\n\n\/\/ server hardware power off\nfunc (s ServerHardware) PowerOff() error {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\treturn pt.PowerExecutor(P_OFF)\n}\n\n\/\/ server hardware power on\nfunc (s ServerHardware) PowerOn() error {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\treturn pt.PowerExecutor(P_ON)\n}\n\n\/\/ get the power state\nfunc (s ServerHardware) GetPowerState() (PowerState, error) {\n\tvar pt *PowerTask\n\tpt = pt.NewPowerTask(s)\n\tif err := pt.GetCurrentPowerState(); err != nil {\n\t\treturn P_UKNOWN, err\n\t}\n\treturn pt.State, nil\n}\n\n\/\/ get a server hardware with uri\nfunc (c *OVClient) GetServerHardware(uri utils.Nstring) (ServerHardware, error) {\n\n\tvar hardware ServerHardware\n\t\/\/ refresh login\n\tc.RefreshLogin()\n\tc.SetAuthHeaderOptions(c.GetAuthHeaderMap())\n\n\t\/\/ rest call\n\tdata, err := c.RestAPICall(rest.GET, uri.String(), nil)\n\tif err != nil {\n\t\treturn hardware, err\n\t}\n\n\tlog.Debugf(\"GetServerHardware %s\", data)\n\tif err := json.Unmarshal([]byte(data), &hardware); err != nil {\n\t\treturn hardware, err\n\t}\n\thardware.Client = c\n\treturn hardware, nil\n}\n\n\/\/ get a server hardware with filters\nfunc (c *OVClient) GetServerHardwareList(filters []string, sort string) (ServerHardwareList, error) {\n\tvar (\n\t\turi        = \"\/rest\/server-hardware\"\n\t\tq          map[string]interface{}\n\t\tserverlist ServerHardwareList\n\t)\n\tq = make(map[string]interface{})\n\tif len(filters) > 0 {\n\t\tq[\"filter\"] = filters\n\t}\n\n\tif sort != \"\" {\n\t\tq[\"sort\"] = sort\n\t}\n\n\t\/\/ refresh login\n\tc.RefreshLogin()\n\tc.SetAuthHeaderOptions(c.GetAuthHeaderMap())\n\t\/\/ Setup query\n\tif len(q) > 0 {\n\t\tc.SetQueryString(q)\n\t}\n\tdata, err := c.RestAPICall(rest.GET, uri, nil)\n\n\t\/\/ parse the url and setup any query strings\n\tvar Url *url.URL\n\tUrl, err = url.Parse(utils.Sanatize(c.Endpoint))\n\tif err != nil {\n\t\treturn serverlist, err\n\t}\n\tUrl.Path += uri\n\tc.GetQueryString(Url)\n\n\tlog.Debugf(\"GetServerHardwareList %s\", data)\n\tif err := json.Unmarshal([]byte(data), &serverlist); err != nil {\n\t\treturn serverlist, err\n\t}\n\treturn serverlist, nil\n}\n\n\/\/ get available server\n\/\/ blades = rest_api(:oneview, :get, \"\/rest\/server-hardware?sort=name:asc&filter=serverHardwareTypeUri='#{server_hardware_type_uri}'&filter=serverGroupUri='#{enclosure_group_uri}'\")\nfunc (c *OVClient) GetAvailableHardware(hardwaretype_uri utils.Nstring, servergroup_uri utils.Nstring) (hw ServerHardware, err error) {\n\tvar (\n\t\thwlist ServerHardwareList\n\t\tf      = []string{\"serverHardwareTypeUri='\" + hardwaretype_uri.String() + \"'\",\n\t\t\t\"serverGroupUri='\" + servergroup_uri.String() + \"'\"}\n\t)\n\tif hwlist, err = c.GetServerHardwareList(f, \"name:desc\"); err != nil {\n\t\treturn hw, err\n\t}\n\tif !(len(hwlist.Members) > 0) {\n\t\treturn hw, errors.New(\"Error! No available blades that are compatible with the server profile!\")\n\t}\n\n\t\/\/ pick an available blade\n\tfor _, blade := range hwlist.Members {\n\t\tif H_NOPROFILE_APPLIED.Equal(blade.State) {\n\t\t\thw = blade\n\t\t\tbreak\n\t\t}\n\t}\n\tif hw.Name == \"\" {\n\t\treturn hw, errors.New(\"No more blades are available for provisioning!\")\n\t}\n\treturn hw, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"crypto\/sha256\"\n\t\/\/_ \"expvar\"\n\t\"flag\"\n\tredigo \"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/pierrre\/imageserver\"\n\timageserver_cache_async \"github.com\/pierrre\/imageserver\/cache\/async\"\n\timageserver_cache_list \"github.com\/pierrre\/imageserver\/cache\/list\"\n\timageserver_cache_memory \"github.com\/pierrre\/imageserver\/cache\/memory\"\n\timageserver_cache_redis \"github.com\/pierrre\/imageserver\/cache\/redis\"\n\timageserver_http \"github.com\/pierrre\/imageserver\/http\"\n\timageserver_http_parser_graphicsmagick \"github.com\/pierrre\/imageserver\/http\/parser\/graphicsmagick\"\n\timageserver_http_parser_list \"github.com\/pierrre\/imageserver\/http\/parser\/list\"\n\timageserver_http_parser_source \"github.com\/pierrre\/imageserver\/http\/parser\/source\"\n\timageserver_processor_graphicsmagick \"github.com\/pierrre\/imageserver\/processor\/graphicsmagick\"\n\timageserver_processor_limit \"github.com\/pierrre\/imageserver\/processor\/limit\"\n\timageserver_provider_cache \"github.com\/pierrre\/imageserver\/provider\/cache\"\n\timageserver_provider_http \"github.com\/pierrre\/imageserver\/provider\/http\"\n\t\"log\"\n\t\"net\/http\"\n\t\/\/_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar verbose bool\n\tflag.BoolVar(&verbose, \"verbose\", false, \"Verbose\")\n\tflag.Parse()\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar cache imageserver.Cache\n\tcache = &imageserver_cache_redis.RedisCache{\n\t\tPool: &redigo.Pool{\n\t\t\tDial: func() (redigo.Conn, error) {\n\t\t\t\treturn redigo.Dial(\"tcp\", \"localhost:6379\")\n\t\t\t},\n\t\t\tMaxIdle: 50,\n\t\t},\n\t\tExpire: time.Duration(7 * 24 * time.Hour),\n\t}\n\tcache = &imageserver_cache_async.AsyncCache{\n\t\tCache: cache,\n\t\tErrFunc: func(err error, key string, image *imageserver.Image, parameters imageserver.Parameters) {\n\t\t\tif verbose {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t},\n\t}\n\tcache = imageserver_cache_list.ListCache{\n\t\timageserver_cache_memory.New(10 * 1024 * 1024),\n\t\tcache,\n\t}\n\n\tprovider := &imageserver_provider_cache.CacheProvider{\n\t\tProvider:     &imageserver_provider_http.HTTPProvider{},\n\t\tCache:        cache,\n\t\tCacheKeyFunc: imageserver_provider_cache.NewSourceHashCacheKeyFunc(sha256.New),\n\t}\n\n\tvar processor imageserver.Processor\n\tprocessor = &imageserver_processor_graphicsmagick.GraphicsMagickProcessor{\n\t\tExecutable: \"gm\",\n\t\tTimeout:    time.Duration(10 * time.Second),\n\t\tAllowedFormats: []string{\n\t\t\t\"jpeg\",\n\t\t\t\"png\",\n\t\t\t\"bmp\",\n\t\t\t\"gif\",\n\t\t},\n\t\tDefaultQualities: map[string]string{\n\t\t\t\"jpeg\": \"85\",\n\t\t},\n\t}\n\tprocessor = imageserver_processor_limit.New(processor, 16)\n\n\timageServer := &imageserver.Server{\n\t\tCache:        cache,\n\t\tCacheKeyFunc: imageserver.NewParametersHashCacheKeyFunc(sha256.New),\n\t\tProvider:     provider,\n\t\tProcessor:    processor,\n\t}\n\n\thttpImageServer := &imageserver_http.Server{\n\t\tParser: &imageserver_http_parser_list.ListParser{\n\t\t\t&imageserver_http_parser_source.SourceParser{},\n\t\t\t&imageserver_http_parser_graphicsmagick.GraphicsMagickParser{},\n\t\t},\n\t\tImageServer: imageServer,\n\t\tETagFunc:    imageserver_http.NewParametersHashETagFunc(sha256.New),\n\t\tExpire:      time.Duration(7 * 24 * time.Hour),\n\t\tRequestFunc: func(request *http.Request) error {\n\t\t\turl := request.URL\n\t\t\tquery := url.Query()\n\t\t\terrorCodeString := query.Get(\"error\")\n\t\t\tif len(errorCodeString) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terrorCode, err := strconv.Atoi(errorCodeString)\n\t\t\tif err != nil {\n\t\t\t\treturn imageserver.NewError(err.Error())\n\t\t\t}\n\t\t\treturn imageserver_http.NewError(errorCode)\n\t\t},\n\t\tHeaderFunc: func(header http.Header, request *http.Request, err error) {\n\t\t\theader.Set(\"X-Hostname\", hostname)\n\t\t},\n\t\tErrorFunc: func(err error, request *http.Request) {\n\t\t\tif verbose {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t},\n\t\tResponseFunc: func(request *http.Request, statusCode int, contentSize int64, err error) {\n\t\t\tif verbose {\n\t\t\t\tvar errString string\n\t\t\t\tif err != nil {\n\t\t\t\t\terrString = err.Error()\n\t\t\t\t}\n\t\t\t\tlog.Println(request.RemoteAddr, request.Method, strconv.Quote(request.URL.String()), statusCode, contentSize, strconv.Quote(errString))\n\t\t\t}\n\t\t},\n\t}\n\n\thttp.Handle(\"\/\", httpImageServer)\n\terr = http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>Add http flag in advanced example<commit_after>\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"crypto\/sha256\"\n\t\/\/_ \"expvar\"\n\t\"flag\"\n\tredigo \"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/pierrre\/imageserver\"\n\timageserver_cache_async \"github.com\/pierrre\/imageserver\/cache\/async\"\n\timageserver_cache_list \"github.com\/pierrre\/imageserver\/cache\/list\"\n\timageserver_cache_memory \"github.com\/pierrre\/imageserver\/cache\/memory\"\n\timageserver_cache_redis \"github.com\/pierrre\/imageserver\/cache\/redis\"\n\timageserver_http \"github.com\/pierrre\/imageserver\/http\"\n\timageserver_http_parser_graphicsmagick \"github.com\/pierrre\/imageserver\/http\/parser\/graphicsmagick\"\n\timageserver_http_parser_list \"github.com\/pierrre\/imageserver\/http\/parser\/list\"\n\timageserver_http_parser_source \"github.com\/pierrre\/imageserver\/http\/parser\/source\"\n\timageserver_processor_graphicsmagick \"github.com\/pierrre\/imageserver\/processor\/graphicsmagick\"\n\timageserver_processor_limit \"github.com\/pierrre\/imageserver\/processor\/limit\"\n\timageserver_provider_cache \"github.com\/pierrre\/imageserver\/provider\/cache\"\n\timageserver_provider_http \"github.com\/pierrre\/imageserver\/provider\/http\"\n\t\"log\"\n\t\"net\/http\"\n\t\/\/_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\tvar verbose bool\n\tvar httpAddr string\n\tflag.BoolVar(&verbose, \"verbose\", false, \"Verbose\")\n\tflag.StringVar(&httpAddr, \"http\", \":8080\", \"Http\")\n\tflag.Parse()\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar cache imageserver.Cache\n\tcache = &imageserver_cache_redis.RedisCache{\n\t\tPool: &redigo.Pool{\n\t\t\tDial: func() (redigo.Conn, error) {\n\t\t\t\treturn redigo.Dial(\"tcp\", \"localhost:6379\")\n\t\t\t},\n\t\t\tMaxIdle: 50,\n\t\t},\n\t\tExpire: time.Duration(7 * 24 * time.Hour),\n\t}\n\tcache = &imageserver_cache_async.AsyncCache{\n\t\tCache: cache,\n\t\tErrFunc: func(err error, key string, image *imageserver.Image, parameters imageserver.Parameters) {\n\t\t\tif verbose {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t},\n\t}\n\tcache = imageserver_cache_list.ListCache{\n\t\timageserver_cache_memory.New(10 * 1024 * 1024),\n\t\tcache,\n\t}\n\n\tprovider := &imageserver_provider_cache.CacheProvider{\n\t\tProvider:     &imageserver_provider_http.HTTPProvider{},\n\t\tCache:        cache,\n\t\tCacheKeyFunc: imageserver_provider_cache.NewSourceHashCacheKeyFunc(sha256.New),\n\t}\n\n\tvar processor imageserver.Processor\n\tprocessor = &imageserver_processor_graphicsmagick.GraphicsMagickProcessor{\n\t\tExecutable: \"gm\",\n\t\tTimeout:    time.Duration(10 * time.Second),\n\t\tAllowedFormats: []string{\n\t\t\t\"jpeg\",\n\t\t\t\"png\",\n\t\t\t\"bmp\",\n\t\t\t\"gif\",\n\t\t},\n\t\tDefaultQualities: map[string]string{\n\t\t\t\"jpeg\": \"85\",\n\t\t},\n\t}\n\tprocessor = imageserver_processor_limit.New(processor, 16)\n\n\timageServer := &imageserver.Server{\n\t\tCache:        cache,\n\t\tCacheKeyFunc: imageserver.NewParametersHashCacheKeyFunc(sha256.New),\n\t\tProvider:     provider,\n\t\tProcessor:    processor,\n\t}\n\n\thttpImageServer := &imageserver_http.Server{\n\t\tParser: &imageserver_http_parser_list.ListParser{\n\t\t\t&imageserver_http_parser_source.SourceParser{},\n\t\t\t&imageserver_http_parser_graphicsmagick.GraphicsMagickParser{},\n\t\t},\n\t\tImageServer: imageServer,\n\t\tETagFunc:    imageserver_http.NewParametersHashETagFunc(sha256.New),\n\t\tExpire:      time.Duration(7 * 24 * time.Hour),\n\t\tRequestFunc: func(request *http.Request) error {\n\t\t\turl := request.URL\n\t\t\tquery := url.Query()\n\t\t\terrorCodeString := query.Get(\"error\")\n\t\t\tif len(errorCodeString) == 0 {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terrorCode, err := strconv.Atoi(errorCodeString)\n\t\t\tif err != nil {\n\t\t\t\treturn imageserver.NewError(err.Error())\n\t\t\t}\n\t\t\treturn imageserver_http.NewError(errorCode)\n\t\t},\n\t\tHeaderFunc: func(header http.Header, request *http.Request, err error) {\n\t\t\theader.Set(\"X-Hostname\", hostname)\n\t\t},\n\t\tErrorFunc: func(err error, request *http.Request) {\n\t\t\tif verbose {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t},\n\t\tResponseFunc: func(request *http.Request, statusCode int, contentSize int64, err error) {\n\t\t\tif verbose {\n\t\t\t\tvar errString string\n\t\t\t\tif err != nil {\n\t\t\t\t\terrString = err.Error()\n\t\t\t\t}\n\t\t\t\tlog.Println(request.RemoteAddr, request.Method, strconv.Quote(request.URL.String()), statusCode, contentSize, strconv.Quote(errString))\n\t\t\t}\n\t\t},\n\t}\n\n\thttp.Handle(\"\/\", httpImageServer)\n\terr = http.ListenAndServe(httpAddr, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package brew\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/goreleaser\/releaser\/config\"\n\t\"github.com\/goreleaser\/releaser\/split\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nconst formulae = `class {{ .Name }} < Formula\n  desc \"{{ .Desc }}\"\n  homepage \"{{ .Homepage }}\"\n  url \"https:\/\/github.com\/{{ .Repo }}\/releases\/download\/{{ .Tag }}\/{{ .BinaryName }}_#{%x(uname -s).gsub(\/\\n\/, '')}_#{%x(uname -m).gsub(\/\\n\/, '')}.tar.gz\"\n  head \"https:\/\/github.com\/{{ .Repo }}.git\"\n  version \"{{ .Tag }}\"\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 string\n}\n\n\/\/ Pipe for brew deployment\ntype Pipe struct{}\n\n\/\/ Name of the pipe\nfunc (Pipe) Name() string {\n\treturn \"Homebrew\"\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(config config.ProjectConfig) error {\n\tif config.Brew.Repo == \"\" {\n\t\treturn nil\n\t}\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: config.Token},\n\t)\n\ttc := oauth2.NewClient(context.Background(), ts)\n\tclient := github.NewClient(tc)\n\n\towner, repo := split.OnSlash(config.Brew.Repo)\n\tname := config.BinaryName + \".rb\"\n\n\tlog.Println(\"Updating\", name, \"on\", config.Brew.Repo, \"...\")\n\tout, err := buildFormulae(config, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsha, err := sha(client, owner, repo, name, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = client.Repositories.UpdateFile(\n\t\towner, repo, name, &github.RepositoryContentFileOptions{\n\t\t\tCommitter: &github.CommitAuthor{\n\t\t\t\tName:  github.String(\"goreleaserbot\"),\n\t\t\t\tEmail: github.String(\"bot@goreleaser\"),\n\t\t\t},\n\t\t\tContent: out.Bytes(),\n\t\t\tMessage: github.String(config.BinaryName + \" version \" + config.Git.CurrentTag),\n\t\t\tSHA:     sha,\n\t\t},\n\t)\n\treturn err\n}\nfunc sha(client *github.Client, owner, repo, name string, out bytes.Buffer) (*string, error) {\n\tvar sha *string\n\tfile, _, _, err := client.Repositories.GetContents(\n\t\towner, repo, name, &github.RepositoryContentGetOptions{},\n\t)\n\tif err == nil {\n\t\tsha = file.SHA\n\t} else {\n\t\tsha = github.String(fmt.Sprintf(\"%s\", sha256.Sum256(out.Bytes())))\n\t}\n\treturn sha, err\n}\n\nfunc buildFormulae(config config.ProjectConfig, client *github.Client) (bytes.Buffer, error) {\n\tdata, err := dataFor(config, 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(config config.ProjectConfig, client *github.Client) (result templateData, err error) {\n\tvar homepage string\n\tvar description string\n\towner, repo := split.OnSlash(config.Repo)\n\trep, _, err := client.Repositories.Get(owner, repo)\n\tif err != nil {\n\t\treturn result, err\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(config.BinaryName),\n\t\tDesc:       description,\n\t\tHomepage:   homepage,\n\t\tRepo:       config.Repo,\n\t\tTag:        config.Git.CurrentTag,\n\t\tBinaryName: config.BinaryName,\n\t\tCaveats:    config.Brew.Caveats,\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>improved code a little<commit_after>package brew\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/goreleaser\/releaser\/config\"\n\t\"github.com\/goreleaser\/releaser\/split\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nconst formulae = `class {{ .Name }} < Formula\n  desc \"{{ .Desc }}\"\n  homepage \"{{ .Homepage }}\"\n  url \"https:\/\/github.com\/{{ .Repo }}\/releases\/download\/{{ .Tag }}\/{{ .BinaryName }}_#{%x(uname -s).gsub(\/\\n\/, '')}_#{%x(uname -m).gsub(\/\\n\/, '')}.tar.gz\"\n  head \"https:\/\/github.com\/{{ .Repo }}.git\"\n  version \"{{ .Tag }}\"\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 string\n}\n\n\/\/ Pipe for brew deployment\ntype Pipe struct{}\n\n\/\/ Name of the pipe\nfunc (Pipe) Name() string {\n\treturn \"Homebrew\"\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(config config.ProjectConfig) error {\n\tif config.Brew.Repo == \"\" {\n\t\treturn nil\n\t}\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: config.Token},\n\t)\n\ttc := oauth2.NewClient(context.Background(), ts)\n\tclient := github.NewClient(tc)\n\n\towner, repo := split.OnSlash(config.Brew.Repo)\n\tname := config.BinaryName + \".rb\"\n\n\tlog.Println(\"Updating\", name, \"on\", config.Brew.Repo, \"...\")\n\tout, err := buildFormulae(config, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsha, err := sha(client, owner, repo, name, out)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, _, err = client.Repositories.UpdateFile(\n\t\towner, repo, name, &github.RepositoryContentFileOptions{\n\t\t\tCommitter: &github.CommitAuthor{\n\t\t\t\tName:  github.String(\"goreleaserbot\"),\n\t\t\t\tEmail: github.String(\"bot@goreleaser\"),\n\t\t\t},\n\t\t\tContent: out.Bytes(),\n\t\t\tMessage: github.String(config.BinaryName + \" version \" + config.Git.CurrentTag),\n\t\t\tSHA:     sha,\n\t\t},\n\t)\n\treturn err\n}\nfunc sha(client *github.Client, owner, repo, name string, out bytes.Buffer) (*string, error) {\n\tfile, _, _, err := client.Repositories.GetContents(\n\t\towner, repo, name, &github.RepositoryContentGetOptions{},\n\t)\n\tif err == nil {\n\t\treturn file.SHA, err\n\t}\n\treturn github.String(fmt.Sprintf(\"%s\", sha256.Sum256(out.Bytes()))), err\n}\n\nfunc buildFormulae(config config.ProjectConfig, client *github.Client) (bytes.Buffer, error) {\n\tdata, err := dataFor(config, 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(config config.ProjectConfig, client *github.Client) (result templateData, err error) {\n\tvar homepage string\n\tvar description string\n\towner, repo := split.OnSlash(config.Repo)\n\trep, _, err := client.Repositories.Get(owner, repo)\n\tif err != nil {\n\t\treturn result, err\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(config.BinaryName),\n\t\tDesc:       description,\n\t\tHomepage:   homepage,\n\t\tRepo:       config.Repo,\n\t\tTag:        config.Git.CurrentTag,\n\t\tBinaryName: config.BinaryName,\n\t\tCaveats:    config.Brew.Caveats,\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>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage message\n\nimport (\n\t\"crypto\/x509\"\n\t\"math\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"github.com\/ava-labs\/avalanchego\/ids\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/units\"\n)\n\nfunc TestCodecPackInvalidOp(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Pack(math.MaxUint8, make(map[Field]interface{}), false)\n\tassert.Error(t, err)\n\n\t_, err = codec.Pack(math.MaxUint8, make(map[Field]interface{}), true)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecPackMissingField(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Pack(Get, make(map[Field]interface{}), false)\n\tassert.Error(t, err)\n\n\t_, err = codec.Pack(Get, make(map[Field]interface{}), true)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecParseInvalidOp(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Parse([]byte{math.MaxUint8}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecParseExtraSpace(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Parse([]byte{byte(GetVersion), 0x00, 0x00}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n\n\t_, err = codec.Parse([]byte{byte(GetVersion), 0x00, 0x01}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n}\n\n\/\/ Test packing and then parsing messages\n\/\/ when using a gzip compressor\nfunc TestCodecPackParseGzip(t *testing.T) {\n\tc, err := NewCodecWithMemoryPool(\"\", prometheus.DefaultRegisterer, 2*units.MiB)\n\tassert.NoError(t, err)\n\tid := ids.GenerateTestID()\n\tcert := &x509.Certificate{}\n\n\tmsgs := []inboundMessage{\n\t\t{\n\t\t\top:     GetVersion,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: Version,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tNetworkID:      uint32(0),\n\t\t\t\tNodeID:         uint32(1337),\n\t\t\t\tMyTime:         uint64(time.Now().Unix()),\n\t\t\t\tIP:             utils.IPDesc{IP: net.IPv4(1, 2, 3, 4)},\n\t\t\t\tVersionStr:     \"v1.2.3\",\n\t\t\t\tVersionTime:    uint64(time.Now().Unix()),\n\t\t\t\tSigBytes:       []byte{'y', 'e', 'e', 't'},\n\t\t\t\tTrackedSubnets: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top:     GetPeerList,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: PeerList,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tSignedPeers: []utils.IPCertDesc{\n\t\t\t\t\t{\n\t\t\t\t\t\tCert:      cert,\n\t\t\t\t\t\tIPDesc:    utils.IPDesc{IP: net.IPv4(1, 2, 3, 4)},\n\t\t\t\t\t\tTime:      uint64(time.Now().Unix()),\n\t\t\t\t\t\tSignature: make([]byte, 65),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top:     Ping,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top:     Pong,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: UptimePong,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tUptime: 80,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: GetAcceptedFrontier,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:   id[:],\n\t\t\t\tRequestID: uint32(1337),\n\t\t\t\tDeadline:  uint64(time.Now().Unix()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: AcceptedFrontier,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: GetAccepted,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tDeadline:     uint64(time.Now().Unix()),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Accepted,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: MultiPut,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:             id[:],\n\t\t\t\tRequestID:           uint32(1337),\n\t\t\t\tMultiContainerBytes: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Get,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:     id[:],\n\t\t\t\tRequestID:   uint32(1337),\n\t\t\t\tDeadline:    uint64(time.Now().Unix()),\n\t\t\t\tContainerID: id[:],\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Put,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:        id[:],\n\t\t\t\tRequestID:      uint32(1337),\n\t\t\t\tContainerID:    id[:],\n\t\t\t\tContainerBytes: make([]byte, 1024),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: PushQuery,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:        id[:],\n\t\t\t\tRequestID:      uint32(1337),\n\t\t\t\tDeadline:       uint64(time.Now().Unix()),\n\t\t\t\tContainerID:    id[:],\n\t\t\t\tContainerBytes: make([]byte, 1024),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: PullQuery,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:     id[:],\n\t\t\t\tRequestID:   uint32(1337),\n\t\t\t\tDeadline:    uint64(time.Now().Unix()),\n\t\t\t\tContainerID: id[:],\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Chits,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, m := range msgs {\n\t\tpackedIntf, err := c.Pack(m.op, m.fields, m.op.Compressable())\n\t\tassert.NoError(t, err, \"failed to pack on operation %s\", m.op)\n\n\t\tunpackedIntf, err := c.Parse(packedIntf.Bytes(), dummyNodeID, dummyOnFinishedHandling)\n\t\tassert.NoError(t, err, \"failed to parse w\/ compression on operation %s\", m.op)\n\n\t\tunpacked := unpackedIntf.(*inboundMessage)\n\n\t\tassert.EqualValues(t, len(m.fields), len(unpacked.fields))\n\t}\n}\n<commit_msg>convert int to uint8<commit_after>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage message\n\nimport (\n\t\"crypto\/x509\"\n\t\"math\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"github.com\/ava-labs\/avalanchego\/ids\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/units\"\n)\n\nfunc TestCodecPackInvalidOp(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Pack(math.MaxUint8, make(map[Field]interface{}), false)\n\tassert.Error(t, err)\n\n\t_, err = codec.Pack(math.MaxUint8, make(map[Field]interface{}), true)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecPackMissingField(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Pack(Get, make(map[Field]interface{}), false)\n\tassert.Error(t, err)\n\n\t_, err = codec.Pack(Get, make(map[Field]interface{}), true)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecParseInvalidOp(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Parse([]byte{math.MaxUint8}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n}\n\nfunc TestCodecParseExtraSpace(t *testing.T) {\n\tcodec, err := NewCodecWithMemoryPool(\"\", prometheus.NewRegistry(), 2*units.MiB)\n\tassert.NoError(t, err)\n\n\t_, err = codec.Parse([]byte{byte(GetVersion), 0x00, 0x00}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n\n\t_, err = codec.Parse([]byte{byte(GetVersion), 0x00, 0x01}, dummyNodeID, dummyOnFinishedHandling)\n\tassert.Error(t, err)\n}\n\n\/\/ Test packing and then parsing messages\n\/\/ when using a gzip compressor\nfunc TestCodecPackParseGzip(t *testing.T) {\n\tc, err := NewCodecWithMemoryPool(\"\", prometheus.DefaultRegisterer, 2*units.MiB)\n\tassert.NoError(t, err)\n\tid := ids.GenerateTestID()\n\tcert := &x509.Certificate{}\n\n\tmsgs := []inboundMessage{\n\t\t{\n\t\t\top:     GetVersion,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: Version,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tNetworkID:      uint32(0),\n\t\t\t\tNodeID:         uint32(1337),\n\t\t\t\tMyTime:         uint64(time.Now().Unix()),\n\t\t\t\tIP:             utils.IPDesc{IP: net.IPv4(1, 2, 3, 4)},\n\t\t\t\tVersionStr:     \"v1.2.3\",\n\t\t\t\tVersionTime:    uint64(time.Now().Unix()),\n\t\t\t\tSigBytes:       []byte{'y', 'e', 'e', 't'},\n\t\t\t\tTrackedSubnets: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top:     GetPeerList,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: PeerList,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tSignedPeers: []utils.IPCertDesc{\n\t\t\t\t\t{\n\t\t\t\t\t\tCert:      cert,\n\t\t\t\t\t\tIPDesc:    utils.IPDesc{IP: net.IPv4(1, 2, 3, 4)},\n\t\t\t\t\t\tTime:      uint64(time.Now().Unix()),\n\t\t\t\t\t\tSignature: make([]byte, 65),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top:     Ping,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top:     Pong,\n\t\t\tfields: map[Field]interface{}{},\n\t\t},\n\t\t{\n\t\t\top: UptimePong,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tUptime: uint8(80),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: GetAcceptedFrontier,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:   id[:],\n\t\t\t\tRequestID: uint32(1337),\n\t\t\t\tDeadline:  uint64(time.Now().Unix()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: AcceptedFrontier,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: GetAccepted,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tDeadline:     uint64(time.Now().Unix()),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Accepted,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: MultiPut,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:             id[:],\n\t\t\t\tRequestID:           uint32(1337),\n\t\t\t\tMultiContainerBytes: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Get,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:     id[:],\n\t\t\t\tRequestID:   uint32(1337),\n\t\t\t\tDeadline:    uint64(time.Now().Unix()),\n\t\t\t\tContainerID: id[:],\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Put,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:        id[:],\n\t\t\t\tRequestID:      uint32(1337),\n\t\t\t\tContainerID:    id[:],\n\t\t\t\tContainerBytes: make([]byte, 1024),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: PushQuery,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:        id[:],\n\t\t\t\tRequestID:      uint32(1337),\n\t\t\t\tDeadline:       uint64(time.Now().Unix()),\n\t\t\t\tContainerID:    id[:],\n\t\t\t\tContainerBytes: make([]byte, 1024),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: PullQuery,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:     id[:],\n\t\t\t\tRequestID:   uint32(1337),\n\t\t\t\tDeadline:    uint64(time.Now().Unix()),\n\t\t\t\tContainerID: id[:],\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\top: Chits,\n\t\t\tfields: map[Field]interface{}{\n\t\t\t\tChainID:      id[:],\n\t\t\t\tRequestID:    uint32(1337),\n\t\t\t\tContainerIDs: [][]byte{id[:]},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, m := range msgs {\n\t\tpackedIntf, err := c.Pack(m.op, m.fields, m.op.Compressable())\n\t\tassert.NoError(t, err, \"failed to pack on operation %s\", m.op)\n\n\t\tunpackedIntf, err := c.Parse(packedIntf.Bytes(), dummyNodeID, dummyOnFinishedHandling)\n\t\tassert.NoError(t, err, \"failed to parse w\/ compression on operation %s\", m.op)\n\n\t\tunpacked := unpackedIntf.(*inboundMessage)\n\n\t\tassert.EqualValues(t, len(m.fields), len(unpacked.fields))\n\t}\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 fs\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseops\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ State required for reading from directories.\ntype dirHandle struct {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tin *inode.DirInode\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tMu syncutil.InvariantMutex\n\n\t\/\/ All entries in the directory. Populated the first time we need one.\n\t\/\/\n\t\/\/ INVARIANT: For each i, entries[i+1].Offset == entries[i].Offset + 1\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tentries []fuseutil.Dirent\n\n\t\/\/ Has entries yet been populated?\n\t\/\/\n\t\/\/ INVARIANT: If !entriesValid, then len(entries) == 0\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tentriesValid bool\n}\n\n\/\/ Create a directory handle that obtains listings from the supplied inode.\nfunc newDirHandle(in *inode.DirInode) (dh *dirHandle) {\n\t\/\/ Set up the basic struct.\n\tdh = &dirHandle{\n\t\tin: in,\n\t}\n\n\t\/\/ Set up invariant checking.\n\tdh.Mu = syncutil.NewInvariantMutex(dh.checkInvariants)\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Dirents, sorted by name.\ntype SortedDirents []fuseutil.Dirent\n\nfunc (p SortedDirents) Len() int           { return len(p) }\nfunc (p SortedDirents) Less(i, j int) bool { return p[i].Name < p[j].Name }\nfunc (p SortedDirents) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }\n\nfunc (dh *dirHandle) checkInvariants() {\n\t\/\/ INVARIANT: For each i, entries[i+1].Offset == entries[i].Offset + 1\n\tfor i := 0; i < len(dh.entries)-1; i++ {\n\t\tif !(dh.entries[i+1].Offset == dh.entries[i].Offset+1) {\n\t\t\tpanic(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"Unexpected offset sequence: %v, %v\",\n\t\t\t\t\tdh.entries[i].Offset,\n\t\t\t\t\tdh.entries[i+1].Offset))\n\t\t}\n\t}\n\n\t\/\/ INVARIANT: If !entriesValid, then len(entries) == 0\n\tif !dh.entriesValid && len(dh.entries) != 0 {\n\t\tpanic(\"Unexpected non-empty entries slice\")\n\t}\n}\n\n\/\/ Read some entries from the directory inode. Return newTok == \"\" (possibly\n\/\/ with a non-empty list of entries) when the end of the directory has been\n\/\/ hit.\n\/\/\n\/\/ The contents of the entries' Offset fields are undefined.\nfunc readSomeEntries(\n\tctx context.Context,\n\tin *inode.DirInode,\n\ttok string) (entries []fuseutil.Dirent, newTok string, err error) {\n\tentries, newTok, err = in.ReadEntries(ctx, tok)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ReadEntries: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Return a bogus inode ID for each entry, but not the root inode ID.\n\t\/\/\n\t\/\/ NOTE(jacobsa): As far as I can tell this is harmless. Minting and\n\t\/\/ returning a real inode ID is difficult because fuse does not count\n\t\/\/ readdir as an operation that increases the inode ID's lookup count and\n\t\/\/ we therefore don't get a forget for it later, but we would like to not\n\t\/\/ have to remember every inode ID that we've ever minted for readdir.\n\t\/\/\n\t\/\/ If it turns out this is not harmless, we'll need to switch to something\n\t\/\/ like inode IDs based on (object name, generation) hashes. But then what\n\t\/\/ about the birthday problem? And more importantly, what about our\n\t\/\/ semantic of not minting a new inode ID when the generation changes due\n\t\/\/ to a local action?\n\tfor i, _ := range entries {\n\t\tentries[i].Inode = fuseops.RootInodeID + 1\n\t}\n\n\treturn\n}\n\n\/\/ Call readSomeEntries in a loop until the directory is exhausted. Return\n\/\/ contents sorted by name and with correct Offset fields.\nfunc readAllEntries(\n\tctx context.Context,\n\tin *inode.DirInode) (entries SortedDirents, err error) {\n\t\/\/ Ensure that our result is sorted, with correct offset fields.\n\tdefer func() {\n\t\tsort.Sort(entries)\n\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tentries[i].Offset = fuseops.DirOffset(i) + 1\n\t\t}\n\t}()\n\n\t\/\/ Read in a loop.\n\tvar tok string\n\tfor {\n\t\tvar batch []fuseutil.Dirent\n\n\t\t\/\/ Accumulate some more entries.\n\t\tbatch, tok, err = readSomeEntries(ctx, in, tok)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tentries = append(entries, batch...)\n\n\t\t\/\/ Are we done?\n\t\tif tok == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Resolve name conflicts between file objects and directory objects (e.g. the\n\/\/ objects \"foo\/bar\" and \"foo\/bar\/\") by appending U+000A, which is illegal in\n\/\/ GCS object names, to conflicting file names.\n\/\/\n\/\/ Input must be sorted by name.\nfunc fixConflictingNames(entries []fuseutil.Dirent) (err error) {\n\t\/\/ Sanity check.\n\tif !sort.IsSorted(SortedDirents(entries)) {\n\t\terr = fmt.Errorf(\"Expected sorted input\")\n\t\treturn\n\t}\n\n\t\/\/ Examine each adjacent pair of names.\n\tfor i, _ := range entries {\n\t\te := &entries[i]\n\n\t\t\/\/ Find the previous entry.\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprev := &entries[i-1]\n\n\t\t\/\/ Does the pair have matching names?\n\t\tif e.Name != prev.Name {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Repair whichever is the file, remembering that there's no way to get any\n\t\t\/\/ other type in the mix.\n\t\tif e.Type == fuseutil.DT_File {\n\t\t\te.Name += inode.ConflictingFileNameSuffix\n\t\t} else {\n\t\t\tif prev.Type != fuseutil.DT_File {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected type for entry: %v\", prev))\n\t\t\t}\n\t\t\tprev.Name += inode.ConflictingFileNameSuffix\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Handle a request to read from the directory, without responding.\n\/\/\n\/\/ Special case: we assume that a zero offset indicates that rewinddir has been\n\/\/ called (since fuse gives us no way to intercept and know for sure), and\n\/\/ start the listing process over again.\n\/\/\n\/\/ LOCKS_REQUIRED(dh.Mu)\nfunc (dh *dirHandle) ReadDir(\n\top *fuseops.ReadDirOp) (err error) {\n\t\/\/ If the request is for offset zero, we assume that either this is the first\n\t\/\/ call or rewinddir has been called. Reset state.\n\tif op.Offset == 0 {\n\t\tdh.entries = nil\n\t\tdh.entriesValid = false\n\t}\n\n\t\/\/ Do we need to read entries from GCS?\n\tif !dh.entriesValid {\n\t\t\/\/ Read entries.\n\t\tvar entries []fuseutil.Dirent\n\t\tentries, err = readAllEntries(op.Context(), dh.in)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"readAllEntries: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Fix name conflicts.\n\t\terr = fixConflictingNames(entries)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"fixConflictingNames: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Update state.\n\t\tdh.entries = entries\n\t\tdh.entriesValid = true\n\t}\n\n\t\/\/ Is the offset past the end of what we have buffered? If so, this must be\n\t\/\/ an invalid seekdir according to posix.\n\tindex := int(op.Offset)\n\tif index > len(dh.entries) {\n\t\terr = fuse.EINVAL\n\t\treturn\n\t}\n\n\t\/\/ We copy out entries until we run out of entries or space.\n\tfor i := index; i < len(dh.entries); i++ {\n\t\top.Data = fuseutil.AppendDirent(op.Data, dh.entries[i])\n\t\tif len(op.Data) > op.Size {\n\t\t\top.Data = op.Data[:op.Size]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>Refactored helpers in preparation for adding filtering.<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 fs\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseops\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ State required for reading from directories.\ntype dirHandle struct {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tin *inode.DirInode\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tMu syncutil.InvariantMutex\n\n\t\/\/ All entries in the directory. Populated the first time we need one.\n\t\/\/\n\t\/\/ INVARIANT: For each i, entries[i+1].Offset == entries[i].Offset + 1\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tentries []fuseutil.Dirent\n\n\t\/\/ Has entries yet been populated?\n\t\/\/\n\t\/\/ INVARIANT: If !entriesValid, then len(entries) == 0\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tentriesValid bool\n}\n\n\/\/ Create a directory handle that obtains listings from the supplied inode.\nfunc newDirHandle(in *inode.DirInode) (dh *dirHandle) {\n\t\/\/ Set up the basic struct.\n\tdh = &dirHandle{\n\t\tin: in,\n\t}\n\n\t\/\/ Set up invariant checking.\n\tdh.Mu = syncutil.NewInvariantMutex(dh.checkInvariants)\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Dirents, sorted by name.\ntype SortedDirents []fuseutil.Dirent\n\nfunc (p SortedDirents) Len() int           { return len(p) }\nfunc (p SortedDirents) Less(i, j int) bool { return p[i].Name < p[j].Name }\nfunc (p SortedDirents) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }\n\nfunc (dh *dirHandle) checkInvariants() {\n\t\/\/ INVARIANT: For each i, entries[i+1].Offset == entries[i].Offset + 1\n\tfor i := 0; i < len(dh.entries)-1; i++ {\n\t\tif !(dh.entries[i+1].Offset == dh.entries[i].Offset+1) {\n\t\t\tpanic(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"Unexpected offset sequence: %v, %v\",\n\t\t\t\t\tdh.entries[i].Offset,\n\t\t\t\t\tdh.entries[i+1].Offset))\n\t\t}\n\t}\n\n\t\/\/ INVARIANT: If !entriesValid, then len(entries) == 0\n\tif !dh.entriesValid && len(dh.entries) != 0 {\n\t\tpanic(\"Unexpected non-empty entries slice\")\n\t}\n}\n\n\/\/ Read some entries from the directory inode. Return newTok == \"\" (possibly\n\/\/ with a non-empty list of entries) when the end of the directory has been\n\/\/ hit.\n\/\/\n\/\/ The contents of the entries' Offset fields are undefined. This function\n\/\/ always behaves as if implicit directories are defined; see notes on\n\/\/ DirInode.ReadEntries.\nfunc readSomeEntries(\n\tctx context.Context,\n\tin *inode.DirInode,\n\ttok string) (entries []fuseutil.Dirent, newTok string, err error) {\n\tentries, newTok, err = in.ReadEntries(ctx, tok)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ReadEntries: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Return a bogus inode ID for each entry, but not the root inode ID.\n\t\/\/\n\t\/\/ NOTE(jacobsa): As far as I can tell this is harmless. Minting and\n\t\/\/ returning a real inode ID is difficult because fuse does not count\n\t\/\/ readdir as an operation that increases the inode ID's lookup count and\n\t\/\/ we therefore don't get a forget for it later, but we would like to not\n\t\/\/ have to remember every inode ID that we've ever minted for readdir.\n\t\/\/\n\t\/\/ If it turns out this is not harmless, we'll need to switch to something\n\t\/\/ like inode IDs based on (object name, generation) hashes. But then what\n\t\/\/ about the birthday problem? And more importantly, what about our\n\t\/\/ semantic of not minting a new inode ID when the generation changes due\n\t\/\/ to a local action?\n\tfor i, _ := range entries {\n\t\tentries[i].Inode = fuseops.RootInodeID + 1\n\t}\n\n\treturn\n}\n\n\/\/ Read all entries for the directory, making no effort to deal with\n\/\/ conflicting names or the lack of implicit directories (see notes on\n\/\/ DirInode.ReadEntries).\n\/\/\n\/\/ Write entries to the supplied channel, without closing. Entry Offset fields\n\/\/ have unspecified contents.\nfunc readEntries(\n\tctx context.Context,\n\tin *inode.DirInode,\n\tentries chan<- fuseutil.Dirent) (err error) {\n\tvar tok string\n\tfor {\n\t\t\/\/ Read a batch.\n\t\tvar batch []fuseutil.Dirent\n\n\t\tbatch, tok, err = readSomeEntries(ctx, in, tok)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Write each to the channel.\n\t\tfor _, e := range batch {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\terr = ctx.Err()\n\t\t\t\treturn\n\n\t\t\tcase entries <- e:\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Are we done?\n\t\tif tok == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc readAllEntries(\n\tctx context.Context,\n\tin *inode.DirInode) (entries SortedDirents, err error) {\n\tb := syncutil.NewBundle(ctx)\n\n\t\/\/ Ensure that our result is sorted, with correct offset fields.\n\tdefer func() {\n\t\tsort.Sort(entries)\n\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tentries[i].Offset = fuseops.DirOffset(i) + 1\n\t\t}\n\t}()\n\n\t\/\/ Read into a channel.\n\tc := make(chan fuseutil.Dirent, 100)\n\tb.Add(func(ctx context.Context) (err error) {\n\t\tdefer close(c)\n\t\terr = readEntries(ctx, in, c)\n\t\treturn\n\t})\n\n\t\/\/ Accumulate into the slice.\n\tb.Add(func(ctx context.Context) (err error) {\n\t\tfor e := range c {\n\t\t\tentries = append(entries, e)\n\t\t}\n\n\t\treturn\n\t})\n\n\t\/\/ Wait.\n\terr = b.Join()\n\n\treturn\n}\n\n\/\/ Resolve name conflicts between file objects and directory objects (e.g. the\n\/\/ objects \"foo\/bar\" and \"foo\/bar\/\") by appending U+000A, which is illegal in\n\/\/ GCS object names, to conflicting file names.\n\/\/\n\/\/ Input must be sorted by name.\nfunc fixConflictingNames(entries []fuseutil.Dirent) (err error) {\n\t\/\/ Sanity check.\n\tif !sort.IsSorted(SortedDirents(entries)) {\n\t\terr = fmt.Errorf(\"Expected sorted input\")\n\t\treturn\n\t}\n\n\t\/\/ Examine each adjacent pair of names.\n\tfor i, _ := range entries {\n\t\te := &entries[i]\n\n\t\t\/\/ Find the previous entry.\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tprev := &entries[i-1]\n\n\t\t\/\/ Does the pair have matching names?\n\t\tif e.Name != prev.Name {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Repair whichever is the file, remembering that there's no way to get any\n\t\t\/\/ other type in the mix.\n\t\tif e.Type == fuseutil.DT_File {\n\t\t\te.Name += inode.ConflictingFileNameSuffix\n\t\t} else {\n\t\t\tif prev.Type != fuseutil.DT_File {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected type for entry: %v\", prev))\n\t\t\t}\n\t\t\tprev.Name += inode.ConflictingFileNameSuffix\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Handle a request to read from the directory, without responding.\n\/\/\n\/\/ Special case: we assume that a zero offset indicates that rewinddir has been\n\/\/ called (since fuse gives us no way to intercept and know for sure), and\n\/\/ start the listing process over again.\n\/\/\n\/\/ LOCKS_REQUIRED(dh.Mu)\nfunc (dh *dirHandle) ReadDir(\n\top *fuseops.ReadDirOp) (err error) {\n\t\/\/ If the request is for offset zero, we assume that either this is the first\n\t\/\/ call or rewinddir has been called. Reset state.\n\tif op.Offset == 0 {\n\t\tdh.entries = nil\n\t\tdh.entriesValid = false\n\t}\n\n\t\/\/ Do we need to read entries from GCS?\n\tif !dh.entriesValid {\n\t\t\/\/ Read entries.\n\t\tvar entries []fuseutil.Dirent\n\t\tentries, err = readAllEntries(op.Context(), dh.in)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"readAllEntries: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Fix name conflicts.\n\t\terr = fixConflictingNames(entries)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"fixConflictingNames: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Update state.\n\t\tdh.entries = entries\n\t\tdh.entriesValid = true\n\t}\n\n\t\/\/ Is the offset past the end of what we have buffered? If so, this must be\n\t\/\/ an invalid seekdir according to posix.\n\tindex := int(op.Offset)\n\tif index > len(dh.entries) {\n\t\terr = fuse.EINVAL\n\t\treturn\n\t}\n\n\t\/\/ We copy out entries until we run out of entries or space.\n\tfor i := index; i < len(dh.entries); i++ {\n\t\top.Data = fuseutil.AppendDirent(op.Data, dh.entries[i])\n\t\tif len(op.Data) > op.Size {\n\t\t\top.Data = op.Data[:op.Size]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar arch string\nvar supportedArch = []string{\"amd64\", \"arm32v7\", \"arm64v8\"}\nvar defaultArch = \"amd64\"\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}\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\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\terr := CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/v4.1.0-1\/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\terr := CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/v4.1.0-1\/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\treturn docker.Build(IntermediateDockerImageName, dockerfile, \".\")\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\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 Dockerhub\nvar DockerPushCmd = &cobra.Command{\n\tUse:   \"push-image\",\n\tShort: \"Publish Authelia docker image to Dockerhub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcheckArchIsSupported(arch)\n\t\tpublishDockerImage(arch)\n\t},\n}\n\n\/\/ DockerManifestCmd Command for pushing Authelia docker manifest to Dockerhub\nvar DockerManifestCmd = &cobra.Command{\n\tUse:   \"push-manifest\",\n\tShort: \"Publish Authelia docker manifest to Dockerhub\",\n\tRun: func(cmd *cobra.Command, args []string) {\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\tpanic(errors.New(\"DOCKER_USERNAME is empty\"))\n\t}\n\n\tif password == \"\" {\n\t\tpanic(errors.New(\"DOCKER_PASSWORD is empty\"))\n\t}\n\n\tfmt.Println(\"Login to dockerhub as \" + username)\n\terr := docker.Login(username, password)\n\n\tif err != nil {\n\t\tfmt.Println(\"Login to dockerhub failed\")\n\t\tpanic(err)\n\t}\n}\n\nfunc deploy(docker *Docker, tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\tfmt.Println(\"===================================================\")\n\tfmt.Println(\"Docker image \" + imageWithTag + \" will be deployed on Dockerhub.\")\n\tfmt.Println(\"===================================================\")\n\n\terr := docker.Tag(DockerImageName, imageWithTag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = docker.Push(imageWithTag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc deployManifest(docker *Docker, tag string, amd64tag string, arm32v7tag string, arm64v8tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\tfmt.Println(\"===================================================\")\n\tfmt.Println(\"Docker manifest \" + imageWithTag + \" will be deployed on Dockerhub.\")\n\tfmt.Println(\"===================================================\")\n\n\terr := docker.Tag(DockerImageName, imageWithTag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = docker.Manifest(imageWithTag, amd64tag, arm32v7tag, arm64v8tag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc publishDockerImage(arch string) {\n\tdocker := &Docker{}\n\n\ttravisBranch := os.Getenv(\"TRAVIS_BRANCH\")\n\ttravisPullRequest := os.Getenv(\"TRAVIS_PULL_REQUEST\")\n\ttravisTag := os.Getenv(\"TRAVIS_TAG\")\n\n\tif travisBranch == \"master\" && travisPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\t} else if travisTag != \"\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, travisTag+\"-\"+arch)\n\t\tdeploy(docker, \"latest-\"+arch)\n\t} else {\n\t\tfmt.Println(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\ttravisBranch := os.Getenv(\"TRAVIS_BRANCH\")\n\ttravisPullRequest := os.Getenv(\"TRAVIS_PULL_REQUEST\")\n\ttravisTag := os.Getenv(\"TRAVIS_TAG\")\n\n\tif travisBranch == \"master\" && travisPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t} else if travisTag != \"\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, travisTag, travisTag+\"-amd64\", travisTag+\"-arm32v7\", travisTag+\"-arm64v8\")\n\t\tdeployManifest(docker, \"latest\", \"latest-amd64\", \"latest-arm32v7\", \"latest-arm64v8\")\n\t} else {\n\t\tfmt.Println(\"Docker manifest will not be published\")\n\t}\n}\n<commit_msg>Fix docker manifest push<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar arch string\nvar supportedArch = []string{\"amd64\", \"arm32v7\", \"arm64v8\"}\nvar defaultArch = \"amd64\"\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}\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\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\terr := CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/v4.1.0-1\/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\terr := CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\terr = CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/v4.1.0-1\/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\treturn docker.Build(IntermediateDockerImageName, dockerfile, \".\")\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\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 Dockerhub\nvar DockerPushCmd = &cobra.Command{\n\tUse:   \"push-image\",\n\tShort: \"Publish Authelia docker image to Dockerhub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcheckArchIsSupported(arch)\n\t\tpublishDockerImage(arch)\n\t},\n}\n\n\/\/ DockerManifestCmd Command for pushing Authelia docker manifest to Dockerhub\nvar DockerManifestCmd = &cobra.Command{\n\tUse:   \"push-manifest\",\n\tShort: \"Publish Authelia docker manifest to Dockerhub\",\n\tRun: func(cmd *cobra.Command, args []string) {\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\tpanic(errors.New(\"DOCKER_USERNAME is empty\"))\n\t}\n\n\tif password == \"\" {\n\t\tpanic(errors.New(\"DOCKER_PASSWORD is empty\"))\n\t}\n\n\tfmt.Println(\"Login to dockerhub as \" + username)\n\terr := docker.Login(username, password)\n\n\tif err != nil {\n\t\tfmt.Println(\"Login to dockerhub failed\")\n\t\tpanic(err)\n\t}\n}\n\nfunc deploy(docker *Docker, tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\tfmt.Println(\"===================================================\")\n\tfmt.Println(\"Docker image \" + imageWithTag + \" will be deployed on Dockerhub.\")\n\tfmt.Println(\"===================================================\")\n\n\terr := docker.Tag(DockerImageName, imageWithTag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = docker.Push(imageWithTag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc deployManifest(docker *Docker, tag string, amd64tag string, arm32v7tag string, arm64v8tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\tfmt.Println(\"===================================================\")\n\tfmt.Println(\"Docker manifest \" + imageWithTag + \" will be deployed on Dockerhub.\")\n\tfmt.Println(\"===================================================\")\n\n\terr := docker.Manifest(imageWithTag, amd64tag, arm32v7tag, arm64v8tag)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc publishDockerImage(arch string) {\n\tdocker := &Docker{}\n\n\ttravisBranch := os.Getenv(\"TRAVIS_BRANCH\")\n\ttravisPullRequest := os.Getenv(\"TRAVIS_PULL_REQUEST\")\n\ttravisTag := os.Getenv(\"TRAVIS_TAG\")\n\n\tif travisBranch == \"master\" && travisPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\t} else if travisTag != \"\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, travisTag+\"-\"+arch)\n\t\tdeploy(docker, \"latest-\"+arch)\n\t} else {\n\t\tfmt.Println(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\ttravisBranch := os.Getenv(\"TRAVIS_BRANCH\")\n\ttravisPullRequest := os.Getenv(\"TRAVIS_PULL_REQUEST\")\n\ttravisTag := os.Getenv(\"TRAVIS_TAG\")\n\n\tif travisBranch == \"master\" && travisPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t} else if travisTag != \"\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, travisTag, travisTag+\"-amd64\", travisTag+\"-arm32v7\", travisTag+\"-arm64v8\")\n\t\tdeployManifest(docker, \"latest\", \"latest-amd64\", \"latest-arm32v7\", \"latest-arm64v8\")\n\t} else {\n\t\tfmt.Println(\"Docker manifest will not be published\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package process\n\nimport (\n    \"bytes\"\n    \"io\"\n    \"os\/exec\"\n    \"github.com\/johnny-morrice\/pipeline\"\n)\n\n\/\/ Config creates a new Info, given the args, and sends it to stdout.\nfunc Config(stdout, stderr io.Writer, args []string) error {\n    config := configbrot(args)\n    return runPipeCmd(config, &bytes.Buffer{}, stdout, stderr)\n}\n\n\/\/ Render sends a new fractal image to the passed stdout pipe, corresponding to the Info\n\/\/ serialized in stdin.\nfunc Render(stdin io.Reader, stdout, stderr io.Writer) error {\n    render := renderbrot()\n    return runPipeCmd(render, stdin, stdout, stderr)\n}\n\n\/\/ ConfigRender sends a new fractal image to the passed stdout pipe, corresponding to configbrot's\n\/\/ processing of the args slice.\nfunc ConfigRender(stdout, stderr io.Writer, args []string) error {\n    config := configbrot(args)\n    render := renderbrot()\n\n    pl := pipeline.New(&bytes.Buffer{}, stdout, stderr)\n    pl.Chain(config, render)\n    return pl.Exec()\n}\n\n\/\/ Zoom magnifies a section of the Info read from stdin, sending it to stdout.\nfunc Zoom(stdin io.Reader, stdout, stderr io.Writer, args[]string) error {\n    zoom := zoombrot(args)\n    return runPipeCmd(zoom, stdin, stdout, stderr)\n}\n\n\/\/ Zoom reads Info from stdin, and sends a fractal to stdout, returning the magnified Info,\n\/\/ serialized as a io.Reader.\nfunc ZoomRender(stdin io.Reader, stdout, stderr io.Writer, args []string) (io.Reader, error) {\n    zoomBuff := &bytes.Buffer{}\n    zoomerr := Zoom(stdin, zoomBuff, stderr, args)\n    if zoomerr != nil {\n        return nil, zoomerr\n    }\n\n    outbuff := &bytes.Buffer{}\n    rendin := io.TeeReader(zoomBuff, outbuff)\n\n    err := Render(rendin, stdout, stderr)\n\n    return outbuff, err\n}\n\nfunc zoombrot(args []string) *exec.Cmd {\n    return exec.Command(\"zoombrot\", args...)\n}\n\nfunc configbrot(args []string) *exec.Cmd {\n    return exec.Command(\"configbrot\", args...)\n}\n\nfunc renderbrot() *exec.Cmd {\n    return exec.Command(\"renderbrot\")\n}\n\nfunc runPipeCmd(cmd *exec.Cmd, stdin io.Reader, stdout, stderr io.Writer) error {\n    cmd.Stdin = stdin\n    cmd.Stdout = stdout\n    cmd.Stderr = stderr\n    return cmd.Run()\n}<commit_msg>Add types to io streams<commit_after>package process\n\nimport (\n    \"bytes\"\n    \"io\"\n    \"os\/exec\"\n    \"github.com\/johnny-morrice\/pipeline\"\n)\n\ntype Infow io.Writer\ntype Infor io.Reader\ntype Pngw io.Writer\ntype Pngr io.Reader\n\nfunc PngBuff() (Pngr, Pngw) {\n    buff := &bytes.Buffer{}\n    return Pngr(buff), Pngw(buff)\n}\n\nfunc InfoBuff() (Infor, Infow) {\n    buff := &bytes.Buffer{}\n    return Infor(buff), Infow(buff)\n}\n\n\/\/ Config creates a new Info, given the args, and sends it to stdout.\nfunc Config(stdout Infow, stderr io.Writer, args []string) error {\n    config := configbrot(args)\n    return runPipeCmd(config, &bytes.Buffer{}, stdout, stderr)\n}\n\n\/\/ Render sends a new fractal image to the passed stdout pipe, corresponding to the Info\n\/\/ serialized in stdin.\nfunc Render(stdin Infor, stdout Pngw, stderr io.Writer) error {\n    render := renderbrot()\n    return runPipeCmd(render, stdin, stdout, stderr)\n}\n\n\/\/ ConfigRender sends a new fractal image to the passed stdout pipe, corresponding to configbrot's\n\/\/ processing of the args slice.\nfunc ConfigRender(stdout Pngw, stderr io.Writer, args []string) error {\n    config := configbrot(args)\n    render := renderbrot()\n\n    pl := pipeline.New(&bytes.Buffer{}, stdout, stderr)\n    pl.Chain(config, render)\n    return pl.Exec()\n}\n\n\/\/ Zoom magnifies a section of the Info read from stdin, sending it to stdout.\nfunc Zoom(stdin Infor, stdout Infow, stderr io.Writer, args[]string) error {\n    zoom := zoombrot(args)\n    return runPipeCmd(zoom, stdin, stdout, stderr)\n}\n\n\/\/ Zoom reads Info from stdin, and sends a fractal to stdout, returning the magnified Info,\n\/\/ serialized as an Infor.\nfunc ZoomRender(stdin Infor, stdout Pngw, stderr io.Writer, args []string) (Infor, error) {\n    zoomBuff := &bytes.Buffer{}\n    zoomerr := Zoom(stdin, zoomBuff, stderr, args)\n    if zoomerr != nil {\n        return nil, zoomerr\n    }\n\n    outbuff := &bytes.Buffer{}\n    rendin := io.TeeReader(zoomBuff, outbuff)\n\n    err := Render(rendin, stdout, stderr)\n\n    return outbuff, err\n}\n\nfunc zoombrot(args []string) *exec.Cmd {\n    return exec.Command(\"zoombrot\", args...)\n}\n\nfunc configbrot(args []string) *exec.Cmd {\n    return exec.Command(\"configbrot\", args...)\n}\n\nfunc renderbrot() *exec.Cmd {\n    return exec.Command(\"renderbrot\")\n}\n\nfunc runPipeCmd(cmd *exec.Cmd, stdin io.Reader, stdout, stderr io.Writer) error {\n    cmd.Stdin = stdin\n    cmd.Stdout = stdout\n    cmd.Stderr = stderr\n    return cmd.Run()\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\tconsole \"github.com\/AsynkronIT\/goconsole\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/mailbox\"\n)\n\n\/\/ sent to producer to request more work\ntype requestMoreWork struct {\n\titems int\n}\ntype requestWorkBehavior struct {\n\ttokens   int64\n\tproducer *actor.PID\n}\n\nfunc (m *requestWorkBehavior) MailboxStarted() {\n\tm.requestMore()\n}\nfunc (m *requestWorkBehavior) MessagePosted(msg interface{}) {\n\n}\nfunc (m *requestWorkBehavior) MessageReceived(msg interface{}) {\n\tatomic.AddInt64(&m.tokens, -1)\n\tif m.tokens == 0 {\n\t\tm.requestMore()\n\t}\n}\nfunc (m *requestWorkBehavior) MailboxEmpty() {\n}\n\nfunc (m *requestWorkBehavior) requestMore() {\n\tlog.Println(\"Requesting more tokens\")\n\tm.tokens = 50\n\tcontext.Send(m.producer, &requestMoreWork{items: 50})\n}\n\ntype producer struct {\n\trequestedWork int\n\tworker        *actor.PID\n}\n\nfunc (p *producer) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *actor.Started:\n\t\t\/\/ spawn our worker\n\t\tworkerProps := actor.PropsFromProducer(func() actor.Actor { return &worker{} }).WithMailbox(mailbox.Unbounded(&requestWorkBehavior{\n\t\t\tproducer: ctx.Self(),\n\t\t}))\n\t\tp.worker = ctx.Spawn(workerProps)\n\tcase *requestMoreWork:\n\t\tp.requestedWork += msg.items\n\t\tlog.Println(\"Producer got a new work request\")\n\t\tctx.Send(ctx.Self(), &produce{})\n\tcase *produce:\n\t\t\/\/ produce more work\n\t\tlog.Println(\"Producer is producing work\")\n\t\tctx.Send(p.worker, &work{})\n\n\t\t\/\/ decrease our workload and tell ourselves to produce more work\n\t\tif p.requestedWork > 0 {\n\t\t\tp.requestedWork--\n\t\t\tctx.Send(ctx.Self(), &produce{})\n\t\t}\n\t}\n}\n\ntype produce struct{}\n\ntype worker struct {\n}\n\nfunc (w *worker) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *work:\n\t\tlog.Printf(\"Worker is working %v\", msg)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\ntype work struct {\n}\n\nvar context *actor.RootContext\n\nfunc main() {\n\tcontext := actor.EmptyRootContext\n\tproducerProps := actor.PropsFromProducer(func() actor.Actor { return &producer{} })\n\tcontext.Spawn(producerProps)\n\n\tconsole.ReadLine()\n}\n<commit_msg>fix(examples\/backpressure): initialize the global context insted local context<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\tconsole \"github.com\/AsynkronIT\/goconsole\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n\t\"github.com\/AsynkronIT\/protoactor-go\/mailbox\"\n)\n\n\/\/ sent to producer to request more work\ntype requestMoreWork struct {\n\titems int\n}\ntype requestWorkBehavior struct {\n\ttokens   int64\n\tproducer *actor.PID\n}\n\nfunc (m *requestWorkBehavior) MailboxStarted() {\n\tm.requestMore()\n}\nfunc (m *requestWorkBehavior) MessagePosted(msg interface{}) {\n\n}\nfunc (m *requestWorkBehavior) MessageReceived(msg interface{}) {\n\tatomic.AddInt64(&m.tokens, -1)\n\tif m.tokens == 0 {\n\t\tm.requestMore()\n\t}\n}\nfunc (m *requestWorkBehavior) MailboxEmpty() {\n}\n\nfunc (m *requestWorkBehavior) requestMore() {\n\tlog.Println(\"Requesting more tokens\")\n\tm.tokens = 50\n\tcontext.Send(m.producer, &requestMoreWork{items: 50})\n}\n\ntype producer struct {\n\trequestedWork int\n\tworker        *actor.PID\n}\n\nfunc (p *producer) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *actor.Started:\n\t\t\/\/ spawn our worker\n\t\tworkerProps := actor.PropsFromProducer(func() actor.Actor { return &worker{} }).WithMailbox(mailbox.Unbounded(&requestWorkBehavior{\n\t\t\tproducer: ctx.Self(),\n\t\t}))\n\t\tp.worker = ctx.Spawn(workerProps)\n\tcase *requestMoreWork:\n\t\tp.requestedWork += msg.items\n\t\tlog.Println(\"Producer got a new work request\")\n\t\tctx.Send(ctx.Self(), &produce{})\n\tcase *produce:\n\t\t\/\/ produce more work\n\t\tlog.Println(\"Producer is producing work\")\n\t\tctx.Send(p.worker, &work{})\n\n\t\t\/\/ decrease our workload and tell ourselves to produce more work\n\t\tif p.requestedWork > 0 {\n\t\t\tp.requestedWork--\n\t\t\tctx.Send(ctx.Self(), &produce{})\n\t\t}\n\t}\n}\n\ntype produce struct{}\n\ntype worker struct {\n}\n\nfunc (w *worker) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *work:\n\t\tlog.Printf(\"Worker is working %v\", msg)\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\ntype work struct {\n}\n\nvar context *actor.RootContext\n\nfunc main() {\n\tcontext = actor.EmptyRootContext\n\tproducerProps := actor.PropsFromProducer(func() actor.Actor { return &producer{} })\n\tcontext.Spawn(producerProps)\n\n\tconsole.ReadLine()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/flynn\/flynn\/Godeps\/_workspace\/src\/github.com\/flynn\/go-docopt\"\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\/cluster\"\n\t\"github.com\/flynn\/flynn\/pkg\/exec\"\n\t\"github.com\/flynn\/flynn\/pkg\/random\"\n\t\"github.com\/flynn\/flynn\/pkg\/version\"\n)\n\nvar clusterc = cluster.NewClient()\n\nfunc init() {\n\tlog.SetFlags(0)\n}\n\nvar typesPattern = regexp.MustCompile(\"types.* -> (.+)\\n\")\n\nconst blobstoreURL = \"http:\/\/blobstore.discoverd\"\nconst scaleTimeout = 20 * time.Second\n\nfunc parsePairs(args *docopt.Args, str string) (map[string]string, error) {\n\tpairs := args.All[str].([]string)\n\titem := make(map[string]string, len(pairs))\n\tfor _, s := range pairs {\n\t\tv := strings.SplitN(s, \"=\", 2)\n\t\tif len(v) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid var format: %q\", s)\n\t\t}\n\t\titem[v[0]] = v[1]\n\t}\n\treturn item, nil\n}\n\nfunc main() {\n\tclient, err := controller.NewClient(\"\", os.Getenv(\"CONTROLLER_KEY\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to connect to controller:\", err)\n\t}\n\n\tusage := `\nUsage: flynn-receiver <app> <rev> [-e <var>=<val>]... [-m <key>=<val>]...\n\nOptions:\n\t-e,--env <var>=<val>\n\t-m,--meta <key>=<val>\n`[1:]\n\targs, _ := docopt.Parse(usage, nil, true, version.String(), false)\n\n\tappName := args.String[\"<app>\"]\n\tenv, err := parsePairs(args, \"--env\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmeta, err := parsePairs(args, \"--meta\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tapp, err := client.GetApp(appName)\n\tif err == controller.ErrNotFound {\n\t\tlog.Fatalf(\"Unknown app %q\", appName)\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error retrieving app:\", err)\n\t}\n\tprevRelease, err := client.GetAppRelease(app.Name)\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error getting current app release:\", err)\n\t}\n\n\tfmt.Printf(\"-----> Building %s...\\n\", app.Name)\n\n\tjobEnv := make(map[string]string)\n\tjobEnv[\"BUILD_CACHE_URL\"] = fmt.Sprintf(\"%s\/%s-cache.tgz\", blobstoreURL, app.ID)\n\tif buildpackURL, ok := env[\"BUILDPACK_URL\"]; ok {\n\t\tjobEnv[\"BUILDPACK_URL\"] = buildpackURL\n\t} else if buildpackURL, ok := prevRelease.Env[\"BUILDPACK_URL\"]; ok {\n\t\tjobEnv[\"BUILDPACK_URL\"] = buildpackURL\n\t}\n\tfor _, k := range []string{\"SSH_CLIENT_KEY\", \"SSH_CLIENT_HOSTS\"} {\n\t\tif v := os.Getenv(k); v != \"\" {\n\t\t\tjobEnv[k] = v\n\t\t}\n\t}\n\tslugURL := fmt.Sprintf(\"%s\/%s\/slug.tgz\", blobstoreURL, random.UUID())\n\n\tjob := &host.Job{\n\t\tConfig: host.ContainerConfig{\n\t\t\tCmd:        []string{slugURL},\n\t\t\tEnv:        jobEnv,\n\t\t\tStdin:      true,\n\t\t\tDisableLog: true,\n\t\t},\n\t\tPartition: \"background\",\n\t\tMetadata: map[string]string{\n\t\t\t\"flynn-controller.app\":      app.ID,\n\t\t\t\"flynn-controller.app_name\": app.Name,\n\t\t\t\"flynn-controller.release\":  prevRelease.ID,\n\t\t\t\"flynn-controller.type\":     \"slugbuilder\",\n\t\t},\n\t}\n\tif sb, ok := prevRelease.Processes[\"slugbuilder\"]; ok {\n\t\tjob.Resources = sb.Resources\n\t}\n\n\tcmd := exec.Job(exec.DockerImage(os.Getenv(\"SLUGBUILDER_IMAGE_URI\")), job)\n\tvar output bytes.Buffer\n\tcmd.Stdout = io.MultiWriter(os.Stdout, &output)\n\tcmd.Stderr = os.Stderr\n\n\tif len(prevRelease.Env) > 0 {\n\t\tstdin, err := cmd.StdinPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tgo appendEnvDir(os.Stdin, stdin, prevRelease.Env)\n\t} else {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatalln(\"Build failed:\", err)\n\t}\n\n\tvar types []string\n\tif match := typesPattern.FindSubmatch(output.Bytes()); match != nil {\n\t\ttypes = strings.Split(string(match[1]), \", \")\n\t}\n\n\tfmt.Printf(\"-----> Creating release...\\n\")\n\n\tartifact := &ct.Artifact{Type: host.ArtifactTypeDocker, URI: os.Getenv(\"SLUGRUNNER_IMAGE_URI\")}\n\tif err := client.CreateArtifact(artifact); err != nil {\n\t\tlog.Fatalln(\"Error creating image artifact:\", err)\n\t}\n\n\tslugArtifact := &ct.Artifact{\n\t\tType: host.ArtifactTypeFile,\n\t\tURI:  slugURL,\n\t\tMeta: map[string]string{\"blobstore\": \"true\"},\n\t}\n\tif err := client.CreateArtifact(slugArtifact); err != nil {\n\t\tlog.Fatalln(\"Error creating slug artifact:\", err)\n\t}\n\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{artifact.ID, slugArtifact.ID},\n\t\tEnv:         prevRelease.Env,\n\t\tMeta:        prevRelease.Meta,\n\t}\n\tif release.Meta == nil {\n\t\trelease.Meta = make(map[string]string, len(meta))\n\t}\n\tif release.Env == nil {\n\t\trelease.Env = make(map[string]string, len(env))\n\t}\n\tfor k, v := range env {\n\t\trelease.Env[k] = v\n\t}\n\tfor k, v := range meta {\n\t\trelease.Meta[k] = v\n\t}\n\tprocs := make(map[string]ct.ProcessType)\n\tfor _, t := range types {\n\t\tproc := prevRelease.Processes[t]\n\t\tproc.Cmd = []string{\"start\", t}\n\t\tif t == \"web\" || strings.HasSuffix(t, \"-web\") {\n\t\t\tproc.Service = app.Name + \"-\" + t\n\t\t\tproc.Ports = []ct.Port{{\n\t\t\t\tPort:  8080,\n\t\t\t\tProto: \"tcp\",\n\t\t\t\tService: &host.Service{\n\t\t\t\t\tName:   proc.Service,\n\t\t\t\t\tCreate: true,\n\t\t\t\t\tCheck:  &host.HealthCheck{Type: \"tcp\"},\n\t\t\t\t},\n\t\t\t}}\n\t\t}\n\t\tprocs[t] = proc\n\t}\n\trelease.Processes = procs\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\tlog.Fatalln(\"Error creating release:\", err)\n\t}\n\tif err := client.DeployAppRelease(app.Name, release.ID); err != nil {\n\t\tlog.Fatalln(\"Error deploying app release:\", err)\n\t}\n\n\tfmt.Println(\"=====> Application deployed\")\n\n\tif needsDefaultScale(app.ID, prevRelease.ID, procs, client) {\n\t\tformation := &ct.Formation{\n\t\t\tAppID:     app.ID,\n\t\t\tReleaseID: release.ID,\n\t\t\tProcesses: map[string]int{\"web\": 1},\n\t\t}\n\n\t\twatcher, err := client.WatchJobEvents(app.ID, release.ID)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error streaming job events\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer watcher.Close()\n\n\t\tif err := client.PutFormation(formation); err != nil {\n\t\t\tlog.Fatalln(\"Error putting formation:\", err)\n\t\t}\n\t\tfmt.Println(\"=====> Waiting for web job to start...\")\n\n\t\terr = watcher.WaitFor(ct.JobEvents{\"web\": ct.JobUpEvents(1)}, scaleTimeout, func(e *ct.Job) error {\n\t\t\tswitch e.State {\n\t\t\tcase ct.JobStateUp:\n\t\t\t\tfmt.Println(\"=====> Default web formation scaled to 1\")\n\t\t\tcase ct.JobStateDown:\n\t\t\t\treturn fmt.Errorf(\"Failed to scale web process type\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\t}\n}\n\n\/\/ needsDefaultScale indicates whether a release needs a default scale based on\n\/\/ whether it has a web process type and either has no previous release or no\n\/\/ previous scale.\nfunc needsDefaultScale(appID, prevReleaseID string, procs map[string]ct.ProcessType, client controller.Client) bool {\n\tif _, ok := procs[\"web\"]; !ok {\n\t\treturn false\n\t}\n\tif prevReleaseID == \"\" {\n\t\treturn true\n\t}\n\t_, err := client.GetFormation(appID, prevReleaseID)\n\treturn err == controller.ErrNotFound\n}\n\nfunc appendEnvDir(stdin io.Reader, pipe io.WriteCloser, env map[string]string) {\n\tdefer pipe.Close()\n\ttr := tar.NewReader(stdin)\n\ttw := tar.NewWriter(pipe)\n\tfor {\n\t\thdr, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\t\/\/ end of tar archive\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\thdr.Name = path.Join(\"app\", hdr.Name)\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := io.Copy(tw, tr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/ append env dir\n\tfor key, value := range env {\n\t\thdr := &tar.Header{\n\t\t\tName:    path.Join(\"env\", key),\n\t\t\tMode:    0644,\n\t\t\tModTime: time.Now(),\n\t\t\tSize:    int64(len(value)),\n\t\t}\n\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(value)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\thdr := &tar.Header{\n\t\tName:    \".ENV_DIR_bdca46b87df0537eaefe79bb632d37709ff1df18\",\n\t\tMode:    0400,\n\t\tModTime: time.Now(),\n\t\tSize:    0,\n\t}\n\tif err := tw.WriteHeader(hdr); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n<commit_msg>gitreceive\/receiver: Use deploy timeout when waiting for web job<commit_after>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/flynn\/flynn\/Godeps\/_workspace\/src\/github.com\/flynn\/go-docopt\"\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\/cluster\"\n\t\"github.com\/flynn\/flynn\/pkg\/exec\"\n\t\"github.com\/flynn\/flynn\/pkg\/random\"\n\t\"github.com\/flynn\/flynn\/pkg\/version\"\n)\n\nvar clusterc = cluster.NewClient()\n\nfunc init() {\n\tlog.SetFlags(0)\n}\n\nvar typesPattern = regexp.MustCompile(\"types.* -> (.+)\\n\")\n\nconst blobstoreURL = \"http:\/\/blobstore.discoverd\"\n\nfunc parsePairs(args *docopt.Args, str string) (map[string]string, error) {\n\tpairs := args.All[str].([]string)\n\titem := make(map[string]string, len(pairs))\n\tfor _, s := range pairs {\n\t\tv := strings.SplitN(s, \"=\", 2)\n\t\tif len(v) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid var format: %q\", s)\n\t\t}\n\t\titem[v[0]] = v[1]\n\t}\n\treturn item, nil\n}\n\nfunc main() {\n\tclient, err := controller.NewClient(\"\", os.Getenv(\"CONTROLLER_KEY\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to connect to controller:\", err)\n\t}\n\n\tusage := `\nUsage: flynn-receiver <app> <rev> [-e <var>=<val>]... [-m <key>=<val>]...\n\nOptions:\n\t-e,--env <var>=<val>\n\t-m,--meta <key>=<val>\n`[1:]\n\targs, _ := docopt.Parse(usage, nil, true, version.String(), false)\n\n\tappName := args.String[\"<app>\"]\n\tenv, err := parsePairs(args, \"--env\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tmeta, err := parsePairs(args, \"--meta\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tapp, err := client.GetApp(appName)\n\tif err == controller.ErrNotFound {\n\t\tlog.Fatalf(\"Unknown app %q\", appName)\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error retrieving app:\", err)\n\t}\n\tprevRelease, err := client.GetAppRelease(app.Name)\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\tlog.Fatalln(\"Error getting current app release:\", err)\n\t}\n\n\tfmt.Printf(\"-----> Building %s...\\n\", app.Name)\n\n\tjobEnv := make(map[string]string)\n\tjobEnv[\"BUILD_CACHE_URL\"] = fmt.Sprintf(\"%s\/%s-cache.tgz\", blobstoreURL, app.ID)\n\tif buildpackURL, ok := env[\"BUILDPACK_URL\"]; ok {\n\t\tjobEnv[\"BUILDPACK_URL\"] = buildpackURL\n\t} else if buildpackURL, ok := prevRelease.Env[\"BUILDPACK_URL\"]; ok {\n\t\tjobEnv[\"BUILDPACK_URL\"] = buildpackURL\n\t}\n\tfor _, k := range []string{\"SSH_CLIENT_KEY\", \"SSH_CLIENT_HOSTS\"} {\n\t\tif v := os.Getenv(k); v != \"\" {\n\t\t\tjobEnv[k] = v\n\t\t}\n\t}\n\tslugURL := fmt.Sprintf(\"%s\/%s\/slug.tgz\", blobstoreURL, random.UUID())\n\n\tjob := &host.Job{\n\t\tConfig: host.ContainerConfig{\n\t\t\tCmd:        []string{slugURL},\n\t\t\tEnv:        jobEnv,\n\t\t\tStdin:      true,\n\t\t\tDisableLog: true,\n\t\t},\n\t\tPartition: \"background\",\n\t\tMetadata: map[string]string{\n\t\t\t\"flynn-controller.app\":      app.ID,\n\t\t\t\"flynn-controller.app_name\": app.Name,\n\t\t\t\"flynn-controller.release\":  prevRelease.ID,\n\t\t\t\"flynn-controller.type\":     \"slugbuilder\",\n\t\t},\n\t}\n\tif sb, ok := prevRelease.Processes[\"slugbuilder\"]; ok {\n\t\tjob.Resources = sb.Resources\n\t}\n\n\tcmd := exec.Job(exec.DockerImage(os.Getenv(\"SLUGBUILDER_IMAGE_URI\")), job)\n\tvar output bytes.Buffer\n\tcmd.Stdout = io.MultiWriter(os.Stdout, &output)\n\tcmd.Stderr = os.Stderr\n\n\tif len(prevRelease.Env) > 0 {\n\t\tstdin, err := cmd.StdinPipe()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tgo appendEnvDir(os.Stdin, stdin, prevRelease.Env)\n\t} else {\n\t\tcmd.Stdin = os.Stdin\n\t}\n\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatalln(\"Build failed:\", err)\n\t}\n\n\tvar types []string\n\tif match := typesPattern.FindSubmatch(output.Bytes()); match != nil {\n\t\ttypes = strings.Split(string(match[1]), \", \")\n\t}\n\n\tfmt.Printf(\"-----> Creating release...\\n\")\n\n\tartifact := &ct.Artifact{Type: host.ArtifactTypeDocker, URI: os.Getenv(\"SLUGRUNNER_IMAGE_URI\")}\n\tif err := client.CreateArtifact(artifact); err != nil {\n\t\tlog.Fatalln(\"Error creating image artifact:\", err)\n\t}\n\n\tslugArtifact := &ct.Artifact{\n\t\tType: host.ArtifactTypeFile,\n\t\tURI:  slugURL,\n\t\tMeta: map[string]string{\"blobstore\": \"true\"},\n\t}\n\tif err := client.CreateArtifact(slugArtifact); err != nil {\n\t\tlog.Fatalln(\"Error creating slug artifact:\", err)\n\t}\n\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{artifact.ID, slugArtifact.ID},\n\t\tEnv:         prevRelease.Env,\n\t\tMeta:        prevRelease.Meta,\n\t}\n\tif release.Meta == nil {\n\t\trelease.Meta = make(map[string]string, len(meta))\n\t}\n\tif release.Env == nil {\n\t\trelease.Env = make(map[string]string, len(env))\n\t}\n\tfor k, v := range env {\n\t\trelease.Env[k] = v\n\t}\n\tfor k, v := range meta {\n\t\trelease.Meta[k] = v\n\t}\n\tprocs := make(map[string]ct.ProcessType)\n\tfor _, t := range types {\n\t\tproc := prevRelease.Processes[t]\n\t\tproc.Cmd = []string{\"start\", t}\n\t\tif t == \"web\" || strings.HasSuffix(t, \"-web\") {\n\t\t\tproc.Service = app.Name + \"-\" + t\n\t\t\tproc.Ports = []ct.Port{{\n\t\t\t\tPort:  8080,\n\t\t\t\tProto: \"tcp\",\n\t\t\t\tService: &host.Service{\n\t\t\t\t\tName:   proc.Service,\n\t\t\t\t\tCreate: true,\n\t\t\t\t\tCheck:  &host.HealthCheck{Type: \"tcp\"},\n\t\t\t\t},\n\t\t\t}}\n\t\t}\n\t\tprocs[t] = proc\n\t}\n\trelease.Processes = procs\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\tlog.Fatalln(\"Error creating release:\", err)\n\t}\n\tif err := client.DeployAppRelease(app.Name, release.ID); err != nil {\n\t\tlog.Fatalln(\"Error deploying app release:\", err)\n\t}\n\n\tfmt.Println(\"=====> Application deployed\")\n\n\tif needsDefaultScale(app.ID, prevRelease.ID, procs, client) {\n\t\tformation := &ct.Formation{\n\t\t\tAppID:     app.ID,\n\t\t\tReleaseID: release.ID,\n\t\t\tProcesses: map[string]int{\"web\": 1},\n\t\t}\n\n\t\twatcher, err := client.WatchJobEvents(app.ID, release.ID)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error streaming job events\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer watcher.Close()\n\n\t\tif err := client.PutFormation(formation); err != nil {\n\t\t\tlog.Fatalln(\"Error putting formation:\", err)\n\t\t}\n\t\tfmt.Println(\"=====> Waiting for web job to start...\")\n\n\t\terr = watcher.WaitFor(ct.JobEvents{\"web\": ct.JobUpEvents(1)}, time.Duration(app.DeployTimeout)*time.Second, func(e *ct.Job) error {\n\t\t\tswitch e.State {\n\t\t\tcase ct.JobStateUp:\n\t\t\t\tfmt.Println(\"=====> Default web formation scaled to 1\")\n\t\t\tcase ct.JobStateDown:\n\t\t\t\treturn fmt.Errorf(\"Failed to scale web process type\")\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err.Error())\n\t\t}\n\t}\n}\n\n\/\/ needsDefaultScale indicates whether a release needs a default scale based on\n\/\/ whether it has a web process type and either has no previous release or no\n\/\/ previous scale.\nfunc needsDefaultScale(appID, prevReleaseID string, procs map[string]ct.ProcessType, client controller.Client) bool {\n\tif _, ok := procs[\"web\"]; !ok {\n\t\treturn false\n\t}\n\tif prevReleaseID == \"\" {\n\t\treturn true\n\t}\n\t_, err := client.GetFormation(appID, prevReleaseID)\n\treturn err == controller.ErrNotFound\n}\n\nfunc appendEnvDir(stdin io.Reader, pipe io.WriteCloser, env map[string]string) {\n\tdefer pipe.Close()\n\ttr := tar.NewReader(stdin)\n\ttw := tar.NewWriter(pipe)\n\tfor {\n\t\thdr, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\t\/\/ end of tar archive\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\thdr.Name = path.Join(\"app\", hdr.Name)\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := io.Copy(tw, tr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/ append env dir\n\tfor key, value := range env {\n\t\thdr := &tar.Header{\n\t\t\tName:    path.Join(\"env\", key),\n\t\t\tMode:    0644,\n\t\t\tModTime: time.Now(),\n\t\t\tSize:    int64(len(value)),\n\t\t}\n\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(value)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\thdr := &tar.Header{\n\t\tName:    \".ENV_DIR_bdca46b87df0537eaefe79bb632d37709ff1df18\",\n\t\tMode:    0400,\n\t\tModTime: time.Now(),\n\t\tSize:    0,\n\t}\n\tif err := tw.WriteHeader(hdr); err != nil {\n\t\tlog.Fatalln(err)\n\t}\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\"fmt\"\n\t\"strings\"\n)\n\nvar (\n\t\/\/ Commit stores the current commit of this build, which includes the\n\t\/\/ most recent tag, the number of commits since that tag (if non-zero),\n\t\/\/ the commit hash, and a dirty marker. This should be set using the\n\t\/\/ -ldflags during compilation.\n\tCommit string\n\n\t\/\/ CommitHash stores the current commit hash of this build, this should\n\t\/\/ be set using the -ldflags during compilation.\n\tCommitHash string\n\n\t\/\/ RawTags contains the raw set of build tags, separated by commas. This\n\t\/\/ should be set using -ldflags during compilation.\n\tRawTags string\n\n\t\/\/ GoVersion stores the go version that the executable was compiled\n\t\/\/ with. This hsould be set using -ldflags during compilation.\n\tGoVersion string\n)\n\n\/\/ semanticAlphabet is the set of characters that are permitted for use in an\n\/\/ AppPreRelease.\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\t\/\/ AppMajor defines the major version of this binary.\n\tAppMajor uint = 0\n\n\t\/\/ AppMinor defines the minor version of this binary.\n\tAppMinor uint = 13\n\n\t\/\/ AppPatch defines the application patch for this binary.\n\tAppPatch uint = 0\n\n\t\/\/ AppPreRelease MUST only contain characters from semanticAlphabet\n\t\/\/ per the semantic versioning spec.\n\tAppPreRelease = \"beta.rc3\"\n)\n\nfunc init() {\n\t\/\/ Assert that AppPreRelease is valid according to the semantic\n\t\/\/ versioning guidelines for pre-release version and build metadata\n\t\/\/ strings. In particular it MUST only contain characters in\n\t\/\/ semanticAlphabet.\n\tfor _, r := range AppPreRelease {\n\t\tif !strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tpanic(fmt.Errorf(\"rune: %v is not in the semantic \"+\n\t\t\t\t\"alphabet\", r))\n\t\t}\n\t}\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 by\n\t\/\/ the semantic versioning spec is automatically appended and should not\n\t\/\/ be contained in the pre-release string.\n\tif AppPreRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, AppPreRelease)\n\t}\n\n\treturn version\n}\n\n\/\/ Tags returns the list of build tags that were compiled into the executable.\nfunc Tags() []string {\n\tif len(RawTags) == 0 {\n\t\treturn nil\n\t}\n\n\treturn strings.Split(RawTags, \",\")\n}\n<commit_msg>build: bump version to v0.13.0-beta.rc4<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\"fmt\"\n\t\"strings\"\n)\n\nvar (\n\t\/\/ Commit stores the current commit of this build, which includes the\n\t\/\/ most recent tag, the number of commits since that tag (if non-zero),\n\t\/\/ the commit hash, and a dirty marker. This should be set using the\n\t\/\/ -ldflags during compilation.\n\tCommit string\n\n\t\/\/ CommitHash stores the current commit hash of this build, this should\n\t\/\/ be set using the -ldflags during compilation.\n\tCommitHash string\n\n\t\/\/ RawTags contains the raw set of build tags, separated by commas. This\n\t\/\/ should be set using -ldflags during compilation.\n\tRawTags string\n\n\t\/\/ GoVersion stores the go version that the executable was compiled\n\t\/\/ with. This hsould be set using -ldflags during compilation.\n\tGoVersion string\n)\n\n\/\/ semanticAlphabet is the set of characters that are permitted for use in an\n\/\/ AppPreRelease.\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\t\/\/ AppMajor defines the major version of this binary.\n\tAppMajor uint = 0\n\n\t\/\/ AppMinor defines the minor version of this binary.\n\tAppMinor uint = 13\n\n\t\/\/ AppPatch defines the application patch for this binary.\n\tAppPatch uint = 0\n\n\t\/\/ AppPreRelease MUST only contain characters from semanticAlphabet\n\t\/\/ per the semantic versioning spec.\n\tAppPreRelease = \"beta.rc4\"\n)\n\nfunc init() {\n\t\/\/ Assert that AppPreRelease is valid according to the semantic\n\t\/\/ versioning guidelines for pre-release version and build metadata\n\t\/\/ strings. In particular it MUST only contain characters in\n\t\/\/ semanticAlphabet.\n\tfor _, r := range AppPreRelease {\n\t\tif !strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tpanic(fmt.Errorf(\"rune: %v is not in the semantic \"+\n\t\t\t\t\"alphabet\", r))\n\t\t}\n\t}\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 by\n\t\/\/ the semantic versioning spec is automatically appended and should not\n\t\/\/ be contained in the pre-release string.\n\tif AppPreRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, AppPreRelease)\n\t}\n\n\treturn version\n}\n\n\/\/ Tags returns the list of build tags that were compiled into the executable.\nfunc Tags() []string {\n\tif len(RawTags) == 0 {\n\t\treturn nil\n\t}\n\n\treturn strings.Split(RawTags, \",\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/mikedanese\/gazel\/third_party\/go\/path\/filepath\"\n\n\tbzl \"github.com\/bazelbuild\/buildifier\/core\"\n\t\"github.com\/golang\/glog\"\n)\n\nvar kubeRoot = flag.String(\"root\", \"\", \"root of kubernetes source\")\nvar dryRun = flag.Bool(\"dry-run\", false, \"run in dry mode\")\n\nfunc main() {\n\tflag.Parse()\n\tflag.Set(\"alsologtostderr\", \"true\")\n\tif *kubeRoot == \"\" {\n\t\tglog.Fatalf(\"-root argument is required\")\n\t}\n\tv := Venderor{\n\t\tctx: context(),\n\t}\n\tif len(flag.Args()) == 1 {\n\t\tv.updateSinglePkg(flag.Args()[0])\n\t} else {\n\t\tv.walkVendor()\n\t\tif err := v.walkRepo(); err != nil {\n\t\t\tglog.Fatalf(\"err: %v\", err)\n\t\t}\n\t}\n}\n\ntype Venderor struct {\n\tctx *build.Context\n}\n\nfunc writeHeaders(file *bzl.File) {\n\tpkgRule := bzl.Rule{\n\t\t&bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: \"package\"},\n\t\t},\n\t}\n\tpkgRule.SetAttr(\"default_visibility\", asExpr([]string{\"\/\/visibility:public\"}))\n\n\tfile.Stmt = append(file.Stmt,\n\t\t[]bzl.Expr{\n\t\t\tpkgRule.Call,\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX:    &bzl.LiteralExpr{Token: \"licenses\"},\n\t\t\t\tList: []bzl.Expr{asExpr([]string{\"notice\"})},\n\t\t\t},\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX: &bzl.LiteralExpr{Token: \"load\"},\n\t\t\t\tList: asExpr([]string{\n\t\t\t\t\t\"@io_bazel_rules_go\/\/go:def.bzl\",\n\t\t\t\t\t\"go_binary\",\n\t\t\t\t\t\"go_library\",\n\t\t\t\t\t\"go_test\",\n\t\t\t\t\t\"cgo_library\",\n\t\t\t\t}).(*bzl.ListExpr).List,\n\t\t\t},\n\t\t}...,\n\t)\n}\n\nfunc writeRules(file *bzl.File, rules []*bzl.Rule) {\n\tfor _, rule := range rules {\n\t\tfile.Stmt = append(file.Stmt, rule.Call)\n\t}\n}\n\nfunc (v *Venderor) resolve(ipath string) Label {\n\tif strings.HasPrefix(ipath, \"k8s.io\/kubernetes\") {\n\t\treturn Label{\n\t\t\tpkg: strings.TrimPrefix(ipath, \"k8s.io\/kubernetes\/\"),\n\t\t\ttag: \"go_default_library\",\n\t\t}\n\t}\n\treturn Label{\n\t\tpkg: \"vendor\",\n\t\ttag: ipath,\n\t}\n}\n\nfunc (v *Venderor) walk(root string, f func(path, ipath string, pkg *build.Package) error) error {\n\treturn sfilepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tipath, err := filepath.Rel(root, path)\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\t\tpkg, err := v.ctx.ImportDir(filepath.Join(*kubeRoot, path), build.ImportComment)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn f(path, ipath, pkg)\n\t})\n}\n\nfunc (v *Venderor) walkRepo() error {\n\tfor _, root := range []string{\n\t\t\".\/pkg\",\n\t\t\".\/cmd\",\n\t\t\".\/third_party\",\n\t\t\".\/plugin\",\n\t\t\".\/test\",\n\t\t\".\/federation\",\n\t} {\n\t\tif err := v.walk(root, v.updatePkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) updateSinglePkg(path string) error {\n\tpkg, err := v.ctx.ImportDir(\".\/\"+path, build.ImportComment)\n\tif err != nil {\n\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn v.updatePkg(path, \"\", pkg)\n}\n\nfunc (v *Venderor) updatePkg(path, _ string, pkg *build.Package) error {\n\tvar rules []*bzl.Rule\n\n\tvar attrs Attrs = make(Attrs)\n\tsrcs := asExpr(merge(pkg.GoFiles, pkg.SFiles)).(*bzl.ListExpr)\n\n\tdeps := v.extractDeps(pkg.Imports)\n\n\tif len(srcs.List) == 0 {\n\t\treturn nil\n\t}\n\tattrs.Set(\"srcs\", srcs)\n\n\tif len(deps.List) > 0 {\n\t\tattrs.Set(\"deps\", deps)\n\t}\n\n\tif pkg.IsCommand() {\n\t\trules = append(rules, newRule(\"go_binary\", filepath.Base(pkg.Dir), attrs))\n\t} else {\n\t\trules = append(rules, newRule(\"go_library\", \"go_default_library\", attrs))\n\t\tif len(pkg.TestGoFiles) != 0 {\n\t\t\trules = append(rules, newRule(\"go_test\", \"go_default_test\", map[string]bzl.Expr{\n\t\t\t\t\"srcs\":    asExpr(pkg.TestGoFiles),\n\t\t\t\t\"deps\":    v.extractDeps(pkg.TestImports),\n\t\t\t\t\"library\": asExpr(\"go_default_library\"),\n\t\t\t}))\n\t\t}\n\t}\n\n\tif len(pkg.XTestGoFiles) != 0 {\n\t\trules = append(rules, newRule(\"go_test\", \"go_default_xtest\", map[string]bzl.Expr{\n\t\t\t\"srcs\": asExpr(pkg.XTestGoFiles),\n\t\t\t\"deps\": v.extractDeps(pkg.XTestImports),\n\t\t}))\n\t}\n\n\twrote, err := ReconcileRules(filepath.Join(path, \"BUILD\"), rules)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif wrote {\n\t\tfmt.Fprintf(os.Stderr, \"wrote BUILD for %q\\n\", pkg.Dir)\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) walkVendor() {\n\tvar rules []*bzl.Rule\n\tif err := v.walk(\".\/vendor\", func(path, ipath string, pkg *build.Package) error {\n\t\tvar attrs Attrs = make(Attrs)\n\n\t\tsrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.GoFiles, pkg.SFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tcgoSrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.CgoFiles, pkg.CFiles, pkg.CXXFiles, pkg.HFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tdeps := v.extractDeps(pkg.Imports)\n\t\tattrs.Set(\"srcs\", srcs)\n\n\t\tif len(deps.List) > 0 {\n\t\t\tattrs.Set(\"deps\", deps)\n\t\t}\n\n\t\tif pkg.IsCommand() {\n\t\t\trules = append(rules, newRule(\"go_binary\", v.resolve(ipath).tag, attrs))\n\t\t} else {\n\t\t\tif len(cgoSrcs.List) != 0 {\n\t\t\t\tcgoPname := v.resolve(ipath).tag + \"_cgo\"\n\t\t\t\tcgoDeps := v.extractDeps(pkg.TestImports)\n\t\t\t\tcgoRule := newRule(\"cgo_library\", cgoPname, map[string]bzl.Expr{\n\t\t\t\t\t\"srcs\":      cgoSrcs,\n\t\t\t\t\t\"clinkopts\": asExpr([]string{\"-ldl\", \"-lz\", \"-lm\", \"-lpthread\", \"-ldl\"}),\n\t\t\t\t})\n\t\t\t\trules = append(rules, cgoRule)\n\t\t\t\tif len(cgoDeps.List) != 0 {\n\t\t\t\t\tcgoRule.SetAttr(\"deps\", cgoDeps)\n\t\t\t\t}\n\t\t\t\tattrs[\"library\"] = asExpr(cgoPname)\n\t\t\t}\n\t\t\trules = append(rules, newRule(\"go_library\", v.resolve(ipath).tag, attrs))\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n\tif _, err := ReconcileRules(\".\/vendor\/BUILD\", rules); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n}\n\nfunc (v *Venderor) extractDeps(deps []string) *bzl.ListExpr {\n\treturn asExpr(\n\t\tapply(\n\t\t\tmerge(deps),\n\t\t\tfilterer(func(s string) bool {\n\t\t\t\tpkg, err := v.ctx.Import(s, *kubeRoot, build.ImportComment)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif !strings.Contains(err.Error(), `cannot find package \"C\"`) {\n\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"extract err: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif pkg.Goroot {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}),\n\t\t\tmapper(func(s string) string {\n\t\t\t\treturn v.resolve(s).String()\n\t\t\t}),\n\t\t),\n\t).(*bzl.ListExpr)\n}\n\ntype Attrs map[string]bzl.Expr\n\nfunc (a Attrs) Set(name string, expr bzl.Expr) {\n\ta[name] = expr\n}\n\ntype Label struct {\n\tpkg, tag string\n}\n\nfunc (l Label) String() string {\n\treturn fmt.Sprintf(\"\/\/%v:%v\", l.pkg, l.tag)\n}\n\nfunc asExpr(e interface{}) bzl.Expr {\n\trv := reflect.ValueOf(e)\n\tswitch rv.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%d\", e)}\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%f\", e)}\n\tcase reflect.String:\n\t\treturn &bzl.StringExpr{Value: e.(string)}\n\tcase reflect.Slice, reflect.Array:\n\t\tvar list []bzl.Expr\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tlist = append(list, asExpr(rv.Index(i).Interface()))\n\t\t}\n\t\treturn &bzl.ListExpr{List: list}\n\tdefault:\n\t\tglog.Fatalf(\"Uh oh\")\n\t\treturn nil\n\t}\n}\n\ntype Sed func(s []string) []string\n\nfunc mapString(in []string, f func(string) string) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tout = append(out, f(s))\n\t}\n\treturn out\n}\n\nfunc mapper(f func(string) string) Sed {\n\treturn func(in []string) []string {\n\t\treturn mapString(in, f)\n\t}\n}\n\nfunc filterString(in []string, f func(string) bool) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tif f(s) {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc filterer(f func(string) bool) Sed {\n\treturn func(in []string) []string {\n\t\treturn filterString(in, f)\n\t}\n}\n\nfunc apply(stream []string, seds ...Sed) []string {\n\tfor _, sed := range seds {\n\t\tstream = sed(stream)\n\t}\n\treturn stream\n}\n\nfunc merge(streams ...[]string) []string {\n\tvar out []string\n\tfor _, stream := range streams {\n\t\tout = append(out, stream...)\n\t}\n\treturn out\n}\n\nfunc newRule(kind, name string, attrs map[string]bzl.Expr) *bzl.Rule {\n\trule := &bzl.Rule{\n\t\tCall: &bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: kind},\n\t\t},\n\t}\n\trule.SetAttr(\"name\", asExpr(name))\n\tfor k, v := range attrs {\n\t\trule.SetAttr(k, v)\n\t}\n\trule.SetAttr(\"tags\", asExpr([]string{\"automanaged\"}))\n\treturn rule\n}\n\nfunc ReconcileRules(path string, rules []*bzl.Rule) (bool, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil && os.IsNotExist(err) {\n\t\tf := &bzl.File{}\n\t\twriteHeaders(f)\n\t\twriteRules(f, rules)\n\t\treturn writeFile(path, f, false)\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tif info.IsDir() {\n\t\treturn false, fmt.Errorf(\"%q cannot be a directory\", path)\n\t}\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tf, err := bzl.Parse(path, b)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\toldRules := make(map[string]*bzl.Rule)\n\tfor _, r := range f.Rules(\"\") {\n\t\toldRules[r.Name()] = r\n\t}\n\tfor _, r := range rules {\n\t\to, ok := oldRules[r.Name()]\n\t\tif !ok {\n\t\t\tf.Stmt = append(f.Stmt, r.Call)\n\t\t\tcontinue\n\t\t}\n\t\tif !RuleIsManaged(o) {\n\t\t\tcontinue\n\t\t}\n\t\treconcileAttr := func(o, n *bzl.Rule, name string) {\n\t\t\tif e := n.Attr(name); e != nil {\n\t\t\t\to.SetAttr(name, e)\n\t\t\t} else {\n\t\t\t\to.DelAttr(name)\n\t\t\t}\n\t\t}\n\t\treconcileAttr(o, r, \"srcs\")\n\t\treconcileAttr(o, r, \"deps\")\n\t\treconcileAttr(o, r, \"library\")\n\t\tdelete(oldRules, r.Name())\n\t}\n\tfor _, r := range oldRules {\n\t\tif !RuleIsManaged(r) {\n\t\t\tcontinue\n\t\t}\n\t\tf.DelRules(r.Kind(), r.Name())\n\t}\n\treturn writeFile(path, f, true)\n}\n\nfunc RuleIsManaged(r *bzl.Rule) bool {\n\tvar automanaged bool\n\tfor _, tag := range r.AttrStrings(\"tags\") {\n\t\tif tag == \"automanaged\" {\n\t\t\tautomanaged = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn automanaged\n}\n\nfunc writeFile(path string, f *bzl.File, exists bool) (bool, error) {\n\tvar info bzl.RewriteInfo\n\tbzl.Rewrite(f, &info)\n\tout := bzl.Format(f)\n\tif exists {\n\t\torig, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif bytes.Compare(out, orig) == 0 {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tif *dryRun {\n\t\treturn true, nil\n\t}\n\treturn true, ioutil.WriteFile(path, out, 0644)\n\n}\n\nfunc context() *build.Context {\n\treturn &build.Context{\n\t\tGOARCH:      \"amd64\",\n\t\tGOOS:        \"linux\",\n\t\tGOROOT:      build.Default.GOROOT,\n\t\tGOPATH:      build.Default.GOPATH,\n\t\tReleaseTags: []string{\"go1.1\", \"go1.2\", \"go1.3\", \"go1.4\", \"go1.5\", \"go1.6\", \"go1.7\"},\n\t\tCompiler:    runtime.Compiler,\n\t\tCgoEnabled:  true,\n\t}\n}\n\nfunc walk(root string, walkFn filepath.WalkFunc) error {\n\treturn nil\n}\n<commit_msg>Check filepath error while walking directories<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/mikedanese\/gazel\/third_party\/go\/path\/filepath\"\n\n\tbzl \"github.com\/bazelbuild\/buildifier\/core\"\n\t\"github.com\/golang\/glog\"\n)\n\nvar kubeRoot = flag.String(\"root\", \"\", \"root of kubernetes source\")\nvar dryRun = flag.Bool(\"dry-run\", false, \"run in dry mode\")\n\nfunc main() {\n\tflag.Parse()\n\tflag.Set(\"alsologtostderr\", \"true\")\n\tif *kubeRoot == \"\" {\n\t\tglog.Fatalf(\"-root argument is required\")\n\t}\n\tv := Venderor{\n\t\tctx: context(),\n\t}\n\tif len(flag.Args()) == 1 {\n\t\tv.updateSinglePkg(flag.Args()[0])\n\t} else {\n\t\tv.walkVendor()\n\t\tif err := v.walkRepo(); err != nil {\n\t\t\tglog.Fatalf(\"err: %v\", err)\n\t\t}\n\t}\n}\n\ntype Venderor struct {\n\tctx *build.Context\n}\n\nfunc writeHeaders(file *bzl.File) {\n\tpkgRule := bzl.Rule{\n\t\t&bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: \"package\"},\n\t\t},\n\t}\n\tpkgRule.SetAttr(\"default_visibility\", asExpr([]string{\"\/\/visibility:public\"}))\n\n\tfile.Stmt = append(file.Stmt,\n\t\t[]bzl.Expr{\n\t\t\tpkgRule.Call,\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX:    &bzl.LiteralExpr{Token: \"licenses\"},\n\t\t\t\tList: []bzl.Expr{asExpr([]string{\"notice\"})},\n\t\t\t},\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX: &bzl.LiteralExpr{Token: \"load\"},\n\t\t\t\tList: asExpr([]string{\n\t\t\t\t\t\"@io_bazel_rules_go\/\/go:def.bzl\",\n\t\t\t\t\t\"go_binary\",\n\t\t\t\t\t\"go_library\",\n\t\t\t\t\t\"go_test\",\n\t\t\t\t\t\"cgo_library\",\n\t\t\t\t}).(*bzl.ListExpr).List,\n\t\t\t},\n\t\t}...,\n\t)\n}\n\nfunc writeRules(file *bzl.File, rules []*bzl.Rule) {\n\tfor _, rule := range rules {\n\t\tfile.Stmt = append(file.Stmt, rule.Call)\n\t}\n}\n\nfunc (v *Venderor) resolve(ipath string) Label {\n\tif strings.HasPrefix(ipath, \"k8s.io\/kubernetes\") {\n\t\treturn Label{\n\t\t\tpkg: strings.TrimPrefix(ipath, \"k8s.io\/kubernetes\/\"),\n\t\t\ttag: \"go_default_library\",\n\t\t}\n\t}\n\treturn Label{\n\t\tpkg: \"vendor\",\n\t\ttag: ipath,\n\t}\n}\n\nfunc (v *Venderor) walk(root string, f func(path, ipath string, pkg *build.Package) error) error {\n\treturn sfilepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tipath, err := filepath.Rel(root, path)\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\t\tpkg, err := v.ctx.ImportDir(filepath.Join(*kubeRoot, path), build.ImportComment)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn f(path, ipath, pkg)\n\t})\n}\n\nfunc (v *Venderor) walkRepo() error {\n\tfor _, root := range []string{\n\t\t\".\/pkg\",\n\t\t\".\/cmd\",\n\t\t\".\/third_party\",\n\t\t\".\/plugin\",\n\t\t\".\/test\",\n\t\t\".\/federation\",\n\t} {\n\t\tif err := v.walk(root, v.updatePkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) updateSinglePkg(path string) error {\n\tpkg, err := v.ctx.ImportDir(\".\/\"+path, build.ImportComment)\n\tif err != nil {\n\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn v.updatePkg(path, \"\", pkg)\n}\n\nfunc (v *Venderor) updatePkg(path, _ string, pkg *build.Package) error {\n\tvar rules []*bzl.Rule\n\n\tvar attrs Attrs = make(Attrs)\n\tsrcs := asExpr(merge(pkg.GoFiles, pkg.SFiles)).(*bzl.ListExpr)\n\n\tdeps := v.extractDeps(pkg.Imports)\n\n\tif len(srcs.List) == 0 {\n\t\treturn nil\n\t}\n\tattrs.Set(\"srcs\", srcs)\n\n\tif len(deps.List) > 0 {\n\t\tattrs.Set(\"deps\", deps)\n\t}\n\n\tif pkg.IsCommand() {\n\t\trules = append(rules, newRule(\"go_binary\", filepath.Base(pkg.Dir), attrs))\n\t} else {\n\t\trules = append(rules, newRule(\"go_library\", \"go_default_library\", attrs))\n\t\tif len(pkg.TestGoFiles) != 0 {\n\t\t\trules = append(rules, newRule(\"go_test\", \"go_default_test\", map[string]bzl.Expr{\n\t\t\t\t\"srcs\":    asExpr(pkg.TestGoFiles),\n\t\t\t\t\"deps\":    v.extractDeps(pkg.TestImports),\n\t\t\t\t\"library\": asExpr(\"go_default_library\"),\n\t\t\t}))\n\t\t}\n\t}\n\n\tif len(pkg.XTestGoFiles) != 0 {\n\t\trules = append(rules, newRule(\"go_test\", \"go_default_xtest\", map[string]bzl.Expr{\n\t\t\t\"srcs\": asExpr(pkg.XTestGoFiles),\n\t\t\t\"deps\": v.extractDeps(pkg.XTestImports),\n\t\t}))\n\t}\n\n\twrote, err := ReconcileRules(filepath.Join(path, \"BUILD\"), rules)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif wrote {\n\t\tfmt.Fprintf(os.Stderr, \"wrote BUILD for %q\\n\", pkg.Dir)\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) walkVendor() {\n\tvar rules []*bzl.Rule\n\tif err := v.walk(\".\/vendor\", func(path, ipath string, pkg *build.Package) error {\n\t\tvar attrs Attrs = make(Attrs)\n\n\t\tsrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.GoFiles, pkg.SFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tcgoSrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.CgoFiles, pkg.CFiles, pkg.CXXFiles, pkg.HFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tdeps := v.extractDeps(pkg.Imports)\n\t\tattrs.Set(\"srcs\", srcs)\n\n\t\tif len(deps.List) > 0 {\n\t\t\tattrs.Set(\"deps\", deps)\n\t\t}\n\n\t\tif pkg.IsCommand() {\n\t\t\trules = append(rules, newRule(\"go_binary\", v.resolve(ipath).tag, attrs))\n\t\t} else {\n\t\t\tif len(cgoSrcs.List) != 0 {\n\t\t\t\tcgoPname := v.resolve(ipath).tag + \"_cgo\"\n\t\t\t\tcgoDeps := v.extractDeps(pkg.TestImports)\n\t\t\t\tcgoRule := newRule(\"cgo_library\", cgoPname, map[string]bzl.Expr{\n\t\t\t\t\t\"srcs\":      cgoSrcs,\n\t\t\t\t\t\"clinkopts\": asExpr([]string{\"-ldl\", \"-lz\", \"-lm\", \"-lpthread\", \"-ldl\"}),\n\t\t\t\t})\n\t\t\t\trules = append(rules, cgoRule)\n\t\t\t\tif len(cgoDeps.List) != 0 {\n\t\t\t\t\tcgoRule.SetAttr(\"deps\", cgoDeps)\n\t\t\t\t}\n\t\t\t\tattrs[\"library\"] = asExpr(cgoPname)\n\t\t\t}\n\t\t\trules = append(rules, newRule(\"go_library\", v.resolve(ipath).tag, attrs))\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n\tif _, err := ReconcileRules(\".\/vendor\/BUILD\", rules); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n}\n\nfunc (v *Venderor) extractDeps(deps []string) *bzl.ListExpr {\n\treturn asExpr(\n\t\tapply(\n\t\t\tmerge(deps),\n\t\t\tfilterer(func(s string) bool {\n\t\t\t\tpkg, err := v.ctx.Import(s, *kubeRoot, build.ImportComment)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif !strings.Contains(err.Error(), `cannot find package \"C\"`) {\n\t\t\t\t\t\tfmt.Fprintf(os.Stderr, \"extract err: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif pkg.Goroot {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}),\n\t\t\tmapper(func(s string) string {\n\t\t\t\treturn v.resolve(s).String()\n\t\t\t}),\n\t\t),\n\t).(*bzl.ListExpr)\n}\n\ntype Attrs map[string]bzl.Expr\n\nfunc (a Attrs) Set(name string, expr bzl.Expr) {\n\ta[name] = expr\n}\n\ntype Label struct {\n\tpkg, tag string\n}\n\nfunc (l Label) String() string {\n\treturn fmt.Sprintf(\"\/\/%v:%v\", l.pkg, l.tag)\n}\n\nfunc asExpr(e interface{}) bzl.Expr {\n\trv := reflect.ValueOf(e)\n\tswitch rv.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%d\", e)}\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%f\", e)}\n\tcase reflect.String:\n\t\treturn &bzl.StringExpr{Value: e.(string)}\n\tcase reflect.Slice, reflect.Array:\n\t\tvar list []bzl.Expr\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tlist = append(list, asExpr(rv.Index(i).Interface()))\n\t\t}\n\t\treturn &bzl.ListExpr{List: list}\n\tdefault:\n\t\tglog.Fatalf(\"Uh oh\")\n\t\treturn nil\n\t}\n}\n\ntype Sed func(s []string) []string\n\nfunc mapString(in []string, f func(string) string) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tout = append(out, f(s))\n\t}\n\treturn out\n}\n\nfunc mapper(f func(string) string) Sed {\n\treturn func(in []string) []string {\n\t\treturn mapString(in, f)\n\t}\n}\n\nfunc filterString(in []string, f func(string) bool) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tif f(s) {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc filterer(f func(string) bool) Sed {\n\treturn func(in []string) []string {\n\t\treturn filterString(in, f)\n\t}\n}\n\nfunc apply(stream []string, seds ...Sed) []string {\n\tfor _, sed := range seds {\n\t\tstream = sed(stream)\n\t}\n\treturn stream\n}\n\nfunc merge(streams ...[]string) []string {\n\tvar out []string\n\tfor _, stream := range streams {\n\t\tout = append(out, stream...)\n\t}\n\treturn out\n}\n\nfunc newRule(kind, name string, attrs map[string]bzl.Expr) *bzl.Rule {\n\trule := &bzl.Rule{\n\t\tCall: &bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: kind},\n\t\t},\n\t}\n\trule.SetAttr(\"name\", asExpr(name))\n\tfor k, v := range attrs {\n\t\trule.SetAttr(k, v)\n\t}\n\trule.SetAttr(\"tags\", asExpr([]string{\"automanaged\"}))\n\treturn rule\n}\n\nfunc ReconcileRules(path string, rules []*bzl.Rule) (bool, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil && os.IsNotExist(err) {\n\t\tf := &bzl.File{}\n\t\twriteHeaders(f)\n\t\twriteRules(f, rules)\n\t\treturn writeFile(path, f, false)\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tif info.IsDir() {\n\t\treturn false, fmt.Errorf(\"%q cannot be a directory\", path)\n\t}\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tf, err := bzl.Parse(path, b)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\toldRules := make(map[string]*bzl.Rule)\n\tfor _, r := range f.Rules(\"\") {\n\t\toldRules[r.Name()] = r\n\t}\n\tfor _, r := range rules {\n\t\to, ok := oldRules[r.Name()]\n\t\tif !ok {\n\t\t\tf.Stmt = append(f.Stmt, r.Call)\n\t\t\tcontinue\n\t\t}\n\t\tif !RuleIsManaged(o) {\n\t\t\tcontinue\n\t\t}\n\t\treconcileAttr := func(o, n *bzl.Rule, name string) {\n\t\t\tif e := n.Attr(name); e != nil {\n\t\t\t\to.SetAttr(name, e)\n\t\t\t} else {\n\t\t\t\to.DelAttr(name)\n\t\t\t}\n\t\t}\n\t\treconcileAttr(o, r, \"srcs\")\n\t\treconcileAttr(o, r, \"deps\")\n\t\treconcileAttr(o, r, \"library\")\n\t\tdelete(oldRules, r.Name())\n\t}\n\tfor _, r := range oldRules {\n\t\tif !RuleIsManaged(r) {\n\t\t\tcontinue\n\t\t}\n\t\tf.DelRules(r.Kind(), r.Name())\n\t}\n\treturn writeFile(path, f, true)\n}\n\nfunc RuleIsManaged(r *bzl.Rule) bool {\n\tvar automanaged bool\n\tfor _, tag := range r.AttrStrings(\"tags\") {\n\t\tif tag == \"automanaged\" {\n\t\t\tautomanaged = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn automanaged\n}\n\nfunc writeFile(path string, f *bzl.File, exists bool) (bool, error) {\n\tvar info bzl.RewriteInfo\n\tbzl.Rewrite(f, &info)\n\tout := bzl.Format(f)\n\tif exists {\n\t\torig, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif bytes.Compare(out, orig) == 0 {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tif *dryRun {\n\t\treturn true, nil\n\t}\n\treturn true, ioutil.WriteFile(path, out, 0644)\n\n}\n\nfunc context() *build.Context {\n\treturn &build.Context{\n\t\tGOARCH:      \"amd64\",\n\t\tGOOS:        \"linux\",\n\t\tGOROOT:      build.Default.GOROOT,\n\t\tGOPATH:      build.Default.GOPATH,\n\t\tReleaseTags: []string{\"go1.1\", \"go1.2\", \"go1.3\", \"go1.4\", \"go1.5\", \"go1.6\", \"go1.7\"},\n\t\tCompiler:    runtime.Compiler,\n\t\tCgoEnabled:  true,\n\t}\n}\n\nfunc walk(root string, walkFn filepath.WalkFunc) error {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"github.com\/coreos\/fleet\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n\n\t\"github.com\/coreos\/fleet\/machine\"\n\t\"github.com\/coreos\/fleet\/registry\"\n\t\"github.com\/coreos\/fleet\/unit\"\n)\n\nfunc NewUnitStatePublisher(mgr unit.UnitManager, reg registry.Registry, mach machine.Machine) *UnitStatePublisher {\n\treturn &UnitStatePublisher{\n\t\tmgr:   mgr,\n\t\treg:   reg,\n\t\tmach:  mach,\n\t\tmutex: sync.RWMutex{},\n\t\tcache: make(map[string]*unit.UnitState),\n\t}\n}\n\ntype UnitStatePublisher struct {\n\tmgr  unit.UnitManager\n\treg  registry.Registry\n\tmach machine.Machine\n\n\tmutex sync.RWMutex\n\tcache map[string]*unit.UnitState\n}\n\n\/\/ Run caches all of the heartbeat objects from the provided channel, publishing\n\/\/ them to the Registry every 5s. Heartbeat objects are also published as they\n\/\/ are received on the channel.\nfunc (p *UnitStatePublisher) Run(beatchan <-chan *unit.UnitStateHeartbeat, stop chan bool) {\n\tgo func() {\n\t\ttick := time.Tick(5 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-tick:\n\t\t\t\tp.publishAll()\n\t\t\t}\n\t\t}\n\t}()\n\n\tmachID := p.mach.State().ID\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase bt := <-beatchan:\n\t\t\tif bt.State != nil {\n\t\t\t\tbt.State.MachineID = machID\n\t\t\t}\n\n\t\t\tp.addToCache(bt)\n\t\t}\n\t}\n}\n\nfunc (p *UnitStatePublisher) publishAll() {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tcache := make(map[string]*unit.UnitState)\n\tfor name, us := range p.cache {\n\t\tp.publishOne(name, us)\n\t\tif us != nil {\n\t\t\tcache[name] = us\n\t\t}\n\t}\n\n\tp.cache = cache\n}\n\nfunc (p *UnitStatePublisher) publishOne(name string, us *unit.UnitState) {\n\tif us == nil {\n\t\tlog.Infof(\"Destroying UnitState(%s) in Registry\", name)\n\t\terr := p.reg.RemoveUnitState(name)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to destroy UnitState(%s) in Registry: %v\", name, err)\n\t\t}\n\t} else {\n\t\t\/\/ Sanity check - don't want to publish incomplete UnitStates\n\t\t\/\/ TODO(jonboulle): consider teasing apart a separate UnitState-like struct\n\t\t\/\/ so we can rely on a UnitState always being fully hydrated?\n\t\tif len(us.UnitHash) == 0 || len(us.MachineID) == 0 {\n\t\t\tlog.Infof(\"Refusing to push UnitState(%s): %#v\", name, us)\n\t\t} else {\n\t\t\tlog.Infof(\"Pushing UnitState(%s) to Registry: %#v\", name, us)\n\t\t\tp.reg.SaveUnitState(name, us)\n\t\t}\n\t}\n}\n\nfunc (p *UnitStatePublisher) addToCache(update *unit.UnitStateHeartbeat) {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tlast := p.cache[update.Name]\n\tp.cache[update.Name] = update.State\n\n\t\/\/ As an optimization, publish changes as they flow in\n\tif !reflect.DeepEqual(last, update.State) {\n\t\tgo p.publishOne(update.Name, update.State)\n\t}\n}\n<commit_msg>agent: tweak UnitStatePublisher logs<commit_after>package agent\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"github.com\/coreos\/fleet\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n\n\t\"github.com\/coreos\/fleet\/machine\"\n\t\"github.com\/coreos\/fleet\/registry\"\n\t\"github.com\/coreos\/fleet\/unit\"\n)\n\nfunc NewUnitStatePublisher(mgr unit.UnitManager, reg registry.Registry, mach machine.Machine) *UnitStatePublisher {\n\treturn &UnitStatePublisher{\n\t\tmgr:   mgr,\n\t\treg:   reg,\n\t\tmach:  mach,\n\t\tmutex: sync.RWMutex{},\n\t\tcache: make(map[string]*unit.UnitState),\n\t}\n}\n\ntype UnitStatePublisher struct {\n\tmgr  unit.UnitManager\n\treg  registry.Registry\n\tmach machine.Machine\n\n\tmutex sync.RWMutex\n\tcache map[string]*unit.UnitState\n}\n\n\/\/ Run caches all of the heartbeat objects from the provided channel, publishing\n\/\/ them to the Registry every 5s. Heartbeat objects are also published as they\n\/\/ are received on the channel.\nfunc (p *UnitStatePublisher) Run(beatchan <-chan *unit.UnitStateHeartbeat, stop chan bool) {\n\tgo func() {\n\t\ttick := time.Tick(5 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-tick:\n\t\t\t\tp.publishAll()\n\t\t\t}\n\t\t}\n\t}()\n\n\tmachID := p.mach.State().ID\n\n\tfor {\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase bt := <-beatchan:\n\t\t\tif bt.State != nil {\n\t\t\t\tbt.State.MachineID = machID\n\t\t\t}\n\n\t\t\tp.addToCache(bt)\n\t\t}\n\t}\n}\n\nfunc (p *UnitStatePublisher) publishAll() {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tcache := make(map[string]*unit.UnitState)\n\tfor name, us := range p.cache {\n\t\tp.publishOne(name, us)\n\t\tif us != nil {\n\t\t\tcache[name] = us\n\t\t}\n\t}\n\n\tp.cache = cache\n}\n\nfunc (p *UnitStatePublisher) publishOne(name string, us *unit.UnitState) {\n\tif us == nil {\n\t\tlog.V(1).Infof(\"Destroying UnitState(%s) in Registry\", name)\n\t\terr := p.reg.RemoveUnitState(name)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to destroy UnitState(%s) in Registry: %v\", name, err)\n\t\t}\n\t} else {\n\t\t\/\/ Sanity check - don't want to publish incomplete UnitStates\n\t\t\/\/ TODO(jonboulle): consider teasing apart a separate UnitState-like struct\n\t\t\/\/ so we can rely on a UnitState always being fully hydrated?\n\t\tif len(us.UnitHash) == 0 {\n\t\t\tlog.Errorf(\"Refusing to push UnitState(%s), no UnitHash: %#v\", name, us)\n\t\t} else if len(us.MachineID) == 0 {\n\t\t\tlog.Errorf(\"Refusing to push UnitState(%s), no MachineID: %#v\", name, us)\n\t\t} else {\n\t\t\tlog.V(1).Infof(\"Pushing UnitState(%s) to Registry: %#v\", name, us)\n\t\t\tp.reg.SaveUnitState(name, us)\n\t\t}\n\t}\n}\n\nfunc (p *UnitStatePublisher) addToCache(update *unit.UnitStateHeartbeat) {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tlast := p.cache[update.Name]\n\tp.cache[update.Name] = update.State\n\n\t\/\/ As an optimization, publish changes as they flow in\n\tif !reflect.DeepEqual(last, update.State) {\n\t\tgo p.publishOne(update.Name, update.State)\n\t}\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\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConfigFile struct {\n\tMongo string\n\tMq    struct {\n\t\tHost          string\n\t\tPort          int\n\t\tComponentUser string\n\t\tPassword      string\n\t\tVhost         string\n\t}\n}\n\ntype Domain struct {\n\tDomainname  string `json:\"Domain\"`\n\tProxy struct {\n\t\tMode        string `json:\"mode\"`\n\t\tUsername    string `json:\"username\"`\n\t\tServicename string `json:\"servicename\"`\n\t\tKey         string `json:\"key\"`\n  }`json:\"Proxy\"`\n\tFullUrl     string `json:\"Domain\"`\n}\n\ntype ServerInfo struct {\n\tBuildNumber string\n\tGitBranch   string\n\tGitCommit   string\n\tConfigUsed  string\n\tConfig      ConfigFile\n\tHostname    Hostname\n\tIP          IP\n\tMongoLogin  string\n}\n\ntype Hostname struct {\n\tPublic string\n\tLocal  string\n}\n\ntype IP struct {\n\tPublic string\n\tLocal  string\n}\n\ntype JenkinsInfo struct {\n\tLastCompletedBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastCompletedBuild\"`\n\tLastStableBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastStableBuild\"`\n\tLastFailedBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastFailedBuild\"`\n}\n\ntype WorkerInfo struct {\n\tName      string    `json:\"name\"`\n\tUuid      string    `json:\"uuid\"`\n\tHostname  string    `json:\"hostname\"`\n\tVersion   int       `json:\"version\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tPid       int       `json:\"pid\"`\n\tState     string    `json:\"state\"`\n\tInfo      string    `json:\"info\"`\n\tClock     string    `json:\"clock\"`\n\tUptime    int       `json:\"uptime\"`\n\tPort      int       `json:\"port\"`\n}\n\ntype StatusInfo struct {\n\tBuildNumber string\n\tKoding   struct {\n\t\tServerHost string\n\t\tBrokerHost string\n\t}\n\tWorkers struct {\n\t\tRunning int\n\t\tDead    int\n\t}\n}\n\ntype HomePage struct {\n\tStatus  StatusInfo\n\tWorkers []WorkerInfo\n\tJenkins *JenkinsInfo\n\tServer  *ServerInfo\n\tBuilds  []int\n}\n\nfunc NewServerInfo() *ServerInfo {\n\treturn &ServerInfo{\n\t\tBuildNumber: \"\",\n\t\tGitBranch:   \"\",\n\t\tGitCommit:   \"\",\n\t\tConfigUsed:  \"\",\n\t\tConfig:      ConfigFile{},\n\t\tHostname:    Hostname{},\n\t\tIP:          IP{},\n\t}\n}\n\nvar templates = template.Must(template.ParseFiles(\"index.html\"))\n\nconst uptimeLayout = \"03:04:00\"\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", viewHandler)\n\thttp.Handle(\"\/bootstrap\/\", http.StripPrefix(\"\/bootstrap\/\", http.FileServer(http.Dir(\"bootstrap\/\"))))\n\n\tfmt.Println(\"koding overview started\")\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\tbuild := r.FormValue(\"build\")\n\tif build == \"\" {\n\t\tbuild = \"latest\"\n\t}\n\n\tworkers, status, err := workerInfo(build)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tjenkins := jenkinsInfo()\n\tbuilds := buildsInfo()\n\n\tserver, err := serverInfo(build)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tserver = NewServerInfo()\n\t}\n\n\tdomain, err := domainInfo()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\ts, b := keyLookup(domain.Proxy.Key)\n\tstatus.Koding.ServerHost = s\n\tstatus.Koding.BrokerHost = b\n\n\thome := HomePage{\n\t\tStatus:  status,\n\t\tWorkers: workers,\n\t\tJenkins: jenkins,\n\t\tServer:  server,\n\t\tBuilds:  builds,\n\t}\n\n\trenderTemplate(w, \"index\", home)\n\treturn\n}\n\nfunc keyLookup(key string) (string, string) {\n\tworkersApi := \"http:\/\/kontrol.in.koding.com\/workers?version=\" + key\n\tresp, err := http.Get(workersApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tworkers := make([]WorkerInfo, 0)\n\terr = json.Unmarshal(body, &workers)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar server string\n\tvar broker string\n\tfor _, w := range workers {\n\t\tif w.Name == \"server\" {\n\t\t\tserver = w.Hostname + \":\" + strconv.Itoa(w.Port)\n\t\t}\n\n\t\tif w.Name == \"broker\" {\n\t\t\tbroker = w.Hostname + \":\" + strconv.Itoa(w.Port)\n\t\t}\n\n\t}\n\n\treturn server, broker\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, home HomePage) {\n\terr := templates.ExecuteTemplate(w, tmpl+\".html\", home)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc jenkinsInfo() *JenkinsInfo {\n\tfmt.Println(\"getting jenkins info\")\n\tj := &JenkinsInfo{}\n\tjenkinsApi := \"http:\/\/salt-master.in.koding.com\/job\/build-koding\/api\/json\"\n\tresp, err := http.Get(jenkinsApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\terr = json.Unmarshal(body, &j)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn j\n}\n\nfunc workerInfo(build string) ([]WorkerInfo, StatusInfo, error) {\n\ts := StatusInfo{}\n\n\tworkersApi := \"http:\/\/kontrol.in.koding.com\/workers?version=\" + build\n\tresp, err := http.Get(workersApi)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\n\tworkers := make([]WorkerInfo, 0)\n\terr = json.Unmarshal(body, &workers)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\n\ts.BuildNumber = build\n\n\tfor i, val := range workers {\n\t\tswitch val.State {\n\t\tcase \"running\":\n\t\t\ts.Workers.Running++\n\t\t\tworkers[i].Info = \"success\"\n\t\tcase \"dead\":\n\t\t\ts.Workers.Dead++\n\t\t\tworkers[i].Info = \"error\"\n\t\tcase \"stopped\":\n\t\t\tworkers[i].Info = \"warning\"\n\t\tcase \"waiting\":\n\t\t\tworkers[i].Info = \"info\"\n\t\t}\n\n\t\td, err := time.ParseDuration(strconv.Itoa(workers[i].Uptime) + \"s\")\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tworkers[i].Clock = d.String()\n\t}\n\n\treturn workers, s, nil\n}\n\nfunc buildsInfo() []int {\n\tserverApi := \"http:\/\/kontrol.in.koding.com\/deployments\"\n\tfmt.Println(serverApi)\n\tresp, err := http.Get(serverApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\ts := &[]ServerInfo{}\n\terr = json.Unmarshal(body, &s)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tbuilds := make([]int, 0)\n\tfor _, serv := range *s {\n\t\tbuild, _ := strconv.Atoi(serv.BuildNumber)\n\t\tbuilds = append(builds, build)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(builds)))\n\n\treturn builds\n}\n\nfunc serverInfo(build string) (*ServerInfo, error) {\n\tserverApi := \"http:\/\/kontrol.in.koding.com\/deployments\/\" + build\n\n\tresp, err := http.Get(serverApi)\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, err\n\t}\n\n\ts := &ServerInfo{}\n\terr = json.Unmarshal(body, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.MongoLogin = parseMongoLogin(s.Config.Mongo)\n\n\treturn s, nil\n}\n\nfunc parseMongoLogin(login string) string {\n\tu, err := url.Parse(\"http:\/\/\" + login)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tmPass, _ := u.User.Password()\n\treturn fmt.Sprintf(\n\t\t\"mongo %s%s -u%s -p%s\",\n\t\tu.Host,\n\t\tu.Path,\n\t\tu.User.Username(),\n\t\tmPass,\n\t)\n}\n\nfunc domainInfo() (Domain, error) {\n\td := &Domain{}\n\tdomainApi := \"http:\/\/kontrol.in.koding.com\/domains\/koding.com\"\n\tresp, err := http.Get(domainApi)\n\tif err != nil {\n\t\treturn *d, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn *d, err\n\t} else {\n\t\tfmt.Println(string(body))\n\t}\n\n\terr = json.Unmarshal(body, &d)\n\tif err != nil {\n\t\tfmt.Println(\"Couldn't unmarshall koding.com into a domain object.\")\n\t\treturn *d, err\n\t}\n\n\treturn *d, fmt.Errorf(\"no domain info available for koding.com\")\n}\n<commit_msg>[kontrol overview] return nil instead of err when things are OK<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype ConfigFile struct {\n\tMongo string\n\tMq    struct {\n\t\tHost          string\n\t\tPort          int\n\t\tComponentUser string\n\t\tPassword      string\n\t\tVhost         string\n\t}\n}\n\ntype Domain struct {\n\tDomainname  string `json:\"Domain\"`\n\tProxy struct {\n\t\tMode        string `json:\"mode\"`\n\t\tUsername    string `json:\"username\"`\n\t\tServicename string `json:\"servicename\"`\n\t\tKey         string `json:\"key\"`\n  }`json:\"Proxy\"`\n\tFullUrl     string `json:\"Domain\"`\n}\n\ntype ServerInfo struct {\n\tBuildNumber string\n\tGitBranch   string\n\tGitCommit   string\n\tConfigUsed  string\n\tConfig      ConfigFile\n\tHostname    Hostname\n\tIP          IP\n\tMongoLogin  string\n}\n\ntype Hostname struct {\n\tPublic string\n\tLocal  string\n}\n\ntype IP struct {\n\tPublic string\n\tLocal  string\n}\n\ntype JenkinsInfo struct {\n\tLastCompletedBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastCompletedBuild\"`\n\tLastStableBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastStableBuild\"`\n\tLastFailedBuild struct {\n\t\tNumber int    `json:\"number\"`\n\t\tUrl    string `json:\"url\"`\n\t} `json:\"lastFailedBuild\"`\n}\n\ntype WorkerInfo struct {\n\tName      string    `json:\"name\"`\n\tUuid      string    `json:\"uuid\"`\n\tHostname  string    `json:\"hostname\"`\n\tVersion   int       `json:\"version\"`\n\tTimestamp time.Time `json:\"timestamp\"`\n\tPid       int       `json:\"pid\"`\n\tState     string    `json:\"state\"`\n\tInfo      string    `json:\"info\"`\n\tClock     string    `json:\"clock\"`\n\tUptime    int       `json:\"uptime\"`\n\tPort      int       `json:\"port\"`\n}\n\ntype StatusInfo struct {\n\tBuildNumber string\n\tKoding   struct {\n\t\tServerHost string\n\t\tBrokerHost string\n\t}\n\tWorkers struct {\n\t\tRunning int\n\t\tDead    int\n\t}\n}\n\ntype HomePage struct {\n\tStatus  StatusInfo\n\tWorkers []WorkerInfo\n\tJenkins *JenkinsInfo\n\tServer  *ServerInfo\n\tBuilds  []int\n}\n\nfunc NewServerInfo() *ServerInfo {\n\treturn &ServerInfo{\n\t\tBuildNumber: \"\",\n\t\tGitBranch:   \"\",\n\t\tGitCommit:   \"\",\n\t\tConfigUsed:  \"\",\n\t\tConfig:      ConfigFile{},\n\t\tHostname:    Hostname{},\n\t\tIP:          IP{},\n\t}\n}\n\nvar templates = template.Must(template.ParseFiles(\"index.html\"))\n\nconst uptimeLayout = \"03:04:00\"\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", viewHandler)\n\thttp.Handle(\"\/bootstrap\/\", http.StripPrefix(\"\/bootstrap\/\", http.FileServer(http.Dir(\"bootstrap\/\"))))\n\n\tfmt.Println(\"koding overview started\")\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc viewHandler(w http.ResponseWriter, r *http.Request) {\n\tbuild := r.FormValue(\"build\")\n\tif build == \"\" {\n\t\tbuild = \"latest\"\n\t}\n\n\tworkers, status, err := workerInfo(build)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tjenkins := jenkinsInfo()\n\tbuilds := buildsInfo()\n\n\tserver, err := serverInfo(build)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tserver = NewServerInfo()\n\t}\n\n\tdomain, err := domainInfo()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\ts, b := keyLookup(domain.Proxy.Key)\n\tstatus.Koding.ServerHost = s\n\tstatus.Koding.BrokerHost = b\n\n\thome := HomePage{\n\t\tStatus:  status,\n\t\tWorkers: workers,\n\t\tJenkins: jenkins,\n\t\tServer:  server,\n\t\tBuilds:  builds,\n\t}\n\n\trenderTemplate(w, \"index\", home)\n\treturn\n}\n\nfunc keyLookup(key string) (string, string) {\n\tworkersApi := \"http:\/\/kontrol.in.koding.com\/workers?version=\" + key\n\tresp, err := http.Get(workersApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tworkers := make([]WorkerInfo, 0)\n\terr = json.Unmarshal(body, &workers)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tvar server string\n\tvar broker string\n\tfor _, w := range workers {\n\t\tif w.Name == \"server\" {\n\t\t\tserver = w.Hostname + \":\" + strconv.Itoa(w.Port)\n\t\t}\n\n\t\tif w.Name == \"broker\" {\n\t\t\tbroker = w.Hostname + \":\" + strconv.Itoa(w.Port)\n\t\t}\n\n\t}\n\n\treturn server, broker\n}\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, home HomePage) {\n\terr := templates.ExecuteTemplate(w, tmpl+\".html\", home)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc jenkinsInfo() *JenkinsInfo {\n\tfmt.Println(\"getting jenkins info\")\n\tj := &JenkinsInfo{}\n\tjenkinsApi := \"http:\/\/salt-master.in.koding.com\/job\/build-koding\/api\/json\"\n\tresp, err := http.Get(jenkinsApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\terr = json.Unmarshal(body, &j)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\treturn j\n}\n\nfunc workerInfo(build string) ([]WorkerInfo, StatusInfo, error) {\n\ts := StatusInfo{}\n\n\tworkersApi := \"http:\/\/kontrol.in.koding.com\/workers?version=\" + build\n\tresp, err := http.Get(workersApi)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\n\tworkers := make([]WorkerInfo, 0)\n\terr = json.Unmarshal(body, &workers)\n\tif err != nil {\n\t\treturn nil, s, err\n\t}\n\n\ts.BuildNumber = build\n\n\tfor i, val := range workers {\n\t\tswitch val.State {\n\t\tcase \"running\":\n\t\t\ts.Workers.Running++\n\t\t\tworkers[i].Info = \"success\"\n\t\tcase \"dead\":\n\t\t\ts.Workers.Dead++\n\t\t\tworkers[i].Info = \"error\"\n\t\tcase \"stopped\":\n\t\t\tworkers[i].Info = \"warning\"\n\t\tcase \"waiting\":\n\t\t\tworkers[i].Info = \"info\"\n\t\t}\n\n\t\td, err := time.ParseDuration(strconv.Itoa(workers[i].Uptime) + \"s\")\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tworkers[i].Clock = d.String()\n\t}\n\n\treturn workers, s, nil\n}\n\nfunc buildsInfo() []int {\n\tserverApi := \"http:\/\/kontrol.in.koding.com\/deployments\"\n\tfmt.Println(serverApi)\n\tresp, err := http.Get(serverApi)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\ts := &[]ServerInfo{}\n\terr = json.Unmarshal(body, &s)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tbuilds := make([]int, 0)\n\tfor _, serv := range *s {\n\t\tbuild, _ := strconv.Atoi(serv.BuildNumber)\n\t\tbuilds = append(builds, build)\n\t}\n\tsort.Sort(sort.Reverse(sort.IntSlice(builds)))\n\n\treturn builds\n}\n\nfunc serverInfo(build string) (*ServerInfo, error) {\n\tserverApi := \"http:\/\/kontrol.in.koding.com\/deployments\/\" + build\n\n\tresp, err := http.Get(serverApi)\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, err\n\t}\n\n\ts := &ServerInfo{}\n\terr = json.Unmarshal(body, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.MongoLogin = parseMongoLogin(s.Config.Mongo)\n\n\treturn s, nil\n}\n\nfunc parseMongoLogin(login string) string {\n\tu, err := url.Parse(\"http:\/\/\" + login)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tmPass, _ := u.User.Password()\n\treturn fmt.Sprintf(\n\t\t\"mongo %s%s -u%s -p%s\",\n\t\tu.Host,\n\t\tu.Path,\n\t\tu.User.Username(),\n\t\tmPass,\n\t)\n}\n\nfunc domainInfo() (Domain, error) {\n\td := &Domain{}\n\tdomainApi := \"http:\/\/kontrol.in.koding.com\/domains\/koding.com\"\n\tresp, err := http.Get(domainApi)\n\tif err != nil {\n\t\treturn *d, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn *d, err\n\t} else {\n\t\tfmt.Println(string(body))\n\t}\n\n\terr = json.Unmarshal(body, &d)\n\tif err != nil {\n\t\tfmt.Println(\"Couldn't unmarshall koding.com into a domain object.\")\n\t\treturn *d, err\n\t}\n\n\treturn *d, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package bubbles is an Elasticsearch bulk insert client.\n\/\/\n\/\/ It connects to an Elasticsearch cluster via the bulk API\n\/\/ (http:\/\/www.elasticsearch.org\/guide\/en\/elasticsearch\/reference\/current\/docs-bulk.html).\n\/\/ Actions are batched into bulk requests. Actions which resulted\n\/\/ in an error are retried individually.\npackage bubbles\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/realzeitmedia\/bubbles\/loges\"\n)\n\nconst (\n\t\/\/ DefaultMaxDocumentsPerBatch is the number of documents a batch needs to\n\t\/\/ have before it is send. This is per connection.\n\tDefaultMaxDocumentsPerBatch = 1000\n\n\t\/\/ DefaultFlushTimeout is the maximum time we batch something before we try\n\t\/\/ to send it to a server.\n\tDefaultFlushTimeout = 10 * time.Second\n\n\t\/\/ DefaultServerTimeout is the time we give ElasticSearch to respond.\n\tDefaultServerTimeout = 1 * time.Minute\n\n\t\/\/ DefaultConnCount is the number of connections per hosts.\n\tDefaultConnCount = 2\n\n\t\/\/ tuneTimeoutRatio determines when we start backing off to keep the request\n\t\/\/ duration under control.\n\ttuneTimeoutRatio = 6\n\n\tserverErrorWait    = 50 * time.Millisecond\n\tserverErrorWaitMax = 10 * time.Second\n\n\tdefaultElasticSearchPort = \"9200\"\n)\n\nvar (\n\terrInvalidResponse = errors.New(\"invalid response\")\n)\n\n\/\/ Bubbles is the main struct to control a queue of Actions going to the\n\/\/ ElasticSearch servers.\ntype Bubbles struct {\n\tq                chan Action\n\tretryQ           chan Action\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\tmaxDocumentCount int\n\tconnCount        int\n\tflushTimeout     time.Duration\n\tserverTimeout    time.Duration\n\tc                loges.Counter\n\te                loges.Errer\n}\n\n\/\/ Opt is any option to New().\ntype Opt func(*Bubbles)\n\n\/\/ OptConnCount is an option to New() to specify the number of connections per\n\/\/ host. The default is DefaultConnCount.\nfunc OptConnCount(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.connCount = n\n\t}\n}\n\n\/\/ OptFlush is an option to New() to specify the flush timeout of a batch. The\n\/\/ default is DefaultFlushTimeout.\nfunc OptFlush(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.flushTimeout = d\n\t}\n}\n\n\/\/ OptServerTimeout is an option to New() to specify the timeout of a single\n\/\/ batch POST to ElasticSearch. All actions in a bulk which is timed out will\n\/\/ be retried. The default is DefaultServerTimeout.\nfunc OptServerTimeout(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.serverTimeout = d\n\t}\n}\n\n\/\/ OptMaxDocs is an option to New() to specify maximum number of documents in a\n\/\/ single batch. The default is DefaultMaxDocumentsPerBatch.\nfunc OptMaxDocs(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.maxDocumentCount = n\n\t}\n}\n\n\/\/ OptCounter is an option to New() to specify something that counts documents.\nfunc OptCounter(c loges.Counter) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.c = c\n\t}\n}\n\n\/\/ OptErrer is an option to New() to specify an error handler. The default\n\/\/ handler uses the log module.\nfunc OptErrer(e loges.Errer) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.e = e\n\t}\n}\n\n\/\/ New makes a new ElasticSearch bulk inserter. It needs a list with 'ip' or\n\/\/ 'ip:port' addresses, options are added via the Opt* functions.\nfunc New(addrs []string, opts ...Opt) *Bubbles {\n\tb := Bubbles{\n\t\tq:                make(chan Action),\n\t\tquit:             make(chan struct{}),\n\t\tmaxDocumentCount: DefaultMaxDocumentsPerBatch,\n\t\tconnCount:        DefaultConnCount,\n\t\tflushTimeout:     DefaultFlushTimeout,\n\t\tserverTimeout:    DefaultServerTimeout,\n\t\tc:                loges.DefaultCounter{},\n\t\te:                loges.DefaultErrer{},\n\t}\n\tfor _, o := range opts {\n\t\to(&b)\n\t}\n\tb.retryQ = make(chan Action, len(addrs)*b.connCount*b.maxDocumentCount)\n\n\tcl := &http.Client{\n\t\tTimeout: b.serverTimeout,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn errors.New(\"no redirect\")\n\t\t},\n\t\tTransport: &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout:   b.serverTimeout,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t}).Dial,\n\t\t\tMaxIdleConnsPerHost: b.connCount,\n\t\t\tDisableCompression:  false,\n\t\t},\n\t}\n\t\/\/ Start a go routine per connection per host\n\tfor _, a := range addrs {\n\t\taddr := withPort(a, defaultElasticSearchPort)\n\t\tfor i := 0; i < b.connCount; i++ {\n\t\t\tb.wg.Add(1)\n\t\t\tgo func(a string) {\n\t\t\t\tclient(&b, cl, a)\n\t\t\t\tb.wg.Done()\n\t\t\t}(addr)\n\t\t}\n\t}\n\treturn &b\n}\n\n\/\/ Enqueue returns the queue to add Actions in a routine. It will block if all bulk\n\/\/ processors are busy.\nfunc (b *Bubbles) Enqueue() chan<- Action {\n\treturn b.q\n}\n\n\/\/ Stop shuts down all ElasticSearch clients. It'll return all Action entries\n\/\/ which were not yet processed, or were up for a retry.\nfunc (b *Bubbles) Stop() []Action {\n\tclose(b.quit)\n\t\/\/ There is no explicit timeout, we rely on b.serverTimeout to shut down\n\t\/\/ everything.\n\tb.wg.Wait()\n\n\t\/\/ Collect and return elements which are in flight.\n\tclose(b.retryQ)\n\tclose(b.q)\n\tpending := make([]Action, 0, len(b.q)+len(b.retryQ))\n\tfor a := range b.q {\n\t\tpending = append(pending, a)\n\t}\n\tfor a := range b.retryQ {\n\t\tpending = append(pending, a)\n\t}\n\treturn pending\n}\n\ntype backoff struct {\n\tlevel        uint8\n\tmax          uint8\n\tmaxBatchSize int\n}\n\nfunc newBackoff(maxBatchSize int) *backoff {\n\tb := &backoff{\n\t\tmaxBatchSize: maxBatchSize,\n\t}\n\t\/\/ Max out when both components do.\n\tfor ; (b.wait() < serverErrorWaitMax || b.size() > 1) && b.level < 32; b.level++ {\n\t}\n\tb.max = b.level\n\tb.level = 0\n\treturn b\n}\n\n\/\/ wait calculates the delay based on the current backoff level.\nfunc (b *backoff) wait() time.Duration {\n\tif b.level == 0 {\n\t\treturn 0 * time.Second\n\t}\n\tw := (1 << (b.level - 1)) * serverErrorWait\n\tif w >= serverErrorWaitMax {\n\t\treturn serverErrorWaitMax\n\t}\n\treturn w\n}\n\n\/\/ batchSize calculates the batchsize based on the current backoff level.\nfunc (b *backoff) size() int {\n\ts := b.maxBatchSize \/ (1 << b.level)\n\tif s <= 1 {\n\t\treturn 1\n\t}\n\treturn s\n}\n\n\/\/ inc increases the backoff level.\nfunc (b *backoff) inc() {\n\tif b.level < b.max {\n\t\tb.level++\n\t}\n}\n\n\/\/ dec decreases the backoff level.\nfunc (b *backoff) dec() {\n\tif b.level > 0 {\n\t\tb.level--\n\t}\n}\n\nfunc min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\/\/ client talks to ElasticSearch. This runs in a go routine in a loop and deals\n\/\/ with a single ElasticSearch address.\nfunc client(b *Bubbles, cl *http.Client, addr string) {\n\tvar (\n\t\turl            = fmt.Sprintf(\"http:\/\/%s\/_bulk\", addr)\n\t\tbackoffTrouble = newBackoff(b.maxDocumentCount)\n\t\tbackoffTune    = newBackoff(b.maxDocumentCount)\n\t\ttuneTimeout    = b.serverTimeout \/ tuneTimeoutRatio\n\t\tscratch        = &bytes.Buffer{}\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase <-time.After(backoffTrouble.wait()):\n\t\t}\n\t\ttuneMax := backoffTune.size()\n\t\ttrouble, batchTime, sent := runBatch(\n\t\t\tb,\n\t\t\tcl,\n\t\t\turl,\n\t\t\tmin(backoffTrouble.size(), tuneMax),\n\t\t\tscratch,\n\t\t)\n\t\tif trouble {\n\t\t\tbackoffTrouble.inc()\n\t\t\tb.c.Trouble()\n\t\t} else {\n\t\t\tbackoffTrouble.dec()\n\t\t}\n\t\tif batchTime > tuneTimeout {\n\t\t\tbackoffTune.inc()\n\t\t} else if batchTime <= tuneTimeout\/2 && sent == tuneMax {\n\t\t\tbackoffTune.dec()\n\t\t}\n\t\tb.c.BatchTime(batchTime)\n\t}\n}\n\n\/\/ runBatch gathers and deals with a batch of actions. It returns\n\/\/ whether there was trouble, how long the actual request took, and\n\/\/ how many items were sent successfully.\nfunc runBatch(\n\tb *Bubbles,\n\tcl *http.Client,\n\turl string,\n\tbatchSize int,\n\tscratch *bytes.Buffer,\n) (bool, time.Duration, int) {\n\tactions := make([]Action, 0, b.maxDocumentCount)\n\t\/\/ First use all retry actions.\nretry:\n\tfor len(actions) < batchSize {\n\t\tselect {\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tdefault:\n\t\t\t\/\/ no more retry actions queued\n\t\t\tbreak retry\n\t\t}\n\t}\n\n\tvar t <-chan time.Time\ngather:\n\tfor len(actions) < batchSize {\n\t\tif t == nil && len(actions) > 0 {\n\t\t\t\/\/ Set timeout on the first element we read\n\t\t\tt = time.After(b.flushTimeout)\n\t\t}\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\tfor _, a := range actions {\n\t\t\t\tb.retryQ <- a\n\t\t\t}\n\t\t\tb.c.Actions(0, len(actions), 0)\n\t\t\treturn false, 0, 0\n\t\tcase <-t:\n\t\t\t\/\/ this case is not enabled until we've got an action\n\t\t\tbreak gather\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tcase a := <-b.q:\n\t\t\tactions = append(actions, a)\n\t\t}\n\t}\n\n\tt0 := time.Now()\n\tres, err := postActions(b.c, cl, url, actions, b.quit, scratch)\n\tdt := time.Since(t0)\n\tif err != nil {\n\t\t\/\/ A server error. Retry these actions later.\n\t\tb.e.Error(err)\n\t\tfor _, a := range actions {\n\t\t\tb.retryQ <- a\n\t\t}\n\t\tb.c.Actions(0, len(actions), 0)\n\t\treturn true, dt, 0\n\t}\n\n\t\/\/ Server has accepted the request an sich, but there can be errors in the\n\t\/\/ individual actions.\n\tif !res.Errors {\n\t\t\/\/ Simple case, no errors present.\n\t\tb.c.Actions(len(actions), 0, 0)\n\t\treturn false, dt, len(actions)\n\t}\n\n\t\/\/ Invalid response from ElasticSearch.\n\tif len(actions) != len(res.Items) {\n\t\tb.e.Error(errInvalidResponse)\n\t\tfor _, a := range actions {\n\t\t\tb.retryQ <- a\n\t\t}\n\t\tb.c.Actions(0, len(actions), 0)\n\t\treturn true, dt, 0\n\t}\n\t\/\/ Figure out which actions have errors.\n\tvar (\n\t\tretries = 0\n\t\terrors  = 0\n\t)\n\tfor i, e := range res.Items {\n\t\ta := actions[i]\n\t\tel, ok := e[string(a.Type)]\n\t\tif !ok {\n\t\t\t\/\/ Unexpected reply from ElasticSearch.\n\t\t\tb.e.Error(errInvalidResponse)\n\t\t\tb.retryQ <- a\n\t\t\tretries++\n\t\t\tcontinue\n\t\t}\n\n\t\tc := el.Status\n\t\tswitch {\n\t\tcase c >= 200 && c < 300:\n\t\t\t\/\/ Document accepted by ElasticSearch.\n\t\tcase c == 429 || (c >= 500 && c < 600):\n\t\t\t\/\/ Server error. Retry it.\n\t\t\t\/\/ We get a 429 when the bulk queue is full, which we just retry as\n\t\t\t\/\/ well.\n\t\t\tb.e.Warning(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"transient error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\tb.retryQ <- a\n\t\t\tretries++\n\t\tcase c >= 400 && c < 500:\n\t\t\t\/\/ Some error. Nothing we can do with it.\n\t\t\tb.e.Error(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\terrors++\n\t\tdefault:\n\t\t\t\/\/ No idea.\n\t\t\tb.e.Error(fmt.Errorf(\"unwelcome response %d: %s\", c, el.Error))\n\t\t\terrors++\n\t\t}\n\t}\n\tsent := len(actions) - errors - retries\n\tb.c.Actions(sent, retries, errors)\n\treturn retries > 0, dt, sent\n}\n\ntype bulkRes struct {\n\tTook   int  `json:\"took\"`\n\tErrors bool `json:\"errors\"`\n\tItems  []map[string]struct {\n\t\tIndex   string `json:\"_index\"`\n\t\tType    string `json:\"_type\"`\n\t\tID      string `json:\"_id\"`\n\t\tVersion int    `json:\"_version\"`\n\t\tStatus  int    `json:\"status\"`\n\t\tError   string `json:\"error\"`\n\t} `json:\"items\"`\n}\n\nfunc interruptibleDo(cl *http.Client, req *http.Request, interrupt <-chan struct{}) (*http.Response, error) {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-interrupt:\n\t\t\tcl.Transport.(*http.Transport).CancelRequest(req)\n\t\tcase <-done:\n\t\t}\n\t}()\n\tdefer close(done)\n\treturn cl.Do(req)\n}\n\nfunc postActions(\n\tc loges.Counter,\n\tcl *http.Client,\n\turl string,\n\tactions []Action,\n\tquit <-chan struct{},\n\tbuf *bytes.Buffer,\n) (*bulkRes, error) {\n\tbuf.Reset()\n\tfor _, a := range actions {\n\t\tbuf.Write(a.Buf())\n\t}\n\tc.SendTotal(buf.Len())\n\n\t\/\/ This doesn't Chunk.\n\treq, err := http.NewRequest(\"POST\", url, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tresp, err := interruptibleDo(cl, req, quit)\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, fmt.Errorf(\"status: %s\", resp.Status)\n\t}\n\n\tvar (\n\t\tbulk bulkRes\n\t\td    = json.NewDecoder(resp.Body)\n\t)\n\tif err := d.Decode(&bulk); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &bulk, nil\n}\n\n\/\/ ActionError wraps an Action we won't retry. It implements the error interface.\ntype ActionError struct {\n\tAction     Action\n\tStatusCode int\n\tMsg        string\n\tServer     string\n}\n\nfunc (e ActionError) Error() string {\n\treturn fmt.Sprintf(\"%s: %s %s\", e.Server, e.Action.Type, e.Msg)\n}\n\n\/\/ withPort adds a default port to an address string.\nfunc withPort(a, port string) string {\n\tif _, _, err := net.SplitHostPort(a); err != nil {\n\t\t\/\/ no port found.\n\t\treturn net.JoinHostPort(a, port)\n\t}\n\treturn a\n}\n<commit_msg>use modern net\/http cancel method<commit_after>\/\/ Package bubbles is an Elasticsearch bulk insert client.\n\/\/\n\/\/ It connects to an Elasticsearch cluster via the bulk API\n\/\/ (http:\/\/www.elasticsearch.org\/guide\/en\/elasticsearch\/reference\/current\/docs-bulk.html).\n\/\/ Actions are batched into bulk requests. Actions which resulted\n\/\/ in an error are retried individually.\npackage bubbles\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/realzeitmedia\/bubbles\/loges\"\n)\n\nconst (\n\t\/\/ DefaultMaxDocumentsPerBatch is the number of documents a batch needs to\n\t\/\/ have before it is send. This is per connection.\n\tDefaultMaxDocumentsPerBatch = 1000\n\n\t\/\/ DefaultFlushTimeout is the maximum time we batch something before we try\n\t\/\/ to send it to a server.\n\tDefaultFlushTimeout = 10 * time.Second\n\n\t\/\/ DefaultServerTimeout is the time we give ElasticSearch to respond.\n\tDefaultServerTimeout = 1 * time.Minute\n\n\t\/\/ DefaultConnCount is the number of connections per hosts.\n\tDefaultConnCount = 2\n\n\t\/\/ tuneTimeoutRatio determines when we start backing off to keep the request\n\t\/\/ duration under control.\n\ttuneTimeoutRatio = 6\n\n\tserverErrorWait    = 50 * time.Millisecond\n\tserverErrorWaitMax = 10 * time.Second\n\n\tdefaultElasticSearchPort = \"9200\"\n)\n\nvar (\n\terrInvalidResponse = errors.New(\"invalid response\")\n)\n\n\/\/ Bubbles is the main struct to control a queue of Actions going to the\n\/\/ ElasticSearch servers.\ntype Bubbles struct {\n\tq                chan Action\n\tretryQ           chan Action\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\tmaxDocumentCount int\n\tconnCount        int\n\tflushTimeout     time.Duration\n\tserverTimeout    time.Duration\n\tc                loges.Counter\n\te                loges.Errer\n}\n\n\/\/ Opt is any option to New().\ntype Opt func(*Bubbles)\n\n\/\/ OptConnCount is an option to New() to specify the number of connections per\n\/\/ host. The default is DefaultConnCount.\nfunc OptConnCount(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.connCount = n\n\t}\n}\n\n\/\/ OptFlush is an option to New() to specify the flush timeout of a batch. The\n\/\/ default is DefaultFlushTimeout.\nfunc OptFlush(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.flushTimeout = d\n\t}\n}\n\n\/\/ OptServerTimeout is an option to New() to specify the timeout of a single\n\/\/ batch POST to ElasticSearch. All actions in a bulk which is timed out will\n\/\/ be retried. The default is DefaultServerTimeout.\nfunc OptServerTimeout(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.serverTimeout = d\n\t}\n}\n\n\/\/ OptMaxDocs is an option to New() to specify maximum number of documents in a\n\/\/ single batch. The default is DefaultMaxDocumentsPerBatch.\nfunc OptMaxDocs(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.maxDocumentCount = n\n\t}\n}\n\n\/\/ OptCounter is an option to New() to specify something that counts documents.\nfunc OptCounter(c loges.Counter) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.c = c\n\t}\n}\n\n\/\/ OptErrer is an option to New() to specify an error handler. The default\n\/\/ handler uses the log module.\nfunc OptErrer(e loges.Errer) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.e = e\n\t}\n}\n\n\/\/ New makes a new ElasticSearch bulk inserter. It needs a list with 'ip' or\n\/\/ 'ip:port' addresses, options are added via the Opt* functions.\nfunc New(addrs []string, opts ...Opt) *Bubbles {\n\tb := Bubbles{\n\t\tq:                make(chan Action),\n\t\tquit:             make(chan struct{}),\n\t\tmaxDocumentCount: DefaultMaxDocumentsPerBatch,\n\t\tconnCount:        DefaultConnCount,\n\t\tflushTimeout:     DefaultFlushTimeout,\n\t\tserverTimeout:    DefaultServerTimeout,\n\t\tc:                loges.DefaultCounter{},\n\t\te:                loges.DefaultErrer{},\n\t}\n\tfor _, o := range opts {\n\t\to(&b)\n\t}\n\tb.retryQ = make(chan Action, len(addrs)*b.connCount*b.maxDocumentCount)\n\n\tcl := &http.Client{\n\t\tTimeout: b.serverTimeout,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn errors.New(\"no redirect\")\n\t\t},\n\t\tTransport: &http.Transport{\n\t\t\tDial: (&net.Dialer{\n\t\t\t\tTimeout:   b.serverTimeout,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t}).Dial,\n\t\t\tMaxIdleConnsPerHost: b.connCount,\n\t\t\tDisableCompression:  false,\n\t\t},\n\t}\n\t\/\/ Start a go routine per connection per host\n\tfor _, a := range addrs {\n\t\taddr := withPort(a, defaultElasticSearchPort)\n\t\tfor i := 0; i < b.connCount; i++ {\n\t\t\tb.wg.Add(1)\n\t\t\tgo func(a string) {\n\t\t\t\tclient(&b, cl, a)\n\t\t\t\tb.wg.Done()\n\t\t\t}(addr)\n\t\t}\n\t}\n\treturn &b\n}\n\n\/\/ Enqueue returns the queue to add Actions in a routine. It will block if all bulk\n\/\/ processors are busy.\nfunc (b *Bubbles) Enqueue() chan<- Action {\n\treturn b.q\n}\n\n\/\/ Stop shuts down all ElasticSearch clients. It'll return all Action entries\n\/\/ which were not yet processed, or were up for a retry.\nfunc (b *Bubbles) Stop() []Action {\n\tclose(b.quit)\n\t\/\/ There is no explicit timeout, we rely on b.serverTimeout to shut down\n\t\/\/ everything.\n\tb.wg.Wait()\n\n\t\/\/ Collect and return elements which are in flight.\n\tclose(b.retryQ)\n\tclose(b.q)\n\tpending := make([]Action, 0, len(b.q)+len(b.retryQ))\n\tfor a := range b.q {\n\t\tpending = append(pending, a)\n\t}\n\tfor a := range b.retryQ {\n\t\tpending = append(pending, a)\n\t}\n\treturn pending\n}\n\ntype backoff struct {\n\tlevel        uint8\n\tmax          uint8\n\tmaxBatchSize int\n}\n\nfunc newBackoff(maxBatchSize int) *backoff {\n\tb := &backoff{\n\t\tmaxBatchSize: maxBatchSize,\n\t}\n\t\/\/ Max out when both components do.\n\tfor ; (b.wait() < serverErrorWaitMax || b.size() > 1) && b.level < 32; b.level++ {\n\t}\n\tb.max = b.level\n\tb.level = 0\n\treturn b\n}\n\n\/\/ wait calculates the delay based on the current backoff level.\nfunc (b *backoff) wait() time.Duration {\n\tif b.level == 0 {\n\t\treturn 0 * time.Second\n\t}\n\tw := (1 << (b.level - 1)) * serverErrorWait\n\tif w >= serverErrorWaitMax {\n\t\treturn serverErrorWaitMax\n\t}\n\treturn w\n}\n\n\/\/ batchSize calculates the batchsize based on the current backoff level.\nfunc (b *backoff) size() int {\n\ts := b.maxBatchSize \/ (1 << b.level)\n\tif s <= 1 {\n\t\treturn 1\n\t}\n\treturn s\n}\n\n\/\/ inc increases the backoff level.\nfunc (b *backoff) inc() {\n\tif b.level < b.max {\n\t\tb.level++\n\t}\n}\n\n\/\/ dec decreases the backoff level.\nfunc (b *backoff) dec() {\n\tif b.level > 0 {\n\t\tb.level--\n\t}\n}\n\nfunc min(x, y int) int {\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}\n\n\/\/ client talks to ElasticSearch. This runs in a go routine in a loop and deals\n\/\/ with a single ElasticSearch address.\nfunc client(b *Bubbles, cl *http.Client, addr string) {\n\tvar (\n\t\turl            = fmt.Sprintf(\"http:\/\/%s\/_bulk\", addr)\n\t\tbackoffTrouble = newBackoff(b.maxDocumentCount)\n\t\tbackoffTune    = newBackoff(b.maxDocumentCount)\n\t\ttuneTimeout    = b.serverTimeout \/ tuneTimeoutRatio\n\t\tscratch        = &bytes.Buffer{}\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase <-time.After(backoffTrouble.wait()):\n\t\t}\n\t\ttuneMax := backoffTune.size()\n\t\ttrouble, batchTime, sent := runBatch(\n\t\t\tb,\n\t\t\tcl,\n\t\t\turl,\n\t\t\tmin(backoffTrouble.size(), tuneMax),\n\t\t\tscratch,\n\t\t)\n\t\tif trouble {\n\t\t\tbackoffTrouble.inc()\n\t\t\tb.c.Trouble()\n\t\t} else {\n\t\t\tbackoffTrouble.dec()\n\t\t}\n\t\tif batchTime > tuneTimeout {\n\t\t\tbackoffTune.inc()\n\t\t} else if batchTime <= tuneTimeout\/2 && sent == tuneMax {\n\t\t\tbackoffTune.dec()\n\t\t}\n\t\tb.c.BatchTime(batchTime)\n\t}\n}\n\n\/\/ runBatch gathers and deals with a batch of actions. It returns\n\/\/ whether there was trouble, how long the actual request took, and\n\/\/ how many items were sent successfully.\nfunc runBatch(\n\tb *Bubbles,\n\tcl *http.Client,\n\turl string,\n\tbatchSize int,\n\tscratch *bytes.Buffer,\n) (bool, time.Duration, int) {\n\tactions := make([]Action, 0, b.maxDocumentCount)\n\t\/\/ First use all retry actions.\nretry:\n\tfor len(actions) < batchSize {\n\t\tselect {\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tdefault:\n\t\t\t\/\/ no more retry actions queued\n\t\t\tbreak retry\n\t\t}\n\t}\n\n\tvar t <-chan time.Time\ngather:\n\tfor len(actions) < batchSize {\n\t\tif t == nil && len(actions) > 0 {\n\t\t\t\/\/ Set timeout on the first element we read\n\t\t\tt = time.After(b.flushTimeout)\n\t\t}\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\tfor _, a := range actions {\n\t\t\t\tb.retryQ <- a\n\t\t\t}\n\t\t\tb.c.Actions(0, len(actions), 0)\n\t\t\treturn false, 0, 0\n\t\tcase <-t:\n\t\t\t\/\/ this case is not enabled until we've got an action\n\t\t\tbreak gather\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tcase a := <-b.q:\n\t\t\tactions = append(actions, a)\n\t\t}\n\t}\n\n\tt0 := time.Now()\n\tres, err := postActions(b.c, cl, url, actions, b.quit, scratch)\n\tdt := time.Since(t0)\n\tif err != nil {\n\t\t\/\/ A server error. Retry these actions later.\n\t\tb.e.Error(err)\n\t\tfor _, a := range actions {\n\t\t\tb.retryQ <- a\n\t\t}\n\t\tb.c.Actions(0, len(actions), 0)\n\t\treturn true, dt, 0\n\t}\n\n\t\/\/ Server has accepted the request an sich, but there can be errors in the\n\t\/\/ individual actions.\n\tif !res.Errors {\n\t\t\/\/ Simple case, no errors present.\n\t\tb.c.Actions(len(actions), 0, 0)\n\t\treturn false, dt, len(actions)\n\t}\n\n\t\/\/ Invalid response from ElasticSearch.\n\tif len(actions) != len(res.Items) {\n\t\tb.e.Error(errInvalidResponse)\n\t\tfor _, a := range actions {\n\t\t\tb.retryQ <- a\n\t\t}\n\t\tb.c.Actions(0, len(actions), 0)\n\t\treturn true, dt, 0\n\t}\n\t\/\/ Figure out which actions have errors.\n\tvar (\n\t\tretries = 0\n\t\terrors  = 0\n\t)\n\tfor i, e := range res.Items {\n\t\ta := actions[i]\n\t\tel, ok := e[string(a.Type)]\n\t\tif !ok {\n\t\t\t\/\/ Unexpected reply from ElasticSearch.\n\t\t\tb.e.Error(errInvalidResponse)\n\t\t\tb.retryQ <- a\n\t\t\tretries++\n\t\t\tcontinue\n\t\t}\n\n\t\tc := el.Status\n\t\tswitch {\n\t\tcase c >= 200 && c < 300:\n\t\t\t\/\/ Document accepted by ElasticSearch.\n\t\tcase c == 429 || (c >= 500 && c < 600):\n\t\t\t\/\/ Server error. Retry it.\n\t\t\t\/\/ We get a 429 when the bulk queue is full, which we just retry as\n\t\t\t\/\/ well.\n\t\t\tb.e.Warning(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"transient error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\tb.retryQ <- a\n\t\t\tretries++\n\t\tcase c >= 400 && c < 500:\n\t\t\t\/\/ Some error. Nothing we can do with it.\n\t\t\tb.e.Error(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\terrors++\n\t\tdefault:\n\t\t\t\/\/ No idea.\n\t\t\tb.e.Error(fmt.Errorf(\"unwelcome response %d: %s\", c, el.Error))\n\t\t\terrors++\n\t\t}\n\t}\n\tsent := len(actions) - errors - retries\n\tb.c.Actions(sent, retries, errors)\n\treturn retries > 0, dt, sent\n}\n\ntype bulkRes struct {\n\tTook   int  `json:\"took\"`\n\tErrors bool `json:\"errors\"`\n\tItems  []map[string]struct {\n\t\tIndex   string `json:\"_index\"`\n\t\tType    string `json:\"_type\"`\n\t\tID      string `json:\"_id\"`\n\t\tVersion int    `json:\"_version\"`\n\t\tStatus  int    `json:\"status\"`\n\t\tError   string `json:\"error\"`\n\t} `json:\"items\"`\n}\n\nfunc postActions(\n\tc loges.Counter,\n\tcl *http.Client,\n\turl string,\n\tactions []Action,\n\tquit <-chan struct{},\n\tbuf *bytes.Buffer,\n) (*bulkRes, error) {\n\tbuf.Reset()\n\tfor _, a := range actions {\n\t\tbuf.Write(a.Buf())\n\t}\n\tc.SendTotal(buf.Len())\n\n\t\/\/ This doesn't Chunk.\n\treq, err := http.NewRequest(\"POST\", url, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Cancel = quit\n\tresp, err := cl.Do(req)\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, fmt.Errorf(\"status: %s\", resp.Status)\n\t}\n\n\tvar (\n\t\tbulk bulkRes\n\t\td    = json.NewDecoder(resp.Body)\n\t)\n\tif err := d.Decode(&bulk); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &bulk, nil\n}\n\n\/\/ ActionError wraps an Action we won't retry. It implements the error interface.\ntype ActionError struct {\n\tAction     Action\n\tStatusCode int\n\tMsg        string\n\tServer     string\n}\n\nfunc (e ActionError) Error() string {\n\treturn fmt.Sprintf(\"%s: %s %s\", e.Server, e.Action.Type, e.Msg)\n}\n\n\/\/ withPort adds a default port to an address string.\nfunc withPort(a, port string) string {\n\tif _, _, err := net.SplitHostPort(a); err != nil {\n\t\t\/\/ no port found.\n\t\treturn net.JoinHostPort(a, port)\n\t}\n\treturn a\n}\n<|endoftext|>"}
{"text":"<commit_before>package sourcegraph\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n)\n\ntype contextKey int\n\nconst (\n\tgrpcEndpointKey contextKey = iota\n\thttpEndpointKey\n\tcredentialsKey\n)\n\n\/\/ WithGRPCEndpoint returns a copy of parent whose clients (obtained\n\/\/ using FromContext) communicate with the given gRPC API endpoint\n\/\/ URL.\nfunc WithGRPCEndpoint(parent context.Context, url *url.URL) context.Context {\n\treturn context.WithValue(parent, grpcEndpointKey, url)\n}\n\n\/\/ GRPCEndpoint returns the context's gRPC endpoint URL that was\n\/\/ previously configured using WithGRPCEndpoint.\nfunc GRPCEndpoint(ctx context.Context) *url.URL {\n\turl, _ := ctx.Value(grpcEndpointKey).(*url.URL)\n\tif url == nil {\n\t\tpanic(\"no gRPC API endpoint URL set in context\")\n\t}\n\treturn url\n}\n\n\/\/ WithHTTPEndpoint returns a copy of parent whose clients (obtained\n\/\/ using FromContext) communicate with the given HTTP API endpoint\n\/\/ URL.\nfunc WithHTTPEndpoint(parent context.Context, url *url.URL) context.Context {\n\treturn context.WithValue(parent, httpEndpointKey, url)\n}\n\n\/\/ HTTPEndpoint returns the context's HTTP API endpoint URL that was\n\/\/ previously configured using WithHTTPEndpoint.\nfunc HTTPEndpoint(ctx context.Context) *url.URL {\n\turl, _ := ctx.Value(httpEndpointKey).(*url.URL)\n\tif url == nil {\n\t\tpanic(\"no HTTP API endpoint URL set in context\")\n\t}\n\treturn url\n}\n\n\/\/ Credentials is implemented by authentication providers that provide\n\/\/ both gRPC and HTTP auth (e.g., API keys, tickets).\ntype Credentials interface {\n\t\/\/ The TokenSource adds authentication info to gRPC calls.\n\tcredentials.Credentials\n\n\t\/\/ NewTransport creates a new HTTP transport that adds\n\t\/\/ authentication info to outgoing HTTP requests and calls the\n\t\/\/ underlying transport. It MUST NOT modify the Credentials object\n\t\/\/ (e.g., it should return a copy of it with its Transport field\n\t\/\/ set to the underlying transport).\n\tNewTransport(underlying http.RoundTripper) http.RoundTripper\n}\n\n\/\/ WithClientCredentials adds cred as a credential provider for future\n\/\/ API clients constructed using this context (with FromContext).\nfunc WithClientCredentials(parent context.Context, cred Credentials) context.Context {\n\tcreds := clientCredentialsFromContext(parent)\n\treturn context.WithValue(parent, credentialsKey, append([]Credentials{cred}, creds...))\n}\n\nfunc clientCredentialsFromContext(ctx context.Context) []Credentials {\n\tcreds, ok := ctx.Value(credentialsKey).([]Credentials)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn creds\n}\n\n\/\/ NewClientFromContext returns a Sourcegraph API client configured\n\/\/ using the context (e.g., authenticated using the context's\n\/\/ credentials (actor & tickets)).\nvar NewClientFromContext = func(ctx context.Context) *Client {\n\ttransport := keepAliveTransport\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithCodec(GRPCCodec),\n\t}\n\n\tgrpcEndpoint := GRPCEndpoint(ctx)\n\tif grpcEndpoint.Scheme == \"https\" {\n\t\topts = append(opts, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, \"\")))\n\t}\n\n\tfor _, cred := range clientCredentialsFromContext(ctx) {\n\t\ttransport = cred.NewTransport(transport)\n\t}\n\topts = append(opts, grpc.WithPerRPCCredentials(contextCredentials{}))\n\n\tconn, err := pooledGRPCDial(grpcEndpoint.Host, opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc := NewClient(&http.Client{Transport: transport}, conn)\n\tc.BaseURL = HTTPEndpoint(ctx)\n\treturn c\n}\n\ntype contextCredentials struct{}\n\nfunc (contextCredentials) GetRequestMetadata(ctx context.Context) (map[string]string, error) {\n\tmd := map[string]string{}\n\tfor _, cred := range clientCredentialsFromContext(ctx) {\n\t\tcredMD, err := cred.GetRequestMetadata(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor k, v := range credMD {\n\t\t\tmd[k] = v\n\t\t}\n\t}\n\treturn md, nil\n}\n<commit_msg>add describe client credentials function for testing<commit_after>package sourcegraph\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n)\n\ntype contextKey int\n\nconst (\n\tgrpcEndpointKey contextKey = iota\n\thttpEndpointKey\n\tcredentialsKey\n)\n\n\/\/ WithGRPCEndpoint returns a copy of parent whose clients (obtained\n\/\/ using FromContext) communicate with the given gRPC API endpoint\n\/\/ URL.\nfunc WithGRPCEndpoint(parent context.Context, url *url.URL) context.Context {\n\treturn context.WithValue(parent, grpcEndpointKey, url)\n}\n\n\/\/ GRPCEndpoint returns the context's gRPC endpoint URL that was\n\/\/ previously configured using WithGRPCEndpoint.\nfunc GRPCEndpoint(ctx context.Context) *url.URL {\n\turl, _ := ctx.Value(grpcEndpointKey).(*url.URL)\n\tif url == nil {\n\t\tpanic(\"no gRPC API endpoint URL set in context\")\n\t}\n\treturn url\n}\n\n\/\/ WithHTTPEndpoint returns a copy of parent whose clients (obtained\n\/\/ using FromContext) communicate with the given HTTP API endpoint\n\/\/ URL.\nfunc WithHTTPEndpoint(parent context.Context, url *url.URL) context.Context {\n\treturn context.WithValue(parent, httpEndpointKey, url)\n}\n\n\/\/ HTTPEndpoint returns the context's HTTP API endpoint URL that was\n\/\/ previously configured using WithHTTPEndpoint.\nfunc HTTPEndpoint(ctx context.Context) *url.URL {\n\turl, _ := ctx.Value(httpEndpointKey).(*url.URL)\n\tif url == nil {\n\t\tpanic(\"no HTTP API endpoint URL set in context\")\n\t}\n\treturn url\n}\n\n\/\/ Credentials is implemented by authentication providers that provide\n\/\/ both gRPC and HTTP auth (e.g., API keys, tickets).\ntype Credentials interface {\n\t\/\/ The TokenSource adds authentication info to gRPC calls.\n\tcredentials.Credentials\n\n\t\/\/ NewTransport creates a new HTTP transport that adds\n\t\/\/ authentication info to outgoing HTTP requests and calls the\n\t\/\/ underlying transport. It MUST NOT modify the Credentials object\n\t\/\/ (e.g., it should return a copy of it with its Transport field\n\t\/\/ set to the underlying transport).\n\tNewTransport(underlying http.RoundTripper) http.RoundTripper\n}\n\n\/\/ WithClientCredentials adds cred as a credential provider for future\n\/\/ API clients constructed using this context (with FromContext).\nfunc WithClientCredentials(parent context.Context, cred Credentials) context.Context {\n\tcreds := clientCredentialsFromContext(parent)\n\treturn context.WithValue(parent, credentialsKey, append([]Credentials{cred}, creds...))\n}\n\nfunc clientCredentialsFromContext(ctx context.Context) []Credentials {\n\tcreds, ok := ctx.Value(credentialsKey).([]Credentials)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn creds\n}\n\n\/\/ DescribeClientCredentials is a testing utility function to test for\n\/\/ credentials in the context.\nfunc DescribeClientCredentials(ctx context.Context) []string {\n\tvar s []string\n\tfor _, v := range clientCredentialsFromContext(ctx) {\n\t\ts = append(s, fmt.Sprintf(\"%v\", v))\n\t}\n\treturn s\n}\n\n\/\/ NewClientFromContext returns a Sourcegraph API client configured\n\/\/ using the context (e.g., authenticated using the context's\n\/\/ credentials (actor & tickets)).\nvar NewClientFromContext = func(ctx context.Context) *Client {\n\ttransport := keepAliveTransport\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithCodec(GRPCCodec),\n\t}\n\n\tgrpcEndpoint := GRPCEndpoint(ctx)\n\tif grpcEndpoint.Scheme == \"https\" {\n\t\topts = append(opts, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, \"\")))\n\t}\n\n\tfor _, cred := range clientCredentialsFromContext(ctx) {\n\t\ttransport = cred.NewTransport(transport)\n\t}\n\topts = append(opts, grpc.WithPerRPCCredentials(contextCredentials{}))\n\n\tconn, err := pooledGRPCDial(grpcEndpoint.Host, opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc := NewClient(&http.Client{Transport: transport}, conn)\n\tc.BaseURL = HTTPEndpoint(ctx)\n\treturn c\n}\n\ntype contextCredentials struct{}\n\nfunc (contextCredentials) GetRequestMetadata(ctx context.Context) (map[string]string, error) {\n\tmd := map[string]string{}\n\tfor _, cred := range clientCredentialsFromContext(ctx) {\n\t\tcredMD, err := cred.GetRequestMetadata(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor k, v := range credMD {\n\t\t\tmd[k] = v\n\t\t}\n\t}\n\treturn md, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/koding\/bongo\"\n)\n\ntype Account struct {\n\t\/\/ unique id of the account\n\tId int64 `json:\"id\"`\n\t\/\/ old id of the account, which is coming from mongo\n\tOldId string `json:\"oldId\"`\n}\n\nfunc NewAccount() *Account {\n\treturn &Account{}\n}\n\nfunc (a *Account) GetId() int64 {\n\treturn a.Id\n}\n\nfunc (a *Account) TableName() string {\n\treturn \"account\"\n}\n\nfunc (a *Account) One(selector map[string]interface{}) error {\n\treturn bongo.B.One(a, a, selector)\n}\n\nfunc (a *Account) FetchOrCreate() error {\n\tif a.OldId == \"\" {\n\t\treturn errors.New(\"old id is not set\")\n\t}\n\n\tselector := map[string]interface{}{\n\t\t\"old_id\": a.OldId,\n\t}\n\n\terr := a.One(selector)\n\tif err == gorm.RecordNotFound {\n\t\tif err := a.Create(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (a *Account) Create() error {\n\tif a.OldId == \"\" {\n\t\treturn errors.New(\"old id is not set\")\n\t}\n\treturn bongo.B.Create(a)\n}\n\nfunc (a *Account) FetchChannels(q *Query) ([]Channel, error) {\n\tcp := NewChannelParticipant()\n\t\/\/ fetch channel ids\n\tcids, err := cp.FetchParticipatedChannelIds(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ fetch channels by their ids\n\tc := NewChannel()\n\tchannels, err := c.FetchByIds(cids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn channels, nil\n}\n\nfunc (a *Account) Follow(targetId int64) (*ChannelParticipant, error) {\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err == nil {\n\t\treturn c.AddParticipant(targetId)\n\t}\n\n\tif err == gorm.RecordNotFound {\n\t\tc, err := a.CreateFollowingFeedChannel()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn c.AddParticipant(targetId)\n\t}\n\treturn nil, err\n}\n\nfunc (a *Account) Unfollow(targetId int64) error {\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err != nil {\n\t\tfmt.Println(1, err)\n\t\treturn err\n\t}\n\tfmt.Println(2)\n\n\treturn c.RemoveParticipant(targetId)\n}\n\nfunc (a *Account) FetchFollowerIds() ([]int64, error) {\n\tfollowerIds := make([]int64, 0)\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\n\t\t\t\"Account id is not set for FetchFollowerChannelIds function \",\n\t\t)\n\t}\n\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err != nil {\n\t\treturn followerIds, err\n\t}\n\n\tparticipants, err := c.FetchParticipantIds()\n\tif err != nil {\n\t\treturn followerIds, err\n\t}\n\n\treturn participants, nil\n}\n\nfunc (a *Account) FetchChannel(channelType string) (*Channel, error) {\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\"Account id is not set\")\n\t}\n\n\tc := NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"creator_id\": a.Id,\n\t\t\"type\":       channelType,\n\t}\n\n\tif err := c.One(selector); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (a *Account) CreateFollowingFeedChannel() (*Channel, error) {\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\"Account id is not set\")\n\t}\n\n\tc := NewChannel()\n\tc.CreatorId = a.Id\n\tc.Name = fmt.Sprintf(\"%d-FollowingFeedChannel\", a.Id)\n\tc.GroupName = Channel_KODING_NAME\n\tc.Purpose = \"Following Feed for Me\"\n\tc.Type = Channel_TYPE_FOLLOWERS\n\tif err := c.Create(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (a *Account) FetchFollowerChannelIds() ([]int64, error) {\n\n\tfollowerIds, err := a.FetchFollowerIds()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp := NewChannelParticipant()\n\tvar channelIds []int64\n\terr = bongo.B.DB.\n\t\tTable(cp.TableName()).\n\t\tWhere(\n\t\t\"creator_id IN (?) and type = ?\",\n\t\tfollowerIds,\n\t\tChannel_TYPE_FOLLOWINGFEED,\n\t).Find(&channelIds).Error\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn channelIds, nil\n}\n<commit_msg>Social: add sql tag properties<commit_after>package models\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/koding\/bongo\"\n)\n\ntype Account struct {\n\t\/\/ unique id of the account\n\tId int64 `json:\"id\"`\n\t\/\/ old id of the account, which is coming from mongo\n\t\/\/ mongo ids has 24 char\n\tOldId string `json:\"oldId\"      sql:\"NOT NULL;UNIQUE;TYPE:VARCHAR(24);\"`\n}\n\nfunc NewAccount() *Account {\n\treturn &Account{}\n}\n\nfunc (a *Account) GetId() int64 {\n\treturn a.Id\n}\n\nfunc (a *Account) TableName() string {\n\treturn \"account\"\n}\n\nfunc (a *Account) One(selector map[string]interface{}) error {\n\treturn bongo.B.One(a, a, selector)\n}\n\nfunc (a *Account) FetchOrCreate() error {\n\tif a.OldId == \"\" {\n\t\treturn errors.New(\"old id is not set\")\n\t}\n\n\tselector := map[string]interface{}{\n\t\t\"old_id\": a.OldId,\n\t}\n\n\terr := a.One(selector)\n\tif err == gorm.RecordNotFound {\n\t\tif err := a.Create(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (a *Account) Create() error {\n\tif a.OldId == \"\" {\n\t\treturn errors.New(\"old id is not set\")\n\t}\n\treturn bongo.B.Create(a)\n}\n\nfunc (a *Account) FetchChannels(q *Query) ([]Channel, error) {\n\tcp := NewChannelParticipant()\n\t\/\/ fetch channel ids\n\tcids, err := cp.FetchParticipatedChannelIds(a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ fetch channels by their ids\n\tc := NewChannel()\n\tchannels, err := c.FetchByIds(cids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn channels, nil\n}\n\nfunc (a *Account) Follow(targetId int64) (*ChannelParticipant, error) {\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err == nil {\n\t\treturn c.AddParticipant(targetId)\n\t}\n\n\tif err == gorm.RecordNotFound {\n\t\tc, err := a.CreateFollowingFeedChannel()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn c.AddParticipant(targetId)\n\t}\n\treturn nil, err\n}\n\nfunc (a *Account) Unfollow(targetId int64) error {\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err != nil {\n\t\tfmt.Println(1, err)\n\t\treturn err\n\t}\n\tfmt.Println(2)\n\n\treturn c.RemoveParticipant(targetId)\n}\n\nfunc (a *Account) FetchFollowerIds() ([]int64, error) {\n\tfollowerIds := make([]int64, 0)\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\n\t\t\t\"Account id is not set for FetchFollowerChannelIds function \",\n\t\t)\n\t}\n\n\tc, err := a.FetchChannel(Channel_TYPE_FOLLOWERS)\n\tif err != nil {\n\t\treturn followerIds, err\n\t}\n\n\tparticipants, err := c.FetchParticipantIds()\n\tif err != nil {\n\t\treturn followerIds, err\n\t}\n\n\treturn participants, nil\n}\n\nfunc (a *Account) FetchChannel(channelType string) (*Channel, error) {\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\"Account id is not set\")\n\t}\n\n\tc := NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"creator_id\": a.Id,\n\t\t\"type\":       channelType,\n\t}\n\n\tif err := c.One(selector); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (a *Account) CreateFollowingFeedChannel() (*Channel, error) {\n\tif a.Id == 0 {\n\t\treturn nil, errors.New(\"Account id is not set\")\n\t}\n\n\tc := NewChannel()\n\tc.CreatorId = a.Id\n\tc.Name = fmt.Sprintf(\"%d-FollowingFeedChannel\", a.Id)\n\tc.GroupName = Channel_KODING_NAME\n\tc.Purpose = \"Following Feed for Me\"\n\tc.Type = Channel_TYPE_FOLLOWERS\n\tif err := c.Create(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (a *Account) FetchFollowerChannelIds() ([]int64, error) {\n\n\tfollowerIds, err := a.FetchFollowerIds()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp := NewChannelParticipant()\n\tvar channelIds []int64\n\terr = bongo.B.DB.\n\t\tTable(cp.TableName()).\n\t\tWhere(\n\t\t\"creator_id IN (?) and type = ?\",\n\t\tfollowerIds,\n\t\tChannel_TYPE_FOLLOWINGFEED,\n\t).Find(&channelIds).Error\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn channelIds, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bubbles\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ DefaultMaxDocumentsPerBatch is the number of documents a batch needs to\n\t\/\/ have before it is send. This is per connection.\n\tDefaultMaxDocumentsPerBatch = 1000\n\n\t\/\/ DefaultFlushTimeout is the maximum time we batch something before we try\n\t\/\/ to send it to a server.\n\tDefaultFlushTimeout = 10 * time.Second\n\n\t\/\/ DefaultServerTimeout is the time we give ElasticSearch to respond. This\n\t\/\/ is also the maximum time Stop() will take.\n\tDefaultServerTimeout = 10 * time.Second\n\n\t\/\/ DefaultConnCount is the number of connections per hosts.\n\tDefaultConnCount = 2\n\n\tserverErrorWait    = 500 * time.Millisecond\n\tserverErrorWaitMax = 16 * time.Second\n\n\tdefaultElasticSearchPort = \"9200\"\n)\n\nvar (\n\terrInvalidResponse = errors.New(\"invalid response\")\n)\n\n\/\/ Bubbles is the main struct to control a queue of Actions going to the\n\/\/ ElasticSearch servers.\ntype Bubbles struct {\n\tq                chan Action\n\tretryQ           chan Action\n\tblocks           chan []Action\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\tmaxDocumentCount int\n\tconnCount        int\n\tflushTimeout     time.Duration\n\tserverTimeout    time.Duration\n\tc                Counter\n\te                Errer\n}\n\n\/\/ Opt is any option to New().\ntype Opt func(*Bubbles)\n\n\/\/ OptConnCount is an option to New() to specify the number of connections per\n\/\/ host. The default is DefaultConnCount.\nfunc OptConnCount(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.connCount = n\n\t}\n}\n\n\/\/ OptFlush is an option to New() to specify the flush timeout of a batch. The\n\/\/ default is DefaultFlushTimeout.\nfunc OptFlush(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.flushTimeout = d\n\t}\n}\n\n\/\/ OptServerTimeout is an option to New() to specify the timeout of a single\n\/\/ batch POST to ElasticSearch. This value is also the maximum time Stop() will\n\/\/ take. All actions in a bulk which is timed out will be retried. The default\n\/\/ is DefaultServerTimeout.\nfunc OptServerTimeout(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.serverTimeout = d\n\t}\n}\n\n\/\/ OptMaxDocs is an option to New() to specify maximum number of documents in a\n\/\/ single batch. The default is DefaultMaxDocumentsPerBatch.\nfunc OptMaxDocs(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.maxDocumentCount = n\n\t}\n}\n\n\/\/ OptCounter is an option to New() to specify something that counts documents.\nfunc OptCounter(c Counter) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.c = c\n\t}\n}\n\n\/\/ OptErrer is an option to New() to specify an error handler. The default\n\/\/ handler uses the log module.\nfunc OptErrer(e Errer) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.e = e\n\t}\n}\n\n\/\/ New makes a new ElasticSearch bulk inserter. It needs a list with 'ip' or\n\/\/ 'ip:port' addresses, options are added via the Opt* functions.\nfunc New(addrs []string, opts ...Opt) *Bubbles {\n\tb := Bubbles{\n\t\tq:                make(chan Action),\n\t\tblocks:           make(chan []Action),\n\t\tquit:             make(chan struct{}),\n\t\tmaxDocumentCount: DefaultMaxDocumentsPerBatch,\n\t\tconnCount:        DefaultConnCount,\n\t\tflushTimeout:     DefaultFlushTimeout,\n\t\tserverTimeout:    DefaultServerTimeout,\n\t\tc:                DefaultCounter{},\n\t\te:                DefaultErrer{},\n\t}\n\tfor _, o := range opts {\n\t\to(&b)\n\t}\n\t\/\/ +1 for our buildBlocks goroutine\n\tb.retryQ = make(chan Action, (1+len(addrs)*b.connCount)*b.maxDocumentCount)\n\n\t\/\/ read from q and write full blocks of actions to b.blocks\n\tb.wg.Add(1)\n\tgo buildBlocks(&b)\n\n\t\/\/ Start a go routine per connection per host\n\tfor _, a := range addrs {\n\t\taddr := withPort(a, defaultElasticSearchPort)\n\t\tfor i := 0; i < b.connCount; i++ {\n\t\t\tb.wg.Add(1)\n\t\t\tgo func(a string) {\n\t\t\t\tclient(&b, a)\n\t\t\t\tb.wg.Done()\n\t\t\t}(addr)\n\t\t}\n\t}\n\treturn &b\n}\n\n\/\/ Enqueue returns the queue to add Actions in a routine. It will block if all bulk\n\/\/ processors are busy.\nfunc (b *Bubbles) Enqueue() chan<- Action {\n\treturn b.q\n}\n\n\/\/ Stop shuts down all ElasticSearch clients. It'll return all Action entries\n\/\/ which were not yet processed, or were up for a retry. It can take\n\/\/ OptServerTimeout to complete.\nfunc (b *Bubbles) Stop() []Action {\n\tclose(b.quit)\n\t\/\/ There is no explicit timeout, we rely on b.serverTimeout to shut down\n\t\/\/ everything.\n\tb.wg.Wait()\n\n\t\/\/ Collect and return elements which are in flight.\n\tclose(b.retryQ)\n\tclose(b.q)\n\tpending := make([]Action, 0, len(b.q)+len(b.retryQ))\n\tfor a := range b.q {\n\t\tpending = append(pending, a)\n\t}\n\tfor a := range b.retryQ {\n\t\tpending = append(pending, a)\n\t}\n\treturn pending\n}\n\n\/\/ buildBlocks reads from the retry Q and the incoming Q and pushes work to the\n\/\/ http clients.\nfunc buildBlocks(b *Bubbles) {\n\tvar block []Action\nloop:\n\tfor {\n\t\tblock = make([]Action, 0, b.maxDocumentCount)\n\n\t\t\/\/ First use all retry actions.\n\tretry:\n\t\tfor len(block) < b.maxDocumentCount {\n\t\t\tselect {\n\t\t\tcase <-b.quit:\n\t\t\t\tbreak loop\n\t\t\tcase a := <-b.retryQ:\n\t\t\t\tblock = append(block, a)\n\t\t\tdefault:\n\t\t\t\t\/\/ no more retry actions queued\n\t\t\t\tbreak retry\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Then wait for more incoming Actions, if we're still not full.\n\t\tvar t <-chan time.Time\n\tgather:\n\t\tfor len(block) < b.maxDocumentCount {\n\t\t\tif t == nil && len(block) > 0 {\n\t\t\t\t\/\/ Set timeout on the first element we read\n\t\t\t\tt = time.After(b.flushTimeout)\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-b.quit:\n\t\t\t\tbreak loop\n\t\t\tcase <-t:\n\t\t\t\t\/\/ this case is not enabled until we've got an action\n\t\t\t\tbreak gather\n\t\t\tcase a := <-b.retryQ:\n\t\t\t\tblock = append(block, a)\n\t\t\tcase a := <-b.q:\n\t\t\t\tblock = append(block, a)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Give the block to an HTTP client.\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\tbreak loop\n\t\tcase b.blocks <- block:\n\t\t\tblock = nil\n\t\t}\n\t}\n\n\t\/\/ Put unhandled elements back on shutdown.\n\tif block != nil {\n\t\tfor _, a := range block {\n\t\t\tb.retryQ <- a\n\t\t}\n\t}\n\tb.wg.Done()\n}\n\n\/\/ client talks to ElasticSearch. This runs in a go routine in a loop and deals\n\/\/ with a single ElasticSearch address.\nfunc client(b *Bubbles, addr string) {\n\turl := fmt.Sprintf(\"http:\/\/%s\/_bulk\", addr)\n\n\tcl := http.Client{\n\t\tTimeout: b.serverTimeout,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn errors.New(\"no redirect\")\n\t\t},\n\t}\n\n\twait := serverErrorWait\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tcase block := <-b.blocks:\n\t\t\tif runBlock(b, cl, url, block) {\n\t\t\t\t\/\/ Some error, back off.\n\t\t\t\tselect {\n\t\t\t\tcase <-b.quit:\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(wait):\n\t\t\t\t\tb.c.Timeout()\n\t\t\t\t\twait *= 2\n\t\t\t\t\tif wait >= serverErrorWaitMax {\n\t\t\t\t\t\twait = serverErrorWaitMax\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twait = serverErrorWait\n\t\t}\n\t}\n}\n\n\/\/ runBlock gathers and deals with a batch of actions. It returns\n\/\/ whether there was an error. On case of error it'll put all retryable Actions\n\/\/ in the retryQ.\nfunc runBlock(b *Bubbles, cl http.Client, url string, block []Action) bool {\n\n\tres, err := postActions(b.c, cl, url, block)\n\tif err != nil {\n\t\t\/\/ A server error. Retry these actions later.\n\t\tb.e.Error(err)\n\t\tfor _, a := range block {\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t}\n\t\treturn true\n\t}\n\n\t\/\/ Server has accepted the request an sich, but there can be errors in the\n\t\/\/ individual actions.\n\tif !res.Errors {\n\t\t\/\/ Simple case, no errors present.\n\t\treturn false\n\t}\n\n\t\/\/ Invalid response from ElasticSearch.\n\tif len(block) != len(res.Items) {\n\t\tb.e.Error(errInvalidResponse)\n\t\tfor _, a := range block {\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t}\n\t\treturn true\n\t}\n\t\/\/ Figure out which actions have errors.\n\tfor i, e := range res.Items {\n\t\ta := block[i]\n\t\tel, ok := e[string(a.Type)]\n\t\tif !ok {\n\t\t\t\/\/ Unexpected reply from ElasticSearch.\n\t\t\tb.e.Error(errInvalidResponse)\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t\tcontinue\n\t\t}\n\n\t\tc := el.Status\n\t\tswitch {\n\t\tcase c >= 200 && c < 300:\n\t\t\t\/\/ Document accepted by ElasticSearch.\n\t\tcase c == 429 || (c >= 500 && c < 600):\n\t\t\t\/\/ Server error. Retry it.\n\t\t\t\/\/ We get a 429 when the bulk queue is full, which we just retry as\n\t\t\t\/\/ well.\n\t\t\tb.e.Warning(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"transient error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\tb.c.Retry(RetryTransient, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\tcase c >= 400 && c < 500:\n\t\t\t\/\/ Some error. Nothing we can do with it.\n\t\t\tb.e.Error(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\tdefault:\n\t\t\t\/\/ No idea.\n\t\t\tb.e.Error(fmt.Errorf(\"unwelcome response %d: %s\", c, el.Error))\n\t\t}\n\t}\n\treturn true\n}\n\ntype bulkRes struct {\n\tTook   int  `json:\"took\"`\n\tErrors bool `json:\"errors\"`\n\tItems  []map[string]struct {\n\t\tIndex   string `json:\"_index\"`\n\t\tType    string `json:\"_type\"`\n\t\tID      string `json:\"_id\"`\n\t\tVersion int    `json:\"_version\"`\n\t\tStatus  int    `json:\"status\"`\n\t\tError   string `json:\"error\"`\n\t} `json:\"items\"`\n}\n\nfunc postActions(c Counter, cl http.Client, url string, actions []Action) (*bulkRes, error) {\n\tbuf := bytes.Buffer{}\n\tfor _, a := range actions {\n\t\tc.Send(a.Type, len(a.Document))\n\t\tbuf.Write(a.Buf())\n\t}\n\tc.SendTotal(buf.Len())\n\n\t\/\/ This doesn't Chunk.\n\tresp, err := cl.Post(url, \"application\/json\", &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar bulk bulkRes\n\tif err := json.Unmarshal(body, &bulk); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &bulk, nil\n}\n\n\/\/ ActionError wraps an Action we won't retry. It implements the error interface.\ntype ActionError struct {\n\tAction     Action\n\tStatusCode int\n\tMsg        string\n\tServer     string\n}\n\nfunc (e ActionError) Error() string {\n\treturn fmt.Sprintf(\"%s: %s %s\", e.Server, e.Action.Type, e.Msg)\n}\n\n\/\/ withPort adds a default port to an address string.\nfunc withPort(a, port string) string {\n\tif _, _, err := net.SplitHostPort(a); err != nil {\n\t\t\/\/ no port found.\n\t\treturn net.JoinHostPort(a, port)\n\t}\n\treturn a\n}\n<commit_msg>Back out the block building change, since it interferes with block size backoff.<commit_after>package bubbles\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ DefaultMaxDocumentsPerBatch is the number of documents a batch needs to\n\t\/\/ have before it is send. This is per connection.\n\tDefaultMaxDocumentsPerBatch = 1000\n\n\t\/\/ DefaultFlushTimeout is the maximum time we batch something before we try\n\t\/\/ to send it to a server.\n\tDefaultFlushTimeout = 10 * time.Second\n\n\t\/\/ DefaultServerTimeout is the time we give ElasticSearch to respond. This\n\t\/\/ is also the maximum time Stop() will take.\n\tDefaultServerTimeout = 10 * time.Second\n\n\t\/\/ DefaultConnCount is the number of connections per hosts.\n\tDefaultConnCount = 2\n\n\tserverErrorWait    = 500 * time.Millisecond\n\tserverErrorWaitMax = 16 * time.Second\n\n\tdefaultElasticSearchPort = \"9200\"\n)\n\nvar (\n\terrInvalidResponse = errors.New(\"invalid response\")\n)\n\n\/\/ Bubbles is the main struct to control a queue of Actions going to the\n\/\/ ElasticSearch servers.\ntype Bubbles struct {\n\tq                chan Action\n\tretryQ           chan Action\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\tmaxDocumentCount int\n\tconnCount        int\n\tflushTimeout     time.Duration\n\tserverTimeout    time.Duration\n\tc                Counter\n\te                Errer\n}\n\n\/\/ Opt is any option to New().\ntype Opt func(*Bubbles)\n\n\/\/ OptConnCount is an option to New() to specify the number of connections per\n\/\/ host. The default is DefaultConnCount.\nfunc OptConnCount(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.connCount = n\n\t}\n}\n\n\/\/ OptFlush is an option to New() to specify the flush timeout of a batch. The\n\/\/ default is DefaultFlushTimeout.\nfunc OptFlush(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.flushTimeout = d\n\t}\n}\n\n\/\/ OptServerTimeout is an option to New() to specify the timeout of a single\n\/\/ batch POST to ElasticSearch. This value is also the maximum time Stop() will\n\/\/ take. All actions in a bulk which is timed out will be retried. The default\n\/\/ is DefaultServerTimeout.\nfunc OptServerTimeout(d time.Duration) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.serverTimeout = d\n\t}\n}\n\n\/\/ OptMaxDocs is an option to New() to specify maximum number of documents in a\n\/\/ single batch. The default is DefaultMaxDocumentsPerBatch.\nfunc OptMaxDocs(n int) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.maxDocumentCount = n\n\t}\n}\n\n\/\/ OptCounter is an option to New() to specify something that counts documents.\nfunc OptCounter(c Counter) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.c = c\n\t}\n}\n\n\/\/ OptErrer is an option to New() to specify an error handler. The default\n\/\/ handler uses the log module.\nfunc OptErrer(e Errer) Opt {\n\treturn func(b *Bubbles) {\n\t\tb.e = e\n\t}\n}\n\n\/\/ New makes a new ElasticSearch bulk inserter. It needs a list with 'ip' or\n\/\/ 'ip:port' addresses, options are added via the Opt* functions.\nfunc New(addrs []string, opts ...Opt) *Bubbles {\n\tb := Bubbles{\n\t\tq:                make(chan Action),\n\t\tquit:             make(chan struct{}),\n\t\tmaxDocumentCount: DefaultMaxDocumentsPerBatch,\n\t\tconnCount:        DefaultConnCount,\n\t\tflushTimeout:     DefaultFlushTimeout,\n\t\tserverTimeout:    DefaultServerTimeout,\n\t\tc:                DefaultCounter{},\n\t\te:                DefaultErrer{},\n\t}\n\tfor _, o := range opts {\n\t\to(&b)\n\t}\n\tb.retryQ = make(chan Action, len(addrs)*b.connCount*b.maxDocumentCount)\n\n\t\/\/ Start a go routine per connection per host\n\tfor _, a := range addrs {\n\t\taddr := withPort(a, defaultElasticSearchPort)\n\t\tfor i := 0; i < b.connCount; i++ {\n\t\t\tb.wg.Add(1)\n\t\t\tgo func(a string) {\n\t\t\t\tclient(&b, a)\n\t\t\t\tb.wg.Done()\n\t\t\t}(addr)\n\t\t}\n\t}\n\treturn &b\n}\n\n\/\/ Enqueue returns the queue to add Actions in a routine. It will block if all bulk\n\/\/ processors are busy.\nfunc (b *Bubbles) Enqueue() chan<- Action {\n\treturn b.q\n}\n\n\/\/ Stop shuts down all ElasticSearch clients. It'll return all Action entries\n\/\/ which were not yet processed, or were up for a retry. It can take\n\/\/ OptServerTimeout to complete.\nfunc (b *Bubbles) Stop() []Action {\n\tclose(b.quit)\n\t\/\/ There is no explicit timeout, we rely on b.serverTimeout to shut down\n\t\/\/ everything.\n\tb.wg.Wait()\n\n\t\/\/ Collect and return elements which are in flight.\n\tclose(b.retryQ)\n\tclose(b.q)\n\tpending := make([]Action, 0, len(b.q)+len(b.retryQ))\n\tfor a := range b.q {\n\t\tpending = append(pending, a)\n\t}\n\tfor a := range b.retryQ {\n\t\tpending = append(pending, a)\n\t}\n\treturn pending\n}\n\n\/\/ client talks to ElasticSearch. This runs in a go routine in a loop and deals\n\/\/ with a single ElasticSearch address.\nfunc client(b *Bubbles, addr string) {\n\turl := fmt.Sprintf(\"http:\/\/%s\/_bulk\", addr)\n\n\tcl := http.Client{\n\t\tTimeout: b.serverTimeout,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn errors.New(\"no redirect\")\n\t\t},\n\t}\n\n\twait := serverErrorWait\n\tfor {\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif runBatch(b, cl, url) {\n\t\t\t\/\/ Some error, back off.\n\t\t\tselect {\n\t\t\tcase <-b.quit:\n\t\t\t\treturn\n\t\t\tcase <-time.After(wait):\n\t\t\t\tb.c.Timeout()\n\t\t\t\twait *= 2\n\t\t\t\tif wait >= serverErrorWaitMax {\n\t\t\t\t\twait = serverErrorWaitMax\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\twait = serverErrorWait\n\t}\n}\n\n\/\/ runBatch gathers and deals with a batch of actions. It returns\n\/\/ whether there was an error.\nfunc runBatch(b *Bubbles, cl http.Client, url string) bool {\n\tactions := make([]Action, 0, b.maxDocumentCount)\n\t\/\/ First use all retry actions.\nretry:\n\tfor len(actions) < b.maxDocumentCount {\n\t\tselect {\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tdefault:\n\t\t\t\/\/ no more retry actions queued\n\t\t\tbreak retry\n\t\t}\n\t}\n\n\tvar t <-chan time.Time\ngather:\n\tfor len(actions) < b.maxDocumentCount {\n\t\tif t == nil && len(actions) > 0 {\n\t\t\t\/\/ Set timeout on the first element we read\n\t\t\tt = time.After(b.flushTimeout)\n\t\t}\n\t\tselect {\n\t\tcase <-b.quit:\n\t\t\tfor _, a := range actions {\n\t\t\t\tb.retryQ <- a\n\t\t\t}\n\t\t\treturn false\n\t\tcase <-t:\n\t\t\t\/\/ this case is not enabled until we've got an action\n\t\t\tbreak gather\n\t\tcase a := <-b.retryQ:\n\t\t\tactions = append(actions, a)\n\t\tcase a := <-b.q:\n\t\t\tactions = append(actions, a)\n\t\t}\n\t}\n\n\tres, err := postActions(b.c, cl, url, actions)\n\tif err != nil {\n\t\t\/\/ A server error. Retry these actions later.\n\t\tb.e.Error(err)\n\t\tfor _, a := range actions {\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t}\n\t\treturn true\n\t}\n\n\t\/\/ Server has accepted the request an sich, but there can be errors in the\n\t\/\/ individual actions.\n\tif !res.Errors {\n\t\t\/\/ Simple case, no errors present.\n\t\treturn false\n\t}\n\n\t\/\/ Invalid response from ElasticSearch.\n\tif len(actions) != len(res.Items) {\n\t\tb.e.Error(errInvalidResponse)\n\t\tfor _, a := range actions {\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t}\n\t\treturn true\n\t}\n\t\/\/ Figure out which actions have errors.\n\tfor i, e := range res.Items {\n\t\ta := actions[i]\n\t\tel, ok := e[string(a.Type)]\n\t\tif !ok {\n\t\t\t\/\/ Unexpected reply from ElasticSearch.\n\t\t\tb.e.Error(errInvalidResponse)\n\t\t\tb.c.Retry(RetryUnlikely, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\t\tcontinue\n\t\t}\n\n\t\tc := el.Status\n\t\tswitch {\n\t\tcase c >= 200 && c < 300:\n\t\t\t\/\/ Document accepted by ElasticSearch.\n\t\tcase c == 429 || (c >= 500 && c < 600):\n\t\t\t\/\/ Server error. Retry it.\n\t\t\t\/\/ We get a 429 when the bulk queue is full, which we just retry as\n\t\t\t\/\/ well.\n\t\t\tb.e.Warning(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"transient error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\t\tb.c.Retry(RetryTransient, a.Type, len(a.Document))\n\t\t\tb.retryQ <- a\n\t\tcase c >= 400 && c < 500:\n\t\t\t\/\/ Some error. Nothing we can do with it.\n\t\t\tb.e.Error(ActionError{\n\t\t\t\tAction:     a,\n\t\t\t\tStatusCode: c,\n\t\t\t\tMsg:        fmt.Sprintf(\"error %d: %s\", c, el.Error),\n\t\t\t\tServer:     url,\n\t\t\t})\n\t\tdefault:\n\t\t\t\/\/ No idea.\n\t\t\tb.e.Error(fmt.Errorf(\"unwelcome response %d: %s\", c, el.Error))\n\t\t}\n\t}\n\treturn true\n}\n\ntype bulkRes struct {\n\tTook   int  `json:\"took\"`\n\tErrors bool `json:\"errors\"`\n\tItems  []map[string]struct {\n\t\tIndex   string `json:\"_index\"`\n\t\tType    string `json:\"_type\"`\n\t\tID      string `json:\"_id\"`\n\t\tVersion int    `json:\"_version\"`\n\t\tStatus  int    `json:\"status\"`\n\t\tError   string `json:\"error\"`\n\t} `json:\"items\"`\n}\n\nfunc postActions(c Counter, cl http.Client, url string, actions []Action) (*bulkRes, error) {\n\tbuf := bytes.Buffer{}\n\tfor _, a := range actions {\n\t\tc.Send(a.Type, len(a.Document))\n\t\tbuf.Write(a.Buf())\n\t}\n\tc.SendTotal(buf.Len())\n\n\t\/\/ This doesn't Chunk.\n\tresp, err := cl.Post(url, \"application\/json\", &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"status %d: %s\", resp.StatusCode, string(body))\n\t}\n\n\tvar bulk bulkRes\n\tif err := json.Unmarshal(body, &bulk); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &bulk, nil\n}\n\n\/\/ ActionError wraps an Action we won't retry. It implements the error interface.\ntype ActionError struct {\n\tAction     Action\n\tStatusCode int\n\tMsg        string\n\tServer     string\n}\n\nfunc (e ActionError) Error() string {\n\treturn fmt.Sprintf(\"%s: %s %s\", e.Server, e.Action.Type, e.Msg)\n}\n\n\/\/ withPort adds a default port to an address string.\nfunc withPort(a, port string) string {\n\tif _, _, err := net.SplitHostPort(a); err != nil {\n\t\t\/\/ no port found.\n\t\treturn net.JoinHostPort(a, port)\n\t}\n\treturn a\n}\n<|endoftext|>"}
{"text":"<commit_before>package facility\n\nimport (\n\t\"github.com\/graniticio\/granitic\/config\"\n\t\"github.com\/graniticio\/granitic\/ioc\"\n\t\"github.com\/graniticio\/granitic\/logging\"\n)\n\ntype FacilityBuilder interface {\n\tBuildAndRegister(lm *logging.ComponentLoggerManager, ca *config.ConfigAccessor, cn *ioc.ComponentContainer) error\n\tFacilityName() string\n\tDependsOnFacilities() []string\n}\n<commit_msg>Documentation<commit_after>\/\/ Package facility defines the high-level features (such as RDBMS management and HTTP servers)\n\/\/ that Granitic makes available to applications. Theses features are pacakaged into groups of components known as a\n\/\/ 'facility'.\npackage facility\n\nimport (\n\t\"github.com\/graniticio\/granitic\/config\"\n\t\"github.com\/graniticio\/granitic\/ioc\"\n\t\"github.com\/graniticio\/granitic\/logging\"\n)\n\ntype FacilityBuilder interface {\n\tBuildAndRegister(lm *logging.ComponentLoggerManager, ca *config.ConfigAccessor, cn *ioc.ComponentContainer) error\n\tFacilityName() string\n\tDependsOnFacilities() []string\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"crypto\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"github.com\/realglobe-Inc\/go-lib-rg\/erro\"\n\t\"strings\"\n)\n\nfunc ParseHashFunction(hashStr string) (crypto.Hash, error) {\n\tswitch strings.ToUpper(hashStr) {\n\tcase \"MD4\": \/\/ code.google.com\/p\/go.crypto\/md4 が要る。\n\t\treturn crypto.MD4, nil\n\tcase \"MD5\":\n\t\treturn crypto.MD5, nil\n\tcase \"SHA1\":\n\t\treturn crypto.SHA1, nil\n\tcase \"SHA224\":\n\t\treturn crypto.SHA224, nil\n\tcase \"SHA256\":\n\t\treturn crypto.SHA256, nil\n\tcase \"SHA384\":\n\t\treturn crypto.SHA384, nil\n\tcase \"SHA512\":\n\t\treturn crypto.SHA512, nil\n\tcase \"MD5SHA1\": \/\/ 公式に no implementation。\n\t\treturn crypto.MD5SHA1, nil\n\tcase \"RIPEMD160\": \/\/ code.google.com\/p\/go.crypto\/ripemd160 が要る。\n\t\treturn crypto.RIPEMD160, nil\n\tdefault:\n\t\treturn 0, erro.New(\"not supported hash function \" + hashStr + \".\")\n\t}\n}\n\nfunc HashFunctionString(hash crypto.Hash) string {\n\tswitch hash {\n\tcase crypto.MD4:\n\t\treturn \"MD4\"\n\tcase crypto.MD5:\n\t\treturn \"MD5\"\n\tcase crypto.SHA1:\n\t\treturn \"SHA1\"\n\tcase crypto.SHA224:\n\t\treturn \"SHA224\"\n\tcase crypto.SHA256:\n\t\treturn \"SHA256\"\n\tcase crypto.SHA384:\n\t\treturn \"SHA384\"\n\tcase crypto.SHA512:\n\t\treturn \"SHA512\"\n\tcase crypto.MD5SHA1:\n\t\treturn \"MD5SHA1\"\n\tcase crypto.RIPEMD160:\n\t\treturn \"RIPEMD160\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc ParseRsaPrivateKey(pemStr string) (*rsa.PrivateKey, error) {\n\tblock, _ := pem.Decode([]byte(pemStr))\n\tif block == nil {\n\t\treturn nil, erro.New(\"no private key.\")\n\t}\n\n\tswitch block.Type {\n\tcase \"RSA PRIVATE KEY\":\n\t\tpriKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, erro.Wrap(err)\n\t\t}\n\t\treturn priKey, nil\n\tdefault:\n\t\treturn nil, erro.New(\"invalid private key type \" + block.Type + \".\")\n\t}\n}\n<commit_msg>PEM 形式から公開鍵をデコードする関数を追加<commit_after>package util\n\nimport (\n\t\"crypto\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"github.com\/realglobe-Inc\/go-lib-rg\/erro\"\n\t\"strings\"\n)\n\nfunc ParseHashFunction(hashStr string) (crypto.Hash, error) {\n\tswitch strings.ToUpper(hashStr) {\n\tcase \"MD4\": \/\/ code.google.com\/p\/go.crypto\/md4 が要る。\n\t\treturn crypto.MD4, nil\n\tcase \"MD5\":\n\t\treturn crypto.MD5, nil\n\tcase \"SHA1\":\n\t\treturn crypto.SHA1, nil\n\tcase \"SHA224\":\n\t\treturn crypto.SHA224, nil\n\tcase \"SHA256\":\n\t\treturn crypto.SHA256, nil\n\tcase \"SHA384\":\n\t\treturn crypto.SHA384, nil\n\tcase \"SHA512\":\n\t\treturn crypto.SHA512, nil\n\tcase \"MD5SHA1\": \/\/ 公式に no implementation。\n\t\treturn crypto.MD5SHA1, nil\n\tcase \"RIPEMD160\": \/\/ code.google.com\/p\/go.crypto\/ripemd160 が要る。\n\t\treturn crypto.RIPEMD160, nil\n\tdefault:\n\t\treturn 0, erro.New(\"not supported hash function \" + hashStr + \".\")\n\t}\n}\n\nfunc HashFunctionString(hash crypto.Hash) string {\n\tswitch hash {\n\tcase crypto.MD4:\n\t\treturn \"MD4\"\n\tcase crypto.MD5:\n\t\treturn \"MD5\"\n\tcase crypto.SHA1:\n\t\treturn \"SHA1\"\n\tcase crypto.SHA224:\n\t\treturn \"SHA224\"\n\tcase crypto.SHA256:\n\t\treturn \"SHA256\"\n\tcase crypto.SHA384:\n\t\treturn \"SHA384\"\n\tcase crypto.SHA512:\n\t\treturn \"SHA512\"\n\tcase crypto.MD5SHA1:\n\t\treturn \"MD5SHA1\"\n\tcase crypto.RIPEMD160:\n\t\treturn \"RIPEMD160\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc ParsePublicKey(pemStr string) (*rsa.PublicKey, error) {\n\tblock, _ := pem.Decode([]byte(pemStr))\n\tif block == nil {\n\t\treturn nil, erro.New(\"no public key.\")\n\t}\n\n\tswitch block.Type {\n\tcase \"PUBLIC KEY\":\n\t\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, erro.Wrap(err)\n\t\t}\n\t\tswitch k := key.(type) {\n\t\tcase *rsa.PublicKey:\n\t\t\treturn k, nil\n\t\tdefault:\n\t\t\treturn nil, erro.New(\"not rsa public key.\")\n\t\t}\n\tdefault:\n\t\treturn nil, erro.New(\"invalid public key type \" + block.Type + \".\")\n\t}\n}\n\nfunc ParseRsaPrivateKey(pemStr string) (*rsa.PrivateKey, error) {\n\tblock, _ := pem.Decode([]byte(pemStr))\n\tif block == nil {\n\t\treturn nil, erro.New(\"no private key.\")\n\t}\n\n\tswitch block.Type {\n\tcase \"RSA PRIVATE KEY\":\n\t\tpriKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, erro.Wrap(err)\n\t\t}\n\t\treturn priKey, nil\n\tdefault:\n\t\treturn nil, erro.New(\"invalid private key type \" + block.Type + \".\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package rabbitmq\n\nimport (\n\t\"github.com\/streadway\/amqp\"\n)\n\ntype Consumer struct {\n\t*RabbitMQ\n\tdeliveries <-chan amqp.Delivery\n\thandler    func(amqp.Delivery)\n\tdone       chan error\n\tsession    Session\n}\n\nfunc (c *Consumer) Deliveries() <-chan amqp.Delivery {\n\treturn c.deliveries\n}\n\n\/\/ This is a constructor for consumer creation\n\/\/ Accepts Exchange, Queue, BindingOptions and ConsumerOptions\nfunc NewConsumer(e Exchange, q Queue, bo BindingOptions, co ConsumerOptions) (*Consumer, error) {\n\trmq, err := newRabbitMQConnection(co.Tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Consumer{\n\t\tRabbitMQ: rmq,\n\t\tdone:     make(chan error),\n\t\tsession: Session{\n\t\t\tExchange:        e,\n\t\t\tQueue:           q,\n\t\t\tConsumerOptions: co,\n\t\t\tBindingOptions:  bo,\n\t\t},\n\t}\n\n\terr = c.connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *Consumer) connect() error {\n\te := c.session.Exchange\n\tq := c.session.Queue\n\tbo := c.session.BindingOptions\n\tco := c.session.ConsumerOptions\n\n\tvar err error\n\n\t\/\/ declaring Exchange\n\tif err = c.channel.ExchangeDeclare(\n\t\te.Name,       \/\/ name of the exchange\n\t\te.Type,       \/\/ type\n\t\te.Durable,    \/\/ durable\n\t\te.AutoDelete, \/\/ delete when complete\n\t\te.Internal,   \/\/ internal\n\t\te.NoWait,     \/\/ noWait\n\t\te.Args,       \/\/ arguments\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ declaring Queue\n\tqueue, err := c.channel.QueueDeclare(\n\t\tq.Name,       \/\/ name of the queue\n\t\tq.Durable,    \/\/ durable\n\t\tq.AutoDelete, \/\/ delete when usused\n\t\tq.Exclusive,  \/\/ exclusive\n\t\tq.NoWait,     \/\/ noWait\n\t\tq.Args,       \/\/ arguments\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ binding Exchange to Queue\n\tif err = c.channel.QueueBind(\n\t\t\/\/ bind to real queue\n\t\tqueue.Name,    \/\/ name of the queue\n\t\tbo.RoutingKey, \/\/ bindingKey\n\t\te.Name,        \/\/ sourceExchange\n\t\tbo.NoWait,     \/\/ noWait\n\t\tbo.Args,       \/\/ arguments\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Exchange bound to Queue, starting Consume\n\tdeliveries, err := c.channel.Consume(\n\t\t\/\/ consume from real queue\n\t\tqueue.Name,   \/\/ name\n\t\tco.Tag,       \/\/ consumerTag,\n\t\tco.AutoAck,   \/\/ autoAck\n\t\tco.Exclusive, \/\/ exclusive\n\t\tco.NoLocal,   \/\/ noLocal\n\t\tco.NoWait,    \/\/ noWait\n\t\tco.Args,      \/\/ arguments\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ should we stop streaming, in order not to consume from server?\n\tc.deliveries = deliveries\n\n\treturn nil\n}\n\n\/\/ Accepts a handler function for every message streamed from RabbitMq\n\/\/ will be called within this handler func\nfunc (c *Consumer) Consume(handler func(delivery amqp.Delivery)) {\n\tc.handler = handler\n\n\t\/\/ handle all consumer errors, if required re-connect\n\t\/\/ there are problems with reconnection logic for now\n\tfor delivery := range c.deliveries {\n\t\thandler(delivery)\n\t}\n\n\tlog.Info(\"handle: deliveries channel closed\")\n\tc.done <- nil\n}\n\n\/\/ Gracefully close all connections and wait\n\/\/ for handler to finish its, messages\nfunc (c *Consumer) Shutdown() error {\n\t\/\/ to-do\n\t\/\/ first stop streaming then close connections\n\terr := shutdown(c.conn, c.channel, c.tag)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tdefer log.Info(\"Consumer shutdown OK\")\n\tlog.Info(\"Waiting for handler to exit\")\n\n\t\/\/ this channel is here for finishing the consumer's ranges of\n\t\/\/ delivery chans.  We need every delivery to be processed, here make\n\t\/\/ sure to wait for all consumers goroutines to finish before exiting our\n\t\/\/ process.\n\treturn <-c.done\n}\n\n\/\/ implementing closer interface\nfunc (c *Consumer) RegisterSignalHandler() {\n\tregisterSignalHandler(c)\n}\n<commit_msg>[RabbitMq] apply better godoc<commit_after>package rabbitmq\n\nimport (\n\t\"github.com\/streadway\/amqp\"\n)\n\ntype Consumer struct {\n\t\/\/ Base struct for Producer\n\t*RabbitMQ\n\n\t\/\/ All deliveries from server will send to this channel\n\tdeliveries <-chan amqp.Delivery\n\n\t\/\/ This handler will be called when a\n\thandler func(amqp.Delivery)\n\n\t\/\/ A notifiyng channel for publishings\n\t\/\/ will be used for sync. between close channel and consume handler\n\tdone chan error\n\n\t\/\/ Current producer connection settings\n\tsession Session\n}\n\nfunc (c *Consumer) Deliveries() <-chan amqp.Delivery {\n\treturn c.deliveries\n}\n\n\/\/ This is a constructor for consumer creation\n\/\/ Accepts Exchange, Queue, BindingOptions and ConsumerOptions\nfunc NewConsumer(e Exchange, q Queue, bo BindingOptions, co ConsumerOptions) (*Consumer, error) {\n\trmq, err := newRabbitMQConnection(co.Tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := &Consumer{\n\t\tRabbitMQ: rmq,\n\t\tdone:     make(chan error),\n\t\tsession: Session{\n\t\t\tExchange:        e,\n\t\t\tQueue:           q,\n\t\t\tConsumerOptions: co,\n\t\t\tBindingOptions:  bo,\n\t\t},\n\t}\n\n\terr = c.connect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc (c *Consumer) connect() error {\n\te := c.session.Exchange\n\tq := c.session.Queue\n\tbo := c.session.BindingOptions\n\tco := c.session.ConsumerOptions\n\n\tvar err error\n\n\t\/\/ declaring Exchange\n\tif err = c.channel.ExchangeDeclare(\n\t\te.Name,       \/\/ name of the exchange\n\t\te.Type,       \/\/ type\n\t\te.Durable,    \/\/ durable\n\t\te.AutoDelete, \/\/ delete when complete\n\t\te.Internal,   \/\/ internal\n\t\te.NoWait,     \/\/ noWait\n\t\te.Args,       \/\/ arguments\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ declaring Queue\n\tqueue, err := c.channel.QueueDeclare(\n\t\tq.Name,       \/\/ name of the queue\n\t\tq.Durable,    \/\/ durable\n\t\tq.AutoDelete, \/\/ delete when usused\n\t\tq.Exclusive,  \/\/ exclusive\n\t\tq.NoWait,     \/\/ noWait\n\t\tq.Args,       \/\/ arguments\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ binding Exchange to Queue\n\tif err = c.channel.QueueBind(\n\t\t\/\/ bind to real queue\n\t\tqueue.Name,    \/\/ name of the queue\n\t\tbo.RoutingKey, \/\/ bindingKey\n\t\te.Name,        \/\/ sourceExchange\n\t\tbo.NoWait,     \/\/ noWait\n\t\tbo.Args,       \/\/ arguments\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Exchange bound to Queue, starting Consume\n\tdeliveries, err := c.channel.Consume(\n\t\t\/\/ consume from real queue\n\t\tqueue.Name,   \/\/ name\n\t\tco.Tag,       \/\/ consumerTag,\n\t\tco.AutoAck,   \/\/ autoAck\n\t\tco.Exclusive, \/\/ exclusive\n\t\tco.NoLocal,   \/\/ noLocal\n\t\tco.NoWait,    \/\/ noWait\n\t\tco.Args,      \/\/ arguments\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ should we stop streaming, in order not to consume from server?\n\tc.deliveries = deliveries\n\n\treturn nil\n}\n\n\/\/ Accepts a handler function for every message streamed from RabbitMq\n\/\/ will be called within this handler func\nfunc (c *Consumer) Consume(handler func(delivery amqp.Delivery)) {\n\tc.handler = handler\n\n\t\/\/ handle all consumer errors, if required re-connect\n\t\/\/ there are problems with reconnection logic for now\n\tfor delivery := range c.deliveries {\n\t\thandler(delivery)\n\t}\n\n\tlog.Info(\"handle: deliveries channel closed\")\n\tc.done <- nil\n}\n\n\/\/ Gracefully close all connections and wait\n\/\/ for handler to finish its, messages\nfunc (c *Consumer) Shutdown() error {\n\t\/\/ to-do\n\t\/\/ first stop streaming then close connections\n\terr := shutdown(c.conn, c.channel, c.tag)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tdefer log.Info(\"Consumer shutdown OK\")\n\tlog.Info(\"Waiting for handler to exit\")\n\n\t\/\/ this channel is here for finishing the consumer's ranges of\n\t\/\/ delivery chans.  We need every delivery to be processed, here make\n\t\/\/ sure to wait for all consumers goroutines to finish before exiting our\n\t\/\/ process.\n\treturn <-c.done\n}\n\n\/\/ implementing closer interface\nfunc (c *Consumer) RegisterSignalHandler() {\n\tregisterSignalHandler(c)\n}\n<|endoftext|>"}
{"text":"<commit_before>package proctl\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc withTestProcess(name string, t *testing.T, fn func(p *DebuggedProcess)) {\n\truntime.LockOSThread()\n\tbase := filepath.Base(name)\n\tif err := exec.Command(\"go\", \"build\", \"-gcflags=-N -l\", \"-o\", base, name+\".go\").Run(); err != nil {\n\t\tt.Fatalf(\"Could not compile %s due to %s\", name, err)\n\t}\n\tdefer os.Remove(\".\/\" + base)\n\n\tp, err := Launch([]string{\".\/\" + base})\n\tif err != nil {\n\t\tt.Fatal(\"Launch():\", err)\n\t}\n\n\tdefer p.Process.Kill()\n\n\tfn(p)\n}\n\nfunc getRegisters(p *DebuggedProcess, t *testing.T) Registers {\n\tregs, err := p.Registers()\n\tif err != nil {\n\t\tt.Fatal(\"Registers():\", err)\n\t}\n\n\treturn regs\n}\n\nfunc dataAtAddr(thread *ThreadContext, addr uint64) ([]byte, error) {\n\tdata := make([]byte, 1)\n\t_, err := readMemory(thread, uintptr(addr), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc assertNoError(err error, t *testing.T, s string) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfname := filepath.Base(file)\n\t\tt.Fatalf(\"failed assertion at %s:%d: %s : %s\\n\", fname, line, s, err)\n\t}\n}\n\nfunc currentPC(p *DebuggedProcess, t *testing.T) uint64 {\n\tpc, err := p.PC()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn pc\n}\n\nfunc currentLineNumber(p *DebuggedProcess, t *testing.T) (string, int) {\n\tpc := currentPC(p, t)\n\tf, l, _ := p.goSymTable.PCToLine(pc)\n\n\treturn f, l\n}\n\nfunc TestExit(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/continuetestprog\", t, func(p *DebuggedProcess) {\n\t\terr := p.Continue()\n\t\tpe, ok := err.(ProcessExitedError)\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Continue() returned unexpected error type %s\", err)\n\t\t}\n\t\tif pe.Status != 0 {\n\t\t\tt.Errorf(\"Unexpected error status: %d\", pe.Status)\n\t\t}\n\t\tif pe.Pid != p.Pid {\n\t\t\tt.Errorf(\"Unexpected process id: %d\", pe.Pid)\n\t\t}\n\t})\n}\n\nfunc TestHalt(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\tgo func() {\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\t\t\terr := p.RequestManualStop()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}()\n\t\terr := p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ Loop through threads and make sure they are all\n\t\t\/\/ actually stopped, err will not be nil if the process\n\t\t\/\/ is still running.\n\t\tfor _, th := range p.Threads {\n\t\t\t_, err := th.Registers()\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err, th.Id)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestStep(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\thelloworldfunc := p.goSymTable.LookupFunc(\"main.helloworld\")\n\t\thelloworldaddr := helloworldfunc.Entry\n\n\t\t_, err := p.Break(helloworldaddr)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\n\t\tregs := getRegisters(p, t)\n\t\trip := regs.PC()\n\n\t\terr = p.Step()\n\t\tassertNoError(err, t, \"Step()\")\n\n\t\tregs = getRegisters(p, t)\n\t\tif rip >= regs.PC() {\n\t\t\tt.Errorf(\"Expected %#v to be greater than %#v\", regs.PC(), rip)\n\t\t}\n\t})\n}\n\nfunc TestBreakPoint(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\thelloworldfunc := p.goSymTable.LookupFunc(\"main.helloworld\")\n\t\thelloworldaddr := helloworldfunc.Entry\n\n\t\tbp, err := p.Break(helloworldaddr)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif pc-1 != bp.Addr && pc != bp.Addr {\n\t\t\tf, l, _ := p.goSymTable.PCToLine(pc)\n\t\t\tt.Fatalf(\"Break not respected:\\nPC:%#v %s:%d\\nFN:%#v \\n\", pc, f, l, bp.Addr)\n\t\t}\n\t})\n}\n\nfunc TestBreakPointInSeperateGoRoutine(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testthreads\", t, func(p *DebuggedProcess) {\n\t\tfn := p.goSymTable.LookupFunc(\"main.anotherthread\")\n\t\tif fn == nil {\n\t\t\tt.Fatal(\"No fn exists\")\n\t\t}\n\n\t\t_, err := p.Break(fn.Entry)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tf, l, _ := p.goSymTable.PCToLine(pc)\n\t\tif f != \"testthreads.go\" && l != 8 {\n\t\t\tt.Fatal(\"Program did not hit breakpoint\")\n\t\t}\n\t})\n}\n\nfunc TestBreakPointWithNonExistantFunction(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\t_, err := p.Break(0)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Should not be able to break at non existant function\")\n\t\t}\n\t})\n}\n\nfunc TestClearBreakPoint(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\tfn := p.goSymTable.LookupFunc(\"main.sleepytime\")\n\t\tbp, err := p.Break(fn.Entry)\n\t\tassertNoError(err, t, \"Break()\")\n\n\t\tbp, err = p.Clear(fn.Entry)\n\t\tassertNoError(err, t, \"Clear()\")\n\n\t\tdata, err := dataAtAddr(p.CurrentThread, bp.Addr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tint3 := []byte{0xcc}\n\t\tif bytes.Equal(data, int3) {\n\t\t\tt.Fatalf(\"Breakpoint was not cleared data: %#v, int3: %#v\", data, int3)\n\t\t}\n\n\t\tif len(p.BreakPoints) != 0 {\n\t\t\tt.Fatal(\"Breakpoint not removed internally\")\n\t\t}\n\t})\n}\n\ntype nextTest struct {\n\tbegin, end int\n}\n\nfunc testnext(testcases []nextTest, initialLocation string, t *testing.T) {\n\tvar executablePath = \"..\/_fixtures\/testnextprog\"\n\twithTestProcess(executablePath, t, func(p *DebuggedProcess) {\n\t\tbp, err := p.BreakByLocation(initialLocation)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\t\tp.Clear(bp.Addr)\n\t\tp.CurrentThread.SetPC(bp.Addr)\n\n\t\tf, ln := currentLineNumber(p, t)\n\t\tfor _, tc := range testcases {\n\t\t\tif ln != tc.begin {\n\t\t\t\tt.Fatalf(\"Program not stopped at correct spot expected %d was %s:%d\", tc.begin, filepath.Base(f), ln)\n\t\t\t}\n\n\t\t\tassertNoError(p.Next(), t, \"Next() returned an error\")\n\n\t\t\tf, ln = currentLineNumber(p, t)\n\t\t\tif ln != tc.end {\n\t\t\t\tt.Fatalf(\"Program did not continue to correct next location expected %d was %s:%d\", tc.end, filepath.Base(f), ln)\n\t\t\t}\n\t\t}\n\n\t\tif len(p.BreakPoints) != 0 {\n\t\t\tt.Fatal(\"Not all breakpoints were cleaned up\", len(p.BreakPoints))\n\t\t}\n\t\tfor _, bp := range p.HWBreakPoints {\n\t\t\tif bp != nil {\n\t\t\t\tt.Fatal(\"Not all breakpoints were cleaned up\", bp.Addr)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestNextGeneral(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{17, 19},\n\t\t{19, 20},\n\t\t{20, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 31},\n\t\t{31, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 31},\n\t\t{31, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 27},\n\t\t{27, 34},\n\t}\n\ttestnext(testcases, \"main.testnext\", t)\n}\n\nfunc TestNextGoroutine(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{46, 47},\n\t\t{47, 42},\n\t}\n\ttestnext(testcases, \"main.testgoroutine\", t)\n}\n\nfunc TestNextFunctionReturn(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{13, 14},\n\t\t{14, 35},\n\t}\n\ttestnext(testcases, \"main.helloworld\", t)\n}\n\nfunc TestRuntimeBreakpoint(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testruntimebreakpoint\")\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\terr := p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, l, _ := p.PCToLine(pc)\n\t\tif l != 10 {\n\t\t\tt.Fatal(\"did not respect breakpoint\")\n\t\t}\n\t})\n}\n\nfunc TestFindReturnAddress(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testnextprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\tvar (\n\t\t\tfdes = p.frameEntries\n\t\t\tgsd  = p.goSymTable\n\t\t)\n\n\t\ttestsourcefile := testfile + \".go\"\n\t\tstart, _, err := gsd.LineToPC(testsourcefile, 24)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t_, err = p.Break(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tregs, err := p.Registers()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tfde, err := fdes.FDEForPC(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tret := fde.ReturnAddressOffset(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\taddr := uint64(int64(regs.SP()) + ret)\n\t\tdata := make([]byte, 8)\n\n\t\treadMemory(p.CurrentThread, uintptr(addr), data)\n\t\taddr = binary.LittleEndian.Uint64(data)\n\n\t\t_, l, _ := p.goSymTable.PCToLine(addr)\n\t\tif l != 40 {\n\t\t\tt.Fatalf(\"return address not found correctly, expected line 40\")\n\t\t}\n\t})\n}\n\nfunc TestSwitchThread(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testnextprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\t\/\/ With invalid thread id\n\t\terr := p.SwitchThread(-1)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected error for invalid thread id\")\n\t\t}\n\t\tpc, err := p.FindLocation(\"main.main\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, err = p.Break(pc)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tvar nt int\n\t\tct := p.CurrentThread.Id\n\t\tfor tid, _ := range p.Threads {\n\t\t\tif tid != ct {\n\t\t\t\tnt = tid\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif nt == 0 {\n\t\t\tt.Fatal(\"could not find thread to switch to\")\n\t\t}\n\t\t\/\/ With valid thread id\n\t\terr = p.SwitchThread(nt)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif p.CurrentThread.Id != nt {\n\t\t\tt.Fatal(\"Did not switch threads\")\n\t\t}\n\t})\n}\n\nfunc TestFunctionCall(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\tpc, err := p.FindLocation(\"main.main\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, err = p.Break(pc)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err = p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfn := p.goSymTable.PCToFunc(pc)\n\t\tif fn == nil {\n\t\t\tt.Fatalf(\"Could not find func for PC: %#v\", pc)\n\t\t}\n\t\tif fn.Name != \"main.main\" {\n\t\t\tt.Fatal(\"Program stopped at incorrect place\")\n\t\t}\n\t\tif err = p.CallFn(\"runtime.getg\", func() error {\n\t\t\tth := p.CurrentThread\n\t\t\tpc, err := th.PC()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tf := th.Process.goSymTable.LookupFunc(\"runtime.getg\")\n\t\t\tif f == nil {\n\t\t\t\tt.Fatalf(\"could not find function %s\", \"runtime.getg\")\n\t\t\t}\n\t\t\tif pc-1 != f.End-2 && pc != f.End-2 {\n\t\t\t\tt.Fatalf(\"wrong pc expected %#v got %#v\", f.End-2, pc-1)\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err = p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfn = p.goSymTable.PCToFunc(pc)\n\t\tif fn == nil {\n\t\t\tt.Fatalf(\"Could not find func for PC: %#v\", pc)\n\t\t}\n\t\tif fn.Name != \"main.main\" {\n\t\t\tt.Fatal(\"Program stopped at incorrect place\")\n\t\t}\n\t})\n}\n<commit_msg>Make TestHalt deterministic<commit_after>package proctl\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc withTestProcess(name string, t *testing.T, fn func(p *DebuggedProcess)) {\n\truntime.LockOSThread()\n\tbase := filepath.Base(name)\n\tif err := exec.Command(\"go\", \"build\", \"-gcflags=-N -l\", \"-o\", base, name+\".go\").Run(); err != nil {\n\t\tt.Fatalf(\"Could not compile %s due to %s\", name, err)\n\t}\n\tdefer os.Remove(\".\/\" + base)\n\n\tp, err := Launch([]string{\".\/\" + base})\n\tif err != nil {\n\t\tt.Fatal(\"Launch():\", err)\n\t}\n\n\tdefer p.Process.Kill()\n\n\tfn(p)\n}\n\nfunc getRegisters(p *DebuggedProcess, t *testing.T) Registers {\n\tregs, err := p.Registers()\n\tif err != nil {\n\t\tt.Fatal(\"Registers():\", err)\n\t}\n\n\treturn regs\n}\n\nfunc dataAtAddr(thread *ThreadContext, addr uint64) ([]byte, error) {\n\tdata := make([]byte, 1)\n\t_, err := readMemory(thread, uintptr(addr), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn data, nil\n}\n\nfunc assertNoError(err error, t *testing.T, s string) {\n\tif err != nil {\n\t\t_, file, line, _ := runtime.Caller(1)\n\t\tfname := filepath.Base(file)\n\t\tt.Fatalf(\"failed assertion at %s:%d: %s : %s\\n\", fname, line, s, err)\n\t}\n}\n\nfunc currentPC(p *DebuggedProcess, t *testing.T) uint64 {\n\tpc, err := p.PC()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\treturn pc\n}\n\nfunc currentLineNumber(p *DebuggedProcess, t *testing.T) (string, int) {\n\tpc := currentPC(p, t)\n\tf, l, _ := p.goSymTable.PCToLine(pc)\n\n\treturn f, l\n}\n\nfunc TestExit(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/continuetestprog\", t, func(p *DebuggedProcess) {\n\t\terr := p.Continue()\n\t\tpe, ok := err.(ProcessExitedError)\n\t\tif !ok {\n\t\t\tt.Fatalf(\"Continue() returned unexpected error type %s\", err)\n\t\t}\n\t\tif pe.Status != 0 {\n\t\t\tt.Errorf(\"Unexpected error status: %d\", pe.Status)\n\t\t}\n\t\tif pe.Pid != p.Pid {\n\t\t\tt.Errorf(\"Unexpected process id: %d\", pe.Pid)\n\t\t}\n\t})\n}\n\nfunc TestHalt(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif p.Running() {\n\t\t\t\t\terr := p.RequestManualStop()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tt.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\terr := p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ Loop through threads and make sure they are all\n\t\t\/\/ actually stopped, err will not be nil if the process\n\t\t\/\/ is still running.\n\t\tfor _, th := range p.Threads {\n\t\t\t_, err := th.Registers()\n\t\t\tif err != nil {\n\t\t\t\tt.Error(err, th.Id)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestStep(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\thelloworldfunc := p.goSymTable.LookupFunc(\"main.helloworld\")\n\t\thelloworldaddr := helloworldfunc.Entry\n\n\t\t_, err := p.Break(helloworldaddr)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\n\t\tregs := getRegisters(p, t)\n\t\trip := regs.PC()\n\n\t\terr = p.Step()\n\t\tassertNoError(err, t, \"Step()\")\n\n\t\tregs = getRegisters(p, t)\n\t\tif rip >= regs.PC() {\n\t\t\tt.Errorf(\"Expected %#v to be greater than %#v\", regs.PC(), rip)\n\t\t}\n\t})\n}\n\nfunc TestBreakPoint(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\thelloworldfunc := p.goSymTable.LookupFunc(\"main.helloworld\")\n\t\thelloworldaddr := helloworldfunc.Entry\n\n\t\tbp, err := p.Break(helloworldaddr)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif pc-1 != bp.Addr && pc != bp.Addr {\n\t\t\tf, l, _ := p.goSymTable.PCToLine(pc)\n\t\t\tt.Fatalf(\"Break not respected:\\nPC:%#v %s:%d\\nFN:%#v \\n\", pc, f, l, bp.Addr)\n\t\t}\n\t})\n}\n\nfunc TestBreakPointInSeperateGoRoutine(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testthreads\", t, func(p *DebuggedProcess) {\n\t\tfn := p.goSymTable.LookupFunc(\"main.anotherthread\")\n\t\tif fn == nil {\n\t\t\tt.Fatal(\"No fn exists\")\n\t\t}\n\n\t\t_, err := p.Break(fn.Entry)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tf, l, _ := p.goSymTable.PCToLine(pc)\n\t\tif f != \"testthreads.go\" && l != 8 {\n\t\t\tt.Fatal(\"Program did not hit breakpoint\")\n\t\t}\n\t})\n}\n\nfunc TestBreakPointWithNonExistantFunction(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\t_, err := p.Break(0)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Should not be able to break at non existant function\")\n\t\t}\n\t})\n}\n\nfunc TestClearBreakPoint(t *testing.T) {\n\twithTestProcess(\"..\/_fixtures\/testprog\", t, func(p *DebuggedProcess) {\n\t\tfn := p.goSymTable.LookupFunc(\"main.sleepytime\")\n\t\tbp, err := p.Break(fn.Entry)\n\t\tassertNoError(err, t, \"Break()\")\n\n\t\tbp, err = p.Clear(fn.Entry)\n\t\tassertNoError(err, t, \"Clear()\")\n\n\t\tdata, err := dataAtAddr(p.CurrentThread, bp.Addr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tint3 := []byte{0xcc}\n\t\tif bytes.Equal(data, int3) {\n\t\t\tt.Fatalf(\"Breakpoint was not cleared data: %#v, int3: %#v\", data, int3)\n\t\t}\n\n\t\tif len(p.BreakPoints) != 0 {\n\t\t\tt.Fatal(\"Breakpoint not removed internally\")\n\t\t}\n\t})\n}\n\ntype nextTest struct {\n\tbegin, end int\n}\n\nfunc testnext(testcases []nextTest, initialLocation string, t *testing.T) {\n\tvar executablePath = \"..\/_fixtures\/testnextprog\"\n\twithTestProcess(executablePath, t, func(p *DebuggedProcess) {\n\t\tbp, err := p.BreakByLocation(initialLocation)\n\t\tassertNoError(err, t, \"Break()\")\n\t\tassertNoError(p.Continue(), t, \"Continue()\")\n\t\tp.Clear(bp.Addr)\n\t\tp.CurrentThread.SetPC(bp.Addr)\n\n\t\tf, ln := currentLineNumber(p, t)\n\t\tfor _, tc := range testcases {\n\t\t\tif ln != tc.begin {\n\t\t\t\tt.Fatalf(\"Program not stopped at correct spot expected %d was %s:%d\", tc.begin, filepath.Base(f), ln)\n\t\t\t}\n\n\t\t\tassertNoError(p.Next(), t, \"Next() returned an error\")\n\n\t\t\tf, ln = currentLineNumber(p, t)\n\t\t\tif ln != tc.end {\n\t\t\t\tt.Fatalf(\"Program did not continue to correct next location expected %d was %s:%d\", tc.end, filepath.Base(f), ln)\n\t\t\t}\n\t\t}\n\n\t\tif len(p.BreakPoints) != 0 {\n\t\t\tt.Fatal(\"Not all breakpoints were cleaned up\", len(p.BreakPoints))\n\t\t}\n\t\tfor _, bp := range p.HWBreakPoints {\n\t\t\tif bp != nil {\n\t\t\t\tt.Fatal(\"Not all breakpoints were cleaned up\", bp.Addr)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestNextGeneral(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{17, 19},\n\t\t{19, 20},\n\t\t{20, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 31},\n\t\t{31, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 31},\n\t\t{31, 23},\n\t\t{23, 24},\n\t\t{24, 26},\n\t\t{26, 27},\n\t\t{27, 34},\n\t}\n\ttestnext(testcases, \"main.testnext\", t)\n}\n\nfunc TestNextGoroutine(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{46, 47},\n\t\t{47, 42},\n\t}\n\ttestnext(testcases, \"main.testgoroutine\", t)\n}\n\nfunc TestNextFunctionReturn(t *testing.T) {\n\ttestcases := []nextTest{\n\t\t{13, 14},\n\t\t{14, 35},\n\t}\n\ttestnext(testcases, \"main.helloworld\", t)\n}\n\nfunc TestRuntimeBreakpoint(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testruntimebreakpoint\")\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\terr := p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err := p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, l, _ := p.PCToLine(pc)\n\t\tif l != 10 {\n\t\t\tt.Fatal(\"did not respect breakpoint\")\n\t\t}\n\t})\n}\n\nfunc TestFindReturnAddress(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testnextprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\tvar (\n\t\t\tfdes = p.frameEntries\n\t\t\tgsd  = p.goSymTable\n\t\t)\n\n\t\ttestsourcefile := testfile + \".go\"\n\t\tstart, _, err := gsd.LineToPC(testsourcefile, 24)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t_, err = p.Break(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tregs, err := p.Registers()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tfde, err := fdes.FDEForPC(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tret := fde.ReturnAddressOffset(start)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\taddr := uint64(int64(regs.SP()) + ret)\n\t\tdata := make([]byte, 8)\n\n\t\treadMemory(p.CurrentThread, uintptr(addr), data)\n\t\taddr = binary.LittleEndian.Uint64(data)\n\n\t\t_, l, _ := p.goSymTable.PCToLine(addr)\n\t\tif l != 40 {\n\t\t\tt.Fatalf(\"return address not found correctly, expected line 40\")\n\t\t}\n\t})\n}\n\nfunc TestSwitchThread(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testnextprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\t\/\/ With invalid thread id\n\t\terr := p.SwitchThread(-1)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected error for invalid thread id\")\n\t\t}\n\t\tpc, err := p.FindLocation(\"main.main\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, err = p.Break(pc)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tvar nt int\n\t\tct := p.CurrentThread.Id\n\t\tfor tid := range p.Threads {\n\t\t\tif tid != ct {\n\t\t\t\tnt = tid\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif nt == 0 {\n\t\t\tt.Fatal(\"could not find thread to switch to\")\n\t\t}\n\t\t\/\/ With valid thread id\n\t\terr = p.SwitchThread(nt)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif p.CurrentThread.Id != nt {\n\t\t\tt.Fatal(\"Did not switch threads\")\n\t\t}\n\t})\n}\n\nfunc TestFunctionCall(t *testing.T) {\n\tvar testfile, _ = filepath.Abs(\"..\/_fixtures\/testprog\")\n\n\twithTestProcess(testfile, t, func(p *DebuggedProcess) {\n\t\tpc, err := p.FindLocation(\"main.main\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t_, err = p.Break(pc)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\terr = p.Continue()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err = p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfn := p.goSymTable.PCToFunc(pc)\n\t\tif fn == nil {\n\t\t\tt.Fatalf(\"Could not find func for PC: %#v\", pc)\n\t\t}\n\t\tif fn.Name != \"main.main\" {\n\t\t\tt.Fatal(\"Program stopped at incorrect place\")\n\t\t}\n\t\tif err = p.CallFn(\"runtime.getg\", func() error {\n\t\t\tth := p.CurrentThread\n\t\t\tpc, err := th.PC()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tf := th.Process.goSymTable.LookupFunc(\"runtime.getg\")\n\t\t\tif f == nil {\n\t\t\t\tt.Fatalf(\"could not find function %s\", \"runtime.getg\")\n\t\t\t}\n\t\t\tif pc-1 != f.End-2 && pc != f.End-2 {\n\t\t\t\tt.Fatalf(\"wrong pc expected %#v got %#v\", f.End-2, pc-1)\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpc, err = p.PC()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfn = p.goSymTable.PCToFunc(pc)\n\t\tif fn == nil {\n\t\t\tt.Fatalf(\"Could not find func for PC: %#v\", pc)\n\t\t}\n\t\tif fn.Name != \"main.main\" {\n\t\t\tt.Fatal(\"Program stopped at incorrect place\")\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>queue remove<commit_after><|endoftext|>"}
{"text":"<commit_before>package metrics\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype SlowQueryMetrics struct {\n\tmutex        sync.Mutex\n\tmetrics      map[string]prometheus.Gauge\n\tmilliseconds int64\n}\n\nfunc NewSlowQueryMetrics(durationToConsiderSlow time.Duration) *SlowQueryMetrics {\n\treturn &SlowQueryMetrics{\n\t\tmilliseconds: durationToConsiderSlow.Nanoseconds() \/ int64(time.Millisecond),\n\t\tmetrics: map[string]prometheus.Gauge{\n\t\t\t\"slow_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_queries_total\",\n\t\t\t\tHelp:      \"Number of slow queries\",\n\t\t\t}),\n\t\t\t\"slow_select_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_select_queries_total\",\n\t\t\t\tHelp:      \"Number of slow SELECT queries\",\n\t\t\t}),\n\t\t\t\"slow_dml_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_dml_queries_total\",\n\t\t\t\tHelp:      \"Number of slow data manipulation queries (INSERT, UPDATE, DELETE)\",\n\t\t\t}),\n\t\t},\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Scrape(db *sql.DB) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tcount := new(float64)\n\terr := db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds' )::interval AND \n\t\t\t\tquery ilike 'select%'`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow select queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_select_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval AND \n\t\t\t\t(query ilike 'insert%' OR query ilike 'update%' OR query ilike 'delete%')`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow dml queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_dml_queries\"].Set(*count)\n\n\treturn nil\n}\n\nfunc (s *SlowQueryMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range s.metrics {\n\t\tm.Describe(ch)\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range s.metrics {\n\t\tm.Collect(ch)\n\t}\n}\n\n\/\/ check interface\nvar _ Collection = new(SlowQueryMetrics)\n<commit_msg>MFD-7<commit_after>package metrics\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype SlowQueryMetrics struct {\n\tmutex        sync.Mutex\n\tmetrics      map[string]prometheus.Gauge\n\tmilliseconds int64\n}\n\nfunc NewSlowQueryMetrics(durationToConsiderSlow time.Duration) *SlowQueryMetrics {\n\n\treturn &SlowQueryMetrics{\n\t\tmilliseconds: int64(durationToConsiderSlow \/ time.Millisecond),\n\t\tmetrics: map[string]prometheus.Gauge{\n\t\t\t\"slow_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_queries_total\",\n\t\t\t\tHelp:      \"Number of slow queries\",\n\t\t\t}),\n\t\t\t\"slow_select_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_select_queries_total\",\n\t\t\t\tHelp:      \"Number of slow SELECT queries\",\n\t\t\t}),\n\t\t\t\"slow_dml_queries\": prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName:      \"slow_dml_queries_total\",\n\t\t\t\tHelp:      \"Number of slow data manipulation queries (INSERT, UPDATE, DELETE)\",\n\t\t\t}),\n\t\t},\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Scrape(db *sql.DB) error {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tcount := new(float64)\n\terr := db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds' )::interval AND \n\t\t\t\tquery ilike 'select%'`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow select queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_select_queries\"].Set(*count)\n\n\terr = db.QueryRow(\n\t\t`SELECT count(*) \n\t\t\t\tFROM pg_stat_activity \n\t\t\t\tWHERE state = 'active' AND \n\t\t\t\tNOW() - query_start > ($1 || ' milliseconds')::interval AND \n\t\t\t\t(query ilike 'insert%' OR query ilike 'update%' OR query ilike 'delete%')`,\n\t\ts.milliseconds).Scan(count)\n\tif err != nil {\n\t\treturn errors.New(\"error counting slow dml queries: \" + err.Error())\n\t}\n\n\ts.metrics[\"slow_dml_queries\"].Set(*count)\n\n\treturn nil\n}\n\nfunc (s *SlowQueryMetrics) Describe(ch chan<- *prometheus.Desc) {\n\tfor _, m := range s.metrics {\n\t\tm.Describe(ch)\n\t}\n}\n\nfunc (s *SlowQueryMetrics) Collect(ch chan<- prometheus.Metric) {\n\tfor _, m := range s.metrics {\n\t\tm.Collect(ch)\n\t}\n}\n\n\/\/ check interface\nvar _ Collection = new(SlowQueryMetrics)\n<|endoftext|>"}
{"text":"<commit_before>package dblentry\n\nimport \"time\"\nimport \"fmt\"\nimport \"strings\"\nimport \"sort\"\n\nimport \"github.com\/prataprc\/goparsec\"\nimport \"github.com\/prataprc\/golog\"\nimport \"github.com\/tn47\/goledger\/api\"\n\n\/\/ Transaction instance for every transaction in the journal file.\ntype Transaction struct {\n\t\/\/ immutable after firstpass\n\tdate     time.Time\n\tedate    time.Time\n\tcode     string\n\ttags     []string\n\tmetadata map[string]interface{}\n\tnotes    []string\n\tlineno   int\n\tlines    []string\n\n\tpostings []*Posting\n}\n\n\/\/ NewTransaction create a new transaction object.\nfunc NewTransaction() *Transaction {\n\ttrans := &Transaction{\n\t\ttags:     []string{},\n\t\tmetadata: map[string]interface{}{},\n\t\tnotes:    []string{},\n\t\tlines:    []string{},\n\t}\n\treturn trans\n}\n\n\/\/---- local accessors\n\nfunc (trans *Transaction) getMetadata(key string) interface{} {\n\tif value, ok := trans.metadata[key]; ok {\n\t\treturn value\n\t}\n\treturn nil\n}\n\nfunc (trans *Transaction) setMetadata(key string, value interface{}) {\n\ttrans.metadata[key] = value\n}\n\nfunc (trans *Transaction) getState() string {\n\tstate := trans.getMetadata(\"state\")\n\tif state != nil {\n\t\treturn state.(string)\n\t}\n\treturn \"\"\n}\n\n\/\/---- exported accessors\n\n\/\/ SetLineno in journal file for this transaction.\nfunc (trans *Transaction) SetLineno(lineno int) {\n\ttrans.lineno = lineno\n}\n\n\/\/ Lineno get lineno in journal file for this transaction.\nfunc (trans *Transaction) Lineno() int {\n\treturn trans.lineno\n}\n\nfunc (trans *Transaction) Addlines(lines ...string) {\n\ttrans.lines = append(trans.lines, lines...)\n}\n\nfunc (trans *Transaction) Printlines() []string {\n\treturn trans.lines\n}\n\n\/\/---- api.Transactor methods.\n\nfunc (trans *Transaction) Date() time.Time {\n\treturn trans.date\n}\n\nfunc (trans *Transaction) Payee() string {\n\tpayee := trans.getMetadata(\"payee\")\n\tif payee != nil {\n\t\treturn payee.(string)\n\t}\n\treturn \"\"\n}\n\nfunc (trans *Transaction) GetPostings() []api.Poster {\n\tpostings := []api.Poster{}\n\tfor _, p := range trans.postings {\n\t\tpostings = append(postings, p)\n\t}\n\treturn postings\n}\n\n\/\/---- ledger parser\n\n\/\/ Yledger return a parser-combinator that can parse first line of a\n\/\/ transaction.\nfunc (trans *Transaction) Yledger(db *Datastore) parsec.Parser {\n\t\/\/ DATE\n\tydate := Ydate(db.getYear())\n\t\/\/ [=EDATE]\n\tyedate := parsec.And(\n\t\tfunc(nodes []parsec.ParsecNode) parsec.ParsecNode {\n\t\t\treturn nodes[1] \/\/ EDATE\n\t\t},\n\t\tytokEqual,\n\t\tydate,\n\t)\n\n\ty := parsec.And(\n\t\tfunc(nodes []parsec.ParsecNode) parsec.ParsecNode {\n\t\t\ttrans.date = nodes[0].(time.Time)\n\t\t\tif edate, ok := nodes[1].(time.Time); ok {\n\t\t\t\ttrans.edate = edate\n\t\t\t}\n\t\t\tif t, ok := nodes[2].(*parsec.Terminal); ok {\n\t\t\t\ttrans.setMetadata(\"state\", prefix2state[[]rune(t.Value)[0]])\n\t\t\t}\n\t\t\tif t, ok := nodes[3].(*parsec.Terminal); ok {\n\t\t\t\ttrans.code = string(t.Value[1 : len(t.Value)-1])\n\t\t\t}\n\n\t\t\tpayee := string(nodes[4].(*parsec.Terminal).Value)\n\t\t\ttrans.setMetadata(\"payee\", payee)\n\n\t\t\tif t, ok := nodes[5].(*parsec.Terminal); ok {\n\t\t\t\tnote := string(t.Value)[1:]\n\t\t\t\ttrans.notes = append(trans.notes, note)\n\t\t\t}\n\n\t\t\tfmsg := \"trans.yledger date:%v code:%v payee:%v\\n\"\n\t\t\tlog.Debugf(fmsg, trans.date, trans.code, payee)\n\t\t\treturn trans\n\t\t},\n\t\tydate,\n\t\tparsec.Maybe(maybenode, yedate),\n\t\tparsec.Maybe(maybenode, ytokPrefix),\n\t\tparsec.Maybe(maybenode, ytokCode),\n\t\tytokPayeestr,\n\t\tparsec.Maybe(maybenode, ytokTransnote),\n\t)\n\treturn y\n}\n\n\/\/ Yledgerblock return a parser combinaty that can parse all the posting\n\/\/ within the transaction.\nfunc (trans *Transaction) Yledgerblock(\n\tdb *Datastore, block []string) (int, error) {\n\n\tif len(block) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tvar node parsec.ParsecNode\n\tvar index int\n\tvar line string\n\n\tfor index, line = range block {\n\t\tscanner := parsec.NewScanner([]byte(line))\n\t\tposting := NewPosting(trans)\n\t\tnode, scanner = posting.Yledger(db)(scanner)\n\t\tswitch val := node.(type) {\n\t\tcase *Posting:\n\t\t\ttrans.postings = append(trans.postings, val)\n\n\t\tcase *Tags:\n\t\t\ttrans.tags = append(trans.tags, val.tags...)\n\t\t\tfor k, v := range val.tagm {\n\t\t\t\ttrans.metadata[k] = v\n\t\t\t}\n\n\t\tcase typeTransnote:\n\t\t\ttrans.notes = append(trans.notes, string(val))\n\n\t\tcase error:\n\t\t\treturn index, val\n\t\t}\n\t\t\/\/ skip trailing whitespace.\n\t\t_, scanner = parsec.Token(`[ \\t]*`, \"WS\")(scanner)\n\t\tif scanner.Endof() == false {\n\t\t\treturn index, fmt.Errorf(\"unable to parse posting\")\n\t\t}\n\t}\n\treturn index, nil\n}\n\n\/\/---- engine\n\nfunc (trans *Transaction) Firstpass(db *Datastore) error {\n\t\/\/ payee-rewrite\n\tif payee, ok := db.matchpayee(trans.Payee()); ok {\n\t\ttrans.setMetadata(\"payee\", payee)\n\t}\n\n\tfor _, posting := range trans.postings {\n\t\tif err := posting.Firstpass(db, trans); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif trans.shouldBalance() {\n\t\tdefaccount := db.GetAccount(db.getBalancingaccount()).(*Account)\n\t\tif ok, err := trans.autobalance1(db, defaccount); err != nil {\n\t\t\treturn err\n\t\t} else if ok == false {\n\t\t\treturn fmt.Errorf(\"unbalanced transaction\")\n\t\t}\n\t\tlog.Debugf(\"transaction balanced\\n\")\n\t}\n\treturn nil\n}\n\nfunc (trans *Transaction) Secondpass(db *Datastore) error {\n\tfor _, posting := range trans.postings {\n\t\tif err := posting.Secondpass(db, trans); err != nil {\n\t\t\treturn fmt.Errorf(\"lineno %v: %v\", trans.lineno, err)\n\t\t}\n\t}\n\treturn db.reporter.Transaction(db, trans)\n}\n\nfunc (trans *Transaction) Clone(ndb *Datastore) *Transaction {\n\tntrans := *trans\n\tntrans.postings = []*Posting{}\n\tfor _, posting := range trans.postings {\n\t\tntrans.postings = append(ntrans.postings, posting.Clone(ndb, &ntrans))\n\t}\n\treturn &ntrans\n}\n\nfunc (trans *Transaction) shouldBalance() bool {\n\tfor _, posting := range trans.postings {\n\t\tvirtual := posting.isVirtual()\n\t\tbalanced := posting.isBalanced()\n\t\tif virtual == true && balanced == false {\n\t\t\treturn false\n\t\t} else if balanced == false {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (trans *Transaction) defaultposting(\n\tdb *Datastore, defacc *Account, commodity *Commodity) *Posting {\n\n\tposting := NewPosting(trans)\n\tposting.account = defacc\n\tposting.commodity = commodity\n\treturn posting\n}\n\nfunc (trans *Transaction) endposting(postings []*Posting) (*Posting, error) {\n\tvar tallypost *Posting\n\tfor _, posting := range postings {\n\t\tif posting.commodity == nil && tallypost != nil {\n\t\t\terr := fmt.Errorf(\"Only one null posting allowed per transaction\")\n\t\t\treturn nil, err\n\t\t} else if posting.commodity == nil {\n\t\t\ttallypost = posting\n\t\t}\n\t}\n\treturn tallypost, nil\n}\n\nfunc (trans *Transaction) autobalance1(\n\tdb *Datastore, defaccount *Account) (bool, error) {\n\n\tif len(trans.postings) == 0 {\n\t\treturn false, fmt.Errorf(\"empty transaction\")\n\n\t} else if len(trans.postings) == 1 && defaccount != nil {\n\t\tcommodity := trans.postings[0].getCostprice()\n\t\tposting := trans.defaultposting(db, defaccount, commodity)\n\t\tposting.commodity.doInverse()\n\t\ttrans.postings = append(trans.postings, posting)\n\t\treturn true, nil\n\n\t} else if len(trans.postings) == 1 {\n\t\treturn false, fmt.Errorf(\"unbalanced transaction\")\n\t}\n\n\tunbcs, _ := trans.doBalance()\n\tif len(unbcs) == 0 {\n\t\treturn true, nil\n\t}\n\n\ttallypost, err := trans.endposting(trans.postings)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(unbcs) == 1 && tallypost == nil {\n\t\treturn false, fmt.Errorf(\"unbalanced transaction\")\n\t} else if tallypost == nil {\n\t\treturn true, nil\n\t}\n\n\ttallypost.commodity = unbcs[0]\n\ttallypost.commodity.doInverse()\n\tif len(unbcs) > 1 {\n\t\taccount := tallypost.account\n\t\tfor _, unbc := range unbcs[1:] {\n\t\t\tposting := trans.defaultposting(db, account, unbc)\n\t\t\tposting.commodity.doInverse()\n\t\t\ttrans.postings = append(trans.postings, posting)\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc (trans *Transaction) doBalance() ([]*Commodity, bool) {\n\tunbalanced := map[string]*Commodity{}\n\tfor _, posting := range trans.postings {\n\t\tif posting.commodity == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcommodity := posting.getCostprice()\n\t\tunbc, ok := unbalanced[commodity.name]\n\t\tif ok {\n\t\t\tunbc.doAdd(commodity)\n\t\t} else {\n\t\t\tunbc = commodity\n\t\t}\n\t\tunbalanced[unbc.name] = unbc\n\t}\n\tcommnames := []string{}\n\tfor name := range unbalanced {\n\t\tcommnames = append(commnames, name)\n\t}\n\tsort.Strings(commnames)\n\n\tunbcs := []*Commodity{}\n\tfor _, name := range commnames {\n\t\tunbc := unbalanced[name]\n\t\tif unbc.amount > float64(0.009) {\n\t\t\tunbcs = append(unbcs, unbc)\n\t\t}\n\t}\n\treturn unbcs, len(unbcs) > 1\n}\n\n\/\/ FitPayee for formatting.\nfunc FitPayee(payee string, maxwidth int) string {\n\tif len(payee) < maxwidth {\n\t\treturn payee\n\t}\n\tscraplen := len(payee) - maxwidth\n\tfields := []string{}\n\tfor _, field := range strings.Fields(payee) {\n\t\tif scraplen <= 0 || len(field) <= 3 {\n\t\t\tfields = append(fields, field)\n\t\t\tcontinue\n\t\t}\n\t\tif len(field[3:]) < scraplen {\n\t\t\tfields = append(fields, field[:3])\n\t\t\tscraplen -= len(field[3:])\n\t\t\tcontinue\n\t\t}\n\t\tfields = append(fields, field[:len(field)-scraplen])\n\t\tscraplen = 0\n\t}\n\treturn strings.Join(fields, \" \")\n}\n<commit_msg>bugfix: issue #38<commit_after>package dblentry\n\nimport \"time\"\nimport \"fmt\"\nimport \"strings\"\nimport \"sort\"\n\nimport \"github.com\/prataprc\/goparsec\"\nimport \"github.com\/prataprc\/golog\"\nimport \"github.com\/tn47\/goledger\/api\"\n\n\/\/ Transaction instance for every transaction in the journal file.\ntype Transaction struct {\n\t\/\/ immutable after firstpass\n\tdate     time.Time\n\tedate    time.Time\n\tcode     string\n\ttags     []string\n\tmetadata map[string]interface{}\n\tnotes    []string\n\tlineno   int\n\tlines    []string\n\n\tpostings []*Posting\n}\n\n\/\/ NewTransaction create a new transaction object.\nfunc NewTransaction() *Transaction {\n\ttrans := &Transaction{\n\t\ttags:     []string{},\n\t\tmetadata: map[string]interface{}{},\n\t\tnotes:    []string{},\n\t\tlines:    []string{},\n\t}\n\treturn trans\n}\n\n\/\/---- local accessors\n\nfunc (trans *Transaction) getMetadata(key string) interface{} {\n\tif value, ok := trans.metadata[key]; ok {\n\t\treturn value\n\t}\n\treturn nil\n}\n\nfunc (trans *Transaction) setMetadata(key string, value interface{}) {\n\ttrans.metadata[key] = value\n}\n\nfunc (trans *Transaction) getState() string {\n\tstate := trans.getMetadata(\"state\")\n\tif state != nil {\n\t\treturn state.(string)\n\t}\n\treturn \"\"\n}\n\n\/\/---- exported accessors\n\n\/\/ SetLineno in journal file for this transaction.\nfunc (trans *Transaction) SetLineno(lineno int) {\n\ttrans.lineno = lineno\n}\n\n\/\/ Lineno get lineno in journal file for this transaction.\nfunc (trans *Transaction) Lineno() int {\n\treturn trans.lineno\n}\n\nfunc (trans *Transaction) Addlines(lines ...string) {\n\ttrans.lines = append(trans.lines, lines...)\n}\n\nfunc (trans *Transaction) Printlines() []string {\n\treturn trans.lines\n}\n\n\/\/---- api.Transactor methods.\n\nfunc (trans *Transaction) Date() time.Time {\n\treturn trans.date\n}\n\nfunc (trans *Transaction) Payee() string {\n\tpayee := trans.getMetadata(\"payee\")\n\tif payee != nil {\n\t\treturn payee.(string)\n\t}\n\treturn \"\"\n}\n\nfunc (trans *Transaction) GetPostings() []api.Poster {\n\tpostings := []api.Poster{}\n\tfor _, p := range trans.postings {\n\t\tpostings = append(postings, p)\n\t}\n\treturn postings\n}\n\n\/\/---- ledger parser\n\n\/\/ Yledger return a parser-combinator that can parse first line of a\n\/\/ transaction.\nfunc (trans *Transaction) Yledger(db *Datastore) parsec.Parser {\n\t\/\/ DATE\n\tydate := Ydate(db.getYear())\n\t\/\/ [=EDATE]\n\tyedate := parsec.And(\n\t\tfunc(nodes []parsec.ParsecNode) parsec.ParsecNode {\n\t\t\treturn nodes[1] \/\/ EDATE\n\t\t},\n\t\tytokEqual,\n\t\tydate,\n\t)\n\n\ty := parsec.And(\n\t\tfunc(nodes []parsec.ParsecNode) parsec.ParsecNode {\n\t\t\ttrans.date = nodes[0].(time.Time)\n\t\t\tif edate, ok := nodes[1].(time.Time); ok {\n\t\t\t\ttrans.edate = edate\n\t\t\t}\n\t\t\tif t, ok := nodes[2].(*parsec.Terminal); ok {\n\t\t\t\ttrans.setMetadata(\"state\", prefix2state[[]rune(t.Value)[0]])\n\t\t\t}\n\t\t\tif t, ok := nodes[3].(*parsec.Terminal); ok {\n\t\t\t\ttrans.code = string(t.Value[1 : len(t.Value)-1])\n\t\t\t}\n\n\t\t\tpayee := string(nodes[4].(*parsec.Terminal).Value)\n\t\t\ttrans.setMetadata(\"payee\", payee)\n\n\t\t\tif t, ok := nodes[5].(*parsec.Terminal); ok {\n\t\t\t\tnote := string(t.Value)[1:]\n\t\t\t\ttrans.notes = append(trans.notes, note)\n\t\t\t}\n\n\t\t\tfmsg := \"trans.yledger date:%v code:%v payee:%v\\n\"\n\t\t\tlog.Debugf(fmsg, trans.date, trans.code, payee)\n\t\t\treturn trans\n\t\t},\n\t\tydate,\n\t\tparsec.Maybe(maybenode, yedate),\n\t\tparsec.Maybe(maybenode, ytokPrefix),\n\t\tparsec.Maybe(maybenode, ytokCode),\n\t\tytokPayeestr,\n\t\tparsec.Maybe(maybenode, ytokTransnote),\n\t)\n\treturn y\n}\n\n\/\/ Yledgerblock return a parser combinaty that can parse all the posting\n\/\/ within the transaction.\nfunc (trans *Transaction) Yledgerblock(\n\tdb *Datastore, block []string) (int, error) {\n\n\tif len(block) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tvar node parsec.ParsecNode\n\tvar index int\n\tvar line string\n\n\tfor index, line = range block {\n\t\tscanner := parsec.NewScanner([]byte(line))\n\t\tposting := NewPosting(trans)\n\t\tnode, scanner = posting.Yledger(db)(scanner)\n\t\tswitch val := node.(type) {\n\t\tcase *Posting:\n\t\t\ttrans.postings = append(trans.postings, val)\n\n\t\tcase *Tags:\n\t\t\ttrans.tags = append(trans.tags, val.tags...)\n\t\t\tfor k, v := range val.tagm {\n\t\t\t\ttrans.metadata[k] = v\n\t\t\t}\n\n\t\tcase typeTransnote:\n\t\t\ttrans.notes = append(trans.notes, string(val))\n\n\t\tcase error:\n\t\t\treturn index, val\n\t\t}\n\t\t\/\/ skip trailing whitespace.\n\t\t_, scanner = parsec.Token(`[ \\t]*`, \"WS\")(scanner)\n\t\tif scanner.Endof() == false {\n\t\t\treturn index, fmt.Errorf(\"unable to parse posting\")\n\t\t}\n\t}\n\treturn index, nil\n}\n\n\/\/---- engine\n\nfunc (trans *Transaction) Firstpass(db *Datastore) error {\n\t\/\/ payee-rewrite\n\tif payee, ok := db.matchpayee(trans.Payee()); ok {\n\t\ttrans.setMetadata(\"payee\", payee)\n\t}\n\n\tfor _, posting := range trans.postings {\n\t\tif err := posting.Firstpass(db, trans); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif trans.shouldBalance() {\n\t\tdefaccount := db.GetAccount(db.getBalancingaccount()).(*Account)\n\t\tif ok, err := trans.autobalance1(db, defaccount); err != nil {\n\t\t\treturn err\n\t\t} else if ok == false {\n\t\t\treturn fmt.Errorf(\"unbalanced transaction\")\n\t\t}\n\t\tlog.Debugf(\"transaction balanced\\n\")\n\t}\n\treturn nil\n}\n\nfunc (trans *Transaction) Secondpass(db *Datastore) error {\n\tfor _, posting := range trans.postings {\n\t\tif err := posting.Secondpass(db, trans); err != nil {\n\t\t\treturn fmt.Errorf(\"lineno %v: %v\", trans.lineno, err)\n\t\t}\n\t}\n\treturn db.reporter.Transaction(db, trans)\n}\n\nfunc (trans *Transaction) Clone(ndb *Datastore) *Transaction {\n\tntrans := *trans\n\tntrans.postings = []*Posting{}\n\tfor _, posting := range trans.postings {\n\t\tntrans.postings = append(ntrans.postings, posting.Clone(ndb, &ntrans))\n\t}\n\treturn &ntrans\n}\n\nfunc (trans *Transaction) shouldBalance() bool {\n\tfor _, posting := range trans.postings {\n\t\tvirtual := posting.isVirtual()\n\t\tbalanced := posting.isBalanced()\n\t\tif virtual == true && balanced == false {\n\t\t\treturn false\n\t\t} else if balanced == false {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (trans *Transaction) defaultposting(\n\tdb *Datastore, defacc *Account, commodity *Commodity) *Posting {\n\n\tposting := NewPosting(trans)\n\tposting.account = defacc\n\tposting.commodity = commodity\n\treturn posting\n}\n\nfunc (trans *Transaction) endposting(postings []*Posting) (*Posting, error) {\n\tvar tallypost *Posting\n\tfor _, posting := range postings {\n\t\tif posting.commodity == nil && tallypost != nil {\n\t\t\terr := fmt.Errorf(\"Only one null posting allowed per transaction\")\n\t\t\treturn nil, err\n\t\t} else if posting.commodity == nil {\n\t\t\ttallypost = posting\n\t\t}\n\t}\n\treturn tallypost, nil\n}\n\nfunc (trans *Transaction) autobalance1(\n\tdb *Datastore, defaccount *Account) (bool, error) {\n\n\tif len(trans.postings) == 0 {\n\t\treturn false, fmt.Errorf(\"empty transaction\")\n\n\t} else if len(trans.postings) == 1 && defaccount != nil {\n\t\tcommodity := trans.postings[0].getCostprice()\n\t\tposting := trans.defaultposting(db, defaccount, commodity)\n\t\tposting.commodity.doInverse()\n\t\ttrans.postings = append(trans.postings, posting)\n\t\treturn true, nil\n\n\t} else if len(trans.postings) == 1 {\n\t\treturn false, fmt.Errorf(\"unbalanced transaction\")\n\t}\n\n\tunbcs, _ := trans.doBalance()\n\tif len(unbcs) == 0 {\n\t\treturn true, nil\n\t}\n\n\ttallypost, err := trans.endposting(trans.postings)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(unbcs) == 1 && tallypost == nil {\n\t\treturn false, fmt.Errorf(\"unbalanced transaction\")\n\t} else if tallypost == nil {\n\t\treturn true, nil\n\t}\n\n\ttallypost.commodity = unbcs[0]\n\ttallypost.commodity.doInverse()\n\tif len(unbcs) > 1 {\n\t\taccount := tallypost.account\n\t\tfor _, unbc := range unbcs[1:] {\n\t\t\tposting := trans.defaultposting(db, account, unbc)\n\t\t\tposting.commodity.doInverse()\n\t\t\ttrans.postings = append(trans.postings, posting)\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc (trans *Transaction) doBalance() ([]*Commodity, bool) {\n\tunbalanced := map[string]*Commodity{}\n\tfor _, posting := range trans.postings {\n\t\tif posting.commodity == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcommodity := posting.getCostprice()\n\t\tunbc, ok := unbalanced[commodity.name]\n\t\tif ok {\n\t\t\tunbc.doAdd(commodity)\n\t\t} else {\n\t\t\tunbc = commodity\n\t\t}\n\t\tunbalanced[unbc.name] = unbc\n\t}\n\tcommnames := []string{}\n\tfor name := range unbalanced {\n\t\tcommnames = append(commnames, name)\n\t}\n\tsort.Strings(commnames)\n\n\tunbcs := []*Commodity{}\n\tfor _, name := range commnames {\n\t\tunbc := unbalanced[name]\n\t\t\/\/ it is supposed to be unbc.amount == 0.0\n\t\t\/\/ issue #38\n\t\tif unbc.amount > float64(0.009) || unbc.amount < -float64(0.009) {\n\t\t\tunbcs = append(unbcs, unbc)\n\t\t}\n\t}\n\treturn unbcs, len(unbcs) > 1\n}\n\n\/\/ FitPayee for formatting.\nfunc FitPayee(payee string, maxwidth int) string {\n\tif len(payee) < maxwidth {\n\t\treturn payee\n\t}\n\tscraplen := len(payee) - maxwidth\n\tfields := []string{}\n\tfor _, field := range strings.Fields(payee) {\n\t\tif scraplen <= 0 || len(field) <= 3 {\n\t\t\tfields = append(fields, field)\n\t\t\tcontinue\n\t\t}\n\t\tif len(field[3:]) < scraplen {\n\t\t\tfields = append(fields, field[:3])\n\t\t\tscraplen -= len(field[3:])\n\t\t\tcontinue\n\t\t}\n\t\tfields = append(fields, field[:len(field)-scraplen])\n\t\tscraplen = 0\n\t}\n\treturn strings.Join(fields, \" \")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/graphql-go\/graphql\"\n)\n\ntype Todo struct {\n\tID   string `json:\"id\"`\n\tText string `json:\"text\"`\n\tDone bool   `json:\"done\"`\n}\n\nvar TodoList []Todo\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\nfunc init() {\n\ttodo1 := Todo{ID: \"a\", Text: \"A todo not to forget\", Done: false}\n\ttodo2 := Todo{ID: \"b\", Text: \"This is the most important\", Done: false}\n\ttodo3 := Todo{ID: \"c\", Text: \"Please do this or else\", Done: false}\n\tTodoList = append(TodoList, todo1, todo2, todo3)\n\n\trand.Seed(time.Now().UnixNano())\n}\n\n\/\/ define custom GraphQL ObjectType `todoType` for our Golang struct `Todo`\n\/\/ Note that\n\/\/ - the fields in our todoType maps with the json tags for the fields in our struct\n\/\/ - the field type matches the field type in our struct\nvar todoType = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"Todo\",\n\tFields: graphql.Fields{\n\t\t\"id\": &graphql.Field{\n\t\t\tType: graphql.String,\n\t\t},\n\t\t\"text\": &graphql.Field{\n\t\t\tType: graphql.String,\n\t\t},\n\t\t\"done\": &graphql.Field{\n\t\t\tType: graphql.Boolean,\n\t\t},\n\t},\n})\n\n\/\/ root mutation\nvar rootMutation = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"RootMutation\",\n\tFields: graphql.Fields{\n\t\t\/*\n\t\t\tcurl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{createTodo(text:\"My+new+todo\"){id,text,done}}'\n\t\t*\/\n\t\t\"createTodo\": &graphql.Field{\n\t\t\tType: todoType, \/\/ the return type for this field\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"text\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.NewNonNull(graphql.String),\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\n\t\t\t\t\/\/ marshall and cast the argument value\n\t\t\t\ttext, _ := params.Args[\"text\"].(string)\n\n\t\t\t\t\/\/ figure out new id\n\t\t\t\tnewID := RandStringRunes(8)\n\n\t\t\t\t\/\/ perform mutation operation here\n\t\t\t\t\/\/ for e.g. create a Todo and save to DB.\n\t\t\t\tnewTodo := Todo{\n\t\t\t\t\tID:   newID,\n\t\t\t\t\tText: text,\n\t\t\t\t\tDone: false,\n\t\t\t\t}\n\n\t\t\t\tTodoList = append(TodoList, newTodo)\n\n\t\t\t\t\/\/ return the new Todo object that we supposedly save to DB\n\t\t\t\t\/\/ Note here that\n\t\t\t\t\/\/ - we are returning a `Todo` struct instance here\n\t\t\t\t\/\/ - we previously specified the return Type to be `todoType`\n\t\t\t\t\/\/ - `Todo` struct maps to `todoType`, as defined in `todoType` ObjectConfig`\n\t\t\t\treturn newTodo, nil\n\t\t\t},\n\t\t},\n\t\t\/*\n\t\t\tcurl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{updateTodo(id:\"a\",done:true){id,text,done}}'\n\t\t*\/\n\t\t\"updateTodo\": &graphql.Field{\n\t\t\tType: todoType, \/\/ the return type for this field\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"done\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.Boolean,\n\t\t\t\t},\n\t\t\t\t\"id\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.NewNonNull(graphql.String),\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\/\/ marshall and cast the argument value\n\t\t\t\tdone, _ := params.Args[\"done\"].(bool)\n\t\t\t\tid, _ := params.Args[\"id\"].(string)\n\t\t\t\taffectedTodo := Todo{}\n\n\t\t\t\t\/\/ Search list for todo with id and change the done variable\n\t\t\t\tfor i := 0; i < len(TodoList); i++ {\n\t\t\t\t\tif TodoList[i].ID == id {\n\t\t\t\t\t\tTodoList[i].Done = done\n\t\t\t\t\t\t\/\/ Assign updated todo so we can return it\n\t\t\t\t\t\taffectedTodo = TodoList[i]\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Return affected todo\n\t\t\t\treturn affectedTodo, nil\n\t\t\t},\n\t\t},\n\t},\n})\n\n\/\/ root query\n\/\/ we just define a trivial example here, since root query is required.\n\/\/ Test with curl\n\/\/ curl -g 'http:\/\/localhost:8080\/graphql?query={lastTodo{id,text,done}}'\nvar rootQuery = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"RootQuery\",\n\tFields: graphql.Fields{\n\n\t\t\/*\n\t\t   curl -g 'http:\/\/localhost:8080\/graphql?query={todo(id:\"b\"){id,text,done}}'\n\t\t*\/\n\t\t\"todo\": &graphql.Field{\n\t\t\tType: todoType,\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"id\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.String,\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\n\t\t\t\tidQuery, isOK := params.Args[\"id\"].(string)\n\t\t\t\tif isOK {\n\t\t\t\t\t\/\/ Search for el with id\n\t\t\t\t\tfor _, todo := range TodoList {\n\t\t\t\t\t\tif todo.ID == idQuery {\n\t\t\t\t\t\t\treturn todo, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn Todo{}, nil\n\t\t\t},\n\t\t},\n\n\t\t\"lastTodo\": &graphql.Field{\n\t\t\tType:        todoType,\n\t\t\tDescription: \"Last todo added\",\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\t\t\t\treturn TodoList[len(TodoList)-1], nil\n\t\t\t},\n\t\t},\n\n\t\t\/*\n\t\t   curl -g 'http:\/\/localhost:8080\/graphql?query={todoList{id,text,done}}'\n\t\t*\/\n\t\t\"todoList\": &graphql.Field{\n\t\t\tType:        graphql.NewList(todoType),\n\t\t\tDescription: \"List of todos\",\n\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\treturn TodoList, nil\n\t\t\t},\n\t\t},\n\t},\n})\n\n\/\/ define schema, with our rootQuery and rootMutation\nvar schema, _ = graphql.NewSchema(graphql.SchemaConfig{\n\tQuery:    rootQuery,\n\tMutation: rootMutation,\n})\n\nfunc executeQuery(query string, schema graphql.Schema) *graphql.Result {\n\tresult := graphql.Do(graphql.Params{\n\t\tSchema:        schema,\n\t\tRequestString: query,\n\t})\n\tif len(result.Errors) > 0 {\n\t\tfmt.Printf(\"wrong result, unexpected errors: %v\", result.Errors)\n\t}\n\treturn result\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/graphql\", func(w http.ResponseWriter, r *http.Request) {\n\t\tresult := executeQuery(r.URL.Query()[\"query\"][0], schema)\n\t\tjson.NewEncoder(w).Encode(result)\n\t})\n\t\/\/ Serve static files\n\tfs := http.FileServer(http.Dir(\"static\"))\n\thttp.Handle(\"\/\", fs)\n\t\/\/ Display some basic instructions\n\tfmt.Println(\"Now server is running on port 8080\")\n\tfmt.Println(\"Get single todo: curl -g 'http:\/\/localhost:8080\/graphql?query={todo(id:\\\"b\\\"){id,text,done}}'\")\n\tfmt.Println(\"Create new todo: curl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{createTodo(text:\\\"My+new+todo\\\"){id,text,done}}'\")\n\tfmt.Println(\"Update a todo: curl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{updateTodo(id:\\\"b\\\",text:\\\"My+new+todo+updated\\\",done:true){id,text,done}}'\")\n\tfmt.Println(\"Load todo list: curl -g 'http:\/\/localhost:8080\/graphql?query={todoList{id,text,done}}'\")\n\tfmt.Println(\"Access the web app via browser at 'http:\/\/localhost:8080'\")\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<commit_msg>Add description to `updateTodo` mutation<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/graphql-go\/graphql\"\n)\n\ntype Todo struct {\n\tID   string `json:\"id\"`\n\tText string `json:\"text\"`\n\tDone bool   `json:\"done\"`\n}\n\nvar TodoList []Todo\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\nfunc init() {\n\ttodo1 := Todo{ID: \"a\", Text: \"A todo not to forget\", Done: false}\n\ttodo2 := Todo{ID: \"b\", Text: \"This is the most important\", Done: false}\n\ttodo3 := Todo{ID: \"c\", Text: \"Please do this or else\", Done: false}\n\tTodoList = append(TodoList, todo1, todo2, todo3)\n\n\trand.Seed(time.Now().UnixNano())\n}\n\n\/\/ define custom GraphQL ObjectType `todoType` for our Golang struct `Todo`\n\/\/ Note that\n\/\/ - the fields in our todoType maps with the json tags for the fields in our struct\n\/\/ - the field type matches the field type in our struct\nvar todoType = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"Todo\",\n\tFields: graphql.Fields{\n\t\t\"id\": &graphql.Field{\n\t\t\tType: graphql.String,\n\t\t},\n\t\t\"text\": &graphql.Field{\n\t\t\tType: graphql.String,\n\t\t},\n\t\t\"done\": &graphql.Field{\n\t\t\tType: graphql.Boolean,\n\t\t},\n\t},\n})\n\n\/\/ root mutation\nvar rootMutation = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"RootMutation\",\n\tFields: graphql.Fields{\n\t\t\/*\n\t\t\tcurl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{createTodo(text:\"My+new+todo\"){id,text,done}}'\n\t\t*\/\n\t\t\"createTodo\": &graphql.Field{\n\t\t\tType: todoType, \/\/ the return type for this field\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"text\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.NewNonNull(graphql.String),\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\n\t\t\t\t\/\/ marshall and cast the argument value\n\t\t\t\ttext, _ := params.Args[\"text\"].(string)\n\n\t\t\t\t\/\/ figure out new id\n\t\t\t\tnewID := RandStringRunes(8)\n\n\t\t\t\t\/\/ perform mutation operation here\n\t\t\t\t\/\/ for e.g. create a Todo and save to DB.\n\t\t\t\tnewTodo := Todo{\n\t\t\t\t\tID:   newID,\n\t\t\t\t\tText: text,\n\t\t\t\t\tDone: false,\n\t\t\t\t}\n\n\t\t\t\tTodoList = append(TodoList, newTodo)\n\n\t\t\t\t\/\/ return the new Todo object that we supposedly save to DB\n\t\t\t\t\/\/ Note here that\n\t\t\t\t\/\/ - we are returning a `Todo` struct instance here\n\t\t\t\t\/\/ - we previously specified the return Type to be `todoType`\n\t\t\t\t\/\/ - `Todo` struct maps to `todoType`, as defined in `todoType` ObjectConfig`\n\t\t\t\treturn newTodo, nil\n\t\t\t},\n\t\t},\n\t\t\/*\n\t\t\tcurl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{updateTodo(id:\"a\",done:true){id,text,done}}'\n\t\t*\/\n\t\t\"updateTodo\": &graphql.Field{\n\t\t\tType:        todoType, \/\/ the return type for this field\n\t\t\tDescription: \"Update existing todo, mark it done or not done\",\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"done\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.Boolean,\n\t\t\t\t},\n\t\t\t\t\"id\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.NewNonNull(graphql.String),\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\t\t\t\t\/\/ marshall and cast the argument value\n\t\t\t\tdone, _ := params.Args[\"done\"].(bool)\n\t\t\t\tid, _ := params.Args[\"id\"].(string)\n\t\t\t\taffectedTodo := Todo{}\n\n\t\t\t\t\/\/ Search list for todo with id and change the done variable\n\t\t\t\tfor i := 0; i < len(TodoList); i++ {\n\t\t\t\t\tif TodoList[i].ID == id {\n\t\t\t\t\t\tTodoList[i].Done = done\n\t\t\t\t\t\t\/\/ Assign updated todo so we can return it\n\t\t\t\t\t\taffectedTodo = TodoList[i]\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Return affected todo\n\t\t\t\treturn affectedTodo, nil\n\t\t\t},\n\t\t},\n\t},\n})\n\n\/\/ root query\n\/\/ we just define a trivial example here, since root query is required.\n\/\/ Test with curl\n\/\/ curl -g 'http:\/\/localhost:8080\/graphql?query={lastTodo{id,text,done}}'\nvar rootQuery = graphql.NewObject(graphql.ObjectConfig{\n\tName: \"RootQuery\",\n\tFields: graphql.Fields{\n\n\t\t\/*\n\t\t   curl -g 'http:\/\/localhost:8080\/graphql?query={todo(id:\"b\"){id,text,done}}'\n\t\t*\/\n\t\t\"todo\": &graphql.Field{\n\t\t\tType: todoType,\n\t\t\tArgs: graphql.FieldConfigArgument{\n\t\t\t\t\"id\": &graphql.ArgumentConfig{\n\t\t\t\t\tType: graphql.String,\n\t\t\t\t},\n\t\t\t},\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\n\t\t\t\tidQuery, isOK := params.Args[\"id\"].(string)\n\t\t\t\tif isOK {\n\t\t\t\t\t\/\/ Search for el with id\n\t\t\t\t\tfor _, todo := range TodoList {\n\t\t\t\t\t\tif todo.ID == idQuery {\n\t\t\t\t\t\t\treturn todo, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn Todo{}, nil\n\t\t\t},\n\t\t},\n\n\t\t\"lastTodo\": &graphql.Field{\n\t\t\tType:        todoType,\n\t\t\tDescription: \"Last todo added\",\n\t\t\tResolve: func(params graphql.ResolveParams) (interface{}, error) {\n\t\t\t\treturn TodoList[len(TodoList)-1], nil\n\t\t\t},\n\t\t},\n\n\t\t\/*\n\t\t   curl -g 'http:\/\/localhost:8080\/graphql?query={todoList{id,text,done}}'\n\t\t*\/\n\t\t\"todoList\": &graphql.Field{\n\t\t\tType:        graphql.NewList(todoType),\n\t\t\tDescription: \"List of todos\",\n\t\t\tResolve: func(p graphql.ResolveParams) (interface{}, error) {\n\t\t\t\treturn TodoList, nil\n\t\t\t},\n\t\t},\n\t},\n})\n\n\/\/ define schema, with our rootQuery and rootMutation\nvar schema, _ = graphql.NewSchema(graphql.SchemaConfig{\n\tQuery:    rootQuery,\n\tMutation: rootMutation,\n})\n\nfunc executeQuery(query string, schema graphql.Schema) *graphql.Result {\n\tresult := graphql.Do(graphql.Params{\n\t\tSchema:        schema,\n\t\tRequestString: query,\n\t})\n\tif len(result.Errors) > 0 {\n\t\tfmt.Printf(\"wrong result, unexpected errors: %v\", result.Errors)\n\t}\n\treturn result\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/graphql\", func(w http.ResponseWriter, r *http.Request) {\n\t\tresult := executeQuery(r.URL.Query()[\"query\"][0], schema)\n\t\tjson.NewEncoder(w).Encode(result)\n\t})\n\t\/\/ Serve static files\n\tfs := http.FileServer(http.Dir(\"static\"))\n\thttp.Handle(\"\/\", fs)\n\t\/\/ Display some basic instructions\n\tfmt.Println(\"Now server is running on port 8080\")\n\tfmt.Println(\"Get single todo: curl -g 'http:\/\/localhost:8080\/graphql?query={todo(id:\\\"b\\\"){id,text,done}}'\")\n\tfmt.Println(\"Create new todo: curl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{createTodo(text:\\\"My+new+todo\\\"){id,text,done}}'\")\n\tfmt.Println(\"Update a todo: curl -g 'http:\/\/localhost:8080\/graphql?query=mutation+_{updateTodo(id:\\\"b\\\",text:\\\"My+new+todo+updated\\\",done:true){id,text,done}}'\")\n\tfmt.Println(\"Load todo list: curl -g 'http:\/\/localhost:8080\/graphql?query={todoList{id,text,done}}'\")\n\tfmt.Println(\"Access the web app via browser at 'http:\/\/localhost:8080'\")\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package openstack\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/networking\/v2\/extensions\/fwaas\/policies\"\n)\n\nfunc resourceFWPolicyV1() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceFWPolicyV1Create,\n\t\tRead:   resourceFWPolicyV1Read,\n\t\tUpdate: resourceFWPolicyV1Update,\n\t\tDelete: resourceFWPolicyV1Delete,\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: schema.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\tOptional: true,\n\t\t\t},\n\t\t\t\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"audited\": &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\"shared\": &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\"tenant_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tComputed: true,\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.Schema{Type: schema.TypeString},\n\t\t\t\tSet:      schema.HashString,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceFWPolicyV1Create(d *schema.ResourceData, meta interface{}) error {\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tv := d.Get(\"rules\").(*schema.Set)\n\n\tlog.Printf(\"[DEBUG] Rules found : %#v\", v)\n\tlog.Printf(\"[DEBUG] Rules count : %d\", v.Len())\n\n\trules := make([]string, v.Len())\n\tfor i, v := range v.List() {\n\t\trules[i] = v.(string)\n\t}\n\n\taudited := d.Get(\"audited\").(bool)\n\tshared := d.Get(\"shared\").(bool)\n\n\topts := policies.CreateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t\tAudited:     &audited,\n\t\tShared:      &shared,\n\t\tTenantID:    d.Get(\"tenant_id\").(string),\n\t\tRules:       rules,\n\t}\n\n\tlog.Printf(\"[DEBUG] Create firewall policy: %#v\", opts)\n\n\tpolicy, err := policies.Create(networkingClient, opts).Extract()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] Firewall policy created: %#v\", policy)\n\n\td.SetId(policy.ID)\n\n\treturn resourceFWPolicyV1Read(d, meta)\n}\n\nfunc resourceFWPolicyV1Read(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[DEBUG] Retrieve information about firewall policy: %s\", d.Id())\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tpolicy, err := policies.Get(networkingClient, d.Id()).Extract()\n\n\tif err != nil {\n\t\treturn CheckDeleted(d, err, \"FW policy\")\n\t}\n\n\td.Set(\"name\", policy.Name)\n\td.Set(\"description\", policy.Description)\n\td.Set(\"shared\", policy.Shared)\n\td.Set(\"audited\", policy.Audited)\n\td.Set(\"tenant_id\", policy.TenantID)\n\treturn nil\n}\n\nfunc resourceFWPolicyV1Update(d *schema.ResourceData, meta interface{}) error {\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\topts := policies.UpdateOpts{}\n\n\tif d.HasChange(\"name\") {\n\t\topts.Name = d.Get(\"name\").(string)\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\topts.Description = d.Get(\"description\").(string)\n\t}\n\n\tif d.HasChange(\"rules\") {\n\t\tv := d.Get(\"rules\").(*schema.Set)\n\n\t\tlog.Printf(\"[DEBUG] Rules found : %#v\", v)\n\t\tlog.Printf(\"[DEBUG] Rules count : %d\", v.Len())\n\n\t\trules := make([]string, v.Len())\n\t\tfor i, v := range v.List() {\n\t\t\trules[i] = v.(string)\n\t\t}\n\t\topts.Rules = rules\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating firewall policy with id %s: %#v\", d.Id(), opts)\n\n\terr = policies.Update(networkingClient, d.Id(), opts).Err\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn resourceFWPolicyV1Read(d, meta)\n}\n\nfunc resourceFWPolicyV1Delete(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[DEBUG] Destroy firewall policy: %s\", d.Id())\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tfor i := 0; i < 15; i++ {\n\n\t\terr = policies.Delete(networkingClient, d.Id()).Err\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\thttpError, ok := err.(*gophercloud.UnexpectedResponseCodeError)\n\t\tif !ok || httpError.Actual != 409 {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ This error usually means that the policy is attached\n\t\t\/\/ to a firewall. At this point, the firewall is probably\n\t\t\/\/ being delete. So, we retry a few times.\n\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\n\treturn err\n}\n<commit_msg>provider\/openstack: Change rules type to List<commit_after>package openstack\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/networking\/v2\/extensions\/fwaas\/policies\"\n)\n\nfunc resourceFWPolicyV1() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceFWPolicyV1Create,\n\t\tRead:   resourceFWPolicyV1Read,\n\t\tUpdate: resourceFWPolicyV1Update,\n\t\tDelete: resourceFWPolicyV1Delete,\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: schema.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\tOptional: true,\n\t\t\t},\n\t\t\t\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"audited\": &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\"shared\": &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\"tenant_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"rules\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceFWPolicyV1Create(d *schema.ResourceData, meta interface{}) error {\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tv := d.Get(\"rules\").([]interface{})\n\n\tlog.Printf(\"[DEBUG] Rules found : %#v\", v)\n\tlog.Printf(\"[DEBUG] Rules count : %d\", len(v))\n\n\trules := make([]string, len(v))\n\tfor i, v := range v {\n\t\trules[i] = v.(string)\n\t}\n\n\taudited := d.Get(\"audited\").(bool)\n\tshared := d.Get(\"shared\").(bool)\n\n\topts := policies.CreateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t\tAudited:     &audited,\n\t\tShared:      &shared,\n\t\tTenantID:    d.Get(\"tenant_id\").(string),\n\t\tRules:       rules,\n\t}\n\n\tlog.Printf(\"[DEBUG] Create firewall policy: %#v\", opts)\n\n\tpolicy, err := policies.Create(networkingClient, opts).Extract()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] Firewall policy created: %#v\", policy)\n\n\td.SetId(policy.ID)\n\n\treturn resourceFWPolicyV1Read(d, meta)\n}\n\nfunc resourceFWPolicyV1Read(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[DEBUG] Retrieve information about firewall policy: %s\", d.Id())\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tpolicy, err := policies.Get(networkingClient, d.Id()).Extract()\n\n\tif err != nil {\n\t\treturn CheckDeleted(d, err, \"FW policy\")\n\t}\n\n\td.Set(\"name\", policy.Name)\n\td.Set(\"description\", policy.Description)\n\td.Set(\"shared\", policy.Shared)\n\td.Set(\"audited\", policy.Audited)\n\td.Set(\"tenant_id\", policy.TenantID)\n\treturn nil\n}\n\nfunc resourceFWPolicyV1Update(d *schema.ResourceData, meta interface{}) error {\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\topts := policies.UpdateOpts{}\n\n\tif d.HasChange(\"name\") {\n\t\topts.Name = d.Get(\"name\").(string)\n\t}\n\n\tif d.HasChange(\"description\") {\n\t\topts.Description = d.Get(\"description\").(string)\n\t}\n\n\tif d.HasChange(\"rules\") {\n\t\tv := d.Get(\"rules\").([]interface{})\n\n\t\tlog.Printf(\"[DEBUG] Rules found : %#v\", v)\n\t\tlog.Printf(\"[DEBUG] Rules count : %d\", len(v))\n\n\t\trules := make([]string, len(v))\n\t\tfor i, v := range v {\n\t\t\trules[i] = v.(string)\n\t\t}\n\t\topts.Rules = rules\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating firewall policy with id %s: %#v\", d.Id(), opts)\n\n\terr = policies.Update(networkingClient, d.Id(), opts).Err\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn resourceFWPolicyV1Read(d, meta)\n}\n\nfunc resourceFWPolicyV1Delete(d *schema.ResourceData, meta interface{}) error {\n\tlog.Printf(\"[DEBUG] Destroy firewall policy: %s\", d.Id())\n\n\tconfig := meta.(*Config)\n\tnetworkingClient, err := config.networkingV2Client(d.Get(\"region\").(string))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack networking client: %s\", err)\n\t}\n\n\tfor i := 0; i < 15; i++ {\n\n\t\terr = policies.Delete(networkingClient, d.Id()).Err\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\thttpError, ok := err.(*gophercloud.UnexpectedResponseCodeError)\n\t\tif !ok || httpError.Actual != 409 {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ This error usually means that the policy is attached\n\t\t\/\/ to a firewall. At this point, the firewall is probably\n\t\t\/\/ being delete. So, we retry a few times.\n\n\t\ttime.Sleep(time.Second * 2)\n\t}\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package ledis\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"github.com\/siddontang\/ledisdb\/store\"\n\t\"time\"\n)\n\nconst (\n\tlistHeadSeq int32 = 1\n\tlistTailSeq int32 = 2\n\n\tlistMinSeq     int32 = 1000\n\tlistMaxSeq     int32 = 1<<31 - 1000\n\tlistInitialSeq int32 = listMinSeq + (listMaxSeq-listMinSeq)\/2\n)\n\nvar errLMetaKey = errors.New(\"invalid lmeta key\")\nvar errListKey = errors.New(\"invalid list key\")\nvar errListSeq = errors.New(\"invalid list sequence, overflow\")\n\nfunc (db *DB) lEncodeMetaKey(key []byte) []byte {\n\tbuf := make([]byte, len(key)+2)\n\tbuf[0] = db.index\n\tbuf[1] = LMetaType\n\n\tcopy(buf[2:], key)\n\treturn buf\n}\n\nfunc (db *DB) lDecodeMetaKey(ek []byte) ([]byte, error) {\n\tif len(ek) < 2 || ek[0] != db.index || ek[1] != LMetaType {\n\t\treturn nil, errLMetaKey\n\t}\n\n\treturn ek[2:], nil\n}\n\nfunc (db *DB) lEncodeListKey(key []byte, seq int32) []byte {\n\tbuf := make([]byte, len(key)+8)\n\n\tpos := 0\n\tbuf[pos] = db.index\n\tpos++\n\tbuf[pos] = ListType\n\tpos++\n\n\tbinary.BigEndian.PutUint16(buf[pos:], uint16(len(key)))\n\tpos += 2\n\n\tcopy(buf[pos:], key)\n\tpos += len(key)\n\n\tbinary.BigEndian.PutUint32(buf[pos:], uint32(seq))\n\n\treturn buf\n}\n\nfunc (db *DB) lDecodeListKey(ek []byte) (key []byte, seq int32, err error) {\n\tif len(ek) < 8 || ek[0] != db.index || ek[1] != ListType {\n\t\terr = errListKey\n\t\treturn\n\t}\n\n\tkeyLen := int(binary.BigEndian.Uint16(ek[2:]))\n\tif keyLen+8 != len(ek) {\n\t\terr = errListKey\n\t\treturn\n\t}\n\n\tkey = ek[4 : 4+keyLen]\n\tseq = int32(binary.BigEndian.Uint32(ek[4+keyLen:]))\n\treturn\n}\n\nfunc (db *DB) lpush(key []byte, whereSeq int32, args ...[]byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar size int32\n\tvar err error\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\theadSeq, tailSeq, size, err = db.lGetMeta(nil, metaKey)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar pushCnt int = len(args)\n\tif pushCnt == 0 {\n\t\treturn int64(size), nil\n\t}\n\n\tvar seq int32 = headSeq\n\tvar delta int32 = -1\n\tif whereSeq == listTailSeq {\n\t\tseq = tailSeq\n\t\tdelta = 1\n\t}\n\n\t\/\/\tappend elements\n\tif size > 0 {\n\t\tseq += delta\n\t}\n\n\tfor i := 0; i < pushCnt; i++ {\n\t\tek := db.lEncodeListKey(key, seq+int32(i)*delta)\n\t\tt.Put(ek, args[i])\n\t}\n\n\tseq += int32(pushCnt-1) * delta\n\tif seq <= listMinSeq || seq >= listMaxSeq {\n\t\treturn 0, errListSeq\n\t}\n\n\t\/\/\tset meta info\n\tif whereSeq == listHeadSeq {\n\t\theadSeq = seq\n\t} else {\n\t\ttailSeq = seq\n\t}\n\n\tdb.lSetMeta(metaKey, headSeq, tailSeq)\n\n\terr = t.Commit()\n\treturn int64(size) + int64(pushCnt), err\n}\n\nfunc (db *DB) lpop(key []byte, whereSeq int32) ([]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\theadSeq, tailSeq, _, err = db.lGetMeta(nil, metaKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar value []byte\n\n\tvar seq int32 = headSeq\n\tif whereSeq == listTailSeq {\n\t\tseq = tailSeq\n\t}\n\n\titemKey := db.lEncodeListKey(key, seq)\n\tvalue, err = db.db.Get(itemKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif whereSeq == listHeadSeq {\n\t\theadSeq += 1\n\t} else {\n\t\ttailSeq -= 1\n\t}\n\n\tt.Delete(itemKey)\n\tsize := db.lSetMeta(metaKey, headSeq, tailSeq)\n\tif size == 0 {\n\t\tdb.rmExpire(t, HashType, key)\n\t}\n\n\terr = t.Commit()\n\treturn value, err\n}\n\n\/\/\tps : here just focus on deleting the list data,\n\/\/\t\t any other likes expire is ignore.\nfunc (db *DB) lDelete(t *tx, key []byte) int64 {\n\tmk := db.lEncodeMetaKey(key)\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\theadSeq, tailSeq, _, err = db.lGetMeta(it, mk)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tvar num int64 = 0\n\tstartKey := db.lEncodeListKey(key, headSeq)\n\tstopKey := db.lEncodeListKey(key, tailSeq)\n\n\trit := store.NewRangeIterator(it, &store.Range{startKey, stopKey, store.RangeClose})\n\tfor ; rit.Valid(); rit.Next() {\n\t\tt.Delete(rit.RawKey())\n\t\tnum++\n\t}\n\n\tt.Delete(mk)\n\n\treturn num\n}\n\nfunc (db *DB) lGetMeta(it *store.Iterator, ek []byte) (headSeq int32, tailSeq int32, size int32, err error) {\n\tvar v []byte\n\tif it != nil {\n\t\tv = it.Find(ek)\n\t} else {\n\t\tv, err = db.db.Get(ek)\n\t}\n\tif err != nil {\n\t\treturn\n\t} else if v == nil {\n\t\theadSeq = listInitialSeq\n\t\ttailSeq = listInitialSeq\n\t\tsize = 0\n\t\treturn\n\t} else {\n\t\theadSeq = int32(binary.LittleEndian.Uint32(v[0:4]))\n\t\ttailSeq = int32(binary.LittleEndian.Uint32(v[4:8]))\n\t\tsize = tailSeq - headSeq + 1\n\t}\n\treturn\n}\n\nfunc (db *DB) lSetMeta(ek []byte, headSeq int32, tailSeq int32) int32 {\n\tt := db.listTx\n\n\tvar size int32 = tailSeq - headSeq + 1\n\tif size < 0 {\n\t\t\/\/\ttodo : log error + panic\n\t} else if size == 0 {\n\t\tt.Delete(ek)\n\t} else {\n\t\tbuf := make([]byte, 8)\n\n\t\tbinary.LittleEndian.PutUint32(buf[0:4], uint32(headSeq))\n\t\tbinary.LittleEndian.PutUint32(buf[4:8], uint32(tailSeq))\n\n\t\tt.Put(ek, buf)\n\t}\n\n\treturn size\n}\n\nfunc (db *DB) lExpireAt(key []byte, when int64) (int64, error) {\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tif llen, err := db.LLen(key); err != nil || llen == 0 {\n\t\treturn 0, err\n\t} else {\n\t\tdb.expireAt(t, ListType, key, when)\n\t\tif err := t.Commit(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn 1, nil\n}\n\nfunc (db *DB) LIndex(key []byte, index int32) ([]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar seq int32\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\theadSeq, tailSeq, _, err = db.lGetMeta(it, metaKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif index >= 0 {\n\t\tseq = headSeq + index\n\t} else {\n\t\tseq = tailSeq + index + 1\n\t}\n\n\tsk := db.lEncodeListKey(key, seq)\n\tv := it.Find(sk)\n\n\treturn v, nil\n}\n\nfunc (db *DB) LLen(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tek := db.lEncodeMetaKey(key)\n\t_, _, size, err := db.lGetMeta(nil, ek)\n\treturn int64(size), err\n}\n\nfunc (db *DB) LPop(key []byte) ([]byte, error) {\n\treturn db.lpop(key, listHeadSeq)\n}\n\nfunc (db *DB) LPush(key []byte, args ...[]byte) (int64, error) {\n\treturn db.lpush(key, listHeadSeq, args...)\n}\n\nfunc (db *DB) LRange(key []byte, start int32, stop int32) ([][]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar headSeq int32\n\tvar llen int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\tif headSeq, _, llen, err = db.lGetMeta(it, metaKey); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif start < 0 {\n\t\tstart = llen + start\n\t}\n\tif stop < 0 {\n\t\tstop = llen + stop\n\t}\n\tif start < 0 {\n\t\tstart = 0\n\t}\n\n\tif start > stop || start >= llen {\n\t\treturn [][]byte{}, nil\n\t}\n\n\tif stop >= llen {\n\t\tstop = llen - 1\n\t}\n\n\tlimit := (stop - start) + 1\n\theadSeq += start\n\n\tv := make([][]byte, 0, limit)\n\n\tstartKey := db.lEncodeListKey(key, headSeq)\n\trit := store.NewRangeLimitIterator(it,\n\t\t&store.Range{\n\t\t\tMin:  startKey,\n\t\t\tMax:  nil,\n\t\t\tType: store.RangeClose},\n\t\t&store.Limit{\n\t\t\tOffset: 0,\n\t\t\tCount:  int(limit)})\n\n\tfor ; rit.Valid(); rit.Next() {\n\t\tv = append(v, rit.Value())\n\t}\n\n\treturn v, nil\n}\n\nfunc (db *DB) RPop(key []byte) ([]byte, error) {\n\treturn db.lpop(key, listTailSeq)\n}\n\nfunc (db *DB) RPush(key []byte, args ...[]byte) (int64, error) {\n\treturn db.lpush(key, listTailSeq, args...)\n}\n\nfunc (db *DB) LClear(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tnum := db.lDelete(t, key)\n\tdb.rmExpire(t, ListType, key)\n\n\terr := t.Commit()\n\treturn num, err\n}\n\nfunc (db *DB) LMclear(keys ...[]byte) (int64, error) {\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tfor _, key := range keys {\n\t\tif err := checkKeySize(key); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tdb.lDelete(t, key)\n\t\tdb.rmExpire(t, ListType, key)\n\n\t}\n\n\terr := t.Commit()\n\treturn int64(len(keys)), err\n}\n\nfunc (db *DB) lFlush() (drop int64, err error) {\n\tminKey := make([]byte, 2)\n\tminKey[0] = db.index\n\tminKey[1] = ListType\n\n\tmaxKey := make([]byte, 2)\n\tmaxKey[0] = db.index\n\tmaxKey[1] = LMetaType + 1\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tdrop, err = db.flushRegion(t, minKey, maxKey)\n\terr = db.expFlush(t, ListType)\n\n\terr = t.Commit()\n\treturn\n}\n\nfunc (db *DB) LExpire(key []byte, duration int64) (int64, error) {\n\tif duration <= 0 {\n\t\treturn 0, errExpireValue\n\t}\n\n\treturn db.lExpireAt(key, time.Now().Unix()+duration)\n}\n\nfunc (db *DB) LExpireAt(key []byte, when int64) (int64, error) {\n\tif when <= time.Now().Unix() {\n\t\treturn 0, errExpireValue\n\t}\n\n\treturn db.lExpireAt(key, when)\n}\n\nfunc (db *DB) LTTL(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn db.ttl(ListType, key)\n}\n\nfunc (db *DB) LPersist(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tn, err := db.rmExpire(t, ListType, key)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\terr = t.Commit()\n\treturn n, err\n}\n<commit_msg>LPut<commit_after>package ledis\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"github.com\/siddontang\/ledisdb\/store\"\n\t\"time\"\n)\n\nconst (\n\tlistHeadSeq int32 = 1\n\tlistTailSeq int32 = 2\n\n\tlistMinSeq     int32 = 1000\n\tlistMaxSeq     int32 = 1<<31 - 1000\n\tlistInitialSeq int32 = listMinSeq + (listMaxSeq-listMinSeq)\/2\n)\n\nvar errLMetaKey = errors.New(\"invalid lmeta key\")\nvar errListKey = errors.New(\"invalid list key\")\nvar errListSeq = errors.New(\"invalid list sequence, overflow\")\n\nfunc (db *DB) lEncodeMetaKey(key []byte) []byte {\n\tbuf := make([]byte, len(key)+2)\n\tbuf[0] = db.index\n\tbuf[1] = LMetaType\n\n\tcopy(buf[2:], key)\n\treturn buf\n}\n\nfunc (db *DB) lDecodeMetaKey(ek []byte) ([]byte, error) {\n\tif len(ek) < 2 || ek[0] != db.index || ek[1] != LMetaType {\n\t\treturn nil, errLMetaKey\n\t}\n\n\treturn ek[2:], nil\n}\n\nfunc (db *DB) lEncodeListKey(key []byte, seq int32) []byte {\n\tbuf := make([]byte, len(key)+8)\n\n\tpos := 0\n\tbuf[pos] = db.index\n\tpos++\n\tbuf[pos] = ListType\n\tpos++\n\n\tbinary.BigEndian.PutUint16(buf[pos:], uint16(len(key)))\n\tpos += 2\n\n\tcopy(buf[pos:], key)\n\tpos += len(key)\n\n\tbinary.BigEndian.PutUint32(buf[pos:], uint32(seq))\n\n\treturn buf\n}\n\nfunc (db *DB) lDecodeListKey(ek []byte) (key []byte, seq int32, err error) {\n\tif len(ek) < 8 || ek[0] != db.index || ek[1] != ListType {\n\t\terr = errListKey\n\t\treturn\n\t}\n\n\tkeyLen := int(binary.BigEndian.Uint16(ek[2:]))\n\tif keyLen+8 != len(ek) {\n\t\terr = errListKey\n\t\treturn\n\t}\n\n\tkey = ek[4 : 4+keyLen]\n\tseq = int32(binary.BigEndian.Uint32(ek[4+keyLen:]))\n\treturn\n}\n\nfunc (db *DB) lpush(key []byte, whereSeq int32, args ...[]byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar size int32\n\tvar err error\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\theadSeq, tailSeq, size, err = db.lGetMeta(nil, metaKey)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar pushCnt int = len(args)\n\tif pushCnt == 0 {\n\t\treturn int64(size), nil\n\t}\n\n\tvar seq int32 = headSeq\n\tvar delta int32 = -1\n\tif whereSeq == listTailSeq {\n\t\tseq = tailSeq\n\t\tdelta = 1\n\t}\n\n\t\/\/\tappend elements\n\tif size > 0 {\n\t\tseq += delta\n\t}\n\n\tfor i := 0; i < pushCnt; i++ {\n\t\tek := db.lEncodeListKey(key, seq+int32(i)*delta)\n\t\tt.Put(ek, args[i])\n\t}\n\n\tseq += int32(pushCnt-1) * delta\n\tif seq <= listMinSeq || seq >= listMaxSeq {\n\t\treturn 0, errListSeq\n\t}\n\n\t\/\/\tset meta info\n\tif whereSeq == listHeadSeq {\n\t\theadSeq = seq\n\t} else {\n\t\ttailSeq = seq\n\t}\n\n\tdb.lSetMeta(metaKey, headSeq, tailSeq)\n\n\terr = t.Commit()\n\treturn int64(size) + int64(pushCnt), err\n}\n\nfunc (db *DB) lpop(key []byte, whereSeq int32) ([]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\theadSeq, tailSeq, _, err = db.lGetMeta(nil, metaKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar value []byte\n\n\tvar seq int32 = headSeq\n\tif whereSeq == listTailSeq {\n\t\tseq = tailSeq\n\t}\n\n\titemKey := db.lEncodeListKey(key, seq)\n\tvalue, err = db.db.Get(itemKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif whereSeq == listHeadSeq {\n\t\theadSeq += 1\n\t} else {\n\t\ttailSeq -= 1\n\t}\n\n\tt.Delete(itemKey)\n\tsize := db.lSetMeta(metaKey, headSeq, tailSeq)\n\tif size == 0 {\n\t\tdb.rmExpire(t, HashType, key)\n\t}\n\n\terr = t.Commit()\n\treturn value, err\n}\n\n\/\/\tps : here just focus on deleting the list data,\n\/\/\t\t any other likes expire is ignore.\nfunc (db *DB) lDelete(t *tx, key []byte) int64 {\n\tmk := db.lEncodeMetaKey(key)\n\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\theadSeq, tailSeq, _, err = db.lGetMeta(it, mk)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tvar num int64 = 0\n\tstartKey := db.lEncodeListKey(key, headSeq)\n\tstopKey := db.lEncodeListKey(key, tailSeq)\n\n\trit := store.NewRangeIterator(it, &store.Range{startKey, stopKey, store.RangeClose})\n\tfor ; rit.Valid(); rit.Next() {\n\t\tt.Delete(rit.RawKey())\n\t\tnum++\n\t}\n\n\tt.Delete(mk)\n\n\treturn num\n}\n\nfunc (db *DB) lGetMeta(it *store.Iterator, ek []byte) (headSeq int32, tailSeq int32, size int32, err error) {\n\tvar v []byte\n\tif it != nil {\n\t\tv = it.Find(ek)\n\t} else {\n\t\tv, err = db.db.Get(ek)\n\t}\n\tif err != nil {\n\t\treturn\n\t} else if v == nil {\n\t\theadSeq = listInitialSeq\n\t\ttailSeq = listInitialSeq\n\t\tsize = 0\n\t\treturn\n\t} else {\n\t\theadSeq = int32(binary.LittleEndian.Uint32(v[0:4]))\n\t\ttailSeq = int32(binary.LittleEndian.Uint32(v[4:8]))\n\t\tsize = tailSeq - headSeq + 1\n\t}\n\treturn\n}\n\nfunc (db *DB) lSetMeta(ek []byte, headSeq int32, tailSeq int32) int32 {\n\tt := db.listTx\n\n\tvar size int32 = tailSeq - headSeq + 1\n\tif size < 0 {\n\t\t\/\/\ttodo : log error + panic\n\t} else if size == 0 {\n\t\tt.Delete(ek)\n\t} else {\n\t\tbuf := make([]byte, 8)\n\n\t\tbinary.LittleEndian.PutUint32(buf[0:4], uint32(headSeq))\n\t\tbinary.LittleEndian.PutUint32(buf[4:8], uint32(tailSeq))\n\n\t\tt.Put(ek, buf)\n\t}\n\n\treturn size\n}\n\nfunc (db *DB) lExpireAt(key []byte, when int64) (int64, error) {\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tif llen, err := db.LLen(key); err != nil || llen == 0 {\n\t\treturn 0, err\n\t} else {\n\t\tdb.expireAt(t, ListType, key, when)\n\t\tif err := t.Commit(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn 1, nil\n}\n\nfunc (db *DB) LIndex(key []byte, index int32) ([]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar seq int32\n\tvar headSeq int32\n\tvar tailSeq int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\theadSeq, tailSeq, _, err = db.lGetMeta(it, metaKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif index >= 0 {\n\t\tseq = headSeq + index\n\t} else {\n\t\tseq = tailSeq + index + 1\n\t}\n\n\tsk := db.lEncodeListKey(key, seq)\n\tv := it.Find(sk)\n\n\treturn v, nil\n}\n\nfunc (db *DB) LLen(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tek := db.lEncodeMetaKey(key)\n\t_, _, size, err := db.lGetMeta(nil, ek)\n\treturn int64(size), err\n}\n\nfunc (db *DB) LPop(key []byte) ([]byte, error) {\n\treturn db.lpop(key, listHeadSeq)\n}\n\nfunc (db *DB) LPush(key []byte, args ...[]byte) (int64, error) {\n\treturn db.lpush(key, listHeadSeq, args...)\n}\nfunc (db *DB) LSet(key []byte, index int32, value []byte) error {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn err\n\t}\n\n\tvar seq int32\n\tvar headSeq int32\n\tvar tailSeq int32\n\t\/\/var size int32\n\tvar err error\n\tt := db.listBatch\n\tt.Lock()\n\tdefer t.Unlock()\n\tmetaKey := db.lEncodeMetaKey(key)\n\n\theadSeq, tailSeq, _, err = db.lGetMeta(nil, metaKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif index >= 0 {\n\t\tseq = headSeq + index\n\t} else {\n\t\tseq = tailSeq + index + 1\n\t}\n\n\tsk := db.lEncodeListKey(key, seq)\n\tt.Put(sk, value)\n\terr = t.Commit()\n\treturn err\n}\n\nfunc (db *DB) LRange(key []byte, start int32, stop int32) ([][]byte, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar headSeq int32\n\tvar llen int32\n\tvar err error\n\n\tmetaKey := db.lEncodeMetaKey(key)\n\n\tit := db.db.NewIterator()\n\tdefer it.Close()\n\n\tif headSeq, _, llen, err = db.lGetMeta(it, metaKey); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif start < 0 {\n\t\tstart = llen + start\n\t}\n\tif stop < 0 {\n\t\tstop = llen + stop\n\t}\n\tif start < 0 {\n\t\tstart = 0\n\t}\n\n\tif start > stop || start >= llen {\n\t\treturn [][]byte{}, nil\n\t}\n\n\tif stop >= llen {\n\t\tstop = llen - 1\n\t}\n\n\tlimit := (stop - start) + 1\n\theadSeq += start\n\n\tv := make([][]byte, 0, limit)\n\n\tstartKey := db.lEncodeListKey(key, headSeq)\n\trit := store.NewRangeLimitIterator(it,\n\t\t&store.Range{\n\t\t\tMin:  startKey,\n\t\t\tMax:  nil,\n\t\t\tType: store.RangeClose},\n\t\t&store.Limit{\n\t\t\tOffset: 0,\n\t\t\tCount:  int(limit)})\n\n\tfor ; rit.Valid(); rit.Next() {\n\t\tv = append(v, rit.Value())\n\t}\n\n\treturn v, nil\n}\n\nfunc (db *DB) RPop(key []byte) ([]byte, error) {\n\treturn db.lpop(key, listTailSeq)\n}\n\nfunc (db *DB) RPush(key []byte, args ...[]byte) (int64, error) {\n\treturn db.lpush(key, listTailSeq, args...)\n}\n\nfunc (db *DB) LClear(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tnum := db.lDelete(t, key)\n\tdb.rmExpire(t, ListType, key)\n\n\terr := t.Commit()\n\treturn num, err\n}\n\nfunc (db *DB) LMclear(keys ...[]byte) (int64, error) {\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tfor _, key := range keys {\n\t\tif err := checkKeySize(key); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tdb.lDelete(t, key)\n\t\tdb.rmExpire(t, ListType, key)\n\n\t}\n\n\terr := t.Commit()\n\treturn int64(len(keys)), err\n}\n\nfunc (db *DB) lFlush() (drop int64, err error) {\n\tminKey := make([]byte, 2)\n\tminKey[0] = db.index\n\tminKey[1] = ListType\n\n\tmaxKey := make([]byte, 2)\n\tmaxKey[0] = db.index\n\tmaxKey[1] = LMetaType + 1\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tdrop, err = db.flushRegion(t, minKey, maxKey)\n\terr = db.expFlush(t, ListType)\n\n\terr = t.Commit()\n\treturn\n}\n\nfunc (db *DB) LExpire(key []byte, duration int64) (int64, error) {\n\tif duration <= 0 {\n\t\treturn 0, errExpireValue\n\t}\n\n\treturn db.lExpireAt(key, time.Now().Unix()+duration)\n}\n\nfunc (db *DB) LExpireAt(key []byte, when int64) (int64, error) {\n\tif when <= time.Now().Unix() {\n\t\treturn 0, errExpireValue\n\t}\n\n\treturn db.lExpireAt(key, when)\n}\n\nfunc (db *DB) LTTL(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn db.ttl(ListType, key)\n}\n\nfunc (db *DB) LPersist(key []byte) (int64, error) {\n\tif err := checkKeySize(key); err != nil {\n\t\treturn 0, err\n\t}\n\n\tt := db.listTx\n\tt.Lock()\n\tdefer t.Unlock()\n\n\tn, err := db.rmExpire(t, ListType, key)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\terr = t.Commit()\n\treturn n, err\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 config\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\n\t\"github.com\/webx-top\/codec\"\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/echo\"\n\t\"github.com\/webx-top\/echo\/middleware\/language\"\n\n\t\"github.com\/admpub\/confl\"\n\t\"github.com\/admpub\/log\"\n\t\"github.com\/admpub\/nging\/application\/library\/caddy\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/extend\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/scookie\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/scron\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/sdb\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/ssystem\"\n\t\"github.com\/admpub\/nging\/application\/library\/ftp\"\n\t\"github.com\/admpub\/securecookie\"\n)\n\nfunc NewConfig() *Config {\n\tc := &Config{}\n\tc.InitExtend()\n\tc.Settings = NewSettings(c)\n\treturn c\n}\n\ntype Config struct {\n\tDB sdb.DB `json:\"db\"`\n\n\tSys ssystem.System `json:\"sys\"`\n\n\tCron scron.Cron `json:\"cron\"`\n\n\tCookie scookie.Config `json:\"cookie\"`\n\n\tCaddy    caddy.Config    `json:\"caddy\"`\n\tFTP      ftp.Config      `json:\"ftp\"`\n\tLanguage language.Config `json:\"language\"`\n\tDownload struct {\n\t\tSavePath string `json:\"savePath\"`\n\t} `json:\"download\"`\n\t\/\/License lib.LicenseData `json:\"license,omitempty\"`\n\tExtend echo.H `json:\"extend,omitempty\"`\n\n\t*Settings `json:\"-\"`\n\n\tconnectedDB bool\n}\n\nfunc (c *Config) IsEnv(env string) bool {\n\treturn c.Sys.IsEnv(env)\n}\n\nfunc (c *Config) IsEnvProd() bool {\n\treturn c.Sys.IsEnv(`prod`)\n}\n\nfunc (c *Config) IsEnvDev() bool {\n\treturn c.Sys.IsEnv(`dev`)\n}\n\nfunc (c *Config) GetMaxRequestBodySize() int {\n\tif c.MaxRequestBodySize > 0 {\n\t\treturn c.MaxRequestBodySize\n\t}\n\tif c.Sys.MaxRequestBodySize > 0 {\n\t\treturn c.Sys.MaxRequestBodySize\n\t}\n\treturn defaultMaxRequestBodyBytes\n}\n\n\/\/ ConnectedDB 数据库是否已连接，如果没有连接则自动连接\nfunc (c *Config) ConnectedDB(autoConn ...bool) bool {\n\tif c.connectedDB {\n\t\treturn c.connectedDB\n\t}\n\tn := len(autoConn)\n\tif n == 0 || (n > 0 && autoConn[0]) {\n\t\terr := c.connectDB()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\treturn c.connectedDB\n}\n\nfunc (c *Config) connectDB() error {\n\terr := ConnectDB(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.connectedDB = true\n\treturn nil\n}\n\nfunc (c *Config) APIKey() string {\n\treturn c.Settings.APIKey\n}\n\nfunc (c *Config) CookieConfig() scookie.Config {\n\treturn c.Cookie\n}\n\nfunc (c *Config) InitExtend() *Config {\n\tc.Extend = echo.H{}\n\textend.Range(func(key string, recv interface{}) {\n\t\tc.Extend[key] = recv\n\t})\n\treturn c\n}\n\nfunc (c *Config) ConfigFromDB() echo.H {\n\treturn c.Settings.GetConfig()\n}\n\nfunc (c *Config) SetDebug(on bool) *Config {\n\tc.Settings.SetDebug(on)\n\treturn c\n}\n\nfunc (c *Config) Codec(lengths ...int) codec.Codec {\n\tlength := 128\n\tif len(lengths) > 0 {\n\t\tlength = lengths[0]\n\t}\n\tif length == 256 {\n\t\treturn default256Codec\n\t}\n\treturn defaultCodec\n}\n\nvar (\n\tdefaultCodec    = codec.NewAesCrypto(`AES-128-CBC`)\n\tdefault256Codec = codec.NewAesCrypto(`AES-256-CBC`)\n)\n\nfunc (c *Config) Encode(raw string, keys ...string) string {\n\tvar key string\n\tif len(keys) > 0 && len(keys[0]) > 0 {\n\t\tkey = com.Md5(keys[0])\n\t} else {\n\t\tkey = c.Cookie.HashKey\n\t}\n\treturn c.Codec().Encode(raw, key)\n}\n\nfunc (c *Config) Decode(encrypted string, keys ...string) string {\n\tif len(encrypted) == 0 {\n\t\treturn ``\n\t}\n\tvar key string\n\tif len(keys) > 0 && len(keys[0]) > 0 {\n\t\tkey = com.Md5(keys[0])\n\t} else {\n\t\tkey = c.Cookie.HashKey\n\t}\n\treturn c.Codec().Decode(encrypted, key)\n}\n\nfunc (c *Config) InitSecretKey() *Config {\n\tc.Cookie.BlockKey = c.GenerateRandomKey()\n\tc.Cookie.HashKey = c.GenerateRandomKey()\n\treturn c\n}\n\nfunc (c *Config) GenerateRandomKey() string {\n\treturn com.Md5(string(securecookie.GenerateRandomKey(32)))\n}\n\nfunc (c *Config) Reload(newConfig *Config) error {\n\tengines := []string{}\n\tif !reflect.DeepEqual(newConfig.Caddy, c.Caddy) {\n\t\tengines = append(engines, `caddy`)\n\t}\n\tif !reflect.DeepEqual(newConfig.FTP, c.FTP) {\n\t\tengines = append(engines, `ftp`)\n\t}\n\tDefaultCLIConfig.Reload(engines...)\n\treturn nil\n}\n\nfunc (c *Config) AsDefault() {\n\techo.Set(`DefaultConfig`, c)\n\tDefaultConfig = c\n\tc.Settings.Init()\n}\n\nfunc (c *Config) SaveToFile() error {\n\tb, err := confl.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdir := filepath.Dir(DefaultCLIConfig.Conf)\n\terr = os.MkdirAll(dir, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/*\n\t\t_, e := os.Stat(DefaultCLIConfig.Conf + `.sample`)\n\t\tif os.IsNotExist(e) {\n\t\t\t\told, err := ioutil.ReadFile(DefaultCLIConfig.Conf)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = ioutil.WriteFile(DefaultCLIConfig.Conf+`.sample`, old, os.ModePerm)\n\t\t\t\t}\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\terr = ioutil.WriteFile(DefaultCLIConfig.Conf, b, os.ModePerm)\n\treturn err\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 config\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\n\t\"github.com\/webx-top\/codec\"\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/echo\"\n\t\"github.com\/webx-top\/echo\/middleware\/language\"\n\n\t\"github.com\/admpub\/confl\"\n\t\"github.com\/admpub\/log\"\n\t\"github.com\/admpub\/nging\/application\/library\/caddy\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/extend\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/scookie\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/scron\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/sdb\"\n\t\"github.com\/admpub\/nging\/application\/library\/config\/subconfig\/ssystem\"\n\t\"github.com\/admpub\/nging\/application\/library\/ftp\"\n\t\"github.com\/admpub\/securecookie\"\n)\n\nfunc NewConfig() *Config {\n\tc := &Config{}\n\tc.InitExtend()\n\tc.Settings = NewSettings(c)\n\treturn c\n}\n\ntype Config struct {\n\tDB       sdb.DB          `json:\"db\"`\n\tSys      ssystem.System  `json:\"sys\"`\n\tCron     scron.Cron      `json:\"cron\"`\n\tCookie   scookie.Config  `json:\"cookie\"`\n\tCaddy    caddy.Config    `json:\"caddy\"`\n\tFTP      ftp.Config      `json:\"ftp\"`\n\tLanguage language.Config `json:\"language\"`\n\tDownload struct {\n\t\tSavePath string `json:\"savePath\"`\n\t} `json:\"download\"`\n\t\/\/License lib.LicenseData `json:\"license,omitempty\"`\n\tExtend    echo.H `json:\"extend,omitempty\"`\n\t*Settings `json:\"-\"`\n\n\tconnectedDB bool\n}\n\nfunc (c *Config) IsEnv(env string) bool {\n\treturn c.Sys.IsEnv(env)\n}\n\nfunc (c *Config) IsEnvProd() bool {\n\treturn c.Sys.IsEnv(`prod`)\n}\n\nfunc (c *Config) IsEnvDev() bool {\n\treturn c.Sys.IsEnv(`dev`)\n}\n\nfunc (c *Config) GetMaxRequestBodySize() int {\n\tif c.MaxRequestBodySize > 0 {\n\t\treturn c.MaxRequestBodySize\n\t}\n\tif c.Sys.MaxRequestBodySize > 0 {\n\t\treturn c.Sys.MaxRequestBodySize\n\t}\n\treturn defaultMaxRequestBodyBytes\n}\n\n\/\/ ConnectedDB 数据库是否已连接，如果没有连接则自动连接\nfunc (c *Config) ConnectedDB(autoConn ...bool) bool {\n\tif c.connectedDB {\n\t\treturn c.connectedDB\n\t}\n\tn := len(autoConn)\n\tif n == 0 || (n > 0 && autoConn[0]) {\n\t\terr := c.connectDB()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\treturn c.connectedDB\n}\n\nfunc (c *Config) connectDB() error {\n\terr := ConnectDB(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.connectedDB = true\n\treturn nil\n}\n\nfunc (c *Config) APIKey() string {\n\treturn c.Settings.APIKey\n}\n\nfunc (c *Config) CookieConfig() scookie.Config {\n\treturn c.Cookie\n}\n\nfunc (c *Config) InitExtend() *Config {\n\tc.Extend = echo.H{}\n\textend.Range(func(key string, recv interface{}) {\n\t\tc.Extend[key] = recv\n\t})\n\treturn c\n}\n\nfunc (c *Config) ConfigFromDB() echo.H {\n\treturn c.Settings.GetConfig()\n}\n\nfunc (c *Config) SetDebug(on bool) *Config {\n\tc.Settings.SetDebug(on)\n\treturn c\n}\n\nfunc (c *Config) Codec(lengths ...int) codec.Codec {\n\tlength := 128\n\tif len(lengths) > 0 {\n\t\tlength = lengths[0]\n\t}\n\tif length == 256 {\n\t\treturn default256Codec\n\t}\n\treturn defaultCodec\n}\n\nvar (\n\tdefaultCodec    = codec.NewAesCrypto(`AES-128-CBC`)\n\tdefault256Codec = codec.NewAesCrypto(`AES-256-CBC`)\n)\n\nfunc (c *Config) Encode(raw string, keys ...string) string {\n\tvar key string\n\tif len(keys) > 0 && len(keys[0]) > 0 {\n\t\tkey = com.Md5(keys[0])\n\t} else {\n\t\tkey = c.Cookie.HashKey\n\t}\n\treturn c.Codec().Encode(raw, key)\n}\n\nfunc (c *Config) Decode(encrypted string, keys ...string) string {\n\tif len(encrypted) == 0 {\n\t\treturn ``\n\t}\n\tvar key string\n\tif len(keys) > 0 && len(keys[0]) > 0 {\n\t\tkey = com.Md5(keys[0])\n\t} else {\n\t\tkey = c.Cookie.HashKey\n\t}\n\treturn c.Codec().Decode(encrypted, key)\n}\n\nfunc (c *Config) InitSecretKey() *Config {\n\tc.Cookie.BlockKey = c.GenerateRandomKey()\n\tc.Cookie.HashKey = c.GenerateRandomKey()\n\treturn c\n}\n\nfunc (c *Config) GenerateRandomKey() string {\n\treturn com.Md5(string(securecookie.GenerateRandomKey(32)))\n}\n\nfunc (c *Config) Reload(newConfig *Config) error {\n\tengines := []string{}\n\tif !reflect.DeepEqual(newConfig.Caddy, c.Caddy) {\n\t\tengines = append(engines, `caddy`)\n\t}\n\tif !reflect.DeepEqual(newConfig.FTP, c.FTP) {\n\t\tengines = append(engines, `ftp`)\n\t}\n\tDefaultCLIConfig.Reload(engines...)\n\treturn nil\n}\n\nfunc (c *Config) AsDefault() {\n\techo.Set(`DefaultConfig`, c)\n\tDefaultConfig = c\n\tc.Settings.Init()\n}\n\nfunc (c *Config) SaveToFile() error {\n\tb, err := confl.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdir := filepath.Dir(DefaultCLIConfig.Conf)\n\terr = os.MkdirAll(dir, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/*\n\t\t_, e := os.Stat(DefaultCLIConfig.Conf + `.sample`)\n\t\tif os.IsNotExist(e) {\n\t\t\t\told, err := ioutil.ReadFile(DefaultCLIConfig.Conf)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = ioutil.WriteFile(DefaultCLIConfig.Conf+`.sample`, old, os.ModePerm)\n\t\t\t\t}\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\terr = ioutil.WriteFile(DefaultCLIConfig.Conf, b, os.ModePerm)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package passwordreset\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestLogin      = \"test user\"\n\ttestPwdVal     = []byte(\"test password value\")\n\ttestSecret     = []byte(\"secret key\")\n\ttestLoginError = errors.New(\"test unknown login error\")\n)\n\nfunc getPwdVal(login string) ([]byte, error) {\n\tif login == testLogin {\n\t\treturn testPwdVal, nil\n\t}\n\treturn testPwdVal, testLoginError\n\t\/\/     ^ return it anyway to test that it's not begin used\n}\n\nfunc TestNew(t *testing.T) {\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewToken(testLogin, 100*time.Second, pwdVal, testSecret)\n\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error %q\", err)\n\t}\n\tif login != testLogin {\n\t\tt.Errorf(\"login: expected %q, got %q\", testLogin, login)\n\t}\n}\n\nfunc TestNewNoPadding(t *testing.T) {\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewTokenNoPadding(testLogin, 100*time.Second, pwdVal, testSecret)\n\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error %q\", err)\n\t}\n\tif login != testLogin {\n\t\tt.Errorf(\"login: expected %q, got %q\", testLogin, login)\n\t}\n}\n\nfunc TestVerify(t *testing.T) {\n\tbad := []string{\n\t\t\"\",\n\t\t\"bad token\",\n\t\t\"Talo3mRjaGVzdITUAGOXYZwCMq7EtHfYH4ILcBgKaoWXDHTJOIlBUfcr\",\n\t}\n\tfor i, token := range bad {\n\t\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\t\tif login != \"\" {\n\t\t\tt.Errorf(`%d: login for bad token: expected \"\", got %q`, i, login)\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Errorf(\"%d: expected error\", i)\n\t\t}\n\t}\n\t\/\/ Test expiration\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewToken(testLogin, -1, pwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err == nil {\n\t\tt.Errorf(\"verified expired token\")\n\t}\n\t\/\/ Test wrong password value\n\tpwdVal = []byte(\"wrong value\")\n\ttoken = NewToken(testLogin, -1, pwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err == nil {\n\t\tt.Errorf(\"verified with wrong password value\")\n\t}\n\t\/\/ Test password value error return\n\tlogin := \"unknown login\"\n\t_, errVal := getPwdVal(login)\n\ttoken = NewToken(login, 100*time.Second, testPwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err != errVal {\n\t\tt.Errorf(\"err: expected %q, got %q\", errVal, err)\n\t}\n}\n<commit_msg>padded token for test<commit_after>package passwordreset\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestLogin      = \"test user\"\n\ttestPwdVal     = []byte(\"test password value\")\n\ttestSecret     = []byte(\"secret key\")\n\ttestLoginError = errors.New(\"test unknown login error\")\n)\n\nfunc getPwdVal(login string) ([]byte, error) {\n\tif login == testLogin {\n\t\treturn testPwdVal, nil\n\t}\n\treturn testPwdVal, testLoginError\n\t\/\/     ^ return it anyway to test that it's not begin used\n}\n\nfunc TestNew(t *testing.T) {\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewToken(testLogin, 100*time.Second, pwdVal, testSecret)\n\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error %q\", err)\n\t}\n\tif login != testLogin {\n\t\tt.Errorf(\"login: expected %q, got %q\", testLogin, login)\n\t}\n}\n\nfunc TestNewNoPadding(t *testing.T) {\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewTokenNoPadding(testLogin, 100*time.Second, pwdVal, testSecret)\n\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error %q\", err)\n\t}\n\tif login != testLogin {\n\t\tt.Errorf(\"login: expected %q, got %q\", testLogin, login)\n\t}\n}\n\nfunc TestVerify(t *testing.T) {\n\tbad := []string{\n\t\t\"\",\n\t\t\"bad token\",\n\t\t\"Talo3mRjaGVzdITUAGOXYZwCMq7EtHfYH4ILcBgKaoWXDHTJOIlBUfcr\",\n\t\t\"Talo3mRjaGVzdITUAGOXYZwCMq7EtHfYH4ILcBgKaoWXDHTJOIlBUfcr=\",\n\t}\n\tfor i, token := range bad {\n\t\tlogin, err := VerifyToken(token, getPwdVal, testSecret)\n\t\tif login != \"\" {\n\t\t\tt.Errorf(`%d: login for bad token: expected \"\", got %q`, i, login)\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Errorf(\"%d: expected error\", i)\n\t\t}\n\t}\n\t\/\/ Test expiration\n\tpwdVal, _ := getPwdVal(testLogin)\n\ttoken := NewToken(testLogin, -1, pwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err == nil {\n\t\tt.Errorf(\"verified expired token\")\n\t}\n\t\/\/ Test wrong password value\n\tpwdVal = []byte(\"wrong value\")\n\ttoken = NewToken(testLogin, -1, pwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err == nil {\n\t\tt.Errorf(\"verified with wrong password value\")\n\t}\n\t\/\/ Test password value error return\n\tlogin := \"unknown login\"\n\t_, errVal := getPwdVal(login)\n\ttoken = NewToken(login, 100*time.Second, testPwdVal, testSecret)\n\tif _, err := VerifyToken(token, getPwdVal, testSecret); err != errVal {\n\t\tt.Errorf(\"err: expected %q, got %q\", errVal, err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\tlog \"github.com\/GameGophers\/nsq-logger\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"golang.org\/x\/net\/context\"\n\t\"os\"\n\t\"os\/signal\"\n\tpb \"proto\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\tSERVICE = \"[RANK]\"\n)\n\nconst (\n\tBOLTDB_FILE    = \"\/data\/RANK-DUMP.DAT\"\n\tBOLTDB_BUCKET  = \"RANKING\"\n\tCHANGES_SIZE   = 65536\n\tCHECK_INTERVAL = 10 * time.Second \/\/ if ranking has changed, how long to check\n)\n\nvar (\n\tERROR_NAME_NOT_EXISTS = errors.New(\"name not exists\")\n)\n\ntype server struct {\n\tranks   map[string]*RankSet\n\tpending chan string\n\tsync.RWMutex\n}\n\nfunc (s *server) init() {\n\ts.ranks = make(map[string]*RankSet)\n\ts.pending = make(chan string, CHANGES_SIZE)\n\ts.restore()\n\tgo s.persistence_task()\n}\n\nfunc (s *server) lock_read(f func()) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tf()\n}\n\nfunc (s *server) lock_write(f func()) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tf()\n}\n\nfunc (s *server) RankChange(ctx context.Context, in *pb.Ranking_Change) (*pb.Ranking_NullResult, error) {\n\t\/\/ check name existence\n\tvar rs *RankSet\n\ts.lock_write(func() {\n\t\trs = s.ranks[in.Name]\n\t\tif rs == nil {\n\t\t\trs = &RankSet{}\n\t\t\trs.init()\n\t\t\ts.ranks[in.Name] = rs\n\t\t}\n\t})\n\n\t\/\/ apply update one the rankset\n\trs.Update(in.UserId, in.Score)\n\ts.pending <- in.Name\n\treturn &pb.Ranking_NullResult{}, nil\n}\n\nfunc (s *server) QueryRankRange(ctx context.Context, in *pb.Ranking_Range) (*pb.Ranking_RankList, error) {\n\tvar rs *RankSet\n\ts.lock_read(func() {\n\t\trs = s.ranks[in.Name]\n\t})\n\n\tif rs == nil {\n\t\treturn nil, ERROR_NAME_NOT_EXISTS\n\t}\n\n\tids, cups := rs.GetList(int(in.StartNo), int(in.EndNo))\n\treturn &pb.Ranking_RankList{UserIds: ids, Scores: cups}, nil\n}\n\nfunc (s *server) QueryUsers(ctx context.Context, in *pb.Ranking_Users) (*pb.Ranking_UserList, error) {\n\tvar rs *RankSet\n\ts.lock_read(func() {\n\t\trs = s.ranks[in.Name]\n\t})\n\n\tif rs == nil {\n\t\treturn nil, ERROR_NAME_NOT_EXISTS\n\t}\n\n\tranks := make([]int32, 0, len(in.UserIds))\n\tscores := make([]int32, 0, len(in.UserIds))\n\tfor _, id := range in.UserIds {\n\t\trank, score := rs.Rank(id)\n\t\tranks = append(ranks, rank)\n\t\tscores = append(scores, score)\n\t}\n\treturn &pb.Ranking_UserList{Ranks: ranks, Scores: scores}, nil\n}\n\n\/\/ persistence ranking tree into db\nfunc (s *server) persistence_task() {\n\ttimer := time.After(CHECK_INTERVAL)\n\tdb := s.open_db()\n\tchanges := make(map[string]bool)\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, syscall.SIGTERM)\n\n\tfor {\n\t\tselect {\n\t\tcase key := <-s.pending:\n\t\t\tchanges[key] = true\n\t\tcase <-timer:\n\t\t\ts.dump_changes(db, changes)\n\t\t\tlog.Infof(\"perisisted %v trees:\", len(changes))\n\t\t\tchanges = make(map[string]bool)\n\t\t\ttimer = time.After(CHECK_INTERVAL)\n\t\tcase <-sig:\n\t\t\ts.dump_changes(db, changes)\n\t\t\tdb.Close()\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}\n\nfunc (s *server) dump_changes(db *bolt.DB, changes map[string]bool) {\n\tfor k := range changes {\n\t\t\/\/ marshal\n\t\tvar rs *RankSet\n\t\ts.lock_read(func() {\n\t\t\trs = s.ranks[k]\n\t\t})\n\t\tif rs == nil {\n\t\t\tlog.Error(\"empty rankset:\", k)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ serialization and save\n\t\tbin, err := rs.Marshal()\n\t\tif err != nil {\n\t\t\tlog.Critical(\"cannot marshal:\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\n\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket([]byte(BOLTDB_BUCKET))\n\t\t\terr := b.Put([]byte(k), bin)\n\t\t\treturn err\n\t\t})\n\t}\n}\n\nfunc (s *server) open_db() *bolt.DB {\n\tdb, err := bolt.Open(BOLTDB_FILE, 0600, nil)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\tos.Exit(-1)\n\t}\n\t\/\/ create bulket\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET))\n\t\tif err != nil {\n\t\t\tlog.Criticalf(\"create bucket: %s\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\t\treturn nil\n\t})\n\treturn db\n}\n\nfunc (s *server) restore() {\n\t\/\/ restore data from db file\n\tdb := s.open_db()\n\tdefer db.Close()\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BOLTDB_BUCKET))\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\trs := &RankSet{}\n\t\t\trs.init()\n\t\t\terr := rs.Unmarshal(v)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(\"rank data corrupted:\", err)\n\t\t\t\tos.Exit(-1)\n\t\t\t}\n\t\t\ts.ranks[string(k)] = rs\n\t\t}\n\n\t\treturn nil\n\t})\n}\n<commit_msg>catch sigint<commit_after>package main\n\nimport (\n\t\"errors\"\n\tlog \"github.com\/GameGophers\/nsq-logger\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"golang.org\/x\/net\/context\"\n\t\"os\"\n\t\"os\/signal\"\n\tpb \"proto\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\tSERVICE = \"[RANK]\"\n)\n\nconst (\n\tBOLTDB_FILE    = \"\/data\/RANK-DUMP.DAT\"\n\tBOLTDB_BUCKET  = \"RANKING\"\n\tCHANGES_SIZE   = 65536\n\tCHECK_INTERVAL = 10 * time.Second \/\/ if ranking has changed, how long to check\n)\n\nvar (\n\tERROR_NAME_NOT_EXISTS = errors.New(\"name not exists\")\n)\n\ntype server struct {\n\tranks   map[string]*RankSet\n\tpending chan string\n\tsync.RWMutex\n}\n\nfunc (s *server) init() {\n\ts.ranks = make(map[string]*RankSet)\n\ts.pending = make(chan string, CHANGES_SIZE)\n\ts.restore()\n\tgo s.persistence_task()\n}\n\nfunc (s *server) lock_read(f func()) {\n\ts.RLock()\n\tdefer s.RUnlock()\n\tf()\n}\n\nfunc (s *server) lock_write(f func()) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tf()\n}\n\nfunc (s *server) RankChange(ctx context.Context, in *pb.Ranking_Change) (*pb.Ranking_NullResult, error) {\n\t\/\/ check name existence\n\tvar rs *RankSet\n\ts.lock_write(func() {\n\t\trs = s.ranks[in.Name]\n\t\tif rs == nil {\n\t\t\trs = &RankSet{}\n\t\t\trs.init()\n\t\t\ts.ranks[in.Name] = rs\n\t\t}\n\t})\n\n\t\/\/ apply update one the rankset\n\trs.Update(in.UserId, in.Score)\n\ts.pending <- in.Name\n\treturn &pb.Ranking_NullResult{}, nil\n}\n\nfunc (s *server) QueryRankRange(ctx context.Context, in *pb.Ranking_Range) (*pb.Ranking_RankList, error) {\n\tvar rs *RankSet\n\ts.lock_read(func() {\n\t\trs = s.ranks[in.Name]\n\t})\n\n\tif rs == nil {\n\t\treturn nil, ERROR_NAME_NOT_EXISTS\n\t}\n\n\tids, cups := rs.GetList(int(in.StartNo), int(in.EndNo))\n\treturn &pb.Ranking_RankList{UserIds: ids, Scores: cups}, nil\n}\n\nfunc (s *server) QueryUsers(ctx context.Context, in *pb.Ranking_Users) (*pb.Ranking_UserList, error) {\n\tvar rs *RankSet\n\ts.lock_read(func() {\n\t\trs = s.ranks[in.Name]\n\t})\n\n\tif rs == nil {\n\t\treturn nil, ERROR_NAME_NOT_EXISTS\n\t}\n\n\tranks := make([]int32, 0, len(in.UserIds))\n\tscores := make([]int32, 0, len(in.UserIds))\n\tfor _, id := range in.UserIds {\n\t\trank, score := rs.Rank(id)\n\t\tranks = append(ranks, rank)\n\t\tscores = append(scores, score)\n\t}\n\treturn &pb.Ranking_UserList{Ranks: ranks, Scores: scores}, nil\n}\n\n\/\/ persistence ranking tree into db\nfunc (s *server) persistence_task() {\n\ttimer := time.After(CHECK_INTERVAL)\n\tdb := s.open_db()\n\tchanges := make(map[string]bool)\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)\n\n\tfor {\n\t\tselect {\n\t\tcase key := <-s.pending:\n\t\t\tchanges[key] = true\n\t\tcase <-timer:\n\t\t\ts.dump_changes(db, changes)\n\t\t\tlog.Infof(\"perisisted %v trees:\", len(changes))\n\t\t\tchanges = make(map[string]bool)\n\t\t\ttimer = time.After(CHECK_INTERVAL)\n\t\tcase <-sig:\n\t\t\ts.dump_changes(db, changes)\n\t\t\tdb.Close()\n\t\t\tlog.Info(\"SIGTERM\")\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}\n\nfunc (s *server) dump_changes(db *bolt.DB, changes map[string]bool) {\n\tfor k := range changes {\n\t\t\/\/ marshal\n\t\tvar rs *RankSet\n\t\ts.lock_read(func() {\n\t\t\trs = s.ranks[k]\n\t\t})\n\t\tif rs == nil {\n\t\t\tlog.Error(\"empty rankset:\", k)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ serialization and save\n\t\tbin, err := rs.Marshal()\n\t\tif err != nil {\n\t\t\tlog.Critical(\"cannot marshal:\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\n\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\tb := tx.Bucket([]byte(BOLTDB_BUCKET))\n\t\t\terr := b.Put([]byte(k), bin)\n\t\t\treturn err\n\t\t})\n\t}\n}\n\nfunc (s *server) open_db() *bolt.DB {\n\tdb, err := bolt.Open(BOLTDB_FILE, 0600, nil)\n\tif err != nil {\n\t\tlog.Critical(err)\n\t\tos.Exit(-1)\n\t}\n\t\/\/ create bulket\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET))\n\t\tif err != nil {\n\t\t\tlog.Criticalf(\"create bucket: %s\", err)\n\t\t\tos.Exit(-1)\n\t\t}\n\t\treturn nil\n\t})\n\treturn db\n}\n\nfunc (s *server) restore() {\n\t\/\/ restore data from db file\n\tdb := s.open_db()\n\tdefer db.Close()\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(BOLTDB_BUCKET))\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\trs := &RankSet{}\n\t\t\trs.init()\n\t\t\terr := rs.Unmarshal(v)\n\t\t\tif err != nil {\n\t\t\t\tlog.Critical(\"rank data corrupted:\", err)\n\t\t\t\tos.Exit(-1)\n\t\t\t}\n\t\t\ts.ranks[string(k)] = rs\n\t\t}\n\n\t\treturn nil\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 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\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text\/tabwriter\"\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\/keybase1\"\n)\n\ntype CmdTeamListMemberships struct {\n\tlibkb.Contextified\n\tteam                 string\n\tjson                 bool\n\tforcePoll            bool\n\tuserAssertion        string\n\tincludeImplicitTeams bool\n\tshowAll              bool\n\tverbose              bool\n\ttabw                 *tabwriter.Writer\n}\n\nfunc (c *CmdTeamListMemberships) SetTeam(s string) {\n\tc.team = s\n}\n\nfunc (c *CmdTeamListMemberships) SetJSON(b bool) {\n\tc.json = b\n}\n\nfunc (c *CmdTeamListMemberships) SetForcePoll(b bool) {\n\tc.forcePoll = b\n}\n\nfunc NewCmdTeamListMembershipsRunner(g *libkb.GlobalContext) *CmdTeamListMemberships {\n\treturn &CmdTeamListMemberships{Contextified: libkb.NewContextified(g)}\n}\n\nfunc newCmdTeamListMemberships(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\tflags := []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"j, json\",\n\t\t\tUsage: \"Output memberships as JSON\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"force-poll\",\n\t\t\tUsage: \"Force a poll of the server for all identities\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"u, user\",\n\t\t\tUsage: \"List memberships for a user assertion\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"include-subteams\",\n\t\t\tUsage: \"Include any subteam memberships as well\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"all\",\n\t\t\tUsage: \"Show all members of all teams you belong to\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"v, verbose\",\n\t\t\tUsage: \"Include more verbose output\",\n\t\t},\n\t}\n\tif develUsage {\n\t\tflags = append(flags, cli.BoolFlag{\n\t\t\tName:  \"include-implicit-teams\",\n\t\t\tUsage: \"[devel only] Include automatic teams that are not normally visible\",\n\t\t})\n\t}\n\treturn cli.Command{\n\t\tName:         \"list-memberships\",\n\t\tArgumentHelp: \"[team name] [--user=username]\",\n\t\tAliases:      []string{\"list-members\"},\n\t\tUsage:        \"List your teams, or people on a team.\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcmd := NewCmdTeamListMembershipsRunner(g)\n\t\t\tcl.ChooseCommand(cmd, \"list-memberships\", c)\n\t\t},\n\t\tFlags: flags,\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) > 1 {\n\t\treturn errors.New(\"at most one team name argument allowed, multiple found\")\n\t}\n\tif len(ctx.Args()) > 0 {\n\t\tc.team = ctx.Args()[0]\n\t}\n\tc.userAssertion = ctx.String(\"user\")\n\tc.includeImplicitTeams = ctx.Bool(\"include-implicit-teams\")\n\tc.showAll = ctx.Bool(\"all\")\n\n\tif c.showAll {\n\t\tif c.team != \"\" {\n\t\t\treturn errors.New(\"cannot specify a team and --all, please choose one\")\n\t\t}\n\t\tif c.userAssertion != \"\" {\n\t\t\treturn errors.New(\"cannot specify a user and --all, please choose one\")\n\t\t}\n\t}\n\n\tc.json = ctx.Bool(\"json\")\n\tc.forcePoll = ctx.Bool(\"force-poll\")\n\tc.verbose = ctx.Bool(\"verbose\")\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) Run() error {\n\tcli, err := GetTeamsClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.team != \"\" {\n\t\treturn c.runGet(cli)\n\t}\n\n\treturn c.runUser(cli)\n}\n\nfunc (c *CmdTeamListMemberships) runGet(cli keybase1.TeamsClient) error {\n\tdetails, err := cli.TeamGet(context.Background(), keybase1.TeamGetArg{Name: c.team, ForceRepoll: c.forcePoll})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.output(details)\n}\n\nfunc (c *CmdTeamListMemberships) runUser(cli keybase1.TeamsClient) error {\n\targ := keybase1.TeamListArg{\n\t\tUserAssertion:        c.userAssertion,\n\t\tAll:                  c.showAll,\n\t\tIncludeImplicitTeams: c.includeImplicitTeams,\n\t}\n\tlist, err := cli.TeamList(context.Background(), arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.json {\n\t\tb, err := json.MarshalIndent(list, \"\", \"    \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdui := c.G().UI.GetDumbOutputUI()\n\t\t_, err = dui.Printf(string(b) + \"\\n\")\n\t\treturn err\n\t}\n\n\tdui := c.G().UI.GetTerminalUI()\n\tc.tabw = new(tabwriter.Writer)\n\tc.tabw.Init(dui.OutputWriter(), 0, 8, 4, ' ', 0)\n\n\t\/\/ Only print the username and full name columns when we're showing other users.\n\tif c.showAll {\n\t\tfmt.Fprintf(c.tabw, \"Team\\tRole\\tUsername\\tFull name\\n\")\n\t} else {\n\t\tfmt.Fprintf(c.tabw, \"Team\\tRole\\n\")\n\t}\n\tfor _, t := range list.Teams {\n\t\tvar role string\n\t\tif t.Implicit != nil {\n\t\t\trole += \"implied admin\"\n\t\t}\n\t\tif t.Role != keybase1.TeamRole_NONE {\n\t\t\tif t.Implicit != nil {\n\t\t\t\trole += \", \"\n\t\t\t}\n\t\t\trole += strings.ToLower(t.Role.String())\n\t\t}\n\t\tif c.showAll {\n\t\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\t%s\\t%s\\n\", t.FqName, role, t.Username, t.FullName)\n\t\t} else {\n\t\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\n\", t.FqName, role)\n\t\t}\n\t}\n\tif c.showAll {\n\t\tc.outputInvites(list.AnnotatedActiveInvites)\n\t}\n\n\tc.tabw.Flush()\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) output(details keybase1.TeamDetails) error {\n\tif c.json {\n\t\treturn c.outputJSON(details)\n\t}\n\n\treturn c.outputTerminal(details)\n}\n\nfunc (c *CmdTeamListMemberships) outputJSON(details keybase1.TeamDetails) error {\n\tb, err := json.MarshalIndent(details, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdui := c.G().UI.GetDumbOutputUI()\n\t_, err = dui.Printf(string(b) + \"\\n\")\n\treturn err\n}\n\nfunc (c *CmdTeamListMemberships) outputTerminal(details keybase1.TeamDetails) error {\n\tdui := c.G().UI.GetTerminalUI()\n\tc.tabw = new(tabwriter.Writer)\n\tc.tabw.Init(dui.OutputWriter(), 0, 8, 2, ' ', 0)\n\n\tc.outputRole(\"owner\", details.Members.Owners)\n\tc.outputRole(\"admin\", details.Members.Admins)\n\tc.outputRole(\"writer\", details.Members.Writers)\n\tc.outputRole(\"reader\", details.Members.Readers)\n\tc.outputInvites(details.AnnotatedActiveInvites)\n\tc.tabw.Flush()\n\n\tif c.verbose {\n\t\tdui.Printf(\"At team key generation: %d\\n\", details.KeyGeneration)\n\t}\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) outputRole(role string, members []keybase1.TeamMemberDetails) {\n\tfor _, member := range members {\n\t\tvar reset string\n\t\tif !member.Active {\n\t\t\treset = \" (inactive due to account reset)\"\n\t\t}\n\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\t%s%s\\n\", c.team, role, member.Username, reset)\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) outputInvites(invites map[keybase1.TeamInviteID]keybase1.AnnotatedTeamInvite) {\n\tfor _, invite := range invites {\n\t\tfmtstring := \"%s\\t%s*\\t%s\\t(* added by %s; awaiting acceptance)\\n\"\n\t\tfmt.Fprintf(c.tabw, fmtstring, invite.TeamName, strings.ToLower(invite.Role.String()), invite.Name, invite.InviterUsername)\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) 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>format invites in list-members with social service (#8994)<commit_after>\/\/ Copyright 2017 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\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"text\/tabwriter\"\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\/keybase1\"\n)\n\ntype CmdTeamListMemberships struct {\n\tlibkb.Contextified\n\tteam                 string\n\tjson                 bool\n\tforcePoll            bool\n\tuserAssertion        string\n\tincludeImplicitTeams bool\n\tshowAll              bool\n\tverbose              bool\n\ttabw                 *tabwriter.Writer\n}\n\nfunc (c *CmdTeamListMemberships) SetTeam(s string) {\n\tc.team = s\n}\n\nfunc (c *CmdTeamListMemberships) SetJSON(b bool) {\n\tc.json = b\n}\n\nfunc (c *CmdTeamListMemberships) SetForcePoll(b bool) {\n\tc.forcePoll = b\n}\n\nfunc NewCmdTeamListMembershipsRunner(g *libkb.GlobalContext) *CmdTeamListMemberships {\n\treturn &CmdTeamListMemberships{Contextified: libkb.NewContextified(g)}\n}\n\nfunc newCmdTeamListMemberships(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\tflags := []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"j, json\",\n\t\t\tUsage: \"Output memberships as JSON\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"force-poll\",\n\t\t\tUsage: \"Force a poll of the server for all identities\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"u, user\",\n\t\t\tUsage: \"List memberships for a user assertion\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"include-subteams\",\n\t\t\tUsage: \"Include any subteam memberships as well\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"all\",\n\t\t\tUsage: \"Show all members of all teams you belong to\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"v, verbose\",\n\t\t\tUsage: \"Include more verbose output\",\n\t\t},\n\t}\n\tif develUsage {\n\t\tflags = append(flags, cli.BoolFlag{\n\t\t\tName:  \"include-implicit-teams\",\n\t\t\tUsage: \"[devel only] Include automatic teams that are not normally visible\",\n\t\t})\n\t}\n\treturn cli.Command{\n\t\tName:         \"list-memberships\",\n\t\tArgumentHelp: \"[team name] [--user=username]\",\n\t\tAliases:      []string{\"list-members\"},\n\t\tUsage:        \"List your teams, or people on a team.\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcmd := NewCmdTeamListMembershipsRunner(g)\n\t\t\tcl.ChooseCommand(cmd, \"list-memberships\", c)\n\t\t},\n\t\tFlags: flags,\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) > 1 {\n\t\treturn errors.New(\"at most one team name argument allowed, multiple found\")\n\t}\n\tif len(ctx.Args()) > 0 {\n\t\tc.team = ctx.Args()[0]\n\t}\n\tc.userAssertion = ctx.String(\"user\")\n\tc.includeImplicitTeams = ctx.Bool(\"include-implicit-teams\")\n\tc.showAll = ctx.Bool(\"all\")\n\n\tif c.showAll {\n\t\tif c.team != \"\" {\n\t\t\treturn errors.New(\"cannot specify a team and --all, please choose one\")\n\t\t}\n\t\tif c.userAssertion != \"\" {\n\t\t\treturn errors.New(\"cannot specify a user and --all, please choose one\")\n\t\t}\n\t}\n\n\tc.json = ctx.Bool(\"json\")\n\tc.forcePoll = ctx.Bool(\"force-poll\")\n\tc.verbose = ctx.Bool(\"verbose\")\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) Run() error {\n\tcli, err := GetTeamsClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.team != \"\" {\n\t\treturn c.runGet(cli)\n\t}\n\n\treturn c.runUser(cli)\n}\n\nfunc (c *CmdTeamListMemberships) runGet(cli keybase1.TeamsClient) error {\n\tdetails, err := cli.TeamGet(context.Background(), keybase1.TeamGetArg{Name: c.team, ForceRepoll: c.forcePoll})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.output(details)\n}\n\nfunc (c *CmdTeamListMemberships) runUser(cli keybase1.TeamsClient) error {\n\targ := keybase1.TeamListArg{\n\t\tUserAssertion:        c.userAssertion,\n\t\tAll:                  c.showAll,\n\t\tIncludeImplicitTeams: c.includeImplicitTeams,\n\t}\n\tlist, err := cli.TeamList(context.Background(), arg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.json {\n\t\tb, err := json.MarshalIndent(list, \"\", \"    \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdui := c.G().UI.GetDumbOutputUI()\n\t\t_, err = dui.Printf(string(b) + \"\\n\")\n\t\treturn err\n\t}\n\n\tdui := c.G().UI.GetTerminalUI()\n\tc.tabw = new(tabwriter.Writer)\n\tc.tabw.Init(dui.OutputWriter(), 0, 8, 4, ' ', 0)\n\n\t\/\/ Only print the username and full name columns when we're showing other users.\n\tif c.showAll {\n\t\tfmt.Fprintf(c.tabw, \"Team\\tRole\\tUsername\\tFull name\\n\")\n\t} else {\n\t\tfmt.Fprintf(c.tabw, \"Team\\tRole\\n\")\n\t}\n\tfor _, t := range list.Teams {\n\t\tvar role string\n\t\tif t.Implicit != nil {\n\t\t\trole += \"implied admin\"\n\t\t}\n\t\tif t.Role != keybase1.TeamRole_NONE {\n\t\t\tif t.Implicit != nil {\n\t\t\t\trole += \", \"\n\t\t\t}\n\t\t\trole += strings.ToLower(t.Role.String())\n\t\t}\n\t\tif c.showAll {\n\t\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\t%s\\t%s\\n\", t.FqName, role, t.Username, t.FullName)\n\t\t} else {\n\t\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\n\", t.FqName, role)\n\t\t}\n\t}\n\tif c.showAll {\n\t\tc.outputInvites(list.AnnotatedActiveInvites)\n\t}\n\n\tc.tabw.Flush()\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) output(details keybase1.TeamDetails) error {\n\tif c.json {\n\t\treturn c.outputJSON(details)\n\t}\n\n\treturn c.outputTerminal(details)\n}\n\nfunc (c *CmdTeamListMemberships) outputJSON(details keybase1.TeamDetails) error {\n\tb, err := json.MarshalIndent(details, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdui := c.G().UI.GetDumbOutputUI()\n\t_, err = dui.Printf(string(b) + \"\\n\")\n\treturn err\n}\n\nfunc (c *CmdTeamListMemberships) outputTerminal(details keybase1.TeamDetails) error {\n\tdui := c.G().UI.GetTerminalUI()\n\tc.tabw = new(tabwriter.Writer)\n\tc.tabw.Init(dui.OutputWriter(), 0, 8, 2, ' ', 0)\n\n\tc.outputRole(\"owner\", details.Members.Owners)\n\tc.outputRole(\"admin\", details.Members.Admins)\n\tc.outputRole(\"writer\", details.Members.Writers)\n\tc.outputRole(\"reader\", details.Members.Readers)\n\tc.outputInvites(details.AnnotatedActiveInvites)\n\tc.tabw.Flush()\n\n\tif c.verbose {\n\t\tdui.Printf(\"At team key generation: %d\\n\", details.KeyGeneration)\n\t}\n\n\treturn nil\n}\n\nfunc (c *CmdTeamListMemberships) outputRole(role string, members []keybase1.TeamMemberDetails) {\n\tfor _, member := range members {\n\t\tvar reset string\n\t\tif !member.Active {\n\t\t\treset = \" (inactive due to account reset)\"\n\t\t}\n\t\tfmt.Fprintf(c.tabw, \"%s\\t%s\\t%s%s\\n\", c.team, role, member.Username, reset)\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) formatInviteName(invite keybase1.AnnotatedTeamInvite) (res string) {\n\tres = string(invite.Name)\n\tcategory, err := invite.Type.C()\n\tif err == nil {\n\t\tswitch category {\n\t\tcase keybase1.TeamInviteCategory_SBS:\n\t\t\tres = fmt.Sprintf(\"%s@%s\", invite.Name, string(invite.Type.Sbs()))\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (c *CmdTeamListMemberships) outputInvites(invites map[keybase1.TeamInviteID]keybase1.AnnotatedTeamInvite) {\n\tfor _, invite := range invites {\n\t\tfmtstring := \"%s\\t%s*\\t%s\\t(* added by %s; awaiting acceptance)\\n\"\n\t\tfmt.Fprintf(c.tabw, fmtstring, invite.TeamName, strings.ToLower(invite.Role.String()),\n\t\t\tc.formatInviteName(invite), invite.InviterUsername)\n\t}\n}\n\nfunc (c *CmdTeamListMemberships) 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>\/\/ GOMAXPROCS=10 go test\n\/\/ GOMAXPROCS=10 go test -bench . -race\n\npackage spin\n\nimport (\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"testing\"\n)\n\nfunc HammerSpinlock(l *Lock, loops int, done chan bool) {\n\tfor i := 0; i < loops; i++ {\n\t\tl.Lock()\n\t\tl.Unlock()\n\t}\n\tdone <- true\n}\n\nfunc TestSpinlock(t *testing.T) {\n\tl := new(Lock)\n\tc := make(chan bool)\n\tfor i := 0; i < 10; i++ {\n\t\tgo HammerSpinlock(l, 1000, c)\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\t<-c\n\t}\n}\n\nfunc BenchmarkUncontendedSpinlock(b *testing.B) {\n\tl := new(Lock)\n\tHammerSpinlock(l, b.N, make(chan bool, 2))\n}\n\nfunc BenchmarkContendedSpinlock(b *testing.B) {\n\tb.StopTimer()\n\tl := new(Lock)\n\tc := make(chan bool)\n\tdefer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))\n\tb.StartTimer()\n\n\tgo HammerSpinlock(l, b.N\/2, c)\n\tgo HammerSpinlock(l, b.N\/2, c)\n\t<-c\n\t<-c\n}\n\nfunc TestSpinlockPanic(t *testing.T) {\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Fatalf(\"unlock of unlocked spinlock did not panic\")\n\t\t}\n\t}()\n\n\tvar l Lock\n\tl.Lock()\n\tl.Unlock()\n\tl.Unlock()\n}\n\nfunc BenchmarkSpinlockUncontended(b *testing.B) {\n\ttype PaddedSpinlock struct {\n\t\tLock\n\t\tpad [128]uint8\n\t}\n\tconst CallsPerSched = 1000\n\tprocs := runtime.GOMAXPROCS(-1)\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tvar l PaddedSpinlock\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tl.Lock.Lock()\n\t\t\t\t\tl.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc benchmarkSpinlock(b *testing.B, slack, work bool) {\n\tconst (\n\t\tCallsPerSched  = 1000\n\t\tLocalWork      = 100\n\t\tGoroutineSlack = 10\n\t)\n\tprocs := runtime.GOMAXPROCS(-1)\n\tif slack {\n\t\tprocs *= GoroutineSlack\n\t}\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tl := new(Lock)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tfoo := 0\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tl.Lock()\n\t\t\t\t\tl.Unlock()\n\t\t\t\t\tif work {\n\t\t\t\t\t\tfor i := 0; i < LocalWork; i++ {\n\t\t\t\t\t\t\tfoo *= 2\n\t\t\t\t\t\t\tfoo \/= 2\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\tc <- foo == 42\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc BenchmarkSpinlock(b *testing.B) {\n\tbenchmarkSpinlock(b, false, false)\n}\n\nfunc BenchmarkSpinlockSlack(b *testing.B) {\n\tbenchmarkSpinlock(b, true, false)\n}\n\nfunc BenchmarkSpinlockWork(b *testing.B) {\n\tbenchmarkSpinlock(b, false, true)\n}\n\nfunc BenchmarkSpinlockWorkSlack(b *testing.B) {\n\tbenchmarkSpinlock(b, true, true)\n}\n<commit_msg>Added comparison mutex benchmarks<commit_after>\/\/ GOMAXPROCS=10 go test\n\/\/ GOMAXPROCS=10 go test -bench . -race\n\npackage spin\n\nimport (\n\t\"runtime\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"testing\"\n)\n\nfunc HammerSpinlock(l *Lock, loops int, done chan bool) {\n\tfor i := 0; i < loops; i++ {\n\t\tl.Lock()\n\t\tl.Unlock()\n\t}\n\tdone <- true\n}\n\nfunc TestSpinlock(t *testing.T) {\n\tl := new(Lock)\n\tc := make(chan bool)\n\tfor i := 0; i < 10; i++ {\n\t\tgo HammerSpinlock(l, 1000, c)\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\t<-c\n\t}\n}\n\nfunc BenchmarkUncontendedSpinlock(b *testing.B) {\n\tl := new(Lock)\n\tHammerSpinlock(l, b.N, make(chan bool, 2))\n}\n\nfunc BenchmarkContendedSpinlock(b *testing.B) {\n\tb.StopTimer()\n\tl := new(Lock)\n\tc := make(chan bool)\n\tdefer runtime.GOMAXPROCS(runtime.GOMAXPROCS(2))\n\tb.StartTimer()\n\n\tgo HammerSpinlock(l, b.N\/2, c)\n\tgo HammerSpinlock(l, b.N\/2, c)\n\t<-c\n\t<-c\n}\n\nfunc TestSpinlockPanic(t *testing.T) {\n\tdefer func() {\n\t\tif recover() == nil {\n\t\t\tt.Fatalf(\"unlock of unlocked spinlock did not panic\")\n\t\t}\n\t}()\n\n\tvar l Lock\n\tl.Lock()\n\tl.Unlock()\n\tl.Unlock()\n}\n\nfunc BenchmarkSpinlockUncontended(b *testing.B) {\n\ttype PaddedSpinlock struct {\n\t\tLock\n\t\tpad [128]uint8\n\t}\n\tconst CallsPerSched = 1000\n\tprocs := runtime.GOMAXPROCS(-1)\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tvar l PaddedSpinlock\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tl.Lock.Lock()\n\t\t\t\t\tl.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc BenchmarkMutexUncontended(b *testing.B) {\n\ttype PaddedMutex struct {\n\t\tsync.Mutex\n\t\tpad [128]uint8\n\t}\n\tconst CallsPerSched = 1000\n\tprocs := runtime.GOMAXPROCS(-1)\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tvar mu PaddedMutex\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tmu.Lock()\n\t\t\t\t\tmu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc benchmarkSpinlock(b *testing.B, slack, work bool) {\n\tconst (\n\t\tCallsPerSched  = 1000\n\t\tLocalWork      = 100\n\t\tGoroutineSlack = 10\n\t)\n\tprocs := runtime.GOMAXPROCS(-1)\n\tif slack {\n\t\tprocs *= GoroutineSlack\n\t}\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tvar l Lock\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tfoo := 0\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tl.Lock()\n\t\t\t\t\tl.Unlock()\n\t\t\t\t\tif work {\n\t\t\t\t\t\tfor i := 0; i < LocalWork; i++ {\n\t\t\t\t\t\t\tfoo *= 2\n\t\t\t\t\t\t\tfoo \/= 2\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\tc <- foo == 42\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc benchmarkMutex(b *testing.B, slack, work bool) {\n\tconst (\n\t\tCallsPerSched  = 1000\n\t\tLocalWork      = 100\n\t\tGoroutineSlack = 10\n\t)\n\tprocs := runtime.GOMAXPROCS(-1)\n\tif slack {\n\t\tprocs *= GoroutineSlack\n\t}\n\tN := int32(b.N \/ CallsPerSched)\n\tc := make(chan bool, procs)\n\tvar mu sync.Mutex\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tfoo := 0\n\t\t\tfor atomic.AddInt32(&N, -1) >= 0 {\n\t\t\t\truntime.Gosched()\n\t\t\t\tfor g := 0; g < CallsPerSched; g++ {\n\t\t\t\t\tmu.Lock()\n\t\t\t\t\tmu.Unlock()\n\t\t\t\t\tif work {\n\t\t\t\t\t\tfor i := 0; i < LocalWork; i++ {\n\t\t\t\t\t\t\tfoo *= 2\n\t\t\t\t\t\t\tfoo \/= 2\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\tc <- foo == 42\n\t\t}()\n\t}\n\tfor p := 0; p < procs; p++ {\n\t\t<-c\n\t}\n}\n\nfunc BenchmarkSpinlock(b *testing.B) {\n\tbenchmarkSpinlock(b, false, false)\n}\n\nfunc BenchmarkMutex(b *testing.B) {\n\tbenchmarkMutex(b, false, false)\n}\n\nfunc BenchmarkSpinlockSlack(b *testing.B) {\n\tbenchmarkSpinlock(b, true, false)\n}\n\nfunc BenchmarkMutexSlack(b *testing.B) {\n\tbenchmarkMutex(b, true, false)\n}\n\nfunc BenchmarkSpinlockWork(b *testing.B) {\n\tbenchmarkSpinlock(b, false, true)\n}\n\nfunc BenchmarkMutexWork(b *testing.B) {\n\tbenchmarkMutex(b, false, true)\n}\n\nfunc BenchmarkSpinlockWorkSlack(b *testing.B) {\n\tbenchmarkSpinlock(b, true, true)\n}\n\nfunc BenchmarkMutexWorkSlack(b *testing.B) {\n\tbenchmarkMutex(b, true, true)\n}\n<|endoftext|>"}
{"text":"<commit_before>package response\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coredns\/coredns\/plugin\/test\"\n\n\t\"github.com\/miekg\/dns\"\n)\n\nfunc TestTypifyNilMsg(t *testing.T) {\n\tvar m *dns.Msg\n\n\tty, _ := Typify(m, time.Now().UTC())\n\tif ty != OtherError {\n\t\tt.Errorf(\"Message wrongly typified, expected OtherError, got %s\", ty)\n\t}\n}\n\nfunc TestTypifyDelegation(t *testing.T) {\n\tm := delegationMsg()\n\tmt, _ := Typify(m, time.Now().UTC())\n\tif mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n}\n\nfunc TestTypifyRRSIG(t *testing.T) {\n\tnow, _ := time.Parse(time.UnixDate, \"Fri Apr 21 10:51:21 BST 2017\")\n\tutc := now.UTC()\n\n\tm := delegationMsgRRSIGOK()\n\tif mt, _ := Typify(m, utc); mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n\n\t\/\/ Still a Delegation because EDNS0 OPT DO bool is not set, so we won't check the sigs.\n\tm = delegationMsgRRSIGFail()\n\tif mt, _ := Typify(m, utc); mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n\n\tm = delegationMsgRRSIGFail()\n\tm = addOpt(m)\n\tif mt, _ := Typify(m, utc); mt != OtherError {\n\t\tt.Errorf(\"Message is wrongly typified, expected OtherError, got %s\", mt)\n\t}\n}\n\nfunc delegationMsg() *dns.Msg {\n\treturn &dns.Msg{\n\t\tNs: []dns.RR{\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tlinode.atoom.net.\"),\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tns-ext.nlnetlabs.nl.\"),\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tomval.tednet.nl.\"),\n\t\t},\n\t\tExtra: []dns.RR{\n\t\t\ttest.A(\"omval.tednet.nl.\t3600\tIN\tA\t185.49.141.42\"),\n\t\t\ttest.AAAA(\"omval.tednet.nl.\t3600\tIN\tAAAA\t2a04:b900:0:100::42\"),\n\t\t},\n\t}\n}\n\nfunc delegationMsgRRSIGOK() *dns.Msg {\n\tdel := delegationMsg()\n\tdel.Ns = append(del.Ns,\n\t\ttest.RRSIG(\"miek.nl.\t\t1800\tIN\tRRSIG\tNS 8 2 1800 20170521031301 20170421031301 12051 miek.nl. PIUu3TKX\/sB\/N1n1E1yWxHHIcPnc2q6Wq9InShk+5ptRqChqKdZNMLDm gCq+1bQAZ7jGvn2PbwTwE65JzES7T+hEiqR5PU23DsidvZyClbZ9l0xG JtKwgzGXLtUHxp4xv\/Plq+rq\/7pOG61bNCxRyS7WS7i7QcCCWT1BCcv+ wZ0=\"),\n\t)\n\treturn del\n}\n\nfunc delegationMsgRRSIGFail() *dns.Msg {\n\tdel := delegationMsg()\n\tdel.Ns = append(del.Ns,\n\t\ttest.RRSIG(\"miek.nl.\t\t1800\tIN\tRRSIG\tNS 8 2 1800 20160521031301 20160421031301 12051 miek.nl. PIUu3TKX\/sB\/N1n1E1yWxHHIcPnc2q6Wq9InShk+5ptRqChqKdZNMLDm gCq+1bQAZ7jGvn2PbwTwE65JzES7T+hEiqR5PU23DsidvZyClbZ9l0xG JtKwgzGXLtUHxp4xv\/Plq+rq\/7pOG61bNCxRyS7WS7i7QcCCWT1BCcv+ wZ0=\"),\n\t)\n\treturn del\n}\n\nfunc addOpt(m *dns.Msg) *dns.Msg {\n\tm.Extra = append(m.Extra, test.OPT(4096, true))\n\treturn m\n}\n<commit_msg>pkg\/response: add extra test for impossible msg (#2727)<commit_after>package response\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coredns\/coredns\/plugin\/test\"\n\n\t\"github.com\/miekg\/dns\"\n)\n\nfunc TestTypifyNilMsg(t *testing.T) {\n\tvar m *dns.Msg\n\n\tty, _ := Typify(m, time.Now().UTC())\n\tif ty != OtherError {\n\t\tt.Errorf(\"Message wrongly typified, expected OtherError, got %s\", ty)\n\t}\n}\n\nfunc TestTypifyDelegation(t *testing.T) {\n\tm := delegationMsg()\n\tmt, _ := Typify(m, time.Now().UTC())\n\tif mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n}\n\nfunc TestTypifyRRSIG(t *testing.T) {\n\tnow, _ := time.Parse(time.UnixDate, \"Fri Apr 21 10:51:21 BST 2017\")\n\tutc := now.UTC()\n\n\tm := delegationMsgRRSIGOK()\n\tif mt, _ := Typify(m, utc); mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n\n\t\/\/ Still a Delegation because EDNS0 OPT DO bool is not set, so we won't check the sigs.\n\tm = delegationMsgRRSIGFail()\n\tif mt, _ := Typify(m, utc); mt != Delegation {\n\t\tt.Errorf(\"Message is wrongly typified, expected Delegation, got %s\", mt)\n\t}\n\n\tm = delegationMsgRRSIGFail()\n\tm.Extra = append(m.Extra, test.OPT(4096, true))\n\tif mt, _ := Typify(m, utc); mt != OtherError {\n\t\tt.Errorf(\"Message is wrongly typified, expected OtherError, got %s\", mt)\n\t}\n}\n\nfunc TestTypifyImpossible(t *testing.T) {\n\t\/\/ create impossible message that denies it's own existence\n\tm := new(dns.Msg)\n\tm.SetQuestion(\"bar.www.example.org.\", dns.TypeAAAA)\n\tm.Rcode = dns.RcodeNameError                                                      \/\/ name does not exist\n\tm.Answer = []dns.RR{test.CNAME(\"bar.www.example.org. IN CNAME foo.example.org.\")} \/\/ but we add a cname with the name!\n\tmt, _ := Typify(m, time.Now().UTC())\n\tif mt != OtherError {\n\t\tt.Errorf(\"Impossible message not typified as OtherError, got %s\", mt)\n\t}\n}\n\nfunc delegationMsg() *dns.Msg {\n\treturn &dns.Msg{\n\t\tNs: []dns.RR{\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tlinode.atoom.net.\"),\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tns-ext.nlnetlabs.nl.\"),\n\t\t\ttest.NS(\"miek.nl.\t3600\tIN\tNS\tomval.tednet.nl.\"),\n\t\t},\n\t\tExtra: []dns.RR{\n\t\t\ttest.A(\"omval.tednet.nl.\t3600\tIN\tA\t185.49.141.42\"),\n\t\t\ttest.AAAA(\"omval.tednet.nl.\t3600\tIN\tAAAA\t2a04:b900:0:100::42\"),\n\t\t},\n\t}\n}\n\nfunc delegationMsgRRSIGOK() *dns.Msg {\n\tdel := delegationMsg()\n\tdel.Ns = append(del.Ns,\n\t\ttest.RRSIG(\"miek.nl.\t\t1800\tIN\tRRSIG\tNS 8 2 1800 20170521031301 20170421031301 12051 miek.nl. PIUu3TKX\/sB\/N1n1E1yWxHHIcPnc2q6Wq9InShk+5ptRqChqKdZNMLDm gCq+1bQAZ7jGvn2PbwTwE65JzES7T+hEiqR5PU23DsidvZyClbZ9l0xG JtKwgzGXLtUHxp4xv\/Plq+rq\/7pOG61bNCxRyS7WS7i7QcCCWT1BCcv+ wZ0=\"),\n\t)\n\treturn del\n}\n\nfunc delegationMsgRRSIGFail() *dns.Msg {\n\tdel := delegationMsg()\n\tdel.Ns = append(del.Ns,\n\t\ttest.RRSIG(\"miek.nl.\t\t1800\tIN\tRRSIG\tNS 8 2 1800 20160521031301 20160421031301 12051 miek.nl. PIUu3TKX\/sB\/N1n1E1yWxHHIcPnc2q6Wq9InShk+5ptRqChqKdZNMLDm gCq+1bQAZ7jGvn2PbwTwE65JzES7T+hEiqR5PU23DsidvZyClbZ9l0xG JtKwgzGXLtUHxp4xv\/Plq+rq\/7pOG61bNCxRyS7WS7i7QcCCWT1BCcv+ wZ0=\"),\n\t)\n\treturn del\n}\n<|endoftext|>"}
{"text":"<commit_before>package npm\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\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\"strings\"\n\n\t\"github.com\/jfrog\/jfrog-cli-go\/artifactory\/utils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/artifactory\/utils\/npm\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/utils\/config\"\n\t\"github.com\/jfrog\/jfrog-client-go\/artifactory\/buildinfo\"\n\t\"github.com\/jfrog\/jfrog-client-go\/artifactory\/services\"\n\tspecutils \"github.com\/jfrog\/jfrog-client-go\/artifactory\/services\/utils\"\n\tclientutils \"github.com\/jfrog\/jfrog-client-go\/utils\"\n\t\"github.com\/jfrog\/jfrog-client-go\/utils\/errorutils\"\n\t\"github.com\/jfrog\/jfrog-client-go\/utils\/log\"\n)\n\ntype NpmPublishCommandArgs struct {\n\tNpmCommand\n\texecutablePath   string\n\tworkingDirectory string\n\tcollectBuildInfo bool\n\tpackedFilePath   string\n\tpackageInfo      *npm.PackageInfo\n\tpublishPath      string\n\ttarballProvided  bool\n\tartifactData     []specutils.FileInfo\n}\n\ntype NpmPublishCommand struct {\n\tconfigFilePath string\n\tcommandName    string\n\t*NpmPublishCommandArgs\n}\n\nfunc NewNpmPublishCommand() *NpmPublishCommand {\n\treturn &NpmPublishCommand{NpmPublishCommandArgs: NewNpmPublishCommandArgs(), commandName: \"rt_npm_publish\"}\n}\n\nfunc NewNpmPublishCommandArgs() *NpmPublishCommandArgs {\n\treturn &NpmPublishCommandArgs{}\n}\n\nfunc (npc *NpmPublishCommand) RtDetails() (*config.ArtifactoryDetails, error) {\n\treturn npc.rtDetails, nil\n}\n\nfunc (npc *NpmPublishCommand) SetConfigFilePath(configFilePath string) *NpmPublishCommand {\n\tnpc.configFilePath = configFilePath\n\treturn npc\n}\n\nfunc (nic *NpmPublishCommand) SetArgs(args []string) *NpmPublishCommand {\n\tnic.NpmPublishCommandArgs.npmArgs = args\n\treturn nic\n}\n\nfunc (npc *NpmPublishCommand) Run() error {\n\tif npc.configFilePath != \"\" {\n\t\t\/\/ Read config file.\n\t\tlog.Debug(\"Preparing to read the config file\", npc.configFilePath)\n\t\tvConfig, err := utils.ReadConfigFile(npc.configFilePath, utils.YAML)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Extract resolution params.\n\t\tdeployerParams, err := utils.GetRepoConfigByPrefix(npc.configFilePath, utils.ProjectConfigDeployerPrefix, vConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, filteredNpmArgs, buildConfiguration, err := utils.ExtractNpmOptionsFromArgs(npc.NpmPublishCommandArgs.npmArgs)\n\t\tRtDetails, err := deployerParams.RtDetails()\n\t\tif err != nil {\n\t\t\treturn errorutils.CheckError(err)\n\t\t}\n\t\tnpc.SetBuildConfiguration(buildConfiguration).SetRepo(deployerParams.TargetRepo()).SetNpmArgs(filteredNpmArgs).SetRtDetails(RtDetails)\n\t}\n\treturn npc.run()\n}\n\nfunc (npc *NpmPublishCommand) run() error {\n\tlog.Info(\"Running npm Publish\")\n\tif err := npc.preparePrerequisites(); err != nil {\n\t\treturn err\n\t}\n\n\tif !npc.tarballProvided {\n\t\tif err := npc.pack(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := npc.deploy(); err != nil {\n\t\tif npc.tarballProvided {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ We should delete the tarball we created\n\t\treturn deleteCreatedTarballAndError(npc.packedFilePath, err)\n\t}\n\n\tif !npc.tarballProvided {\n\t\tif err := deleteCreatedTarball(npc.packedFilePath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !npc.collectBuildInfo {\n\t\tlog.Info(\"npm publish finished successfully.\")\n\t\treturn nil\n\t}\n\n\tif err := npc.saveArtifactData(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"npm publish finished successfully.\")\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) CommandName() string {\n\treturn npc.CommandName()\n}\n\nfunc (npc *NpmPublishCommand) preparePrerequisites() error {\n\tlog.Debug(\"Preparing prerequisites.\")\n\tnpmExecPath, err := exec.LookPath(\"npm\")\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tif npmExecPath == \"\" {\n\t\treturn errorutils.CheckError(errors.New(\"Could not find 'npm' executable\"))\n\t}\n\n\tnpc.executablePath = npmExecPath\n\tlog.Debug(\"Using npm executable:\", npc.executablePath)\n\tcurrentDir, err := os.Getwd()\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tcurrentDir, err = filepath.Abs(currentDir)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tnpc.workingDirectory = currentDir\n\tlog.Debug(\"Working directory set to:\", npc.workingDirectory)\n\tnpc.collectBuildInfo = len(npc.buildConfiguration.BuildName) > 0 && len(npc.buildConfiguration.BuildNumber) > 0\n\tif err = npc.setPublishPath(); err != nil {\n\t\treturn err\n\t}\n\n\tartDetails, err := npc.rtDetails.CreateArtAuthConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = utils.CheckIfRepoExists(npc.repo, artDetails); err != nil {\n\t\treturn err\n\t}\n\n\treturn npc.setPackageInfo()\n}\n\nfunc (npc *NpmPublishCommand) pack() error {\n\tlog.Debug(\"Creating npm package.\")\n\tif err := npm.Pack(npc.npmArgs, npc.executablePath); err != nil {\n\t\treturn err\n\t}\n\n\tnpc.packedFilePath = filepath.Join(npc.workingDirectory, npc.packageInfo.GetExpectedPackedFileName())\n\tlog.Debug(\"Created npm package at\", npc.packedFilePath)\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) deploy() (err error) {\n\tlog.Debug(\"Deploying npm package.\")\n\tif err = npc.readPackageInfoFromTarball(); err != nil {\n\t\treturn err\n\t}\n\n\ttarget := fmt.Sprintf(\"%s\/%s\", npc.repo, npc.packageInfo.GetDeployPath())\n\tartifactsFileInfo, err := npc.doDeploy(target, npc.rtDetails)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnpc.artifactData = artifactsFileInfo\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) doDeploy(target string, artDetails *config.ArtifactoryDetails) (artifactsFileInfo []specutils.FileInfo, err error) {\n\tservicesManager, err := utils.CreateServiceManager(artDetails, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tup := services.UploadParams{}\n\tup.ArtifactoryCommonParams = &specutils.ArtifactoryCommonParams{Pattern: npc.packedFilePath, Target: target}\n\tif npc.collectBuildInfo {\n\t\tutils.SaveBuildGeneralDetails(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber)\n\t\tprops, err := utils.CreateBuildProperties(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tup.ArtifactoryCommonParams.Props = props\n\t}\n\tartifactsFileInfo, _, failed, err := servicesManager.UploadFiles(up)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ We deploying only one Artifact which have to be deployed, in case of failure we should fail\n\tif failed > 0 {\n\t\treturn nil, errorutils.CheckError(errors.New(\"Failed to upload the npm package to Artifactory. See Artifactory logs for more details.\"))\n\t}\n\treturn artifactsFileInfo, nil\n}\n\nfunc (npc *NpmPublishCommand) saveArtifactData() error {\n\tlog.Debug(\"Saving npm package artifact build info data.\")\n\tvar buildArtifacts []buildinfo.Artifact\n\tfor _, artifact := range npc.artifactData {\n\t\tbuildArtifacts = append(buildArtifacts, artifact.ToBuildArtifacts())\n\t}\n\n\tpopulateFunc := func(partial *buildinfo.Partial) {\n\t\tpartial.Artifacts = buildArtifacts\n\t\tif npc.buildConfiguration.Module == \"\" {\n\t\t\tnpc.buildConfiguration.Module = npc.packageInfo.BuildInfoModuleId()\n\t\t}\n\t\tpartial.ModuleId = npc.buildConfiguration.Module\n\t}\n\treturn utils.SavePartialBuildInfo(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber, populateFunc)\n}\n\nfunc (npc *NpmPublishCommand) setPublishPath() error {\n\tlog.Debug(\"Reading Package Json.\")\n\n\tnpc.publishPath = npc.workingDirectory\n\tif len(npc.npmArgs) > 0 && !strings.HasPrefix(strings.TrimSpace(npc.npmArgs[0]), \"-\") {\n\t\tpath := strings.TrimSpace(npc.npmArgs[0])\n\t\tpath = clientutils.ReplaceTildeWithUserHome(path)\n\n\t\tif filepath.IsAbs(path) {\n\t\t\tnpc.publishPath = path\n\t\t} else {\n\t\t\tnpc.publishPath = filepath.Join(npc.workingDirectory, path)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) setPackageInfo() error {\n\tlog.Debug(\"Setting Package Info.\")\n\tfileInfo, err := os.Stat(npc.publishPath)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tnpc.packageInfo, err = npm.ReadPackageInfoFromPackageJson(npc.publishPath)\n\t\treturn err\n\t}\n\tlog.Debug(\"The provided path is not a directory, we assume this is a compressed npm package\")\n\tnpc.tarballProvided = true\n\tnpc.packedFilePath = npc.publishPath\n\treturn npc.readPackageInfoFromTarball()\n}\n\nfunc (npc *NpmPublishCommand) readPackageInfoFromTarball() error {\n\tlog.Debug(\"Extracting info from npm package:\", npc.packedFilePath)\n\ttarball, err := os.Open(npc.packedFilePath)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\tdefer tarball.Close()\n\tgZipReader, err := gzip.NewReader(tarball)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\ttarReader := tar.NewReader(gZipReader)\n\tfor {\n\t\thdr, err := tarReader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn errorutils.CheckError(errors.New(\"Could not find 'package.json' in the compressed npm package: \" + npc.packedFilePath))\n\t\t\t}\n\t\t\treturn errorutils.CheckError(err)\n\t\t}\n\t\tif strings.HasSuffix(hdr.Name, \"package.json\") {\n\t\t\tpackageJson, err := ioutil.ReadAll(tarReader)\n\t\t\tif err != nil {\n\t\t\t\treturn errorutils.CheckError(err)\n\t\t\t}\n\n\t\t\tnpc.packageInfo, err = npm.ReadPackageInfo(packageJson)\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc deleteCreatedTarballAndError(packedFilePath string, currentError error) error {\n\tif err := deleteCreatedTarball(packedFilePath); err != nil {\n\t\terrorText := fmt.Sprintf(\"Two errors occurred: \\n%s \\n%s\", currentError, err)\n\t\treturn errorutils.CheckError(errors.New(errorText))\n\t}\n\treturn currentError\n}\n\nfunc deleteCreatedTarball(packedFilePath string) error {\n\tif err := os.Remove(packedFilePath); err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\tlog.Debug(\"Successfully deleted the created npm package:\", packedFilePath)\n\treturn nil\n}\n<commit_msg>Fix stackoverflow in npm publish (#504)<commit_after>package npm\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\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\"strings\"\n\n\t\"github.com\/jfrog\/jfrog-cli-go\/artifactory\/utils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/artifactory\/utils\/npm\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/utils\/config\"\n\t\"github.com\/jfrog\/jfrog-client-go\/artifactory\/buildinfo\"\n\t\"github.com\/jfrog\/jfrog-client-go\/artifactory\/services\"\n\tspecutils \"github.com\/jfrog\/jfrog-client-go\/artifactory\/services\/utils\"\n\tclientutils \"github.com\/jfrog\/jfrog-client-go\/utils\"\n\t\"github.com\/jfrog\/jfrog-client-go\/utils\/errorutils\"\n\t\"github.com\/jfrog\/jfrog-client-go\/utils\/log\"\n)\n\ntype NpmPublishCommandArgs struct {\n\tNpmCommand\n\texecutablePath   string\n\tworkingDirectory string\n\tcollectBuildInfo bool\n\tpackedFilePath   string\n\tpackageInfo      *npm.PackageInfo\n\tpublishPath      string\n\ttarballProvided  bool\n\tartifactData     []specutils.FileInfo\n}\n\ntype NpmPublishCommand struct {\n\tconfigFilePath string\n\tcommandName    string\n\t*NpmPublishCommandArgs\n}\n\nfunc NewNpmPublishCommand() *NpmPublishCommand {\n\treturn &NpmPublishCommand{NpmPublishCommandArgs: NewNpmPublishCommandArgs(), commandName: \"rt_npm_publish\"}\n}\n\nfunc NewNpmPublishCommandArgs() *NpmPublishCommandArgs {\n\treturn &NpmPublishCommandArgs{}\n}\n\nfunc (npc *NpmPublishCommand) RtDetails() (*config.ArtifactoryDetails, error) {\n\treturn npc.rtDetails, nil\n}\n\nfunc (npc *NpmPublishCommand) SetConfigFilePath(configFilePath string) *NpmPublishCommand {\n\tnpc.configFilePath = configFilePath\n\treturn npc\n}\n\nfunc (nic *NpmPublishCommand) SetArgs(args []string) *NpmPublishCommand {\n\tnic.NpmPublishCommandArgs.npmArgs = args\n\treturn nic\n}\n\nfunc (npc *NpmPublishCommand) Run() error {\n\tif npc.configFilePath != \"\" {\n\t\t\/\/ Read config file.\n\t\tlog.Debug(\"Preparing to read the config file\", npc.configFilePath)\n\t\tvConfig, err := utils.ReadConfigFile(npc.configFilePath, utils.YAML)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Extract resolution params.\n\t\tdeployerParams, err := utils.GetRepoConfigByPrefix(npc.configFilePath, utils.ProjectConfigDeployerPrefix, vConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, filteredNpmArgs, buildConfiguration, err := utils.ExtractNpmOptionsFromArgs(npc.NpmPublishCommandArgs.npmArgs)\n\t\tRtDetails, err := deployerParams.RtDetails()\n\t\tif err != nil {\n\t\t\treturn errorutils.CheckError(err)\n\t\t}\n\t\tnpc.SetBuildConfiguration(buildConfiguration).SetRepo(deployerParams.TargetRepo()).SetNpmArgs(filteredNpmArgs).SetRtDetails(RtDetails)\n\t}\n\treturn npc.run()\n}\n\nfunc (npc *NpmPublishCommand) run() error {\n\tlog.Info(\"Running npm Publish\")\n\tif err := npc.preparePrerequisites(); err != nil {\n\t\treturn err\n\t}\n\n\tif !npc.tarballProvided {\n\t\tif err := npc.pack(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := npc.deploy(); err != nil {\n\t\tif npc.tarballProvided {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ We should delete the tarball we created\n\t\treturn deleteCreatedTarballAndError(npc.packedFilePath, err)\n\t}\n\n\tif !npc.tarballProvided {\n\t\tif err := deleteCreatedTarball(npc.packedFilePath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !npc.collectBuildInfo {\n\t\tlog.Info(\"npm publish finished successfully.\")\n\t\treturn nil\n\t}\n\n\tif err := npc.saveArtifactData(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Info(\"npm publish finished successfully.\")\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) CommandName() string {\n\treturn npc.commandName\n}\n\nfunc (npc *NpmPublishCommand) preparePrerequisites() error {\n\tlog.Debug(\"Preparing prerequisites.\")\n\tnpmExecPath, err := exec.LookPath(\"npm\")\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tif npmExecPath == \"\" {\n\t\treturn errorutils.CheckError(errors.New(\"Could not find 'npm' executable\"))\n\t}\n\n\tnpc.executablePath = npmExecPath\n\tlog.Debug(\"Using npm executable:\", npc.executablePath)\n\tcurrentDir, err := os.Getwd()\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tcurrentDir, err = filepath.Abs(currentDir)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tnpc.workingDirectory = currentDir\n\tlog.Debug(\"Working directory set to:\", npc.workingDirectory)\n\tnpc.collectBuildInfo = len(npc.buildConfiguration.BuildName) > 0 && len(npc.buildConfiguration.BuildNumber) > 0\n\tif err = npc.setPublishPath(); err != nil {\n\t\treturn err\n\t}\n\n\tartDetails, err := npc.rtDetails.CreateArtAuthConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = utils.CheckIfRepoExists(npc.repo, artDetails); err != nil {\n\t\treturn err\n\t}\n\n\treturn npc.setPackageInfo()\n}\n\nfunc (npc *NpmPublishCommand) pack() error {\n\tlog.Debug(\"Creating npm package.\")\n\tif err := npm.Pack(npc.npmArgs, npc.executablePath); err != nil {\n\t\treturn err\n\t}\n\n\tnpc.packedFilePath = filepath.Join(npc.workingDirectory, npc.packageInfo.GetExpectedPackedFileName())\n\tlog.Debug(\"Created npm package at\", npc.packedFilePath)\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) deploy() (err error) {\n\tlog.Debug(\"Deploying npm package.\")\n\tif err = npc.readPackageInfoFromTarball(); err != nil {\n\t\treturn err\n\t}\n\n\ttarget := fmt.Sprintf(\"%s\/%s\", npc.repo, npc.packageInfo.GetDeployPath())\n\tartifactsFileInfo, err := npc.doDeploy(target, npc.rtDetails)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnpc.artifactData = artifactsFileInfo\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) doDeploy(target string, artDetails *config.ArtifactoryDetails) (artifactsFileInfo []specutils.FileInfo, err error) {\n\tservicesManager, err := utils.CreateServiceManager(artDetails, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tup := services.UploadParams{}\n\tup.ArtifactoryCommonParams = &specutils.ArtifactoryCommonParams{Pattern: npc.packedFilePath, Target: target}\n\tif npc.collectBuildInfo {\n\t\tutils.SaveBuildGeneralDetails(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber)\n\t\tprops, err := utils.CreateBuildProperties(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tup.ArtifactoryCommonParams.Props = props\n\t}\n\tartifactsFileInfo, _, failed, err := servicesManager.UploadFiles(up)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ We deploying only one Artifact which have to be deployed, in case of failure we should fail\n\tif failed > 0 {\n\t\treturn nil, errorutils.CheckError(errors.New(\"Failed to upload the npm package to Artifactory. See Artifactory logs for more details.\"))\n\t}\n\treturn artifactsFileInfo, nil\n}\n\nfunc (npc *NpmPublishCommand) saveArtifactData() error {\n\tlog.Debug(\"Saving npm package artifact build info data.\")\n\tvar buildArtifacts []buildinfo.Artifact\n\tfor _, artifact := range npc.artifactData {\n\t\tbuildArtifacts = append(buildArtifacts, artifact.ToBuildArtifacts())\n\t}\n\n\tpopulateFunc := func(partial *buildinfo.Partial) {\n\t\tpartial.Artifacts = buildArtifacts\n\t\tif npc.buildConfiguration.Module == \"\" {\n\t\t\tnpc.buildConfiguration.Module = npc.packageInfo.BuildInfoModuleId()\n\t\t}\n\t\tpartial.ModuleId = npc.buildConfiguration.Module\n\t}\n\treturn utils.SavePartialBuildInfo(npc.buildConfiguration.BuildName, npc.buildConfiguration.BuildNumber, populateFunc)\n}\n\nfunc (npc *NpmPublishCommand) setPublishPath() error {\n\tlog.Debug(\"Reading Package Json.\")\n\n\tnpc.publishPath = npc.workingDirectory\n\tif len(npc.npmArgs) > 0 && !strings.HasPrefix(strings.TrimSpace(npc.npmArgs[0]), \"-\") {\n\t\tpath := strings.TrimSpace(npc.npmArgs[0])\n\t\tpath = clientutils.ReplaceTildeWithUserHome(path)\n\n\t\tif filepath.IsAbs(path) {\n\t\t\tnpc.publishPath = path\n\t\t} else {\n\t\t\tnpc.publishPath = filepath.Join(npc.workingDirectory, path)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (npc *NpmPublishCommand) setPackageInfo() error {\n\tlog.Debug(\"Setting Package Info.\")\n\tfileInfo, err := os.Stat(npc.publishPath)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\tif fileInfo.IsDir() {\n\t\tnpc.packageInfo, err = npm.ReadPackageInfoFromPackageJson(npc.publishPath)\n\t\treturn err\n\t}\n\tlog.Debug(\"The provided path is not a directory, we assume this is a compressed npm package\")\n\tnpc.tarballProvided = true\n\tnpc.packedFilePath = npc.publishPath\n\treturn npc.readPackageInfoFromTarball()\n}\n\nfunc (npc *NpmPublishCommand) readPackageInfoFromTarball() error {\n\tlog.Debug(\"Extracting info from npm package:\", npc.packedFilePath)\n\ttarball, err := os.Open(npc.packedFilePath)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\tdefer tarball.Close()\n\tgZipReader, err := gzip.NewReader(tarball)\n\tif err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\n\ttarReader := tar.NewReader(gZipReader)\n\tfor {\n\t\thdr, err := tarReader.Next()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn errorutils.CheckError(errors.New(\"Could not find 'package.json' in the compressed npm package: \" + npc.packedFilePath))\n\t\t\t}\n\t\t\treturn errorutils.CheckError(err)\n\t\t}\n\t\tif strings.HasSuffix(hdr.Name, \"package.json\") {\n\t\t\tpackageJson, err := ioutil.ReadAll(tarReader)\n\t\t\tif err != nil {\n\t\t\t\treturn errorutils.CheckError(err)\n\t\t\t}\n\n\t\t\tnpc.packageInfo, err = npm.ReadPackageInfo(packageJson)\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc deleteCreatedTarballAndError(packedFilePath string, currentError error) error {\n\tif err := deleteCreatedTarball(packedFilePath); err != nil {\n\t\terrorText := fmt.Sprintf(\"Two errors occurred: \\n%s \\n%s\", currentError, err)\n\t\treturn errorutils.CheckError(errors.New(errorText))\n\t}\n\treturn currentError\n}\n\nfunc deleteCreatedTarball(packedFilePath string) error {\n\tif err := os.Remove(packedFilePath); err != nil {\n\t\treturn errorutils.CheckError(err)\n\t}\n\tlog.Debug(\"Successfully deleted the created npm package:\", packedFilePath)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"web\"\n    \"strings\"\n    \"godis\"\n    \"fmt\"\n    \"os\"\n    \"url\"\n    \"flag\"\n    \"strconv\"\n    \"time\"\n    \"json\"\n    \"http\"\n)\n\nconst(\n    \/\/ special key in redis, that is our global counter\n    COUNTER = \"__counter__\"\n    HTTP = \"http\"\n    ROLL = \"https:\/\/www.youtube.com\/watch?v=jRHmvy5eaG4\" \n)\n\n\nvar (\n    redis *godis.Client\n    config *Config\n)\n\n\ntype KurzUrl struct{\n    Key string\n    ShortUrl string\n    LongUrl string\n    CreationDate int64\n    Clicks int64\n}\n\n\/\/ Converts the KurzUrl to JSON.\nfunc (k KurzUrl) Json()[]byte{\n    b, _ := json.Marshal(k)\n    return b\n}\n\n\/\/ Creates a new KurzUrl instance. The Given key, shorturl and longurl will\n\/\/ be used. Clicks will be set to 0 and CreationDate to time.Nanoseconds()\nfunc NewKurzUrl(key, shorturl, longurl string) *KurzUrl{\n    kurl := new(KurzUrl)\n    kurl.CreationDate = time.Nanoseconds()\n    kurl.Key = key\n    kurl.LongUrl = longurl\n    kurl.ShortUrl = shorturl\n    kurl.Clicks = 0\n    return kurl\n}\n\n\n\nfunc info(ctx *web.Context, short string) {\n    kurl, err :=  load(short)\n    if err == nil{\n        ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n        ctx.Write(kurl.Json())\n        ctx.WriteString(\"\\n\")\n    } else{\n        ctx.Redirect(http.StatusNotFound, ROLL)\n    }\n}\n\/\/ function to resolve a shorturl and redirect\nfunc resolve(ctx *web.Context, short string) {\n    if strings.HasSuffix(short, \"+\"){\n        info(ctx, strings.Replace(short, \"+\", \"\", 1))\n        return\n    }\n    redirect, err := redis.Hget(short, \"LongUrl\")\n    if err == nil {\n        go redis.Hincrby(short, \"Clicks\", 1)\n        ctx.Redirect(http.StatusMovedPermanently,\n             redirect.String())\n    } else {\n        ctx.Redirect(http.StatusMovedPermanently,\n            ROLL)\n    }\n}\n\n\n\/\/ Determines if the string rawurl is a valid URL to be stored.\nfunc isValidUrl(rawurl string) (u *url.URL, err os.Error){\n    if len(rawurl) == 0{\n        return nil, os.NewError(\"empty url\")\n    }\n    \/\/ XXX this needs some love...\n    if !strings.HasPrefix(rawurl, HTTP){\n        rawurl = fmt.Sprintf(\"%s:\/\/%s\", HTTP, rawurl)\n    }\n    return url.Parse(rawurl)\n}\n\n\/\/ stores a new KurzUrl for the given key, shorturl and longurl. Existing\n\/\/ ones with the same url will be overwritten\nfunc store(key, shorturl, longurl string)*KurzUrl{\n    kurl := NewKurzUrl(key, shorturl, longurl)\n    go redis.Hset(kurl.Key, \"LongUrl\", kurl.LongUrl)\n    go redis.Hset(kurl.Key, \"ShortUrl\", kurl.ShortUrl)\n    go redis.Hset(kurl.Key, \"CreationDate\", kurl.CreationDate)\n    go redis.Hset(kurl.Key, \"Clicks\", kurl.Clicks)\n    return kurl\n}\n\n\/\/ loads a KurzUrl instance for the given key. If the key is\n\/\/ not found, os.Error is returned.\nfunc load(key string) (kurl *KurzUrl, err os.Error){\n    if ok, _ := redis.Hexists(key, \"ShortUrl\"); ok{\n        kurl := new(KurzUrl)\n        kurl.Key = key\n        reply, _ := redis.Hmget(key, \"LongUrl\", \"ShortUrl\", \"CreationDate\", \"Clicks\")\n        kurl.LongUrl, kurl.ShortUrl, kurl.CreationDate, kurl.Clicks =\n            reply.Elems[0].Elem.String(), reply.Elems[1].Elem.String(),\n            reply.Elems[2].Elem.Int64(), reply.Elems[3].Elem.Int64()\n        return kurl, nil\n    }\n    return nil, os.NewError(\"unknown key: \" + key )\n}\n\n\n\/\/ function to shorten and store a url\nfunc shorten(ctx *web.Context, data string){\n    host := config.GetStringDefault(\"hostname\", \"localhost\")\n    r, _ := ctx.Request.Params[\"url\"]\n    theUrl, err := isValidUrl(string(r))\n    if err == nil{\n        ctr, _ := redis.Incr(COUNTER)\n        encoded := Encode(ctr)\n        location := fmt.Sprintf(\"%s:\/\/%s\/%s\", HTTP, host, encoded)\n\n        kurl := store(encoded, location, theUrl.Raw)\n\n        ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n        ctx.SetHeader(\"Location\", location, true)\n        ctx.StartResponse(http.StatusCreated)\n        ctx.Write(kurl.Json())\n        ctx.WriteString(\"\\n\")\n    }else{\n       ctx.Redirect(http.StatusNotFound, ROLL)\n    }\n}\n\n\nfunc latest(ctx *web.Context, data string){\n    howmany, err := strconv.Atoi64(data)\n    if err != nil {\n        howmany = 10\n    }\n    c, _ := redis.Get(COUNTER)\n\n    last := c.Int64()\n    upTo := (last - howmany)\n\n    ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n    ctx.WriteString(\"{ \\\"urls\\\" : [\")\n    for i := last; i > upTo && i > 0; i -= 1{\n        kurl, err := load(Encode(i))\n        if err == nil{\n            ctx.Write(kurl.Json())\n            if i != upTo + 1 {\n                ctx.WriteString(\",\")\n            }\n        }\n    }\n    ctx.WriteString(\"] }\")\n    ctx.WriteString(\"\\n\")\n}\n\n\n\/\/ bootstraps the server\nfunc bootstrap(path string) os.Error {\n    config = NewConfig(path)\n    config.Parse()\n\n    host := config.GetStringDefault(\"redis.address\", \"tcp:localhost:6379\")\n    db := config.GetIntDefault(\"redis.database\", 0)\n    passwd := config.GetStringDefault(\"redis.password\", \"\")\n\n    redis = godis.New(host, db, passwd)\n\n    web.Config.StaticDir = config.GetStringDefault(\"static-directory\", \"\")\n\n    web.Post(\"\/shorten\/(.*)\", shorten)\n    web.Get(\"\/latest\/(.*)\", latest)\n    web.Get(\"\/info\/(.*)\", info)\n    web.Get(\"\/(.*)\", resolve)\n\n    return nil\n}\n\n\n\/\/ main function that starts everything\nfunc main() {\n    flag.Parse()\n    cfgFile := flag.Arg(0)\n    err := bootstrap(cfgFile)\n    if err == nil {\n                listen := config.GetStringDefault(\"listen\", \"0.0.0.0\")\n        port := config.GetStringDefault(\"port\", \"9999\")\n        web.Run(fmt.Sprintf(\"%s:%s\", listen, port))\n    }\n}\n\n<commit_msg>refactoring of regexes to have a faster and more stable routing within the app<commit_after>package main\n\nimport (\n    \"web\"\n    \"strings\"\n    \"godis\"\n    \"fmt\"\n    \"os\"\n    \"url\"\n    \"flag\"\n    \"strconv\"\n    \"time\"\n    \"json\"\n    \"http\"\n)\n\nconst(\n    \/\/ special key in redis, that is our global counter\n    COUNTER = \"__counter__\"\n    HTTP = \"http\"\n    ROLL = \"https:\/\/www.youtube.com\/watch?v=jRHmvy5eaG4\" \n)\n\n\nvar (\n    redis *godis.Client\n    config *Config\n)\n\n\ntype KurzUrl struct{\n    Key string\n    ShortUrl string\n    LongUrl string\n    CreationDate int64\n    Clicks int64\n}\n\n\/\/ Converts the KurzUrl to JSON.\nfunc (k KurzUrl) Json()[]byte{\n    b, _ := json.Marshal(k)\n    return b\n}\n\n\/\/ Creates a new KurzUrl instance. The Given key, shorturl and longurl will\n\/\/ be used. Clicks will be set to 0 and CreationDate to time.Nanoseconds()\nfunc NewKurzUrl(key, shorturl, longurl string) *KurzUrl{\n    kurl := new(KurzUrl)\n    kurl.CreationDate = time.Nanoseconds()\n    kurl.Key = key\n    kurl.LongUrl = longurl\n    kurl.ShortUrl = shorturl\n    kurl.Clicks = 0\n    return kurl\n}\n\n\nfunc info(ctx *web.Context, short string) {\n    if strings.HasSuffix(short, \"+\"){\n        short = strings.Replace(short, \"+\", \"\", 1)\n    }\n\n    kurl, err :=  load(short)\n    if err == nil{\n        ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n        ctx.Write(kurl.Json())\n        ctx.WriteString(\"\\n\")\n    } else{\n        ctx.Redirect(http.StatusNotFound, ROLL)\n    }\n}\n\/\/ function to resolve a shorturl and redirect\nfunc resolve(ctx *web.Context, short string) {\n        redirect, err := redis.Hget(short, \"LongUrl\")\n    if err == nil {\n        go redis.Hincrby(short, \"Clicks\", 1)\n        ctx.Redirect(http.StatusMovedPermanently,\n             redirect.String())\n    } else {\n        ctx.Redirect(http.StatusMovedPermanently,\n            ROLL)\n    }\n}\n\n\n\/\/ Determines if the string rawurl is a valid URL to be stored.\nfunc isValidUrl(rawurl string) (u *url.URL, err os.Error){\n    if len(rawurl) == 0{\n        return nil, os.NewError(\"empty url\")\n    }\n    \/\/ XXX this needs some love...\n    if !strings.HasPrefix(rawurl, HTTP){\n        rawurl = fmt.Sprintf(\"%s:\/\/%s\", HTTP, rawurl)\n    }\n    return url.Parse(rawurl)\n}\n\n\/\/ stores a new KurzUrl for the given key, shorturl and longurl. Existing\n\/\/ ones with the same url will be overwritten\nfunc store(key, shorturl, longurl string)*KurzUrl{\n    kurl := NewKurzUrl(key, shorturl, longurl)\n    go redis.Hset(kurl.Key, \"LongUrl\", kurl.LongUrl)\n    go redis.Hset(kurl.Key, \"ShortUrl\", kurl.ShortUrl)\n    go redis.Hset(kurl.Key, \"CreationDate\", kurl.CreationDate)\n    go redis.Hset(kurl.Key, \"Clicks\", kurl.Clicks)\n    return kurl\n}\n\n\/\/ loads a KurzUrl instance for the given key. If the key is\n\/\/ not found, os.Error is returned.\nfunc load(key string) (kurl *KurzUrl, err os.Error){\n    if ok, _ := redis.Hexists(key, \"ShortUrl\"); ok{\n        kurl := new(KurzUrl)\n        kurl.Key = key\n        reply, _ := redis.Hmget(key, \"LongUrl\", \"ShortUrl\", \"CreationDate\", \"Clicks\")\n        kurl.LongUrl, kurl.ShortUrl, kurl.CreationDate, kurl.Clicks =\n            reply.Elems[0].Elem.String(), reply.Elems[1].Elem.String(),\n            reply.Elems[2].Elem.Int64(), reply.Elems[3].Elem.Int64()\n        return kurl, nil\n    }\n    return nil, os.NewError(\"unknown key: \" + key )\n}\n\n\n\/\/ function to shorten and store a url\nfunc shorten(ctx *web.Context, data string){\n    host := config.GetStringDefault(\"hostname\", \"localhost\")\n    r, _ := ctx.Request.Params[\"url\"]\n    theUrl, err := isValidUrl(string(r))\n    if err == nil{\n        ctr, _ := redis.Incr(COUNTER)\n        encoded := Encode(ctr)\n        location := fmt.Sprintf(\"%s:\/\/%s\/%s\", HTTP, host, encoded)\n\n        kurl := store(encoded, location, theUrl.Raw)\n\n        ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n        ctx.SetHeader(\"Location\", location, true)\n        ctx.StartResponse(http.StatusCreated)\n        ctx.Write(kurl.Json())\n        ctx.WriteString(\"\\n\")\n    }else{\n       ctx.Redirect(http.StatusNotFound, ROLL)\n    }\n}\n\n\nfunc latest(ctx *web.Context, data string){\n    howmany, err := strconv.Atoi64(data)\n    if err != nil {\n        howmany = 10\n    }\n    c, _ := redis.Get(COUNTER)\n\n    last := c.Int64()\n    upTo := (last - howmany)\n\n    ctx.SetHeader(\"Content-Type\", \"application\/json\", true)\n    ctx.WriteString(\"{ \\\"urls\\\" : [\")\n    for i := last; i > upTo && i > 0; i -= 1{\n        kurl, err := load(Encode(i))\n        if err == nil{\n            ctx.Write(kurl.Json())\n            if i != upTo + 1 {\n                ctx.WriteString(\",\")\n            }\n        }\n    }\n    ctx.WriteString(\"] }\")\n    ctx.WriteString(\"\\n\")\n}\n\n\n\/\/ bootstraps the server\nfunc bootstrap(path string) os.Error {\n    config = NewConfig(path)\n    config.Parse()\n\n    host := config.GetStringDefault(\"redis.address\", \"tcp:localhost:6379\")\n    db := config.GetIntDefault(\"redis.database\", 0)\n    passwd := config.GetStringDefault(\"redis.password\", \"\")\n\n    redis = godis.New(host, db, passwd)\n\n    web.Config.StaticDir = config.GetStringDefault(\"static-directory\", \"\")\n\n    web.Post(\"\/shorten\/(.*)\", shorten)\n\n    web.Get(\"\/([a-zA-Z0-9]*)\", resolve)\n    web.Get(\"\/([a-zA-Z0-9]*)\\\\+\", info)\n    web.Get(\"\/latest\/([0-9]*)\", latest)\n    web.Get(\"\/info\/([a-zA-Z0-9]*)\", info)\n\n    return nil\n}\n\n\n\/\/ main function that starts everything\nfunc main() {\n    flag.Parse()\n    cfgFile := flag.Arg(0)\n    err := bootstrap(cfgFile)\n    if err == nil {\n                listen := config.GetStringDefault(\"listen\", \"0.0.0.0\")\n        port := config.GetStringDefault(\"port\", \"9999\")\n        web.Run(fmt.Sprintf(\"%s:%s\", listen, port))\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package azurerm\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/arm\/keyvault\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n\t\"github.com\/satori\/uuid\"\n\t\"github.com\/terraform-providers\/terraform-provider-azurerm\/azurerm\/utils\"\n)\n\n\/\/ As can be seen in the API definition, the Sku Family only supports the value\n\/\/ `A` and is a required field\n\/\/ https:\/\/github.com\/Azure\/azure-rest-api-specs\/blob\/master\/arm-keyvault\/2015-06-01\/swagger\/keyvault.json#L239\nvar armKeyVaultSkuFamily = \"A\"\n\nfunc resourceArmKeyVault() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceArmKeyVaultCreate,\n\t\tRead:   resourceArmKeyVaultRead,\n\t\tUpdate: resourceArmKeyVaultCreate,\n\t\tDelete: resourceArmKeyVaultDelete,\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\"name\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validateKeyVaultName,\n\t\t\t},\n\n\t\t\t\"location\": locationSchema(),\n\n\t\t\t\"resource_group_name\": resourceGroupNameSchema(),\n\n\t\t\t\"sku\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tRequired: 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\"name\": {\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\tstring(keyvault.Standard),\n\t\t\t\t\t\t\t\tstring(keyvault.Premium),\n\t\t\t\t\t\t\t}, false),\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\"vault_uri\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validateUUID,\n\t\t\t},\n\n\t\t\t\"access_policy\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tMinItems: 1,\n\t\t\t\tMaxItems: 16,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"tenant_id\": {\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: validateUUID,\n\t\t\t\t\t\t},\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\tRequired:     true,\n\t\t\t\t\t\t\tValidateFunc: validateUUID,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"application_id\": {\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\tValidateFunc: validateUUID,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"certificate_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.All),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Create),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Delete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Deleteissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Get),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Getissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Import),\n\t\t\t\t\t\t\t\t\tstring(keyvault.List),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Listissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Managecontacts),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Manageissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Setissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Update),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"key_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsAll),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsBackup),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsCreate),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsDecrypt),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsDelete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsEncrypt),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsGet),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsImport),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsList),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsRestore),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsSign),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsUnwrapKey),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsUpdate),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsVerify),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsWrapKey),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"secret_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsAll),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsDelete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsGet),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsList),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsSet),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\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\t\"enabled_for_deployment\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"enabled_for_disk_encryption\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"enabled_for_template_deployment\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceArmKeyVaultCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\tlog.Printf(\"[INFO] preparing arguments for Azure ARM KeyVault creation.\")\n\n\tname := d.Get(\"name\").(string)\n\tlocation := d.Get(\"location\").(string)\n\tresGroup := d.Get(\"resource_group_name\").(string)\n\ttenantUUID := uuid.FromStringOrNil(d.Get(\"tenant_id\").(string))\n\tenabledForDeployment := d.Get(\"enabled_for_deployment\").(bool)\n\tenabledForDiskEncryption := d.Get(\"enabled_for_disk_encryption\").(bool)\n\tenabledForTemplateDeployment := d.Get(\"enabled_for_template_deployment\").(bool)\n\ttags := d.Get(\"tags\").(map[string]interface{})\n\n\tparameters := keyvault.VaultCreateOrUpdateParameters{\n\t\tLocation: &location,\n\t\tProperties: &keyvault.VaultProperties{\n\t\t\tTenantID:                     &tenantUUID,\n\t\t\tSku:                          expandKeyVaultSku(d),\n\t\t\tAccessPolicies:               expandKeyVaultAccessPolicies(d),\n\t\t\tEnabledForDeployment:         &enabledForDeployment,\n\t\t\tEnabledForDiskEncryption:     &enabledForDiskEncryption,\n\t\t\tEnabledForTemplateDeployment: &enabledForTemplateDeployment,\n\t\t},\n\t\tTags: expandTags(tags),\n\t}\n\n\t_, err := client.CreateOrUpdate(resGroup, name, parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tread, err := client.Get(resGroup, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif read.ID == nil {\n\t\treturn fmt.Errorf(\"Cannot read KeyVault %s (resource group %s) ID\", name, resGroup)\n\t}\n\n\td.SetId(*read.ID)\n\n\treturn resourceArmKeyVaultRead(d, meta)\n}\n\nfunc resourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\n\tid, err := parseAzureResourceID(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\tresGroup := id.ResourceGroup\n\tname := id.Path[\"vaults\"]\n\n\tresp, err := client.Get(resGroup, name)\n\tif err != nil {\n\t\tif utils.ResponseWasNotFound(resp.Response) {\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Error making Read request on Azure KeyVault %s: %+v\", name, err)\n\t}\n\n\td.Set(\"name\", resp.Name)\n\td.Set(\"resource_group_name\", resGroup)\n\td.Set(\"location\", azureRMNormalizeLocation(*resp.Location))\n\td.Set(\"tenant_id\", resp.Properties.TenantID.String())\n\td.Set(\"enabled_for_deployment\", resp.Properties.EnabledForDeployment)\n\td.Set(\"enabled_for_disk_encryption\", resp.Properties.EnabledForDiskEncryption)\n\td.Set(\"enabled_for_template_deployment\", resp.Properties.EnabledForTemplateDeployment)\n\td.Set(\"sku\", flattenKeyVaultSku(resp.Properties.Sku))\n\td.Set(\"access_policy\", flattenKeyVaultAccessPolicies(resp.Properties.AccessPolicies))\n\td.Set(\"vault_uri\", resp.Properties.VaultURI)\n\n\tflattenAndSetTags(d, resp.Tags)\n\n\treturn nil\n}\n\nfunc resourceArmKeyVaultDelete(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\n\tid, err := parseAzureResourceID(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\tresGroup := id.ResourceGroup\n\tname := id.Path[\"vaults\"]\n\n\t_, err = client.Delete(resGroup, name)\n\n\treturn err\n}\n\nfunc expandKeyVaultSku(d *schema.ResourceData) *keyvault.Sku {\n\tskuSets := d.Get(\"sku\").(*schema.Set).List()\n\tsku := skuSets[0].(map[string]interface{})\n\n\treturn &keyvault.Sku{\n\t\tFamily: &armKeyVaultSkuFamily,\n\t\tName:   keyvault.SkuName(sku[\"name\"].(string)),\n\t}\n}\n\nfunc expandKeyVaultAccessPolicies(d *schema.ResourceData) *[]keyvault.AccessPolicyEntry {\n\tpolicies := d.Get(\"access_policy\").([]interface{})\n\tresult := make([]keyvault.AccessPolicyEntry, 0, len(policies))\n\n\tfor _, policySet := range policies {\n\t\tpolicyRaw := policySet.(map[string]interface{})\n\n\t\tcertificatePermissionsRaw := policyRaw[\"certificate_permissions\"].([]interface{})\n\t\tcertificatePermissions := []keyvault.CertificatePermissions{}\n\t\tfor _, permission := range certificatePermissionsRaw {\n\t\t\tcertificatePermissions = append(certificatePermissions, keyvault.CertificatePermissions(permission.(string)))\n\t\t}\n\n\t\tkeyPermissionsRaw := policyRaw[\"key_permissions\"].([]interface{})\n\t\tkeyPermissions := []keyvault.KeyPermissions{}\n\t\tfor _, permission := range keyPermissionsRaw {\n\t\t\tkeyPermissions = append(keyPermissions, keyvault.KeyPermissions(permission.(string)))\n\t\t}\n\n\t\tsecretPermissionsRaw := policyRaw[\"secret_permissions\"].([]interface{})\n\t\tsecretPermissions := []keyvault.SecretPermissions{}\n\t\tfor _, permission := range secretPermissionsRaw {\n\t\t\tsecretPermissions = append(secretPermissions, keyvault.SecretPermissions(permission.(string)))\n\t\t}\n\n\t\tpolicy := keyvault.AccessPolicyEntry{\n\t\t\tPermissions: &keyvault.Permissions{\n\t\t\t\tCertificates: &certificatePermissions,\n\t\t\t\tKeys:         &keyPermissions,\n\t\t\t\tSecrets:      &secretPermissions,\n\t\t\t},\n\t\t}\n\n\t\ttenantUUID := uuid.FromStringOrNil(policyRaw[\"tenant_id\"].(string))\n\t\tpolicy.TenantID = &tenantUUID\n\t\tobjectUUID := policyRaw[\"object_id\"].(string)\n\t\tpolicy.ObjectID = &objectUUID\n\n\t\tif v := policyRaw[\"application_id\"]; v != \"\" {\n\t\t\tapplicationUUID := uuid.FromStringOrNil(v.(string))\n\t\t\tpolicy.ApplicationID = &applicationUUID\n\t\t}\n\n\t\tresult = append(result, policy)\n\t}\n\n\treturn &result\n}\n\nfunc flattenKeyVaultSku(sku *keyvault.Sku) []interface{} {\n\tresult := map[string]interface{}{\n\t\t\"name\": string(sku.Name),\n\t}\n\n\treturn []interface{}{result}\n}\n\nfunc flattenKeyVaultAccessPolicies(policies *[]keyvault.AccessPolicyEntry) []interface{} {\n\tresult := make([]interface{}, 0, len(*policies))\n\n\tfor _, policy := range *policies {\n\t\tpolicyRaw := make(map[string]interface{})\n\n\t\tkeyPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Keys))\n\t\tfor _, keyPermission := range *policy.Permissions.Keys {\n\t\t\tkeyPermissionsRaw = append(keyPermissionsRaw, string(keyPermission))\n\t\t}\n\n\t\tsecretPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Secrets))\n\t\tfor _, secretPermission := range *policy.Permissions.Secrets {\n\t\t\tsecretPermissionsRaw = append(secretPermissionsRaw, string(secretPermission))\n\t\t}\n\n\t\tpolicyRaw[\"tenant_id\"] = policy.TenantID.String()\n\t\tpolicyRaw[\"object_id\"] = *policy.ObjectID\n\t\tif policy.ApplicationID != nil {\n\t\t\tpolicyRaw[\"application_id\"] = policy.ApplicationID.String()\n\t\t}\n\t\tpolicyRaw[\"key_permissions\"] = keyPermissionsRaw\n\t\tpolicyRaw[\"secret_permissions\"] = secretPermissionsRaw\n\n\t\tif policy.Permissions.Certificates != nil {\n\t\t\tcertificatePermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Certificates))\n\t\t\tfor _, certificatePermission := range *policy.Permissions.Certificates {\n\t\t\t\tcertificatePermissionsRaw = append(certificatePermissionsRaw, string(certificatePermission))\n\t\t\t}\n\t\t\tpolicyRaw[\"certificate_permissions\"] = certificatePermissionsRaw\n\t\t}\n\n\t\tresult = append(result, policyRaw)\n\t}\n\n\treturn result\n}\n\nfunc validateKeyVaultName(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\tif matched := regexp.MustCompile(`^[a-zA-Z0-9-]{3,24}$`).Match([]byte(value)); !matched {\n\t\terrors = append(errors, fmt.Errorf(\"%q may only contain alphanumeric characters and dashes and must be between 3-24 chars\", k))\n\t}\n\n\treturn\n}\n<commit_msg>Ensuring the Key Vault is available before completion<commit_after>package azurerm\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\n\t\"time\"\n\n\t\"net\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/arm\/keyvault\"\n\t\"github.com\/hashicorp\/go-getter\/helper\/url\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n\t\"github.com\/satori\/uuid\"\n\t\"github.com\/terraform-providers\/terraform-provider-azurerm\/azurerm\/utils\"\n)\n\n\/\/ As can be seen in the API definition, the Sku Family only supports the value\n\/\/ `A` and is a required field\n\/\/ https:\/\/github.com\/Azure\/azure-rest-api-specs\/blob\/master\/arm-keyvault\/2015-06-01\/swagger\/keyvault.json#L239\nvar armKeyVaultSkuFamily = \"A\"\n\nfunc resourceArmKeyVault() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceArmKeyVaultCreate,\n\t\tRead:   resourceArmKeyVaultRead,\n\t\tUpdate: resourceArmKeyVaultCreate,\n\t\tDelete: resourceArmKeyVaultDelete,\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\"name\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validateKeyVaultName,\n\t\t\t},\n\n\t\t\t\"location\": locationSchema(),\n\n\t\t\t\"resource_group_name\": resourceGroupNameSchema(),\n\n\t\t\t\"sku\": {\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tRequired: 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\"name\": {\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\tstring(keyvault.Standard),\n\t\t\t\t\t\t\t\tstring(keyvault.Premium),\n\t\t\t\t\t\t\t}, false),\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\"vault_uri\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tenant_id\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validateUUID,\n\t\t\t},\n\n\t\t\t\"access_policy\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tMinItems: 1,\n\t\t\t\tMaxItems: 16,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"tenant_id\": {\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: validateUUID,\n\t\t\t\t\t\t},\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\tRequired:     true,\n\t\t\t\t\t\t\tValidateFunc: validateUUID,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"application_id\": {\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\tValidateFunc: validateUUID,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"certificate_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.All),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Create),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Delete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Deleteissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Get),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Getissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Import),\n\t\t\t\t\t\t\t\t\tstring(keyvault.List),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Listissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Managecontacts),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Manageissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Setissuers),\n\t\t\t\t\t\t\t\t\tstring(keyvault.Update),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"key_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsAll),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsBackup),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsCreate),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsDecrypt),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsDelete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsEncrypt),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsGet),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsImport),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsList),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsRestore),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsSign),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsUnwrapKey),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsUpdate),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsVerify),\n\t\t\t\t\t\t\t\t\tstring(keyvault.KeyPermissionsWrapKey),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"secret_permissions\": {\n\t\t\t\t\t\t\tType:     schema.TypeList,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsAll),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsDelete),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsGet),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsList),\n\t\t\t\t\t\t\t\t\tstring(keyvault.SecretPermissionsSet),\n\t\t\t\t\t\t\t\t}, true),\n\t\t\t\t\t\t\t\tDiffSuppressFunc: ignoreCaseDiffSuppressFunc,\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\t\"enabled_for_deployment\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"enabled_for_disk_encryption\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"enabled_for_template_deployment\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceArmKeyVaultCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\tlog.Printf(\"[INFO] preparing arguments for Azure ARM KeyVault creation.\")\n\n\tname := d.Get(\"name\").(string)\n\tlocation := d.Get(\"location\").(string)\n\tresGroup := d.Get(\"resource_group_name\").(string)\n\ttenantUUID := uuid.FromStringOrNil(d.Get(\"tenant_id\").(string))\n\tenabledForDeployment := d.Get(\"enabled_for_deployment\").(bool)\n\tenabledForDiskEncryption := d.Get(\"enabled_for_disk_encryption\").(bool)\n\tenabledForTemplateDeployment := d.Get(\"enabled_for_template_deployment\").(bool)\n\ttags := d.Get(\"tags\").(map[string]interface{})\n\n\tparameters := keyvault.VaultCreateOrUpdateParameters{\n\t\tLocation: &location,\n\t\tProperties: &keyvault.VaultProperties{\n\t\t\tTenantID:                     &tenantUUID,\n\t\t\tSku:                          expandKeyVaultSku(d),\n\t\t\tAccessPolicies:               expandKeyVaultAccessPolicies(d),\n\t\t\tEnabledForDeployment:         &enabledForDeployment,\n\t\t\tEnabledForDiskEncryption:     &enabledForDiskEncryption,\n\t\t\tEnabledForTemplateDeployment: &enabledForTemplateDeployment,\n\t\t},\n\t\tTags: expandTags(tags),\n\t}\n\n\t_, err := client.CreateOrUpdate(resGroup, name, parameters)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tread, err := client.Get(resGroup, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif read.ID == nil {\n\t\treturn fmt.Errorf(\"Cannot read KeyVault %s (resource group %s) ID\", name, resGroup)\n\t}\n\n\td.SetId(*read.ID)\n\n\tif d.IsNewResource() {\n\t\tif props := read.Properties; props != nil {\n\t\t\tif vault := props.VaultURI; vault != nil {\n\t\t\t\terr := resource.Retry(30*time.Second, checkKeyVaultDNSIsAvailable(*vault))\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\n\treturn resourceArmKeyVaultRead(d, meta)\n}\n\nfunc resourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\n\tid, err := parseAzureResourceID(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\tresGroup := id.ResourceGroup\n\tname := id.Path[\"vaults\"]\n\n\tresp, err := client.Get(resGroup, name)\n\tif err != nil {\n\t\tif utils.ResponseWasNotFound(resp.Response) {\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Error making Read request on Azure KeyVault %s: %+v\", name, err)\n\t}\n\n\td.Set(\"name\", resp.Name)\n\td.Set(\"resource_group_name\", resGroup)\n\td.Set(\"location\", azureRMNormalizeLocation(*resp.Location))\n\td.Set(\"tenant_id\", resp.Properties.TenantID.String())\n\td.Set(\"enabled_for_deployment\", resp.Properties.EnabledForDeployment)\n\td.Set(\"enabled_for_disk_encryption\", resp.Properties.EnabledForDiskEncryption)\n\td.Set(\"enabled_for_template_deployment\", resp.Properties.EnabledForTemplateDeployment)\n\td.Set(\"sku\", flattenKeyVaultSku(resp.Properties.Sku))\n\td.Set(\"access_policy\", flattenKeyVaultAccessPolicies(resp.Properties.AccessPolicies))\n\td.Set(\"vault_uri\", resp.Properties.VaultURI)\n\n\tflattenAndSetTags(d, resp.Tags)\n\n\treturn nil\n}\n\nfunc resourceArmKeyVaultDelete(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).keyVaultClient\n\n\tid, err := parseAzureResourceID(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\tresGroup := id.ResourceGroup\n\tname := id.Path[\"vaults\"]\n\n\t_, err = client.Delete(resGroup, name)\n\n\treturn err\n}\n\nfunc expandKeyVaultSku(d *schema.ResourceData) *keyvault.Sku {\n\tskuSets := d.Get(\"sku\").(*schema.Set).List()\n\tsku := skuSets[0].(map[string]interface{})\n\n\treturn &keyvault.Sku{\n\t\tFamily: &armKeyVaultSkuFamily,\n\t\tName:   keyvault.SkuName(sku[\"name\"].(string)),\n\t}\n}\n\nfunc expandKeyVaultAccessPolicies(d *schema.ResourceData) *[]keyvault.AccessPolicyEntry {\n\tpolicies := d.Get(\"access_policy\").([]interface{})\n\tresult := make([]keyvault.AccessPolicyEntry, 0, len(policies))\n\n\tfor _, policySet := range policies {\n\t\tpolicyRaw := policySet.(map[string]interface{})\n\n\t\tcertificatePermissionsRaw := policyRaw[\"certificate_permissions\"].([]interface{})\n\t\tcertificatePermissions := []keyvault.CertificatePermissions{}\n\t\tfor _, permission := range certificatePermissionsRaw {\n\t\t\tcertificatePermissions = append(certificatePermissions, keyvault.CertificatePermissions(permission.(string)))\n\t\t}\n\n\t\tkeyPermissionsRaw := policyRaw[\"key_permissions\"].([]interface{})\n\t\tkeyPermissions := []keyvault.KeyPermissions{}\n\t\tfor _, permission := range keyPermissionsRaw {\n\t\t\tkeyPermissions = append(keyPermissions, keyvault.KeyPermissions(permission.(string)))\n\t\t}\n\n\t\tsecretPermissionsRaw := policyRaw[\"secret_permissions\"].([]interface{})\n\t\tsecretPermissions := []keyvault.SecretPermissions{}\n\t\tfor _, permission := range secretPermissionsRaw {\n\t\t\tsecretPermissions = append(secretPermissions, keyvault.SecretPermissions(permission.(string)))\n\t\t}\n\n\t\tpolicy := keyvault.AccessPolicyEntry{\n\t\t\tPermissions: &keyvault.Permissions{\n\t\t\t\tCertificates: &certificatePermissions,\n\t\t\t\tKeys:         &keyPermissions,\n\t\t\t\tSecrets:      &secretPermissions,\n\t\t\t},\n\t\t}\n\n\t\ttenantUUID := uuid.FromStringOrNil(policyRaw[\"tenant_id\"].(string))\n\t\tpolicy.TenantID = &tenantUUID\n\t\tobjectUUID := policyRaw[\"object_id\"].(string)\n\t\tpolicy.ObjectID = &objectUUID\n\n\t\tif v := policyRaw[\"application_id\"]; v != \"\" {\n\t\t\tapplicationUUID := uuid.FromStringOrNil(v.(string))\n\t\t\tpolicy.ApplicationID = &applicationUUID\n\t\t}\n\n\t\tresult = append(result, policy)\n\t}\n\n\treturn &result\n}\n\nfunc flattenKeyVaultSku(sku *keyvault.Sku) []interface{} {\n\tresult := map[string]interface{}{\n\t\t\"name\": string(sku.Name),\n\t}\n\n\treturn []interface{}{result}\n}\n\nfunc flattenKeyVaultAccessPolicies(policies *[]keyvault.AccessPolicyEntry) []interface{} {\n\tresult := make([]interface{}, 0, len(*policies))\n\n\tfor _, policy := range *policies {\n\t\tpolicyRaw := make(map[string]interface{})\n\n\t\tkeyPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Keys))\n\t\tfor _, keyPermission := range *policy.Permissions.Keys {\n\t\t\tkeyPermissionsRaw = append(keyPermissionsRaw, string(keyPermission))\n\t\t}\n\n\t\tsecretPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Secrets))\n\t\tfor _, secretPermission := range *policy.Permissions.Secrets {\n\t\t\tsecretPermissionsRaw = append(secretPermissionsRaw, string(secretPermission))\n\t\t}\n\n\t\tpolicyRaw[\"tenant_id\"] = policy.TenantID.String()\n\t\tpolicyRaw[\"object_id\"] = *policy.ObjectID\n\t\tif policy.ApplicationID != nil {\n\t\t\tpolicyRaw[\"application_id\"] = policy.ApplicationID.String()\n\t\t}\n\t\tpolicyRaw[\"key_permissions\"] = keyPermissionsRaw\n\t\tpolicyRaw[\"secret_permissions\"] = secretPermissionsRaw\n\n\t\tif policy.Permissions.Certificates != nil {\n\t\t\tcertificatePermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Certificates))\n\t\t\tfor _, certificatePermission := range *policy.Permissions.Certificates {\n\t\t\t\tcertificatePermissionsRaw = append(certificatePermissionsRaw, string(certificatePermission))\n\t\t\t}\n\t\t\tpolicyRaw[\"certificate_permissions\"] = certificatePermissionsRaw\n\t\t}\n\n\t\tresult = append(result, policyRaw)\n\t}\n\n\treturn result\n}\n\nfunc validateKeyVaultName(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\tif matched := regexp.MustCompile(`^[a-zA-Z0-9-]{3,24}$`).Match([]byte(value)); !matched {\n\t\terrors = append(errors, fmt.Errorf(\"%q may only contain alphanumeric characters and dashes and must be between 3-24 chars\", k))\n\t}\n\n\treturn\n}\n\nfunc checkKeyVaultDNSIsAvailable(vaultUri string) func() *resource.RetryError {\n\treturn func() *resource.RetryError {\n\t\turi, err := url.Parse(vaultUri)\n\t\tif err != nil {\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\n\t\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:443\", uri.Host))\n\t\tif err != nil {\n\t\t\treturn resource.RetryableError(err)\n\t\t}\n\n\t\t_ = conn.Close()\n\t\treturn nil\n\t}\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 bloom\n\nimport (\n\t\"encoding\/binary\"\n\t\"math\"\n\t\"sync\"\n\n\t\"github.com\/btcboost\/copernicus\/model\/outpoint\"\n\t\"github.com\/btcboost\/copernicus\/model\/script\"\n\t\"github.com\/btcboost\/copernicus\/model\/tx\"\n\t\"github.com\/btcboost\/copernicus\/net\/wire\"\n\t\"github.com\/btcboost\/copernicus\/util\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype MsgTx tx.Tx\n\n\/\/ ln2Squared is simply the square of the natural log of 2.\nconst ln2Squared = math.Ln2 * math.Ln2\n\n\/\/ minUint32 is a convenience function to return the minimum value of the two\n\/\/ passed uint32 values.\nfunc minUint32(a, b uint32) uint32 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\/\/ Filter defines a bitcoin bloom filter that provides easy manipulation of raw\n\/\/ filter data.\ntype Filter struct {\n\tmtx           sync.Mutex\n\tmsgFilterLoad *wire.MsgFilterLoad\n}\n\n\/\/ NewFilter creates a new bloom filter instance, mainly to be used by SPV\n\/\/ clients.  The tweak parameter is a random value added to the seed value.\n\/\/ The false positive rate is the probability of a false positive where 1.0 is\n\/\/ \"match everything\" and zero is unachievable.  Thus, providing any false\n\/\/ positive rates less than 0 or greater than 1 will be adjusted to the valid\n\/\/ range.\n\/\/\n\/\/ For more information on what values to use for both elements and fprate,\n\/\/ see https:\/\/en.wikipedia.org\/wiki\/Bloom_filter.\nfunc NewFilter(elements, tweak uint32, fprate float64, flags wire.BloomUpdateType) *Filter {\n\t\/\/ Massage the false positive rate to sane values.\n\tif fprate > 1.0 {\n\t\tfprate = 1.0\n\t}\n\tif fprate < 1e-9 {\n\t\tfprate = 1e-9\n\t}\n\n\t\/\/ Calculate the size of the filter in bytes for the given number of\n\t\/\/ elements and false positive rate.\n\t\/\/\n\t\/\/ Equivalent to m = -(n*ln(p) \/ ln(2)^2), where m is in bits.\n\t\/\/ Then clamp it to the maximum filter size and convert to bytes.\n\tdataLen := uint32(-1 * float64(elements) * math.Log(fprate) \/ ln2Squared)\n\tdataLen = minUint32(dataLen, wire.MaxFilterLoadFilterSize*8) \/ 8\n\n\t\/\/ Calculate the number of hash functions based on the size of the\n\t\/\/ filter calculated above and the number of elements.\n\t\/\/\n\t\/\/ Equivalent to k = (m\/n) * ln(2)\n\t\/\/ Then clamp it to the maximum allowed hash funcs.\n\thashFuncs := uint32(float64(dataLen*8) \/ float64(elements) * math.Ln2)\n\thashFuncs = minUint32(hashFuncs, wire.MaxFilterLoadHashFuncs)\n\n\tdata := make([]byte, dataLen)\n\tmsg := wire.NewMsgFilterLoad(data, hashFuncs, tweak, flags)\n\n\treturn &Filter{\n\t\tmsgFilterLoad: msg,\n\t}\n}\n\n\/\/ LoadFilter creates a new Filter instance with the given underlying\n\/\/ wire.MsgFilterLoad.\nfunc LoadFilter(filter *wire.MsgFilterLoad) *Filter {\n\treturn &Filter{\n\t\tmsgFilterLoad: filter,\n\t}\n}\n\n\/\/ IsLoaded returns true if a filter is loaded, otherwise false.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) IsLoaded() bool {\n\tbf.mtx.Lock()\n\tloaded := bf.msgFilterLoad != nil\n\tbf.mtx.Unlock()\n\treturn loaded\n}\n\n\/\/ Reload loads a new filter replacing any existing filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Reload(filter *wire.MsgFilterLoad) {\n\tbf.mtx.Lock()\n\tbf.msgFilterLoad = filter\n\tbf.mtx.Unlock()\n}\n\n\/\/ Unload unloads the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Unload() {\n\tbf.mtx.Lock()\n\tbf.msgFilterLoad = nil\n\tbf.mtx.Unlock()\n}\n\n\/\/ hash returns the bit offset in the bloom filter which corresponds to the\n\/\/ passed data for the given indepedent hash function number.\nfunc (bf *Filter) hash(hashNum uint32, data []byte) uint32 {\n\t\/\/ bitcoind: 0xfba4c795 chosen as it guarantees a reasonable bit\n\t\/\/ difference between hashNum values.\n\t\/\/\n\t\/\/ Note that << 3 is equivalent to multiplying by 8, but is faster.\n\t\/\/ Thus the returned hash is brought into range of the number of bits\n\t\/\/ the filter has and returned.\n\tmm := MurmurHash3(hashNum*0xfba4c795+bf.msgFilterLoad.Tweak, data)\n\treturn mm % (uint32(len(bf.msgFilterLoad.Filter)) << 3)\n}\n\n\/\/ matches returns true if the bloom filter might contain the passed data and\n\/\/ false if it definitely does not.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matches(data []byte) bool {\n\tif bf.msgFilterLoad == nil {\n\t\treturn false\n\t}\n\n\t\/\/ The bloom filter does not contain the data if any of the bit offsets\n\t\/\/ which result from hashing the data using each independent hash\n\t\/\/ function are not set.  The shifts and masks below are a faster\n\t\/\/ equivalent of:\n\t\/\/   arrayIndex := idx \/ 8     (idx >> 3)\n\t\/\/   bitOffset := idx % 8      (idx & 7)\n\t\/\/\/  if filter[arrayIndex] & 1<<bitOffset == 0 { ... }\n\tfor i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ {\n\t\tidx := bf.hash(i, data)\n\t\tif bf.msgFilterLoad.Filter[idx>>3]&(1<<(idx&7)) == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Matches returns true if the bloom filter might contain the passed data and\n\/\/ false if it definitely does not.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Matches(data []byte) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matches(data)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ matchesOutPoint returns true if the bloom filter might contain the passed\n\/\/ outpoint and false if it definitely does not.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matchesOutPoint(outpoint *outpoint.OutPoint) bool {\n\t\/\/ Serialize\n\tvar buf [util.Hash256Size + 4]byte\n\tcopy(buf[:], outpoint.Hash[:])\n\tbinary.LittleEndian.PutUint32(buf[util.Hash256Size:], outpoint.Index)\n\n\treturn bf.matches(buf[:])\n}\n\n\/\/ MatchesOutPoint returns true if the bloom filter might contain the passed\n\/\/ outpoint and false if it definitely does not.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MatchesOutPoint(outpoint *outpoint.OutPoint) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matchesOutPoint(outpoint)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ add adds the passed byte slice to the bloom filter.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) add(data []byte) {\n\tif bf.msgFilterLoad == nil {\n\t\treturn\n\t}\n\n\t\/\/ Adding data to a bloom filter consists of setting all of the bit\n\t\/\/ offsets which result from hashing the data using each independent\n\t\/\/ hash function.  The shifts and masks below are a faster equivalent\n\t\/\/ of:\n\t\/\/   arrayIndex := idx \/ 8    (idx >> 3)\n\t\/\/   bitOffset := idx % 8     (idx & 7)\n\t\/\/\/  filter[arrayIndex] |= 1<<bitOffset\n\tfor i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ {\n\t\tidx := bf.hash(i, data)\n\t\tbf.msgFilterLoad.Filter[idx>>3] |= (1 << (7 & idx))\n\t}\n}\n\n\/\/ Add adds the passed byte slice to the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Add(data []byte) {\n\tbf.mtx.Lock()\n\tbf.add(data)\n\tbf.mtx.Unlock()\n}\n\n\/\/ AddHash adds the passed chainhash.Hash to the Filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) AddHash(hash *util.Hash) {\n\tbf.mtx.Lock()\n\tbf.add(hash[:])\n\tbf.mtx.Unlock()\n}\n\n\/\/ addOutPoint adds the passed transaction outpoint to the bloom filter.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) addOutPoint(outpoint *outpoint.OutPoint) {\n\t\/\/ Serialize\n\tvar buf [util.Hash256Size + 4]byte\n\tcopy(buf[:], outpoint.Hash[:])\n\tbinary.LittleEndian.PutUint32(buf[util.Hash256Size:], outpoint.Index)\n\n\tbf.add(buf[:])\n}\n\n\/\/ AddOutPoint adds the passed transaction outpoint to the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) AddOutPoint(outpoint *outpoint.OutPoint) {\n\tbf.mtx.Lock()\n\tbf.addOutPoint(outpoint)\n\tbf.mtx.Unlock()\n}\n\n\/\/ maybeAddOutpoint potentially adds the passed outpoint to the bloom filter\n\/\/ depending on the bloom update flags and the type of the passed public key\n\/\/ script.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) maybeAddOutpoint(outHash *util.Hash, outIdx uint32) {\n\tswitch bf.msgFilterLoad.Flags {\n\tcase wire.BloomUpdateAll:\n\t\toutpoint := outpoint.NewOutPoint(outHash, outIdx)\n\t\tbf.addOutPoint(outpoint)\n\tcase wire.BloomUpdateP2PubkeyOnly:\n\t\tvar sc *script.Script\n\t\tclass, err := sc.CheckScriptPubKeyStandard()\n\t\tif err != nil {\n\t\t\terrors.New(\"The script not standard...\")\n\t\t} else if class == script.ScriptPubkey || class == script.ScriptMultiSig {\n\t\t\toutpoint := outpoint.NewOutPoint(outHash, outIdx)\n\t\t\tbf.addOutPoint(outpoint)\n\t\t}\n\t}\n}\n\n\/\/ matchTxAndUpdate returns true if the bloom filter matches data within the\n\/\/ passed transaction, otherwise false is returned.  If the filter does match\n\/\/ the passed transaction, it will also update the filter depending on the bloom\n\/\/ update flags set via the loaded filter if needed.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matchTxAndUpdate(tx *tx.Tx) bool {\n\t\/\/ Check if the filter matches the hash of the transaction.\n\t\/\/ This is useful for finding transactions when they appear in a block.\n\tmatched := bf.matches(tx.GetHash()[:])\n\n\t\/\/ Check if the filter matches any data elements in the public key\n\t\/\/ scripts of any of the outputs.  When it does, add the outpoint that\n\t\/\/ matched so transactions which spend from the matched transaction are\n\t\/\/ also included in the filter.  This removes the burden of updating the\n\t\/\/ filter for this scenario from the client.  It is also more efficient\n\t\/\/ on the network since it avoids the need for another filteradd message\n\t\/\/ from the client and avoids some potential races that could otherwise\n\t\/\/ occur.\n\n\t\/\/for i, txOut := range tx.GetOuts() {\n\t\/\/\tpushedData, err := script.PushedData(txOut.GetScriptPubKey())\n\t\/\/\tif err != nil {\n\t\/\/\t\tcontinue\n\t\/\/\t}\n\t\/\/\n\t\/\/\tfor _, data := range pushedData {\n\t\/\/\t\tif !bf.matches(data) {\n\t\/\/\t\t\tcontinue\n\t\/\/\t\t}\n\t\/\/\n\t\/\/\t\tmatched = true\n\t\/\/\t\thash := tx.GetHash()\n\t\/\/\t\tbf.maybeAddOutpoint(&hash, uint32(i))\n\t\/\/\t\tbreak\n\t\/\/\t}\n\t\/\/}\n\n\t\/\/ Nothing more to do if a match has already been made.\n\tif matched {\n\t\treturn true\n\t}\n\n\t\/\/ At this point, the transaction and none of the data elements in the\n\t\/\/ public key scripts of its outputs matched.\n\n\t\/\/ Check if the filter matches any outpoints this transaction spends or\n\t\/\/ any any data elements in the signature scripts of any of the inputs.\n\n\t\/\/for _, txin := range tx.GetIns() {\n\t\/\/\tif bf.matchesOutPoint(txin.PreviousOutPoint) {\n\t\/\/\t\treturn true\n\t\/\/\t}\n\t\/\/\n\t\/\/\tpushedData, err := script.PushedData(txin.GetScriptSig())\n\t\/\/\tif err != nil {\n\t\/\/\t\tcontinue\n\t\/\/\t}\n\t\/\/\tfor _, data := range pushedData {\n\t\/\/\t\tif bf.matches(data) {\n\t\/\/\t\t\treturn true\n\t\/\/\t\t}\n\t\/\/\t}\n\t\/\/}\n\n\treturn false\n}\n\n\/\/ MatchTxAndUpdate returns true if the bloom filter matches data within the\n\/\/ passed transaction, otherwise false is returned.  If the filter does match\n\/\/ the passed transaction, it will also update the filter depending on the bloom\n\/\/ update flags set via the loaded filter if needed.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MatchTxAndUpdate(tx *tx.Tx) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matchTxAndUpdate(tx)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ MsgFilterLoad returns the underlying wire.MsgFilterLoad for the bloom\n\/\/ filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MsgFilterLoad() *wire.MsgFilterLoad {\n\tbf.mtx.Lock()\n\tmsg := bf.msgFilterLoad\n\tbf.mtx.Unlock()\n\treturn msg\n}\n<commit_msg>fix filter.go<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 bloom\n\nimport (\n\t\"encoding\/binary\"\n\t\"math\"\n\t\"sync\"\n\n\t\"github.com\/btcboost\/copernicus\/model\/outpoint\"\n\t\/\/ \"github.com\/btcboost\/copernicus\/model\/script\"\n\t\"github.com\/btcboost\/copernicus\/model\/tx\"\n\t\"github.com\/btcboost\/copernicus\/net\/wire\"\n\t\"github.com\/btcboost\/copernicus\/util\"\n\t\/\/ \"github.com\/pkg\/errors\"\n)\n\ntype MsgTx tx.Tx\n\n\/\/ ln2Squared is simply the square of the natural log of 2.\nconst ln2Squared = math.Ln2 * math.Ln2\n\n\/\/ minUint32 is a convenience function to return the minimum value of the two\n\/\/ passed uint32 values.\nfunc minUint32(a, b uint32) uint32 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n\/\/ Filter defines a bitcoin bloom filter that provides easy manipulation of raw\n\/\/ filter data.\ntype Filter struct {\n\tmtx           sync.Mutex\n\tmsgFilterLoad *wire.MsgFilterLoad\n}\n\n\/\/ NewFilter creates a new bloom filter instance, mainly to be used by SPV\n\/\/ clients.  The tweak parameter is a random value added to the seed value.\n\/\/ The false positive rate is the probability of a false positive where 1.0 is\n\/\/ \"match everything\" and zero is unachievable.  Thus, providing any false\n\/\/ positive rates less than 0 or greater than 1 will be adjusted to the valid\n\/\/ range.\n\/\/\n\/\/ For more information on what values to use for both elements and fprate,\n\/\/ see https:\/\/en.wikipedia.org\/wiki\/Bloom_filter.\nfunc NewFilter(elements, tweak uint32, fprate float64, flags wire.BloomUpdateType) *Filter {\n\t\/\/ Massage the false positive rate to sane values.\n\tif fprate > 1.0 {\n\t\tfprate = 1.0\n\t}\n\tif fprate < 1e-9 {\n\t\tfprate = 1e-9\n\t}\n\n\t\/\/ Calculate the size of the filter in bytes for the given number of\n\t\/\/ elements and false positive rate.\n\t\/\/\n\t\/\/ Equivalent to m = -(n*ln(p) \/ ln(2)^2), where m is in bits.\n\t\/\/ Then clamp it to the maximum filter size and convert to bytes.\n\tdataLen := uint32(-1 * float64(elements) * math.Log(fprate) \/ ln2Squared)\n\tdataLen = minUint32(dataLen, wire.MaxFilterLoadFilterSize*8) \/ 8\n\n\t\/\/ Calculate the number of hash functions based on the size of the\n\t\/\/ filter calculated above and the number of elements.\n\t\/\/\n\t\/\/ Equivalent to k = (m\/n) * ln(2)\n\t\/\/ Then clamp it to the maximum allowed hash funcs.\n\thashFuncs := uint32(float64(dataLen*8) \/ float64(elements) * math.Ln2)\n\thashFuncs = minUint32(hashFuncs, wire.MaxFilterLoadHashFuncs)\n\n\tdata := make([]byte, dataLen)\n\tmsg := wire.NewMsgFilterLoad(data, hashFuncs, tweak, flags)\n\n\treturn &Filter{\n\t\tmsgFilterLoad: msg,\n\t}\n}\n\n\/\/ LoadFilter creates a new Filter instance with the given underlying\n\/\/ wire.MsgFilterLoad.\nfunc LoadFilter(filter *wire.MsgFilterLoad) *Filter {\n\treturn &Filter{\n\t\tmsgFilterLoad: filter,\n\t}\n}\n\n\/\/ IsLoaded returns true if a filter is loaded, otherwise false.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) IsLoaded() bool {\n\tbf.mtx.Lock()\n\tloaded := bf.msgFilterLoad != nil\n\tbf.mtx.Unlock()\n\treturn loaded\n}\n\n\/\/ Reload loads a new filter replacing any existing filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Reload(filter *wire.MsgFilterLoad) {\n\tbf.mtx.Lock()\n\tbf.msgFilterLoad = filter\n\tbf.mtx.Unlock()\n}\n\n\/\/ Unload unloads the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Unload() {\n\tbf.mtx.Lock()\n\tbf.msgFilterLoad = nil\n\tbf.mtx.Unlock()\n}\n\n\/\/ hash returns the bit offset in the bloom filter which corresponds to the\n\/\/ passed data for the given indepedent hash function number.\nfunc (bf *Filter) hash(hashNum uint32, data []byte) uint32 {\n\t\/\/ bitcoind: 0xfba4c795 chosen as it guarantees a reasonable bit\n\t\/\/ difference between hashNum values.\n\t\/\/\n\t\/\/ Note that << 3 is equivalent to multiplying by 8, but is faster.\n\t\/\/ Thus the returned hash is brought into range of the number of bits\n\t\/\/ the filter has and returned.\n\tmm := MurmurHash3(hashNum*0xfba4c795+bf.msgFilterLoad.Tweak, data)\n\treturn mm % (uint32(len(bf.msgFilterLoad.Filter)) << 3)\n}\n\n\/\/ matches returns true if the bloom filter might contain the passed data and\n\/\/ false if it definitely does not.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matches(data []byte) bool {\n\tif bf.msgFilterLoad == nil {\n\t\treturn false\n\t}\n\n\t\/\/ The bloom filter does not contain the data if any of the bit offsets\n\t\/\/ which result from hashing the data using each independent hash\n\t\/\/ function are not set.  The shifts and masks below are a faster\n\t\/\/ equivalent of:\n\t\/\/   arrayIndex := idx \/ 8     (idx >> 3)\n\t\/\/   bitOffset := idx % 8      (idx & 7)\n\t\/\/\/  if filter[arrayIndex] & 1<<bitOffset == 0 { ... }\n\tfor i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ {\n\t\tidx := bf.hash(i, data)\n\t\tif bf.msgFilterLoad.Filter[idx>>3]&(1<<(idx&7)) == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Matches returns true if the bloom filter might contain the passed data and\n\/\/ false if it definitely does not.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Matches(data []byte) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matches(data)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ matchesOutPoint returns true if the bloom filter might contain the passed\n\/\/ outpoint and false if it definitely does not.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matchesOutPoint(outpoint *outpoint.OutPoint) bool {\n\t\/\/ Serialize\n\tvar buf [util.Hash256Size + 4]byte\n\tcopy(buf[:], outpoint.Hash[:])\n\tbinary.LittleEndian.PutUint32(buf[util.Hash256Size:], outpoint.Index)\n\n\treturn bf.matches(buf[:])\n}\n\n\/\/ MatchesOutPoint returns true if the bloom filter might contain the passed\n\/\/ outpoint and false if it definitely does not.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MatchesOutPoint(outpoint *outpoint.OutPoint) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matchesOutPoint(outpoint)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ add adds the passed byte slice to the bloom filter.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) add(data []byte) {\n\tif bf.msgFilterLoad == nil {\n\t\treturn\n\t}\n\n\t\/\/ Adding data to a bloom filter consists of setting all of the bit\n\t\/\/ offsets which result from hashing the data using each independent\n\t\/\/ hash function.  The shifts and masks below are a faster equivalent\n\t\/\/ of:\n\t\/\/   arrayIndex := idx \/ 8    (idx >> 3)\n\t\/\/   bitOffset := idx % 8     (idx & 7)\n\t\/\/\/  filter[arrayIndex] |= 1<<bitOffset\n\tfor i := uint32(0); i < bf.msgFilterLoad.HashFuncs; i++ {\n\t\tidx := bf.hash(i, data)\n\t\tbf.msgFilterLoad.Filter[idx>>3] |= (1 << (7 & idx))\n\t}\n}\n\n\/\/ Add adds the passed byte slice to the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) Add(data []byte) {\n\tbf.mtx.Lock()\n\tbf.add(data)\n\tbf.mtx.Unlock()\n}\n\n\/\/ AddHash adds the passed chainhash.Hash to the Filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) AddHash(hash *util.Hash) {\n\tbf.mtx.Lock()\n\tbf.add(hash[:])\n\tbf.mtx.Unlock()\n}\n\n\/\/ addOutPoint adds the passed transaction outpoint to the bloom filter.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) addOutPoint(outpoint *outpoint.OutPoint) {\n\t\/\/ Serialize\n\tvar buf [util.Hash256Size + 4]byte\n\tcopy(buf[:], outpoint.Hash[:])\n\tbinary.LittleEndian.PutUint32(buf[util.Hash256Size:], outpoint.Index)\n\n\tbf.add(buf[:])\n}\n\n\/\/ AddOutPoint adds the passed transaction outpoint to the bloom filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) AddOutPoint(outpoint *outpoint.OutPoint) {\n\tbf.mtx.Lock()\n\tbf.addOutPoint(outpoint)\n\tbf.mtx.Unlock()\n}\n\n\/\/ maybeAddOutpoint potentially adds the passed outpoint to the bloom filter\n\/\/ depending on the bloom update flags and the type of the passed public key\n\/\/ script.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) maybeAddOutpoint(outHash *util.Hash, outIdx uint32) {\n\t\/\/ switch bf.msgFilterLoad.Flags {\n\t\/\/ case wire.BloomUpdateAll:\n\t\/\/ \toutpoint := outpoint.NewOutPoint(outHash, outIdx)\n\t\/\/ \tbf.addOutPoint(outpoint)\n\t\/\/ case wire.BloomUpdateP2PubkeyOnly:\n\t\/\/ \tvar sc *script.Script\n\t\/\/ \tclass, err := sc.CheckScriptPubKeyStandard()\n\t\/\/ \tif err != nil {\n\t\/\/ \t\terrors.New(\"The script not standard...\")\n\t\/\/ \t} else if class == script.ScriptPubkey || class == script.ScriptMultiSig {\n\t\/\/ \t\toutpoint := outpoint.NewOutPoint(outHash, outIdx)\n\t\/\/ \t\tbf.addOutPoint(outpoint)\n\t\/\/ \t}\n\t\/\/ }\n}\n\n\/\/ matchTxAndUpdate returns true if the bloom filter matches data within the\n\/\/ passed transaction, otherwise false is returned.  If the filter does match\n\/\/ the passed transaction, it will also update the filter depending on the bloom\n\/\/ update flags set via the loaded filter if needed.\n\/\/\n\/\/ This function MUST be called with the filter lock held.\nfunc (bf *Filter) matchTxAndUpdate(tx *tx.Tx) bool {\n\t\/\/ Check if the filter matches the hash of the transaction.\n\t\/\/ This is useful for finding transactions when they appear in a block.\n\t\/\/ matched := bf.matches(tx.GetHash()[:])\n\n\t\/\/ Check if the filter matches any data elements in the public key\n\t\/\/ scripts of any of the outputs.  When it does, add the outpoint that\n\t\/\/ matched so transactions which spend from the matched transaction are\n\t\/\/ also included in the filter.  This removes the burden of updating the\n\t\/\/ filter for this scenario from the client.  It is also more efficient\n\t\/\/ on the network since it avoids the need for another filteradd message\n\t\/\/ from the client and avoids some potential races that could otherwise\n\t\/\/ occur.\n\n\t\/\/for i, txOut := range tx.GetOuts() {\n\t\/\/\tpushedData, err := script.PushedData(txOut.GetScriptPubKey())\n\t\/\/\tif err != nil {\n\t\/\/\t\tcontinue\n\t\/\/\t}\n\t\/\/\n\t\/\/\tfor _, data := range pushedData {\n\t\/\/\t\tif !bf.matches(data) {\n\t\/\/\t\t\tcontinue\n\t\/\/\t\t}\n\t\/\/\n\t\/\/\t\tmatched = true\n\t\/\/\t\thash := tx.GetHash()\n\t\/\/\t\tbf.maybeAddOutpoint(&hash, uint32(i))\n\t\/\/\t\tbreak\n\t\/\/\t}\n\t\/\/}\n\n\t\/\/ Nothing more to do if a match has already been made.\n\t\/\/ if matched {\n\t\/\/ \treturn true\n\t\/\/ }\n\n\t\/\/ At this point, the transaction and none of the data elements in the\n\t\/\/ public key scripts of its outputs matched.\n\n\t\/\/ Check if the filter matches any outpoints this transaction spends or\n\t\/\/ any any data elements in the signature scripts of any of the inputs.\n\n\t\/\/for _, txin := range tx.GetIns() {\n\t\/\/\tif bf.matchesOutPoint(txin.PreviousOutPoint) {\n\t\/\/\t\treturn true\n\t\/\/\t}\n\t\/\/\n\t\/\/\tpushedData, err := script.PushedData(txin.GetScriptSig())\n\t\/\/\tif err != nil {\n\t\/\/\t\tcontinue\n\t\/\/\t}\n\t\/\/\tfor _, data := range pushedData {\n\t\/\/\t\tif bf.matches(data) {\n\t\/\/\t\t\treturn true\n\t\/\/\t\t}\n\t\/\/\t}\n\t\/\/}\n\n\treturn false\n}\n\n\/\/ MatchTxAndUpdate returns true if the bloom filter matches data within the\n\/\/ passed transaction, otherwise false is returned.  If the filter does match\n\/\/ the passed transaction, it will also update the filter depending on the bloom\n\/\/ update flags set via the loaded filter if needed.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MatchTxAndUpdate(tx *tx.Tx) bool {\n\tbf.mtx.Lock()\n\tmatch := bf.matchTxAndUpdate(tx)\n\tbf.mtx.Unlock()\n\treturn match\n}\n\n\/\/ MsgFilterLoad returns the underlying wire.MsgFilterLoad for the bloom\n\/\/ filter.\n\/\/\n\/\/ This function is safe for concurrent access.\nfunc (bf *Filter) MsgFilterLoad() *wire.MsgFilterLoad {\n\tbf.mtx.Lock()\n\tmsg := bf.msgFilterLoad\n\tbf.mtx.Unlock()\n\treturn msg\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 template\n\nimport (\n\t\"bytes\";\n\t\"fmt\";\n\t\"io\";\n\t\"os\";\n\t\"reflect\";\n\t\"template\";\n\t\"testing\";\n)\n\ntype Test struct {\n\tin, out string\n}\n\ntype T struct {\n\titem string;\n\tvalue string;\n}\n\ntype S struct {\n\theader string;\n\tinteger int;\n\traw string;\n\tinnerT T;\n\tdata []T;\n\tpdata []*T;\n\tempty []*T;\n\temptystring string;\n\tnull []*T;\n}\n\nvar t1 = T{ \"ItemNumber1\", \"ValueNumber1\" }\nvar t2 = T{ \"ItemNumber2\", \"ValueNumber2\" }\n\nfunc uppercase(v interface{}) string {\n\ts := v.(string);\n\tt := \"\";\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i];\n\t\tif 'a' <= c && c <= 'z' {\n\t\t\tc = c + 'A' - 'a'\n\t\t}\n\t\tt += string(c);\n\t}\n\treturn t;\n}\n\nfunc plus1(v interface{}) string {\n\ti := v.(int);\n\treturn fmt.Sprint(i + 1);\n}\n\nfunc writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) {\n\treturn func(w io.Writer, v interface{}, format string) {\n\t\tio.WriteString(w, f(v));\n\t}\n}\n\n\nvar formatters = FormatterMap {\n\t\"uppercase\" : writer(uppercase),\n\t\"+1\" : writer(plus1),\n}\n\nvar tests = []*Test {\n\t\/\/ Simple\n\t&Test{ \"\", \"\" },\n\t&Test{ \"abc\\ndef\\n\", \"abc\\ndef\\n\" },\n\t&Test{ \" {.meta-left}   \\n\", \"{\" },\n\t&Test{ \" {.meta-right}   \\n\", \"}\" },\n\t&Test{ \" {.space}   \\n\", \" \" },\n\t&Test{ \" {.tab}   \\n\", \"\\t\" },\n\t&Test{ \"     {#comment}   \\n\", \"\" },\n\n\t\/\/ Variables at top level\n\t&Test{\n\t\t\"{header}={integer}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\n\t\/\/ Section\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"some text for the section\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"some text for the section\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section empty }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section null }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.section @ }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data}{.end} {header}\\n\",\n\n\t\t\" Header\\n\"\n\t},\n\n\t\/\/ Repeated\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should not appear\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\t&Test{\n\t\t\"{.section @ }\\n\"\n\t\t\"{.repeated section empty }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should appear: empty field\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"this should appear: empty field\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.alternates with}DIVIDER\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should not appear\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"DIVIDER\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\n\t\/\/ Nested names\n\t&Test{\n\t\t\"{.section @ }\\n\"\n\t\t\"{innerT.item}={innerT.value}\\n\"\n\t\t\"{.end}\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t},\n\n\t\/\/ Formatters\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header|uppercase}={integer|+1}\\n\"\n\t\t\"{header|html}={integer|str}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"HEADER=78\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\n\t&Test{\n\t\t\"{raw}\\n\"\n\t\t\"{raw|html}\\n\",\n\n\t\t\"&<>!@ #$%^\\n\"\n\t\t\"&amp;&lt;&gt;!@ #$%^\\n\"\n\t},\n\n\t&Test{\n\t\t\"{.section emptystring}emptystring{.end}\\n\"\n\t\t\"{.section header}header{.end}\\n\",\n\n\t\t\"\\nheader\\n\"\n\t},\n}\n\nfunc TestAll(t *testing.T) {\n\ts := new(S);\n\t\/\/ initialized by hand for clarity.\n\ts.header = \"Header\";\n\ts.integer = 77;\n\ts.raw = \"&<>!@ #$%^\";\n\ts.innerT = t1;\n\ts.data = []T{ t1, t2 };\n\ts.pdata = []*T{ &t1, &t2 };\n\ts.empty = []*T{ };\n\ts.null = nil;\n\n\tvar buf bytes.Buffer;\n\tfor i, test := range tests {\n\t\tbuf.Reset();\n\t\ttmpl, err := Parse(test.in, formatters);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected parse error:\", err);\n\t\t\tcontinue;\n\t\t}\n\t\terr = tmpl.Execute(s, &buf);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected execute error:\", err)\n\t\t}\n\t\tif string(buf.Data()) != test.out {\n\t\t\tt.Errorf(\"for %q: expected %q got %q\", test.in, test.out, string(buf.Data()));\n\t\t}\n\t}\n}\n\nfunc TestStringDriverType(t *testing.T) {\n\ttmpl, err := Parse(\"template: {@}\", nil);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\tvar b bytes.Buffer;\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected execute error:\", err)\n\t}\n\ts := string(b.Data());\n\tif s != \"template: hello\" {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", \"template: hello\", s)\n\t}\n}\n\nfunc TestTwice(t *testing.T) {\n\ttmpl, err := Parse(\"template: {@}\", nil);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\tvar b bytes.Buffer;\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\ts := string(b.Data());\n\ttext := \"template: hello\";\n\tif s != text {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", text, s);\n\t}\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\ts = string(b.Data());\n\ttext += text;\n\tif s != text {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", text, s);\n\t}\n}\n\nfunc TestCustomDelims(t *testing.T) {\n\t\/\/ try various lengths.  zero should catch error.\n\tfor i := 0; i < 7; i++ {\n\t\tfor j := 0; j < 7; j++ {\n\t\t\ttmpl := New(nil);\n\t\t\t\/\/ first two chars deliberately the same to test equal left and right delims\n\t\t\tldelim := \"$!#$%^&\"[0:i];\n\t\t\trdelim := \"$*&^%$!\"[0:j];\n\t\t\ttmpl.SetDelims(ldelim, rdelim);\n\t\t\t\/\/ if braces, this would be template: {@}{.meta-left}{.meta-right}\n\t\t\ttext := \"template: \" +\n\t\t\t\tldelim + \"@\" + rdelim +\n\t\t\t\tldelim + \".meta-left\" + rdelim +\n\t\t\t\tldelim + \".meta-right\" + rdelim;\n\t\t\terr := tmpl.Parse(text);\n\t\t\tif err != nil {\n\t\t\t\tif i == 0 || j == 0 {\t\/\/ expected\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tt.Error(\"unexpected parse error:\", err)\n\t\t\t} else if i == 0 || j == 0 {\n\t\t\t\tt.Errorf(\"expected parse error for empty delimiter: %d %d %q %q\", i, j, ldelim, rdelim);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar b bytes.Buffer;\n\t\t\terr = tmpl.Execute(\"hello\", &b);\n\t\t\ts := string(b.Data());\n\t\t\tif s != \"template: hello\" + ldelim + rdelim {\n\t\t\t\tt.Errorf(\"failed delim check(%q %q) %q got %q\", ldelim, rdelim, text, s)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>add test of invariant in findVar<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 template\n\nimport (\n\t\"bytes\";\n\t\"fmt\";\n\t\"io\";\n\t\"os\";\n\t\"reflect\";\n\t\"template\";\n\t\"testing\";\n)\n\ntype Test struct {\n\tin, out string\n}\n\ntype T struct {\n\titem string;\n\tvalue string;\n}\n\ntype S struct {\n\theader string;\n\tinteger int;\n\traw string;\n\tinnerT T;\n\tinnerPointerT *T;\n\tdata []T;\n\tpdata []*T;\n\tempty []*T;\n\temptystring string;\n\tnull []*T;\n}\n\nvar t1 = T{ \"ItemNumber1\", \"ValueNumber1\" }\nvar t2 = T{ \"ItemNumber2\", \"ValueNumber2\" }\n\nfunc uppercase(v interface{}) string {\n\ts := v.(string);\n\tt := \"\";\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i];\n\t\tif 'a' <= c && c <= 'z' {\n\t\t\tc = c + 'A' - 'a'\n\t\t}\n\t\tt += string(c);\n\t}\n\treturn t;\n}\n\nfunc plus1(v interface{}) string {\n\ti := v.(int);\n\treturn fmt.Sprint(i + 1);\n}\n\nfunc writer(f func(interface{}) string) (func(io.Writer, interface{}, string)) {\n\treturn func(w io.Writer, v interface{}, format string) {\n\t\tio.WriteString(w, f(v));\n\t}\n}\n\n\nvar formatters = FormatterMap {\n\t\"uppercase\" : writer(uppercase),\n\t\"+1\" : writer(plus1),\n}\n\nvar tests = []*Test {\n\t\/\/ Simple\n\t&Test{ \"\", \"\" },\n\t&Test{ \"abc\\ndef\\n\", \"abc\\ndef\\n\" },\n\t&Test{ \" {.meta-left}   \\n\", \"{\" },\n\t&Test{ \" {.meta-right}   \\n\", \"}\" },\n\t&Test{ \" {.space}   \\n\", \" \" },\n\t&Test{ \" {.tab}   \\n\", \"\\t\" },\n\t&Test{ \"     {#comment}   \\n\", \"\" },\n\n\t\/\/ Variables at top level\n\t&Test{\n\t\t\"{header}={integer}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\n\t\/\/ Section\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"some text for the section\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"some text for the section\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section empty }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section null }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.section @ }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data}{.end} {header}\\n\",\n\n\t\t\" Header\\n\"\n\t},\n\n\t\/\/ Repeated\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should not appear\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\t&Test{\n\t\t\"{.section @ }\\n\"\n\t\t\"{.repeated section empty }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should appear: empty field\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"this should appear: empty field\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.alternates with}DIVIDER\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"this should not appear\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"DIVIDER\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\n\t\/\/ Nested names\n\t&Test{\n\t\t\"{.section @ }\\n\"\n\t\t\"{innerT.item}={innerT.value}\\n\"\n\t\t\"{.end}\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t},\n\n\t\/\/ Formatters\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header|uppercase}={integer|+1}\\n\"\n\t\t\"{header|html}={integer|str}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"HEADER=78\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\n\t&Test{\n\t\t\"{raw}\\n\"\n\t\t\"{raw|html}\\n\",\n\n\t\t\"&<>!@ #$%^\\n\"\n\t\t\"&amp;&lt;&gt;!@ #$%^\\n\"\n\t},\n\n\t&Test{\n\t\t\"{.section emptystring}emptystring{.end}\\n\"\n\t\t\"{.section header}header{.end}\\n\",\n\n\t\t\"\\nheader\\n\"\n\t},\n}\n\nfunc TestAll(t *testing.T) {\n\ts := new(S);\n\t\/\/ initialized by hand for clarity.\n\ts.header = \"Header\";\n\ts.integer = 77;\n\ts.raw = \"&<>!@ #$%^\";\n\ts.innerT = t1;\n\ts.data = []T{ t1, t2 };\n\ts.pdata = []*T{ &t1, &t2 };\n\ts.empty = []*T{ };\n\ts.null = nil;\n\n\tvar buf bytes.Buffer;\n\tfor i, test := range tests {\n\t\tbuf.Reset();\n\t\ttmpl, err := Parse(test.in, formatters);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected parse error:\", err);\n\t\t\tcontinue;\n\t\t}\n\t\terr = tmpl.Execute(s, &buf);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected execute error:\", err)\n\t\t}\n\t\tif string(buf.Data()) != test.out {\n\t\t\tt.Errorf(\"for %q: expected %q got %q\", test.in, test.out, string(buf.Data()));\n\t\t}\n\t}\n}\n\nfunc TestStringDriverType(t *testing.T) {\n\ttmpl, err := Parse(\"template: {@}\", nil);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\tvar b bytes.Buffer;\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected execute error:\", err)\n\t}\n\ts := string(b.Data());\n\tif s != \"template: hello\" {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", \"template: hello\", s)\n\t}\n}\n\nfunc TestTwice(t *testing.T) {\n\ttmpl, err := Parse(\"template: {@}\", nil);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\tvar b bytes.Buffer;\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\ts := string(b.Data());\n\ttext := \"template: hello\";\n\tif s != text {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", text, s);\n\t}\n\terr = tmpl.Execute(\"hello\", &b);\n\tif err != nil {\n\t\tt.Error(\"unexpected parse error:\", err)\n\t}\n\ts = string(b.Data());\n\ttext += text;\n\tif s != text {\n\t\tt.Errorf(\"failed passing string as data: expected %q got %q\", text, s);\n\t}\n}\n\nfunc TestCustomDelims(t *testing.T) {\n\t\/\/ try various lengths.  zero should catch error.\n\tfor i := 0; i < 7; i++ {\n\t\tfor j := 0; j < 7; j++ {\n\t\t\ttmpl := New(nil);\n\t\t\t\/\/ first two chars deliberately the same to test equal left and right delims\n\t\t\tldelim := \"$!#$%^&\"[0:i];\n\t\t\trdelim := \"$*&^%$!\"[0:j];\n\t\t\ttmpl.SetDelims(ldelim, rdelim);\n\t\t\t\/\/ if braces, this would be template: {@}{.meta-left}{.meta-right}\n\t\t\ttext := \"template: \" +\n\t\t\t\tldelim + \"@\" + rdelim +\n\t\t\t\tldelim + \".meta-left\" + rdelim +\n\t\t\t\tldelim + \".meta-right\" + rdelim;\n\t\t\terr := tmpl.Parse(text);\n\t\t\tif err != nil {\n\t\t\t\tif i == 0 || j == 0 {\t\/\/ expected\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tt.Error(\"unexpected parse error:\", err)\n\t\t\t} else if i == 0 || j == 0 {\n\t\t\t\tt.Errorf(\"expected parse error for empty delimiter: %d %d %q %q\", i, j, ldelim, rdelim);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar b bytes.Buffer;\n\t\t\terr = tmpl.Execute(\"hello\", &b);\n\t\t\ts := string(b.Data());\n\t\t\tif s != \"template: hello\" + ldelim + rdelim {\n\t\t\t\tt.Errorf(\"failed delim check(%q %q) %q got %q\", ldelim, rdelim, text, s)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Test that a variable evaluates to the field itself and does not further indirection\nfunc TestVarIndirection(t *testing.T) {\n\ts := new(S);\n\t\/\/ initialized by hand for clarity.\n\ts.innerPointerT = &t1;\n\n\tvar buf bytes.Buffer;\n\tinput := \"{.section @}{innerPointerT}{.end}\";\n\ttmpl, err := Parse(input, nil);\n\tif err != nil {\n\t\tt.Fatal(\"unexpected parse error:\", err);\n\t}\n\terr = tmpl.Execute(s, &buf);\n\tif err != nil {\n\t\tt.Fatal(\"unexpected execute error:\", err)\n\t}\n\texpect := fmt.Sprintf(\"%v\", &t1);\t\/\/ output should be hex address of t1\n\tif string(buf.Data()) != expect {\n\t\tt.Errorf(\"for %q: expected %q got %q\", input, expect, string(buf.Data()));\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kontrol\n\nimport (\n\t\"koding\/db\/models\"\n\t\"testing\"\n\n\t\"gopkg.in\/mgo.v2\/bson\"\n\n\t\"github.com\/koding\/kite\/protocol\"\n)\n\nfunc TestFilterResult(t *testing.T) {\n\tkite1 := &KodingKiteWithToken{\n\t\tKite: protocol.Kite{\n\t\t\tID: \"id_1\",\n\t\t},\n\t\t\/\/ other fields are not used\n\t}\n\n\tkite2 := &KodingKiteWithToken{\n\t\tKite: protocol.Kite{\n\t\t\tID: \"id_2\",\n\t\t},\n\t}\n\n\tpastDueGroup := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"past_due\",\n\t\t\t},\n\t\t},\n\t}\n\n\tactiveGroup1 := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"active\",\n\t\t\t},\n\t\t},\n\t}\n\tactiveGroup2 := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"active\",\n\t\t\t},\n\t\t},\n\t}\n\n\ttests := []struct {\n\t\tname                 string\n\t\tgetKodingKitesResult *GetKodingKitesResult\n\t\tgroups               []*models.Group\n\t\tkitesByGroupID       map[string][]*KodingKiteWithToken\n\n\t\tresponse *GetKodingKitesResult\n\t}{\n\t\t{\n\t\t\tname: \"should stay same - everything is perfect\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, activeGroup2},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1, kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"remove past_due_group's kites when there is another group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"remove past_due_group's kites when there isnt any other group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove if the group is not in  group list\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove anything if there is no group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove anything if there is no past due group kite\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, activeGroup2, pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tactiveGroup2.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\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\t\/\/ t.Parallel()\n\t\t\tfilterRes := filterResult(test.getKodingKitesResult, test.groups, test.kitesByGroupID)\n\t\t\tif len(test.response.Kites) != len(filterRes.Kites) {\n\t\t\t\tt.Fatalf(\"len expected %d, got %d\", len(test.response.Kites), len(filterRes.Kites))\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(test.response.Kites); i++ {\n\t\t\t\texpected := test.response.Kites[i]\n\t\t\t\tgot := filterRes.Kites[i]\n\n\t\t\t\tif expected.Kite.ID != filterRes.Kites[i].Kite.ID {\n\t\t\t\t\tt.Fatalf(\"kite id expected %s, got %s\", expected.Kite.ID, got.Kite.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>go.race: parallelization is fixed for test<commit_after>package kontrol\n\nimport (\n\t\"koding\/db\/models\"\n\t\"testing\"\n\n\t\"gopkg.in\/mgo.v2\/bson\"\n\n\t\"github.com\/koding\/kite\/protocol\"\n)\n\nfunc TestFilterResult(t *testing.T) {\n\tkite1 := &KodingKiteWithToken{\n\t\tKite: protocol.Kite{\n\t\t\tID: \"id_1\",\n\t\t},\n\t\t\/\/ other fields are not used\n\t}\n\n\tkite2 := &KodingKiteWithToken{\n\t\tKite: protocol.Kite{\n\t\t\tID: \"id_2\",\n\t\t},\n\t}\n\n\tpastDueGroup := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"past_due\",\n\t\t\t},\n\t\t},\n\t}\n\n\tactiveGroup1 := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"active\",\n\t\t\t},\n\t\t},\n\t}\n\tactiveGroup2 := &models.Group{\n\t\tId: bson.NewObjectId(),\n\t\tPayment: models.Payment{\n\t\t\tSubscription: models.Subscription{\n\t\t\t\tStatus: \"active\",\n\t\t\t},\n\t\t},\n\t}\n\n\ttests := []struct {\n\t\tname                 string\n\t\tgetKodingKitesResult *GetKodingKitesResult\n\t\tgroups               []*models.Group\n\t\tkitesByGroupID       map[string][]*KodingKiteWithToken\n\n\t\tresponse *GetKodingKitesResult\n\t}{\n\t\t{\n\t\t\tname: \"should stay same - everything is perfect\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, activeGroup2},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1, kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"remove past_due_group's kites when there is another group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"remove past_due_group's kites when there isnt any other group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove if the group is not in  group list\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove anything if there is no group\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tpastDueGroup.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should not remove anything if there is no past due group kite\",\n\t\t\tgetKodingKitesResult: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t\tgroups: []*models.Group{activeGroup1, activeGroup2, pastDueGroup},\n\t\t\tkitesByGroupID: map[string][]*KodingKiteWithToken{\n\t\t\t\tactiveGroup1.Id.Hex(): {kite1},\n\t\t\t\tactiveGroup2.Id.Hex(): {kite2},\n\t\t\t},\n\t\t\tresponse: &GetKodingKitesResult{\n\t\t\t\tKites: []*KodingKiteWithToken{kite1, kite2},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\t\/\/ capture range variable here\n\t\t\/\/ otherwise values will not be assigned correctly\n\t\ttest := test\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tfilterRes := filterResult(test.getKodingKitesResult, test.groups, test.kitesByGroupID)\n\t\t\tif len(test.response.Kites) != len(filterRes.Kites) {\n\t\t\t\tt.Fatalf(\"len expected %d, got %d\", len(test.response.Kites), len(filterRes.Kites))\n\t\t\t}\n\n\t\t\tfor i := 0; i < len(test.response.Kites); i++ {\n\t\t\t\texpected := test.response.Kites[i]\n\t\t\t\tgot := filterRes.Kites[i]\n\n\t\t\t\tif expected.Kite.ID != filterRes.Kites[i].Kite.ID {\n\t\t\t\t\tt.Fatalf(\"kite id expected %s, got %s\", expected.Kite.ID, got.Kite.ID)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Tekton 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 tektonconfig\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tmf \"github.com\/manifestival\/manifestival\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\n\t\"github.com\/tektoncd\/operator\/pkg\/apis\/operator\/v1alpha1\"\n\tclientset \"github.com\/tektoncd\/operator\/pkg\/client\/clientset\/versioned\"\n\ttektonConfigreconciler \"github.com\/tektoncd\/operator\/pkg\/client\/injection\/reconciler\/operator\/v1alpha1\/tektonconfig\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/common\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/kubernetes\/tektonconfig\/pipeline\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/kubernetes\/tektonconfig\/trigger\"\n\t\"knative.dev\/pkg\/logging\"\n\tpkgreconciler \"knative.dev\/pkg\/reconciler\"\n)\n\n\/\/ Reconciler implements controller.Reconciler for TektonConfig resources.\ntype Reconciler struct {\n\t\/\/ kubeClientSet allows us to talk to the k8s for core APIs\n\tkubeClientSet kubernetes.Interface\n\t\/\/ operatorClientSet allows us to configure operator objects\n\toperatorClientSet clientset.Interface\n\t\/\/ manifest is empty, but with a valid client and logger. all\n\t\/\/ manifests are immutable, and any created during reconcile are\n\t\/\/ expected to be appended to this one, obviating the passing of\n\t\/\/ client & logger\n\tmanifest mf.Manifest\n\t\/\/ Platform-specific behavior to affect the transform\n\textension common.Extension\n}\n\n\/\/ Check that our Reconciler implements controller.Reconciler\nvar _ tektonConfigreconciler.Interface = (*Reconciler)(nil)\nvar _ tektonConfigreconciler.Finalizer = (*Reconciler)(nil)\n\n\/\/ FinalizeKind removes all resources after deletion of a TektonConfig.\nfunc (r *Reconciler) FinalizeKind(ctx context.Context, original *v1alpha1.TektonConfig) pkgreconciler.Event {\n\tlogger := logging.FromContext(ctx)\n\n\t\/\/ List all TektonConfigs to determine if cluster-scoped resources should be deleted.\n\ttps, err := r.operatorClientSet.OperatorV1alpha1().TektonConfigs().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list all TektonConfigs: %w\", err)\n\t}\n\n\tfor _, tp := range tps.Items {\n\t\tif tp.GetDeletionTimestamp().IsZero() {\n\t\t\t\/\/ Not deleting all TektonPipelines. Nothing to do here.\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif original.Spec.Profile == common.ProfileLite {\n\t\treturn pipeline.TektonPipelineCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonPipelines(), common.PipelineResourceName)\n\t} else {\n\t\t\/\/ TektonPipeline and TektonTrigger is common for profile type basic and all\n\t\tif err := pipeline.TektonPipelineCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonPipelines(), common.PipelineResourceName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := trigger.TektonTriggerCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonTriggers(), common.TriggerResourceName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := r.extension.Finalize(ctx, original); err != nil {\n\t\tlogger.Error(\"Failed to finalize platform resources\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ReconcileKind compares the actual state with the desired, and attempts to\n\/\/ converge the two.\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, tc *v1alpha1.TektonConfig) pkgreconciler.Event {\n\tlogger := logging.FromContext(ctx)\n\ttc.Status.InitializeConditions()\n\ttc.Status.ObservedGeneration = tc.Generation\n\n\tlogger.Infow(\"Reconciling TektonConfig\", \"status\", tc.Status)\n\tif tc.GetName() != common.ConfigResourceName {\n\t\tmsg := fmt.Sprintf(\"Resource ignored, Expected Name: %s, Got Name: %s\",\n\t\t\tcommon.ConfigResourceName,\n\t\t\ttc.GetName(),\n\t\t)\n\t\tlogger.Error(msg)\n\t\ttc.GetStatus().MarkInstallFailed(msg)\n\t\treturn nil\n\t}\n\n\tif err := r.extension.PreReconcile(ctx, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\n\tvar stages common.Stages\n\tif tc.Spec.Profile == common.ProfileLite {\n\t\tstages = common.Stages{\n\t\t\tr.createPipelineCR,\n\t\t}\n\t} else {\n\t\t\/\/ TektonPipeline and TektonTrigger is common for profile type basic and all\n\t\tstages = common.Stages{\n\t\t\tr.createPipelineCR,\n\t\t\tr.createTriggerCR,\n\t\t}\n\t}\n\n\tif err := common.Prune(r.kubeClientSet, ctx, tc); err != nil {\n\t\tlogger.Error(err)\n\t}\n\n\tmanifest := r.manifest.Append()\n\tif err := stages.Execute(ctx, &manifest, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\tif err := r.extension.PostReconcile(ctx, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\ttc.Status.MarkInstallSucceeded()\n\ttc.Status.MarkDeploymentsAvailable()\n\treturn nil\n}\n\nfunc (r *Reconciler) createPipelineCR(ctx context.Context, manifest *mf.Manifest, comp v1alpha1.TektonComponent) error {\n\treturn pipeline.CreatePipelineCR(comp, r.operatorClientSet.OperatorV1alpha1())\n}\n\nfunc (r *Reconciler) createTriggerCR(ctx context.Context, manifest *mf.Manifest, comp v1alpha1.TektonComponent) error {\n\treturn trigger.CreateTriggerCR(comp, r.operatorClientSet.OperatorV1alpha1())\n}\n<commit_msg>call prune at the end of the Reconcile<commit_after>\/*\nCopyright 2020 The Tekton 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 tektonconfig\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\tmf \"github.com\/manifestival\/manifestival\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\n\t\"github.com\/tektoncd\/operator\/pkg\/apis\/operator\/v1alpha1\"\n\tclientset \"github.com\/tektoncd\/operator\/pkg\/client\/clientset\/versioned\"\n\ttektonConfigreconciler \"github.com\/tektoncd\/operator\/pkg\/client\/injection\/reconciler\/operator\/v1alpha1\/tektonconfig\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/common\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/kubernetes\/tektonconfig\/pipeline\"\n\t\"github.com\/tektoncd\/operator\/pkg\/reconciler\/kubernetes\/tektonconfig\/trigger\"\n\t\"knative.dev\/pkg\/logging\"\n\tpkgreconciler \"knative.dev\/pkg\/reconciler\"\n)\n\n\/\/ Reconciler implements controller.Reconciler for TektonConfig resources.\ntype Reconciler struct {\n\t\/\/ kubeClientSet allows us to talk to the k8s for core APIs\n\tkubeClientSet kubernetes.Interface\n\t\/\/ operatorClientSet allows us to configure operator objects\n\toperatorClientSet clientset.Interface\n\t\/\/ manifest is empty, but with a valid client and logger. all\n\t\/\/ manifests are immutable, and any created during reconcile are\n\t\/\/ expected to be appended to this one, obviating the passing of\n\t\/\/ client & logger\n\tmanifest mf.Manifest\n\t\/\/ Platform-specific behavior to affect the transform\n\textension common.Extension\n}\n\n\/\/ Check that our Reconciler implements controller.Reconciler\nvar _ tektonConfigreconciler.Interface = (*Reconciler)(nil)\nvar _ tektonConfigreconciler.Finalizer = (*Reconciler)(nil)\n\n\/\/ FinalizeKind removes all resources after deletion of a TektonConfig.\nfunc (r *Reconciler) FinalizeKind(ctx context.Context, original *v1alpha1.TektonConfig) pkgreconciler.Event {\n\tlogger := logging.FromContext(ctx)\n\n\t\/\/ List all TektonConfigs to determine if cluster-scoped resources should be deleted.\n\ttps, err := r.operatorClientSet.OperatorV1alpha1().TektonConfigs().List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to list all TektonConfigs: %w\", err)\n\t}\n\n\tfor _, tp := range tps.Items {\n\t\tif tp.GetDeletionTimestamp().IsZero() {\n\t\t\t\/\/ Not deleting all TektonPipelines. Nothing to do here.\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif original.Spec.Profile == common.ProfileLite {\n\t\treturn pipeline.TektonPipelineCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonPipelines(), common.PipelineResourceName)\n\t} else {\n\t\t\/\/ TektonPipeline and TektonTrigger is common for profile type basic and all\n\t\tif err := pipeline.TektonPipelineCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonPipelines(), common.PipelineResourceName); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := trigger.TektonTriggerCRDelete(r.operatorClientSet.OperatorV1alpha1().TektonTriggers(), common.TriggerResourceName); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := r.extension.Finalize(ctx, original); err != nil {\n\t\tlogger.Error(\"Failed to finalize platform resources\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ReconcileKind compares the actual state with the desired, and attempts to\n\/\/ converge the two.\nfunc (r *Reconciler) ReconcileKind(ctx context.Context, tc *v1alpha1.TektonConfig) pkgreconciler.Event {\n\tlogger := logging.FromContext(ctx)\n\ttc.Status.InitializeConditions()\n\ttc.Status.ObservedGeneration = tc.Generation\n\n\tlogger.Infow(\"Reconciling TektonConfig\", \"status\", tc.Status)\n\tif tc.GetName() != common.ConfigResourceName {\n\t\tmsg := fmt.Sprintf(\"Resource ignored, Expected Name: %s, Got Name: %s\",\n\t\t\tcommon.ConfigResourceName,\n\t\t\ttc.GetName(),\n\t\t)\n\t\tlogger.Error(msg)\n\t\ttc.GetStatus().MarkInstallFailed(msg)\n\t\treturn nil\n\t}\n\n\tif err := r.extension.PreReconcile(ctx, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\n\tvar stages common.Stages\n\tif tc.Spec.Profile == common.ProfileLite {\n\t\tstages = common.Stages{\n\t\t\tr.createPipelineCR,\n\t\t}\n\t} else {\n\t\t\/\/ TektonPipeline and TektonTrigger is common for profile type basic and all\n\t\tstages = common.Stages{\n\t\t\tr.createPipelineCR,\n\t\t\tr.createTriggerCR,\n\t\t}\n\t}\n\n\tmanifest := r.manifest.Append()\n\tif err := stages.Execute(ctx, &manifest, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\tif err := r.extension.PostReconcile(ctx, tc); err != nil {\n\t\ttc.GetStatus().MarkInstallFailed(err.Error())\n\t\treturn err\n\t}\n\n\tif err := common.Prune(r.kubeClientSet, ctx, tc); err != nil {\n\t\tlogger.Error(err)\n\t}\n\n\ttc.Status.MarkInstallSucceeded()\n\ttc.Status.MarkDeploymentsAvailable()\n\treturn nil\n}\n\nfunc (r *Reconciler) createPipelineCR(ctx context.Context, manifest *mf.Manifest, comp v1alpha1.TektonComponent) error {\n\treturn pipeline.CreatePipelineCR(comp, r.operatorClientSet.OperatorV1alpha1())\n}\n\nfunc (r *Reconciler) createTriggerCR(ctx context.Context, manifest *mf.Manifest, comp v1alpha1.TektonComponent) error {\n\treturn trigger.CreateTriggerCR(comp, r.operatorClientSet.OperatorV1alpha1())\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\", \"coverage\"}\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\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 := \"v5.1.0-2\"\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 != stringTrue {\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 != stringTrue {\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 = masterTag\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\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\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 DockerHub.\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 DockerHub.\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\tswitch {\n\tcase ciTag != \"\":\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\t\t\tlogin(docker)\n\t\t\tdeploy(docker, tags[1]+\"-\"+arch)\n\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\tcase ciBranch != masterTag && !publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeploy(docker, ciBranch+\"-\"+arch)\n\tcase ciBranch != masterTag && publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeploy(docker, \"PR\"+ciPullRequest+\"-\"+arch)\n\tcase ciBranch == masterTag && ciPullRequest == stringFalse:\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\tdefault:\n\t\tlog.Info(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\tswitch {\n\tcase ciTag != \"\":\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\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\tcase ciBranch != masterTag && !publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeployManifest(docker, ciBranch, ciBranch+\"-amd64\", ciBranch+\"-arm32v7\", ciBranch+\"-arm64v8\")\n\tcase ciBranch != masterTag && publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"PR\"+ciPullRequest, \"PR\"+ciPullRequest+\"-amd64\", \"PR\"+ciPullRequest+\"-arm32v7\", \"PR\"+ciPullRequest+\"-arm64v8\")\n\tcase ciBranch == masterTag && ciPullRequest == stringFalse:\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t\tpublishDockerReadme(docker)\n\tdefault:\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>[CI] Update QEMU to v5.1.0-5 (#1393)<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\", \"coverage\"}\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\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 := \"v5.1.0-5\"\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 != stringTrue {\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 != stringTrue {\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 = masterTag\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\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\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 DockerHub.\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 DockerHub.\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\tswitch {\n\tcase ciTag != \"\":\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\t\t\tlogin(docker)\n\t\t\tdeploy(docker, tags[1]+\"-\"+arch)\n\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\tcase ciBranch != masterTag && !publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeploy(docker, ciBranch+\"-\"+arch)\n\tcase ciBranch != masterTag && publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeploy(docker, \"PR\"+ciPullRequest+\"-\"+arch)\n\tcase ciBranch == masterTag && ciPullRequest == stringFalse:\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\tdefault:\n\t\tlog.Info(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\tswitch {\n\tcase ciTag != \"\":\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\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\tcase ciBranch != masterTag && !publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeployManifest(docker, ciBranch, ciBranch+\"-amd64\", ciBranch+\"-arm32v7\", ciBranch+\"-arm64v8\")\n\tcase ciBranch != masterTag && publicRepo.MatchString(ciBranch):\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"PR\"+ciPullRequest, \"PR\"+ciPullRequest+\"-amd64\", \"PR\"+ciPullRequest+\"-arm32v7\", \"PR\"+ciPullRequest+\"-arm64v8\")\n\tcase ciBranch == masterTag && ciPullRequest == stringFalse:\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t\tpublishDockerReadme(docker)\n\tdefault:\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 main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"go\/types\"\n\n\t\"golang.org\/x\/tools\/go\/loader\"\n)\n\nvar (\n\tbuildContext = build.Default\n\n\tloaderConfig = loader.Config{\n\t\tTypeChecker: types.Config{FakeImportC: true},\n\t\tBuild:       &buildContext,\n\t\tAllowErrors: true,\n\t}\n\n\tconfig *srcfileConfig\n\n\tgoBinaryName string\n\n\tvalidVersions = []string{\"\", \"1.3\", \"1.2\", \"1.1\", \"1\"}\n\n\t\/\/ effectiveConfigGOPATHs is a list of GOPATH dirs that were\n\t\/\/ created as a result of the GOPATH config property. These are\n\t\/\/ the dirs that are appended to the actual build context GOPATH.\n\teffectiveConfigGOPATHs []string\n)\n\n\/\/ isInEffectiveConfigGOPATH is true if dir is underneath any of the\n\/\/ dirs in effectiveConfigGOPATHs.\nfunc isInEffectiveConfigGOPATH(dir string) bool {\n\tfor _, gopath := range effectiveConfigGOPATHs {\n\t\tif pathHasPrefix(dir, gopath) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype srcfileConfig struct {\n\t\/\/ GOROOT, if specified, is made absolute (prefixed with the\n\t\/\/ directory that the repository being built is checked out to)\n\t\/\/ and is set as the GOROOT environment variable.\n\tGOROOT string\n\n\t\/\/ GOROOTForCmd, if set, is used as the GOROOT env var when\n\t\/\/ invoking the \"go\" tool.\n\tGOROOTForCmd string\n\n\t\/\/ GOPATH's colon-separated dirs, if specified, are made absolute\n\t\/\/ (prefixed with the directory that the repository being built is\n\t\/\/ checked out to) and the resulting value is appended to the\n\t\/\/ GOPATH environment variable during the build.\n\tGOPATH string\n\n\t\/\/ GOVERSION is the version of the go tool that srclib-go\n\t\/\/ should shell out to. If GOVERSION is empty, the system's\n\t\/\/ default go binary is used. The only valid values for\n\t\/\/ GOVERSION are the empty string, \"1.3\", \"1.2\", \"1.1\", and\n\t\/\/ \"1\", which are transformed into \"go\", \"go1.3\", ..., \"go1\",\n\t\/\/ respectively, when the binary is called.\n\tGOVERSION string\n\n\tPkgPatterns []string \/\/ pattern passed to `go list` (defaults to {\".\/...\"})\n\n\t\/\/ SkipGodeps makes srclib-go skip the Godeps\/_workspace directory when\n\t\/\/ scanning for packages. This causes references to those packages to point\n\t\/\/ to the files in their respective repositories instead of the local copies\n\t\/\/ inside of Godeps\/_workspace.\n\tSkipGodeps bool\n\n\t\/\/ ImportPathRoot is a prefix which is used when converting from repository\n\t\/\/ URI to Go import path.\n\tImportPathRoot string\n\n\t\/\/ VendorDirs are a list of all src directories used by a package,\n\t\/\/ relative to the repository root. These are used for\n\t\/\/ GO15VENDOREXPERIMENT related vendor support, and this is usually\n\t\/\/ not set by the user. At build time a GOPATH is created which will\n\t\/\/ include each VendorDir on it linked to src. VendorDirs should be\n\t\/\/ sorted by longest path to shortest (ie most specific to least\n\t\/\/ specific)\n\tVendorDirs []string\n}\n\n\/\/ unmarshalTypedConfig parses config from the Config field of the source unit.\n\/\/ It stores it in the config global variable.\n\/\/\n\/\/ Callers should typically call config.apply() after calling\n\/\/ unmarshalTypedConfig to actually apply the config.\nfunc unmarshalTypedConfig(cfg map[string]interface{}) error {\n\tdata, err := json.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\treturn err\n\t}\n\n\tif config == nil {\n\t\tconfig = &srcfileConfig{}\n\t}\n\n\treturn config.apply()\n}\n\n\/\/ apply applies the configuration.\nfunc (c *srcfileConfig) apply() error {\n\t\/\/ KLUDGE: determine whether we're in the stdlib and if so, set GOROOT to \".\" before applying config.\n\t\/\/ This is necessary for the stdlib unit names to be correct.\n\tcloneURL, err := exec.Command(\"git\", \"config\", \"--get\", \"remote.origin.url\").Output()\n\tif err == nil && strings.HasSuffix(strings.TrimSpace(string(cloneURL)), \"github.com\/golang\/go\") && c.GOROOT == \"\" {\n\t\tc.GOROOT = \".\"\n\t}\n\n\tvar versionValid bool\n\tfor _, v := range validVersions {\n\t\tif config.GOVERSION == v {\n\t\t\tversionValid = true\n\t\t\tgoBinaryName = fmt.Sprintf(\"go%s\", config.GOVERSION)\n\t\t\tif config.GOVERSION != \"\" && config.GOROOT == \"\" {\n\t\t\t\t\/\/ If GOROOT is empty, assign $GOROOT<version_num> to it.\n\t\t\t\tnewGOROOT := os.Getenv(fmt.Sprintf(\"GOROOT%s\", strings.Replace(config.GOVERSION, \".\", \"\", -1)))\n\t\t\t\tif newGOROOT != \"\" {\n\t\t\t\t\tconfig.GOROOTForCmd = newGOROOT\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !versionValid {\n\t\treturn fmt.Errorf(\"The version %s is not valid. Use one of the following: %v\", config.GOVERSION, validVersions)\n\t}\n\n\tif config.GOROOT != \"\" {\n\t\t\/\/ clean\/absolutize all paths\n\t\tconfig.GOROOT = filepath.Clean(config.GOROOT)\n\t\tif !filepath.IsAbs(config.GOROOT) {\n\t\t\tconfig.GOROOT = filepath.Join(cwd, config.GOROOT)\n\t\t}\n\n\t\tbuildContext.GOROOT = c.GOROOT\n\t\tloaderConfig.Build = &buildContext\n\t}\n\n\tif config.GOPATH != \"\" {\n\t\t\/\/ clean\/absolutize all paths\n\t\tdirs := cleanDirs(filepath.SplitList(config.GOPATH))\n\t\tconfig.GOPATH = strings.Join(dirs, string(filepath.ListSeparator))\n\n\t\tdirs = append(dirs, filepath.SplitList(buildContext.GOPATH)...)\n\t\tbuildContext.GOPATH = strings.Join(uniq(dirs), string(filepath.ListSeparator))\n\t\tloaderConfig.Build = &buildContext\n\t}\n\n\tconfig.VendorDirs = cleanDirs(config.VendorDirs)\n\n\tif config.GOROOTForCmd == \"\" {\n\t\tconfig.GOROOTForCmd = buildContext.GOROOT\n\t}\n\n\treturn nil\n}\n\nfunc (c *srcfileConfig) env() []string {\n\treturn []string{\n\t\t\"PATH=\" + os.Getenv(\"PATH\"),\n\t\t\"GOARCH=\" + buildContext.GOARCH,\n\t\t\"GOOS=\" + buildContext.GOOS,\n\t\t\"GOROOT=\" + config.GOROOTForCmd,\n\t\t\"GOPATH=\" + buildContext.GOPATH,\n\t\t\"GO15VENDOREXPERIMENT=1\",\n\t}\n}\n\nfunc pathHasPrefix(path, prefix string) bool {\n\treturn prefix == \".\" || path == prefix || strings.HasPrefix(path, prefix+string(filepath.Separator))\n}\n\n\/\/ cleanDirs takes a list of paths cleans\/abs them + removes duplicates\nfunc cleanDirs(dirs []string) []string {\n\tdirs = uniq(dirs)\n\tfor i, dir := range dirs {\n\t\tdir = filepath.Clean(dir)\n\t\tif !filepath.IsAbs(dir) {\n\t\t\tdir = filepath.Join(cwd, dir)\n\t\t}\n\t\tdirs[i] = dir\n\t}\n\treturn dirs\n}\n\n\/\/ uniq maintains the order of s.\nfunc uniq(s []string) []string {\n\tseen := make(map[string]struct{}, len(s))\n\tvar uniq []string\n\tfor _, s := range s {\n\t\tif _, seen := seen[s]; seen {\n\t\t\tcontinue\n\t\t}\n\t\tseen[s] = struct{}{}\n\t\tuniq = append(uniq, s)\n\t}\n\treturn uniq\n}\n<commit_msg>add default importer for reading .a object files<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"go\/importer\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"go\/types\"\n\n\t\"golang.org\/x\/tools\/go\/loader\"\n)\n\nvar (\n\tbuildContext = build.Default\n\n\tloaderConfig = loader.Config{\n\t\tTypeChecker: types.Config{\n\t\t\tImporter:    importer.Default(),\n\t\t\tFakeImportC: true,\n\t\t},\n\t\tBuild:       &buildContext,\n\t\tAllowErrors: true,\n\t}\n\n\tconfig *srcfileConfig\n\n\tgoBinaryName string\n\n\tvalidVersions = []string{\"\", \"1.3\", \"1.2\", \"1.1\", \"1\"}\n\n\t\/\/ effectiveConfigGOPATHs is a list of GOPATH dirs that were\n\t\/\/ created as a result of the GOPATH config property. These are\n\t\/\/ the dirs that are appended to the actual build context GOPATH.\n\teffectiveConfigGOPATHs []string\n)\n\n\/\/ isInEffectiveConfigGOPATH is true if dir is underneath any of the\n\/\/ dirs in effectiveConfigGOPATHs.\nfunc isInEffectiveConfigGOPATH(dir string) bool {\n\tfor _, gopath := range effectiveConfigGOPATHs {\n\t\tif pathHasPrefix(dir, gopath) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype srcfileConfig struct {\n\t\/\/ GOROOT, if specified, is made absolute (prefixed with the\n\t\/\/ directory that the repository being built is checked out to)\n\t\/\/ and is set as the GOROOT environment variable.\n\tGOROOT string\n\n\t\/\/ GOROOTForCmd, if set, is used as the GOROOT env var when\n\t\/\/ invoking the \"go\" tool.\n\tGOROOTForCmd string\n\n\t\/\/ GOPATH's colon-separated dirs, if specified, are made absolute\n\t\/\/ (prefixed with the directory that the repository being built is\n\t\/\/ checked out to) and the resulting value is appended to the\n\t\/\/ GOPATH environment variable during the build.\n\tGOPATH string\n\n\t\/\/ GOVERSION is the version of the go tool that srclib-go\n\t\/\/ should shell out to. If GOVERSION is empty, the system's\n\t\/\/ default go binary is used. The only valid values for\n\t\/\/ GOVERSION are the empty string, \"1.3\", \"1.2\", \"1.1\", and\n\t\/\/ \"1\", which are transformed into \"go\", \"go1.3\", ..., \"go1\",\n\t\/\/ respectively, when the binary is called.\n\tGOVERSION string\n\n\tPkgPatterns []string \/\/ pattern passed to `go list` (defaults to {\".\/...\"})\n\n\t\/\/ SkipGodeps makes srclib-go skip the Godeps\/_workspace directory when\n\t\/\/ scanning for packages. This causes references to those packages to point\n\t\/\/ to the files in their respective repositories instead of the local copies\n\t\/\/ inside of Godeps\/_workspace.\n\tSkipGodeps bool\n\n\t\/\/ ImportPathRoot is a prefix which is used when converting from repository\n\t\/\/ URI to Go import path.\n\tImportPathRoot string\n\n\t\/\/ VendorDirs are a list of all src directories used by a package,\n\t\/\/ relative to the repository root. These are used for\n\t\/\/ GO15VENDOREXPERIMENT related vendor support, and this is usually\n\t\/\/ not set by the user. At build time a GOPATH is created which will\n\t\/\/ include each VendorDir on it linked to src. VendorDirs should be\n\t\/\/ sorted by longest path to shortest (ie most specific to least\n\t\/\/ specific)\n\tVendorDirs []string\n}\n\n\/\/ unmarshalTypedConfig parses config from the Config field of the source unit.\n\/\/ It stores it in the config global variable.\n\/\/\n\/\/ Callers should typically call config.apply() after calling\n\/\/ unmarshalTypedConfig to actually apply the config.\nfunc unmarshalTypedConfig(cfg map[string]interface{}) error {\n\tdata, err := json.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := json.Unmarshal(data, &config); err != nil {\n\t\treturn err\n\t}\n\n\tif config == nil {\n\t\tconfig = &srcfileConfig{}\n\t}\n\n\treturn config.apply()\n}\n\n\/\/ apply applies the configuration.\nfunc (c *srcfileConfig) apply() error {\n\t\/\/ KLUDGE: determine whether we're in the stdlib and if so, set GOROOT to \".\" before applying config.\n\t\/\/ This is necessary for the stdlib unit names to be correct.\n\tcloneURL, err := exec.Command(\"git\", \"config\", \"--get\", \"remote.origin.url\").Output()\n\tif err == nil && strings.HasSuffix(strings.TrimSpace(string(cloneURL)), \"github.com\/golang\/go\") && c.GOROOT == \"\" {\n\t\tc.GOROOT = \".\"\n\t}\n\n\tvar versionValid bool\n\tfor _, v := range validVersions {\n\t\tif config.GOVERSION == v {\n\t\t\tversionValid = true\n\t\t\tgoBinaryName = fmt.Sprintf(\"go%s\", config.GOVERSION)\n\t\t\tif config.GOVERSION != \"\" && config.GOROOT == \"\" {\n\t\t\t\t\/\/ If GOROOT is empty, assign $GOROOT<version_num> to it.\n\t\t\t\tnewGOROOT := os.Getenv(fmt.Sprintf(\"GOROOT%s\", strings.Replace(config.GOVERSION, \".\", \"\", -1)))\n\t\t\t\tif newGOROOT != \"\" {\n\t\t\t\t\tconfig.GOROOTForCmd = newGOROOT\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !versionValid {\n\t\treturn fmt.Errorf(\"The version %s is not valid. Use one of the following: %v\", config.GOVERSION, validVersions)\n\t}\n\n\tif config.GOROOT != \"\" {\n\t\t\/\/ clean\/absolutize all paths\n\t\tconfig.GOROOT = filepath.Clean(config.GOROOT)\n\t\tif !filepath.IsAbs(config.GOROOT) {\n\t\t\tconfig.GOROOT = filepath.Join(cwd, config.GOROOT)\n\t\t}\n\n\t\tbuildContext.GOROOT = c.GOROOT\n\t\tloaderConfig.Build = &buildContext\n\t}\n\n\tif config.GOPATH != \"\" {\n\t\t\/\/ clean\/absolutize all paths\n\t\tdirs := cleanDirs(filepath.SplitList(config.GOPATH))\n\t\tconfig.GOPATH = strings.Join(dirs, string(filepath.ListSeparator))\n\n\t\tdirs = append(dirs, filepath.SplitList(buildContext.GOPATH)...)\n\t\tbuildContext.GOPATH = strings.Join(uniq(dirs), string(filepath.ListSeparator))\n\t\tloaderConfig.Build = &buildContext\n\t}\n\n\tconfig.VendorDirs = cleanDirs(config.VendorDirs)\n\n\tif config.GOROOTForCmd == \"\" {\n\t\tconfig.GOROOTForCmd = buildContext.GOROOT\n\t}\n\n\treturn nil\n}\n\nfunc (c *srcfileConfig) env() []string {\n\treturn []string{\n\t\t\"PATH=\" + os.Getenv(\"PATH\"),\n\t\t\"GOARCH=\" + buildContext.GOARCH,\n\t\t\"GOOS=\" + buildContext.GOOS,\n\t\t\"GOROOT=\" + config.GOROOTForCmd,\n\t\t\"GOPATH=\" + buildContext.GOPATH,\n\t\t\"GO15VENDOREXPERIMENT=1\",\n\t}\n}\n\nfunc pathHasPrefix(path, prefix string) bool {\n\treturn prefix == \".\" || path == prefix || strings.HasPrefix(path, prefix+string(filepath.Separator))\n}\n\n\/\/ cleanDirs takes a list of paths cleans\/abs them + removes duplicates\nfunc cleanDirs(dirs []string) []string {\n\tdirs = uniq(dirs)\n\tfor i, dir := range dirs {\n\t\tdir = filepath.Clean(dir)\n\t\tif !filepath.IsAbs(dir) {\n\t\t\tdir = filepath.Join(cwd, dir)\n\t\t}\n\t\tdirs[i] = dir\n\t}\n\treturn dirs\n}\n\n\/\/ uniq maintains the order of s.\nfunc uniq(s []string) []string {\n\tseen := make(map[string]struct{}, len(s))\n\tvar uniq []string\n\tfor _, s := range s {\n\t\tif _, seen := seen[s]; seen {\n\t\t\tcontinue\n\t\t}\n\t\tseen[s] = struct{}{}\n\t\tuniq = append(uniq, s)\n\t}\n\treturn uniq\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $ go run gazel.go -r .\/vendor\n\/\/ $ go run gazel.go -r .\/federation\n\/\/ $ go run gazel.go -r .\/contrib\n\/\/ $ go run gazel.go -r .\/plugin\n\/\/ $ go run gazel.go -r .\/test\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\tbzl \"github.com\/bazelbuild\/buildifier\/core\"\n\t\"github.com\/golang\/glog\"\n)\n\nvar kubeRoot = os.Getenv(\"KUBE_ROOT\")\nvar dryRun = flag.Bool(\"dry-run\", false, \"run in dry mode\")\n\nfunc main() {\n\tflag.Parse()\n\tflag.Set(\"alsologtostderr\", \"true\")\n\tv := Venderor{\n\t\tctx: &build.Default,\n\t}\n\tif len(os.Args) == 2 {\n\t\tv.updateSinglePkg(os.Args[1])\n\t} else {\n\t\tv.walkVendor()\n\t\tif err := v.walkRepo(); err != nil {\n\t\t\tglog.Fatalf(\"err: %v\", err)\n\t\t}\n\t}\n}\n\ntype Venderor struct {\n\tctx *build.Context\n}\n\nfunc writeHeaders(file *bzl.File) {\n\tpkgRule := bzl.Rule{\n\t\t&bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: \"package\"},\n\t\t},\n\t}\n\tpkgRule.SetAttr(\"default_visibility\", asExpr([]string{\"\/\/visibility:public\"}))\n\n\tfile.Stmt = append(file.Stmt,\n\t\t[]bzl.Expr{\n\t\t\tpkgRule.Call,\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX:    &bzl.LiteralExpr{Token: \"licenses\"},\n\t\t\t\tList: []bzl.Expr{asExpr([]string{\"notice\"})},\n\t\t\t},\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX: &bzl.LiteralExpr{Token: \"load\"},\n\t\t\t\tList: asExpr([]string{\n\t\t\t\t\t\"@io_bazel_rules_go\/\/go:def.bzl\",\n\t\t\t\t\t\"go_binary\",\n\t\t\t\t\t\"go_library\",\n\t\t\t\t\t\"go_test\",\n\t\t\t\t\t\"cgo_library\",\n\t\t\t\t}).(*bzl.ListExpr).List,\n\t\t\t},\n\t\t}...,\n\t)\n}\n\nfunc writeRules(file *bzl.File, rules []*bzl.Rule) {\n\tfor _, rule := range rules {\n\t\tfile.Stmt = append(file.Stmt, rule.Call)\n\t}\n}\n\nfunc (v *Venderor) resolve(ipath string) Label {\n\tif strings.HasPrefix(ipath, \"k8s.io\/kubernetes\") {\n\t\treturn Label{\n\t\t\tpkg: strings.TrimPrefix(ipath, \"k8s.io\/kubernetes\/\"),\n\t\t\ttag: \"go_default_library\",\n\t\t}\n\t}\n\treturn Label{\n\t\tpkg: \"vendor\",\n\t\ttag: ipath,\n\t}\n}\n\nfunc (v *Venderor) walk(root string, f func(path, ipath string, pkg *build.Package) error) error {\n\treturn filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tipath, err := filepath.Rel(root, path)\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\t\tpkg, err := v.ctx.ImportDir(filepath.Join(kubeRoot, path), build.ImportComment)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn f(path, ipath, pkg)\n\t})\n}\n\nfunc (v *Venderor) walkRepo() error {\n\tfor _, root := range []string{\n\t\t\".\/pkg\",\n\t\t\".\/cmd\",\n\t\t\".\/third_party\",\n\t\t\".\/plugin\",\n\t\t\".\/test\",\n\t\t\".\/federation\",\n\t} {\n\t\tif err := v.walk(root, v.updatePkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) updateSinglePkg(path string) error {\n\tpkg, err := v.ctx.ImportDir(\".\/\"+path, build.ImportComment)\n\tif err != nil {\n\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn v.updatePkg(path, \"\", pkg)\n}\n\nfunc (v *Venderor) updatePkg(path, _ string, pkg *build.Package) error {\n\tvar rules []*bzl.Rule\n\n\tvar attrs Attrs = make(Attrs)\n\tsrcs := asExpr(merge(pkg.GoFiles, pkg.SFiles)).(*bzl.ListExpr)\n\n\tdeps := v.extractDeps(pkg.Imports)\n\n\tif len(srcs.List) == 0 {\n\t\treturn nil\n\t}\n\tattrs.Set(\"srcs\", srcs)\n\n\tif len(deps.List) > 0 {\n\t\tattrs.Set(\"deps\", deps)\n\t}\n\n\tif pkg.IsCommand() {\n\t\trules = append(rules, newRule(\"go_binary\", filepath.Base(pkg.Dir), attrs))\n\t} else {\n\t\trules = append(rules, newRule(\"go_library\", \"go_default_library\", attrs))\n\t\tif len(pkg.TestGoFiles) != 0 {\n\t\t\trules = append(rules, newRule(\"go_test\", \"go_default_test\", map[string]bzl.Expr{\n\t\t\t\t\"srcs\":    asExpr(pkg.TestGoFiles),\n\t\t\t\t\"deps\":    v.extractDeps(pkg.TestImports),\n\t\t\t\t\"library\": asExpr(\"go_default_library\"),\n\t\t\t}))\n\t\t}\n\t}\n\n\tif len(pkg.XTestGoFiles) != 0 {\n\t\trules = append(rules, newRule(\"go_test\", \"go_default_xtest\", map[string]bzl.Expr{\n\t\t\t\"srcs\": asExpr(pkg.XTestGoFiles),\n\t\t\t\"deps\": v.extractDeps(pkg.XTestImports),\n\t\t}))\n\t}\n\n\twrote, err := ReconcileRules(filepath.Join(path, \"BUILD\"), rules)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif wrote {\n\t\tfmt.Fprintf(os.Stderr, \"wrote BUILD for %q\\n\", pkg.ImportPath)\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) walkVendor() {\n\tvar rules []*bzl.Rule\n\tif err := v.walk(\".\/vendor\", func(path, ipath string, pkg *build.Package) error {\n\t\tvar attrs Attrs = make(Attrs)\n\n\t\tsrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.GoFiles, pkg.SFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tcgoSrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.CgoFiles, pkg.CFiles, pkg.CXXFiles, pkg.HFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tdeps := v.extractDeps(pkg.Imports)\n\t\tattrs.Set(\"srcs\", srcs)\n\n\t\tif len(deps.List) > 0 {\n\t\t\tattrs.Set(\"deps\", deps)\n\t\t}\n\n\t\tif pkg.IsCommand() {\n\t\t\trules = append(rules, newRule(\"go_binary\", v.resolve(ipath).tag, attrs))\n\t\t} else {\n\t\t\tif len(cgoSrcs.List) != 0 {\n\t\t\t\tcgoPname := v.resolve(ipath).tag + \"_cgo\"\n\t\t\t\tcgoDeps := v.extractDeps(pkg.TestImports)\n\t\t\t\tcgoRule := newRule(\"cgo_library\", cgoPname, map[string]bzl.Expr{\n\t\t\t\t\t\"srcs\":      cgoSrcs,\n\t\t\t\t\t\"clinkopts\": asExpr([]string{\"-ldl\", \"-lz\", \"-lm\", \"-lpthread\", \"-ldl\"}),\n\t\t\t\t})\n\t\t\t\trules = append(rules, cgoRule)\n\t\t\t\tif len(cgoDeps.List) != 0 {\n\t\t\t\t\tcgoRule.SetAttr(\"deps\", cgoDeps)\n\t\t\t\t}\n\t\t\t\tattrs[\"library\"] = asExpr(cgoPname)\n\t\t\t}\n\t\t\trules = append(rules, newRule(\"go_library\", v.resolve(ipath).tag, attrs))\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n\tif _, err := ReconcileRules(\".\/vendor\/BUILD\", rules); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n}\n\nfunc (v *Venderor) extractDeps(deps []string) *bzl.ListExpr {\n\treturn asExpr(\n\t\tapply(\n\t\t\tmerge(deps),\n\t\t\tfilterer(func(s string) bool {\n\t\t\t\tpkg, err := v.ctx.Import(s, kubeRoot, build.ImportComment)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif pkg.Goroot {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}),\n\t\t\tmapper(func(s string) string {\n\t\t\t\treturn v.resolve(s).String()\n\t\t\t}),\n\t\t),\n\t).(*bzl.ListExpr)\n}\n\ntype Attrs map[string]bzl.Expr\n\nfunc (a Attrs) Set(name string, expr bzl.Expr) {\n\ta[name] = expr\n}\n\ntype Label struct {\n\tpkg, tag string\n}\n\nfunc (l Label) String() string {\n\treturn fmt.Sprintf(\"\/\/%v:%v\", l.pkg, l.tag)\n}\n\nfunc asExpr(e interface{}) bzl.Expr {\n\trv := reflect.ValueOf(e)\n\tswitch rv.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%d\", e)}\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%f\", e)}\n\tcase reflect.String:\n\t\treturn &bzl.StringExpr{Value: e.(string)}\n\tcase reflect.Slice, reflect.Array:\n\t\tvar list []bzl.Expr\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tlist = append(list, asExpr(rv.Index(i).Interface()))\n\t\t}\n\t\treturn &bzl.ListExpr{List: list}\n\tdefault:\n\t\tglog.Fatalf(\"Uh oh\")\n\t\treturn nil\n\t}\n}\n\ntype Sed func(s []string) []string\n\nfunc mapString(in []string, f func(string) string) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tout = append(out, f(s))\n\t}\n\treturn out\n}\n\nfunc mapper(f func(string) string) Sed {\n\treturn func(in []string) []string {\n\t\treturn mapString(in, f)\n\t}\n}\n\nfunc filterString(in []string, f func(string) bool) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tif f(s) {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc filterer(f func(string) bool) Sed {\n\treturn func(in []string) []string {\n\t\treturn filterString(in, f)\n\t}\n}\n\nfunc apply(stream []string, seds ...Sed) []string {\n\tfor _, sed := range seds {\n\t\tstream = sed(stream)\n\t}\n\treturn stream\n}\n\nfunc merge(streams ...[]string) []string {\n\tvar out []string\n\tfor _, stream := range streams {\n\t\tout = append(out, stream...)\n\t}\n\treturn out\n}\n\nfunc newRule(kind, name string, attrs map[string]bzl.Expr) *bzl.Rule {\n\trule := &bzl.Rule{\n\t\tCall: &bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: kind},\n\t\t},\n\t}\n\trule.SetAttr(\"name\", asExpr(name))\n\tfor _, k := range sortKeys(attrs) {\n\t\trule.SetAttr(k, attrs[k])\n\t}\n\trule.SetAttr(\"tags\", asExpr([]string{\"automanaged\"}))\n\treturn rule\n}\n\nfunc sortKeys(attrs map[string]bzl.Expr) []string {\n\tks := []string{}\n\tfor k, _ := range attrs {\n\t\tks = append(ks, k)\n\t}\n\tsort.Sort(orderedAttrs(ks))\n\treturn ks\n}\n\ntype orderedAttrs []string\n\nvar orderedAttrsPriority = map[string]int{\n\t\"name\":    1,\n\t\"srcs\":    2,\n\t\"deps\":    3,\n\t\"library\": 4,\n\t\"tags\":    5,\n}\n\nfunc (o orderedAttrs) Len() int {\n\treturn len(o)\n}\n\nfunc (o orderedAttrs) Swap(i, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n\nfunc (o orderedAttrs) Less(i, j int) bool {\n\tip, iok := orderedAttrsPriority[o[i]]\n\tjp, jok := orderedAttrsPriority[o[j]]\n\tif iok && jok {\n\t\treturn ip < jp\n\t}\n\tif iok && !jok {\n\t\treturn false\n\t}\n\tif jok && !iok {\n\t\treturn true\n\t}\n\treturn o[i] < o[j]\n}\n\nfunc ReconcileRules(path string, rules []*bzl.Rule) (bool, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil && os.IsNotExist(err) {\n\t\tf := &bzl.File{}\n\t\twriteHeaders(f)\n\t\twriteRules(f, rules)\n\t\treturn true, writeFile(path, bzl.Format(f))\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tif info.IsDir() {\n\t\treturn false, fmt.Errorf(\"%q cannot be a directory\", path)\n\t}\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tf, err := bzl.Parse(path, b)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\toldRules := make(map[string]*bzl.Rule)\n\tfor _, r := range f.Rules(\"\") {\n\t\toldRules[r.Name()] = r\n\t}\n\tfor _, r := range rules {\n\t\to, ok := oldRules[r.Name()]\n\t\tif !ok {\n\t\t\tf.Stmt = append(f.Stmt, r.Call)\n\t\t\tcontinue\n\t\t}\n\t\tif !RuleIsManaged(o) {\n\t\t\tcontinue\n\t\t}\n\t\treconcileAttr := func(o, n *bzl.Rule, name string) {\n\t\t\tif e := n.Attr(name); e != nil {\n\t\t\t\to.SetAttr(name, e)\n\t\t\t} else {\n\t\t\t\to.DelAttr(name)\n\t\t\t}\n\t\t}\n\t\treconcileAttr(o, r, \"srcs\")\n\t\treconcileAttr(o, r, \"deps\")\n\t\treconcileAttr(o, r, \"library\")\n\t\tdelete(oldRules, r.Name())\n\t}\n\tfor _, r := range oldRules {\n\t\tif !RuleIsManaged(r) {\n\t\t\tcontinue\n\t\t}\n\t\tf.DelRules(r.Kind(), r.Name())\n\t}\n\tout := bzl.Format(f)\n\torig, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif bytes.Compare(out, orig) == 0 {\n\t\treturn false, err\n\t}\n\treturn true, writeFile(path, bzl.Format(f))\n}\n\nfunc RuleIsManaged(r *bzl.Rule) bool {\n\tvar automanaged bool\n\tfor _, tag := range r.AttrStrings(\"tags\") {\n\t\tif tag == \"automanaged\" {\n\t\t\tautomanaged = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn automanaged\n}\n\nfunc writeFile(path string, b []byte) error {\n\tif *dryRun {\n\t\treturn nil\n\t}\n\treturn ioutil.WriteFile(path, b, 0644)\n\n}\n<commit_msg>fix flag bug<commit_after>\/\/ $ go run gazel.go -r .\/vendor\n\/\/ $ go run gazel.go -r .\/federation\n\/\/ $ go run gazel.go -r .\/contrib\n\/\/ $ go run gazel.go -r .\/plugin\n\/\/ $ go run gazel.go -r .\/test\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"strings\"\n\n\tbzl \"github.com\/bazelbuild\/buildifier\/core\"\n\t\"github.com\/golang\/glog\"\n)\n\nvar kubeRoot = os.Getenv(\"KUBE_ROOT\")\nvar dryRun = flag.Bool(\"dry-run\", false, \"run in dry mode\")\n\nfunc main() {\n\tflag.Parse()\n\tflag.Set(\"alsologtostderr\", \"true\")\n\tv := Venderor{\n\t\tctx: &build.Default,\n\t}\n\tif len(flag.Args()) == 2 {\n\t\tv.updateSinglePkg(flag.Args()[1])\n\t} else {\n\t\tv.walkVendor()\n\t\tif err := v.walkRepo(); err != nil {\n\t\t\tglog.Fatalf(\"err: %v\", err)\n\t\t}\n\t}\n}\n\ntype Venderor struct {\n\tctx *build.Context\n}\n\nfunc writeHeaders(file *bzl.File) {\n\tpkgRule := bzl.Rule{\n\t\t&bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: \"package\"},\n\t\t},\n\t}\n\tpkgRule.SetAttr(\"default_visibility\", asExpr([]string{\"\/\/visibility:public\"}))\n\n\tfile.Stmt = append(file.Stmt,\n\t\t[]bzl.Expr{\n\t\t\tpkgRule.Call,\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX:    &bzl.LiteralExpr{Token: \"licenses\"},\n\t\t\t\tList: []bzl.Expr{asExpr([]string{\"notice\"})},\n\t\t\t},\n\t\t\t&bzl.CallExpr{\n\t\t\t\tX: &bzl.LiteralExpr{Token: \"load\"},\n\t\t\t\tList: asExpr([]string{\n\t\t\t\t\t\"@io_bazel_rules_go\/\/go:def.bzl\",\n\t\t\t\t\t\"go_binary\",\n\t\t\t\t\t\"go_library\",\n\t\t\t\t\t\"go_test\",\n\t\t\t\t\t\"cgo_library\",\n\t\t\t\t}).(*bzl.ListExpr).List,\n\t\t\t},\n\t\t}...,\n\t)\n}\n\nfunc writeRules(file *bzl.File, rules []*bzl.Rule) {\n\tfor _, rule := range rules {\n\t\tfile.Stmt = append(file.Stmt, rule.Call)\n\t}\n}\n\nfunc (v *Venderor) resolve(ipath string) Label {\n\tif strings.HasPrefix(ipath, \"k8s.io\/kubernetes\") {\n\t\treturn Label{\n\t\t\tpkg: strings.TrimPrefix(ipath, \"k8s.io\/kubernetes\/\"),\n\t\t\ttag: \"go_default_library\",\n\t\t}\n\t}\n\treturn Label{\n\t\tpkg: \"vendor\",\n\t\ttag: ipath,\n\t}\n}\n\nfunc (v *Venderor) walk(root string, f func(path, ipath string, pkg *build.Package) error) error {\n\treturn filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tipath, err := filepath.Rel(root, path)\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\t\tpkg, err := v.ctx.ImportDir(filepath.Join(kubeRoot, path), build.ImportComment)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\t\treturn nil\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn f(path, ipath, pkg)\n\t})\n}\n\nfunc (v *Venderor) walkRepo() error {\n\tfor _, root := range []string{\n\t\t\".\/pkg\",\n\t\t\".\/cmd\",\n\t\t\".\/third_party\",\n\t\t\".\/plugin\",\n\t\t\".\/test\",\n\t\t\".\/federation\",\n\t} {\n\t\tif err := v.walk(root, v.updatePkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) updateSinglePkg(path string) error {\n\tpkg, err := v.ctx.ImportDir(\".\/\"+path, build.ImportComment)\n\tif err != nil {\n\t\tif _, ok := err.(*build.NoGoError); err != nil && ok {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn v.updatePkg(path, \"\", pkg)\n}\n\nfunc (v *Venderor) updatePkg(path, _ string, pkg *build.Package) error {\n\tvar rules []*bzl.Rule\n\n\tvar attrs Attrs = make(Attrs)\n\tsrcs := asExpr(merge(pkg.GoFiles, pkg.SFiles)).(*bzl.ListExpr)\n\n\tdeps := v.extractDeps(pkg.Imports)\n\n\tif len(srcs.List) == 0 {\n\t\treturn nil\n\t}\n\tattrs.Set(\"srcs\", srcs)\n\n\tif len(deps.List) > 0 {\n\t\tattrs.Set(\"deps\", deps)\n\t}\n\n\tif pkg.IsCommand() {\n\t\trules = append(rules, newRule(\"go_binary\", filepath.Base(pkg.Dir), attrs))\n\t} else {\n\t\trules = append(rules, newRule(\"go_library\", \"go_default_library\", attrs))\n\t\tif len(pkg.TestGoFiles) != 0 {\n\t\t\trules = append(rules, newRule(\"go_test\", \"go_default_test\", map[string]bzl.Expr{\n\t\t\t\t\"srcs\":    asExpr(pkg.TestGoFiles),\n\t\t\t\t\"deps\":    v.extractDeps(pkg.TestImports),\n\t\t\t\t\"library\": asExpr(\"go_default_library\"),\n\t\t\t}))\n\t\t}\n\t}\n\n\tif len(pkg.XTestGoFiles) != 0 {\n\t\trules = append(rules, newRule(\"go_test\", \"go_default_xtest\", map[string]bzl.Expr{\n\t\t\t\"srcs\": asExpr(pkg.XTestGoFiles),\n\t\t\t\"deps\": v.extractDeps(pkg.XTestImports),\n\t\t}))\n\t}\n\n\twrote, err := ReconcileRules(filepath.Join(path, \"BUILD\"), rules)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif wrote {\n\t\tfmt.Fprintf(os.Stderr, \"wrote BUILD for %q\\n\", pkg.ImportPath)\n\t}\n\treturn nil\n}\n\nfunc (v *Venderor) walkVendor() {\n\tvar rules []*bzl.Rule\n\tif err := v.walk(\".\/vendor\", func(path, ipath string, pkg *build.Package) error {\n\t\tvar attrs Attrs = make(Attrs)\n\n\t\tsrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.GoFiles, pkg.SFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tcgoSrcs := asExpr(\n\t\t\tapply(\n\t\t\t\tmerge(pkg.CgoFiles, pkg.CFiles, pkg.CXXFiles, pkg.HFiles),\n\t\t\t\tmapper(func(s string) string {\n\t\t\t\t\treturn strings.TrimPrefix(filepath.Join(path, s), \"vendor\/\")\n\t\t\t\t}),\n\t\t\t),\n\t\t).(*bzl.ListExpr)\n\n\t\tdeps := v.extractDeps(pkg.Imports)\n\t\tattrs.Set(\"srcs\", srcs)\n\n\t\tif len(deps.List) > 0 {\n\t\t\tattrs.Set(\"deps\", deps)\n\t\t}\n\n\t\tif pkg.IsCommand() {\n\t\t\trules = append(rules, newRule(\"go_binary\", v.resolve(ipath).tag, attrs))\n\t\t} else {\n\t\t\tif len(cgoSrcs.List) != 0 {\n\t\t\t\tcgoPname := v.resolve(ipath).tag + \"_cgo\"\n\t\t\t\tcgoDeps := v.extractDeps(pkg.TestImports)\n\t\t\t\tcgoRule := newRule(\"cgo_library\", cgoPname, map[string]bzl.Expr{\n\t\t\t\t\t\"srcs\":      cgoSrcs,\n\t\t\t\t\t\"clinkopts\": asExpr([]string{\"-ldl\", \"-lz\", \"-lm\", \"-lpthread\", \"-ldl\"}),\n\t\t\t\t})\n\t\t\t\trules = append(rules, cgoRule)\n\t\t\t\tif len(cgoDeps.List) != 0 {\n\t\t\t\t\tcgoRule.SetAttr(\"deps\", cgoDeps)\n\t\t\t\t}\n\t\t\t\tattrs[\"library\"] = asExpr(cgoPname)\n\t\t\t}\n\t\t\trules = append(rules, newRule(\"go_library\", v.resolve(ipath).tag, attrs))\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n\tif _, err := ReconcileRules(\".\/vendor\/BUILD\", rules); err != nil {\n\t\tglog.Fatalf(\"err: %v\", err)\n\t}\n}\n\nfunc (v *Venderor) extractDeps(deps []string) *bzl.ListExpr {\n\treturn asExpr(\n\t\tapply(\n\t\t\tmerge(deps),\n\t\t\tfilterer(func(s string) bool {\n\t\t\t\tpkg, err := v.ctx.Import(s, kubeRoot, build.ImportComment)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif pkg.Goroot {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\treturn true\n\t\t\t}),\n\t\t\tmapper(func(s string) string {\n\t\t\t\treturn v.resolve(s).String()\n\t\t\t}),\n\t\t),\n\t).(*bzl.ListExpr)\n}\n\ntype Attrs map[string]bzl.Expr\n\nfunc (a Attrs) Set(name string, expr bzl.Expr) {\n\ta[name] = expr\n}\n\ntype Label struct {\n\tpkg, tag string\n}\n\nfunc (l Label) String() string {\n\treturn fmt.Sprintf(\"\/\/%v:%v\", l.pkg, l.tag)\n}\n\nfunc asExpr(e interface{}) bzl.Expr {\n\trv := reflect.ValueOf(e)\n\tswitch rv.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\t\treflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%d\", e)}\n\tcase reflect.Float32, reflect.Float64:\n\t\treturn &bzl.LiteralExpr{Token: fmt.Sprintf(\"%f\", e)}\n\tcase reflect.String:\n\t\treturn &bzl.StringExpr{Value: e.(string)}\n\tcase reflect.Slice, reflect.Array:\n\t\tvar list []bzl.Expr\n\t\tfor i := 0; i < rv.Len(); i++ {\n\t\t\tlist = append(list, asExpr(rv.Index(i).Interface()))\n\t\t}\n\t\treturn &bzl.ListExpr{List: list}\n\tdefault:\n\t\tglog.Fatalf(\"Uh oh\")\n\t\treturn nil\n\t}\n}\n\ntype Sed func(s []string) []string\n\nfunc mapString(in []string, f func(string) string) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tout = append(out, f(s))\n\t}\n\treturn out\n}\n\nfunc mapper(f func(string) string) Sed {\n\treturn func(in []string) []string {\n\t\treturn mapString(in, f)\n\t}\n}\n\nfunc filterString(in []string, f func(string) bool) []string {\n\tvar out []string\n\tfor _, s := range in {\n\t\tif f(s) {\n\t\t\tout = append(out, s)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc filterer(f func(string) bool) Sed {\n\treturn func(in []string) []string {\n\t\treturn filterString(in, f)\n\t}\n}\n\nfunc apply(stream []string, seds ...Sed) []string {\n\tfor _, sed := range seds {\n\t\tstream = sed(stream)\n\t}\n\treturn stream\n}\n\nfunc merge(streams ...[]string) []string {\n\tvar out []string\n\tfor _, stream := range streams {\n\t\tout = append(out, stream...)\n\t}\n\treturn out\n}\n\nfunc newRule(kind, name string, attrs map[string]bzl.Expr) *bzl.Rule {\n\trule := &bzl.Rule{\n\t\tCall: &bzl.CallExpr{\n\t\t\tX: &bzl.LiteralExpr{Token: kind},\n\t\t},\n\t}\n\trule.SetAttr(\"name\", asExpr(name))\n\tfor k, v := range attrs {\n\t\trule.SetAttr(k, v)\n\t}\n\trule.SetAttr(\"tags\", asExpr([]string{\"automanaged\"}))\n\treturn rule\n}\n\nfunc ReconcileRules(path string, rules []*bzl.Rule) (bool, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil && os.IsNotExist(err) {\n\t\tf := &bzl.File{}\n\t\twriteHeaders(f)\n\t\twriteRules(f, rules)\n\t\treturn writeFile(path, f, false)\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\tif info.IsDir() {\n\t\treturn false, fmt.Errorf(\"%q cannot be a directory\", path)\n\t}\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tf, err := bzl.Parse(path, b)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\toldRules := make(map[string]*bzl.Rule)\n\tfor _, r := range f.Rules(\"\") {\n\t\toldRules[r.Name()] = r\n\t}\n\tfor _, r := range rules {\n\t\to, ok := oldRules[r.Name()]\n\t\tif !ok {\n\t\t\tf.Stmt = append(f.Stmt, r.Call)\n\t\t\tcontinue\n\t\t}\n\t\tif !RuleIsManaged(o) {\n\t\t\tcontinue\n\t\t}\n\t\treconcileAttr := func(o, n *bzl.Rule, name string) {\n\t\t\tif e := n.Attr(name); e != nil {\n\t\t\t\to.SetAttr(name, e)\n\t\t\t} else {\n\t\t\t\to.DelAttr(name)\n\t\t\t}\n\t\t}\n\t\treconcileAttr(o, r, \"srcs\")\n\t\treconcileAttr(o, r, \"deps\")\n\t\treconcileAttr(o, r, \"library\")\n\t\tdelete(oldRules, r.Name())\n\t}\n\tfor _, r := range oldRules {\n\t\tif !RuleIsManaged(r) {\n\t\t\tcontinue\n\t\t}\n\t\tf.DelRules(r.Kind(), r.Name())\n\t}\n\treturn writeFile(path, f, true)\n}\n\nfunc RuleIsManaged(r *bzl.Rule) bool {\n\tvar automanaged bool\n\tfor _, tag := range r.AttrStrings(\"tags\") {\n\t\tif tag == \"automanaged\" {\n\t\t\tautomanaged = true\n\t\t\tbreak\n\t\t}\n\t}\n\treturn automanaged\n}\n\nfunc writeFile(path string, f *bzl.File, exists bool) (bool, error) {\n\tvar info bzl.RewriteInfo\n\tbzl.Rewrite(f, &info)\n\tout := bzl.Format(f)\n\tif exists {\n\t\torig, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif bytes.Compare(out, orig) == 0 {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\tif *dryRun {\n\t\treturn true, nil\n\t}\n\treturn true, ioutil.WriteFile(path, out, 0644)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package kite\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\t\"koding\/newkite\/dnode\"\n\t\"koding\/newkite\/dnode\/rpc\"\n\t\"koding\/newkite\/protocol\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst DefaultCallTimeout = 4000 \/\/ milliseconds\n\n\/\/ RemoteKite is the client for communicating with another Kite.\n\/\/ It has Call() and Go() methods for calling methods sync\/async way.\ntype RemoteKite struct {\n\t\/\/ The information about the kite that we are connecting to.\n\tprotocol.Kite\n\n\t\/\/ A reference to the current Kite running.\n\tlocalKite *Kite\n\n\t\/\/ A reference to the Kite's logger for easy access.\n\tLog *logging.Logger\n\n\t\/\/ Credentials that we sent in each request.\n\tAuthentication callAuthentication\n\n\t\/\/ dnode RPC client that processes messages.\n\tclient *rpc.Client\n\n\t\/\/ To signal waiters of Go() on disconnect.\n\tdisconnect chan bool\n\n\t\/\/ Duration to wait reply from remote when making a request with Call().\n\tcallTimeout time.Duration\n}\n\n\/\/ NewRemoteKite returns a pointer to a new RemoteKite. The returned instance\n\/\/ is not connected. You have to call Dial() or DialForever() before calling\n\/\/ Call() and Go() methods.\nfunc (k *Kite) NewRemoteKite(kite protocol.Kite, auth callAuthentication) *RemoteKite {\n\tr := &RemoteKite{\n\t\tKite:           kite,\n\t\tlocalKite:      k,\n\t\tLog:            k.Log,\n\t\tAuthentication: auth,\n\t\tclient:         k.server.NewClientWithHandlers(),\n\t\tdisconnect:     make(chan bool),\n\t}\n\tr.SetCallTimeout(DefaultCallTimeout)\n\n\t\/\/ We need a reference to the local kite when a method call is received.\n\tr.client.Properties()[\"localKite\"] = k\n\n\tr.OnConnect(func() {\n\t\tif r.Authentication.ValidUntil == nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Start a goroutine that will renew the token before it expires.\n\t\tgo r.tokenRenewer()\n\t})\n\n\tvar m sync.Mutex\n\tr.OnDisconnect(func() {\n\t\tm.Lock()\n\t\tclose(r.disconnect)\n\t\tr.disconnect = make(chan bool)\n\t\tm.Unlock()\n\t})\n\n\treturn r\n}\n\n\/\/ newRemoteKiteWithClient returns a pointer to new RemoteKite instance.\n\/\/ The client will be replaced with the given client.\n\/\/ Used to give the Kite method handler a working RemoteKite to call methods\n\/\/ on other side.\nfunc (k *Kite) newRemoteKiteWithClient(kite protocol.Kite, auth callAuthentication, client *rpc.Client) *RemoteKite {\n\tr := k.NewRemoteKite(kite, auth)\n\tr.client = client\n\tr.client.Properties()[\"localKite\"] = k\n\treturn r\n}\n\nfunc (r *RemoteKite) SetCallTimeout(ms uint) {\n\tr.callTimeout = time.Duration(ms) * time.Millisecond\n}\n\n\/\/ Dial connects to the remote Kite. Returns error if it can't.\nfunc (r *RemoteKite) Dial() (err error) {\n\taddr := r.Kite.Addr()\n\tr.Log.Info(\"Dialing remote kite: [%s %s]\", r.Kite.Name, addr)\n\treturn r.client.Dial(\"ws:\/\/\" + addr + \"\/dnode\")\n}\n\n\/\/ Dial connects to the remote Kite. If it can't connect, it retries indefinitely.\nfunc (r *RemoteKite) DialForever() {\n\taddr := r.Kite.Addr()\n\tr.Log.Info(\"Dialing remote kite: [%s %s]\", r.Kite.Name, addr)\n\tr.client.DialForever(\"ws:\/\/\" + addr + \"\/dnode\")\n}\n\nfunc (r *RemoteKite) Close() {\n\tr.client.Close()\n}\n\n\/\/ OnConnect registers a function to run on connect.\nfunc (r *RemoteKite) OnConnect(handler func()) {\n\tr.client.OnConnect(handler)\n}\n\n\/\/ OnDisconnect registers a function to run on disconnect.\nfunc (r *RemoteKite) OnDisconnect(handler func()) {\n\tr.client.OnDisconnect(handler)\n}\n\nfunc (r *RemoteKite) tokenRenewer() {\n\tfor {\n\t\trenewTime := r.Authentication.ValidUntil.Add(-30 * time.Second)\n\t\tselect {\n\t\tcase <-time.After(renewTime.Sub(time.Now().UTC())):\n\t\t\tif err := r.renewTokenUntilDisconnect(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-r.disconnect:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ renewToken retries until the request is successful or disconnect.\nfunc (r *RemoteKite) renewTokenUntilDisconnect() error {\n\tconst retryInterval = 10 * time.Second\n\n\tif err := r.renewToken(); err == nil {\n\t\treturn nil\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(retryInterval):\n\t\t\tif err := r.renewToken(); err != nil {\n\t\t\t\tr.Log.Error(\"error: %s Cannot renew token for Kite: %s I will retry in %d seconds...\", err.Error(), r.Kite.ID, retryInterval)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbreak\n\t\tcase <-r.disconnect:\n\t\t\treturn errors.New(\"disconnect\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *RemoteKite) renewToken() error {\n\ttkn, err := r.localKite.Kontrol.GetToken(&r.Kite)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalidUntil := time.Now().UTC().Add(time.Duration(tkn.TTL) * time.Second)\n\tr.Authentication.Key = tkn.Key\n\tr.Authentication.ValidUntil = &validUntil\n\n\treturn nil\n}\n\n\/\/ CallOptions is the type of first argument in the dnode message.\n\/\/ Second argument is a callback function.\n\/\/ It is used when unmarshalling a dnode message.\ntype CallOptions struct {\n\t\/\/ Arguments to the method\n\tWithArgs       *dnode.Partial     `json:\"withArgs\"`\n\tKite           protocol.Kite      `json:\"kite\"`\n\tAuthentication callAuthentication `json:\"authentication\"`\n}\n\n\/\/ callOptionsOut is the same structure with CallOptions.\n\/\/ It is used when marshalling a dnode message.\ntype callOptionsOut struct {\n\tCallOptions\n\t\/\/ Override this when sending because args will not be a *dnode.Partial.\n\tWithArgs interface{} `json:\"withArgs\"`\n}\n\n\/\/ That's what we send as a first argument in dnode message.\nfunc (r *RemoteKite) makeOptions(args interface{}) *callOptionsOut {\n\treturn &callOptionsOut{\n\t\tWithArgs: args,\n\t\tCallOptions: CallOptions{\n\t\t\tKite:           r.localKite.Kite,\n\t\t\tAuthentication: r.Authentication,\n\t\t},\n\t}\n}\n\ntype callAuthentication struct {\n\t\/\/ Type can be \"kodingKey\", \"token\" or \"sessionID\" for now.\n\tType       string     `json:\"type\"`\n\tKey        string     `json:\"key\"`\n\tValidUntil *time.Time `json:\"-\"`\n}\n\ntype response struct {\n\tResult *dnode.Partial\n\tErr    error\n}\n\n\/\/ Call makes a blocking method call to the server.\n\/\/ Waits until the callback function is called by the other side and\n\/\/ returns the result and the error.\nfunc (r *RemoteKite) Call(method string, args interface{}) (result *dnode.Partial, err error) {\n\tresponse := <-r.Go(method, args)\n\treturn response.Result, response.Err\n}\n\n\/\/ Go makes an unblocking method call to the server.\n\/\/ It returns a channel that the caller can wait on it to get the response.\nfunc (r *RemoteKite) Go(method string, args interface{}) chan *response {\n\t\/\/ We will return this channel to the caller.\n\t\/\/ It can wait on this channel to get the response.\n\tr.Log.Debug(\"Calling method [%s] on kite [%s]\", method, r.Name)\n\tresponseChan := make(chan *response, 1)\n\n\tr.send(method, args, responseChan)\n\n\treturn responseChan\n}\n\n\/\/ send sends the method with callback to the server.\nfunc (r *RemoteKite) send(method string, args interface{}, responseChan chan *response) {\n\t\/\/ To clean the sent callback after response is received.\n\t\/\/ Send\/Receive in a channel to prevent race condition because\n\t\/\/ the callback is run in a separate goroutine.\n\tremoveCallback := make(chan uint64, 1)\n\n\t\/\/ When a callback is called it will send the response to this channel.\n\tdoneChan := make(chan *response, 1)\n\n\topts := r.makeOptions(args)\n\tcb := r.makeResponseCallback(doneChan, removeCallback)\n\n\tcallbacks, err := r.client.Call(method, opts, cb)\n\tif err != nil {\n\t\tresponseChan <- &response{\n\t\t\tResult: nil,\n\t\t\tErr: fmt.Errorf(\"Calling method [%s] on [%s] error: %s\",\n\t\t\t\tmethod, r.Kite.Name, err),\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Waits until the response has came or the connection has disconnected.\n\tgo func() {\n\t\tselect {\n\t\tcase <-r.disconnect:\n\t\t\tresponseChan <- &response{nil, errors.New(\"Client disconnected\")}\n\t\tcase resp := <-doneChan:\n\t\t\tresponseChan <- resp\n\t\tcase <-time.After(r.callTimeout):\n\t\t\tresponseChan <- &response{nil, errors.New(\"Timeout\")}\n\n\t\t\t\/\/ Remove the callback function from the map so we do not\n\t\t\t\/\/ consume memory for unused callbacks.\n\t\t\tif id, ok := <-removeCallback; ok {\n\t\t\t\tr.client.RemoveCallback(id)\n\t\t\t}\n\t\t}\n\t}()\n\n\tsendCallbackID(callbacks, removeCallback)\n}\n\n\/\/ sendCallbackID send the callback number to be deleted after response is received.\nfunc sendCallbackID(callbacks map[string]dnode.Path, ch chan uint64) {\n\tif len(callbacks) > 0 {\n\t\t\/\/ Find max callback ID.\n\t\tmax := uint64(0)\n\t\tfor id, _ := range callbacks {\n\t\t\ti, _ := strconv.ParseUint(id, 10, 64)\n\t\t\tif i > max {\n\t\t\t\tmax = i\n\t\t\t}\n\t\t}\n\n\t\tch <- max\n\t} else {\n\t\tclose(ch)\n\t}\n}\n\n\/\/ makeResponseCallback prepares and returns a callback function sent to the server.\n\/\/ The caller of the Call() is blocked until the server calls this callback function.\n\/\/ Sets theResponse and notifies the caller by sending to done channel.\nfunc (r *RemoteKite) makeResponseCallback(doneChan chan *response, removeCallback <-chan uint64) Callback {\n\treturn Callback(func(request *Request) {\n\t\tvar (\n\t\t\terr    error          \/\/ First argument\n\t\t\tresult *dnode.Partial \/\/ Second argument\n\t\t)\n\n\t\t\/\/ Notify that the callback is finished.\n\t\tdefer func() { doneChan <- &response{result, err} }()\n\n\t\t\/\/ Remove the callback function from the map so we do not\n\t\t\/\/ consume memory for unused callbacks.\n\t\tif id, ok := <-removeCallback; ok {\n\t\t\tr.client.RemoveCallback(id)\n\t\t}\n\n\t\t\/\/ Arguments to our response callback It is a slice of length 2.\n\t\t\/\/ The first argument is the error string,\n\t\t\/\/ the second argument is the result.\n\t\tresponseArgs := request.Args.MustSliceOfLength(2)\n\n\t\t\/\/ The second argument is our result.\n\t\tresult = responseArgs[1]\n\n\t\t\/\/ This is error argument. Unmarshal panics if it is null.\n\t\tif responseArgs[0] == nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Read the error argument in response.\n\t\tvar kiteErr *Error\n\t\terr = responseArgs[0].Unmarshal(kiteErr)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = kiteErr\n\t})\n}\n<commit_msg>kite: add comment<commit_after>package kite\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\t\"koding\/newkite\/dnode\"\n\t\"koding\/newkite\/dnode\/rpc\"\n\t\"koding\/newkite\/protocol\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst DefaultCallTimeout = 4000 \/\/ milliseconds\n\n\/\/ RemoteKite is the client for communicating with another Kite.\n\/\/ It has Call() and Go() methods for calling methods sync\/async way.\ntype RemoteKite struct {\n\t\/\/ The information about the kite that we are connecting to.\n\tprotocol.Kite\n\n\t\/\/ A reference to the current Kite running.\n\tlocalKite *Kite\n\n\t\/\/ A reference to the Kite's logger for easy access.\n\tLog *logging.Logger\n\n\t\/\/ Credentials that we sent in each request.\n\tAuthentication callAuthentication\n\n\t\/\/ dnode RPC client that processes messages.\n\tclient *rpc.Client\n\n\t\/\/ To signal waiters of Go() on disconnect.\n\tdisconnect chan bool\n\n\t\/\/ Duration to wait reply from remote when making a request with Call().\n\tcallTimeout time.Duration\n}\n\n\/\/ NewRemoteKite returns a pointer to a new RemoteKite. The returned instance\n\/\/ is not connected. You have to call Dial() or DialForever() before calling\n\/\/ Call() and Go() methods.\nfunc (k *Kite) NewRemoteKite(kite protocol.Kite, auth callAuthentication) *RemoteKite {\n\tr := &RemoteKite{\n\t\tKite:           kite,\n\t\tlocalKite:      k,\n\t\tLog:            k.Log,\n\t\tAuthentication: auth,\n\t\tclient:         k.server.NewClientWithHandlers(),\n\t\tdisconnect:     make(chan bool),\n\t}\n\tr.SetCallTimeout(DefaultCallTimeout)\n\n\t\/\/ We need a reference to the local kite when a method call is received.\n\tr.client.Properties()[\"localKite\"] = k\n\n\tr.OnConnect(func() {\n\t\tif r.Authentication.ValidUntil == nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Start a goroutine that will renew the token before it expires.\n\t\tgo r.tokenRenewer()\n\t})\n\n\tvar m sync.Mutex\n\tr.OnDisconnect(func() {\n\t\tm.Lock()\n\t\tclose(r.disconnect)\n\t\tr.disconnect = make(chan bool)\n\t\tm.Unlock()\n\t})\n\n\treturn r\n}\n\n\/\/ newRemoteKiteWithClient returns a pointer to new RemoteKite instance.\n\/\/ The client will be replaced with the given client.\n\/\/ Used to give the Kite method handler a working RemoteKite to call methods\n\/\/ on other side.\nfunc (k *Kite) newRemoteKiteWithClient(kite protocol.Kite, auth callAuthentication, client *rpc.Client) *RemoteKite {\n\tr := k.NewRemoteKite(kite, auth)\n\tr.client = client\n\tr.client.Properties()[\"localKite\"] = k\n\treturn r\n}\n\n\/\/ SetCallTimeout sets the timeout duration for requests made with Call().\nfunc (r *RemoteKite) SetCallTimeout(ms uint) {\n\tr.callTimeout = time.Duration(ms) * time.Millisecond\n}\n\n\/\/ Dial connects to the remote Kite. Returns error if it can't.\nfunc (r *RemoteKite) Dial() (err error) {\n\taddr := r.Kite.Addr()\n\tr.Log.Info(\"Dialing remote kite: [%s %s]\", r.Kite.Name, addr)\n\treturn r.client.Dial(\"ws:\/\/\" + addr + \"\/dnode\")\n}\n\n\/\/ Dial connects to the remote Kite. If it can't connect, it retries indefinitely.\nfunc (r *RemoteKite) DialForever() {\n\taddr := r.Kite.Addr()\n\tr.Log.Info(\"Dialing remote kite: [%s %s]\", r.Kite.Name, addr)\n\tr.client.DialForever(\"ws:\/\/\" + addr + \"\/dnode\")\n}\n\nfunc (r *RemoteKite) Close() {\n\tr.client.Close()\n}\n\n\/\/ OnConnect registers a function to run on connect.\nfunc (r *RemoteKite) OnConnect(handler func()) {\n\tr.client.OnConnect(handler)\n}\n\n\/\/ OnDisconnect registers a function to run on disconnect.\nfunc (r *RemoteKite) OnDisconnect(handler func()) {\n\tr.client.OnDisconnect(handler)\n}\n\nfunc (r *RemoteKite) tokenRenewer() {\n\tfor {\n\t\trenewTime := r.Authentication.ValidUntil.Add(-30 * time.Second)\n\t\tselect {\n\t\tcase <-time.After(renewTime.Sub(time.Now().UTC())):\n\t\t\tif err := r.renewTokenUntilDisconnect(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-r.disconnect:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ renewToken retries until the request is successful or disconnect.\nfunc (r *RemoteKite) renewTokenUntilDisconnect() error {\n\tconst retryInterval = 10 * time.Second\n\n\tif err := r.renewToken(); err == nil {\n\t\treturn nil\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(retryInterval):\n\t\t\tif err := r.renewToken(); err != nil {\n\t\t\t\tr.Log.Error(\"error: %s Cannot renew token for Kite: %s I will retry in %d seconds...\", err.Error(), r.Kite.ID, retryInterval)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbreak\n\t\tcase <-r.disconnect:\n\t\t\treturn errors.New(\"disconnect\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *RemoteKite) renewToken() error {\n\ttkn, err := r.localKite.Kontrol.GetToken(&r.Kite)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalidUntil := time.Now().UTC().Add(time.Duration(tkn.TTL) * time.Second)\n\tr.Authentication.Key = tkn.Key\n\tr.Authentication.ValidUntil = &validUntil\n\n\treturn nil\n}\n\n\/\/ CallOptions is the type of first argument in the dnode message.\n\/\/ Second argument is a callback function.\n\/\/ It is used when unmarshalling a dnode message.\ntype CallOptions struct {\n\t\/\/ Arguments to the method\n\tWithArgs       *dnode.Partial     `json:\"withArgs\"`\n\tKite           protocol.Kite      `json:\"kite\"`\n\tAuthentication callAuthentication `json:\"authentication\"`\n}\n\n\/\/ callOptionsOut is the same structure with CallOptions.\n\/\/ It is used when marshalling a dnode message.\ntype callOptionsOut struct {\n\tCallOptions\n\t\/\/ Override this when sending because args will not be a *dnode.Partial.\n\tWithArgs interface{} `json:\"withArgs\"`\n}\n\n\/\/ That's what we send as a first argument in dnode message.\nfunc (r *RemoteKite) makeOptions(args interface{}) *callOptionsOut {\n\treturn &callOptionsOut{\n\t\tWithArgs: args,\n\t\tCallOptions: CallOptions{\n\t\t\tKite:           r.localKite.Kite,\n\t\t\tAuthentication: r.Authentication,\n\t\t},\n\t}\n}\n\ntype callAuthentication struct {\n\t\/\/ Type can be \"kodingKey\", \"token\" or \"sessionID\" for now.\n\tType       string     `json:\"type\"`\n\tKey        string     `json:\"key\"`\n\tValidUntil *time.Time `json:\"-\"`\n}\n\ntype response struct {\n\tResult *dnode.Partial\n\tErr    error\n}\n\n\/\/ Call makes a blocking method call to the server.\n\/\/ Waits until the callback function is called by the other side and\n\/\/ returns the result and the error.\nfunc (r *RemoteKite) Call(method string, args interface{}) (result *dnode.Partial, err error) {\n\tresponse := <-r.Go(method, args)\n\treturn response.Result, response.Err\n}\n\n\/\/ Go makes an unblocking method call to the server.\n\/\/ It returns a channel that the caller can wait on it to get the response.\nfunc (r *RemoteKite) Go(method string, args interface{}) chan *response {\n\t\/\/ We will return this channel to the caller.\n\t\/\/ It can wait on this channel to get the response.\n\tr.Log.Debug(\"Calling method [%s] on kite [%s]\", method, r.Name)\n\tresponseChan := make(chan *response, 1)\n\n\tr.send(method, args, responseChan)\n\n\treturn responseChan\n}\n\n\/\/ send sends the method with callback to the server.\nfunc (r *RemoteKite) send(method string, args interface{}, responseChan chan *response) {\n\t\/\/ To clean the sent callback after response is received.\n\t\/\/ Send\/Receive in a channel to prevent race condition because\n\t\/\/ the callback is run in a separate goroutine.\n\tremoveCallback := make(chan uint64, 1)\n\n\t\/\/ When a callback is called it will send the response to this channel.\n\tdoneChan := make(chan *response, 1)\n\n\topts := r.makeOptions(args)\n\tcb := r.makeResponseCallback(doneChan, removeCallback)\n\n\tcallbacks, err := r.client.Call(method, opts, cb)\n\tif err != nil {\n\t\tresponseChan <- &response{\n\t\t\tResult: nil,\n\t\t\tErr: fmt.Errorf(\"Calling method [%s] on [%s] error: %s\",\n\t\t\t\tmethod, r.Kite.Name, err),\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Waits until the response has came or the connection has disconnected.\n\tgo func() {\n\t\tselect {\n\t\tcase <-r.disconnect:\n\t\t\tresponseChan <- &response{nil, errors.New(\"Client disconnected\")}\n\t\tcase resp := <-doneChan:\n\t\t\tresponseChan <- resp\n\t\tcase <-time.After(r.callTimeout):\n\t\t\tresponseChan <- &response{nil, errors.New(\"Timeout\")}\n\n\t\t\t\/\/ Remove the callback function from the map so we do not\n\t\t\t\/\/ consume memory for unused callbacks.\n\t\t\tif id, ok := <-removeCallback; ok {\n\t\t\t\tr.client.RemoveCallback(id)\n\t\t\t}\n\t\t}\n\t}()\n\n\tsendCallbackID(callbacks, removeCallback)\n}\n\n\/\/ sendCallbackID send the callback number to be deleted after response is received.\nfunc sendCallbackID(callbacks map[string]dnode.Path, ch chan uint64) {\n\tif len(callbacks) > 0 {\n\t\t\/\/ Find max callback ID.\n\t\tmax := uint64(0)\n\t\tfor id, _ := range callbacks {\n\t\t\ti, _ := strconv.ParseUint(id, 10, 64)\n\t\t\tif i > max {\n\t\t\t\tmax = i\n\t\t\t}\n\t\t}\n\n\t\tch <- max\n\t} else {\n\t\tclose(ch)\n\t}\n}\n\n\/\/ makeResponseCallback prepares and returns a callback function sent to the server.\n\/\/ The caller of the Call() is blocked until the server calls this callback function.\n\/\/ Sets theResponse and notifies the caller by sending to done channel.\nfunc (r *RemoteKite) makeResponseCallback(doneChan chan *response, removeCallback <-chan uint64) Callback {\n\treturn Callback(func(request *Request) {\n\t\tvar (\n\t\t\terr    error          \/\/ First argument\n\t\t\tresult *dnode.Partial \/\/ Second argument\n\t\t)\n\n\t\t\/\/ Notify that the callback is finished.\n\t\tdefer func() { doneChan <- &response{result, err} }()\n\n\t\t\/\/ Remove the callback function from the map so we do not\n\t\t\/\/ consume memory for unused callbacks.\n\t\tif id, ok := <-removeCallback; ok {\n\t\t\tr.client.RemoveCallback(id)\n\t\t}\n\n\t\t\/\/ Arguments to our response callback It is a slice of length 2.\n\t\t\/\/ The first argument is the error string,\n\t\t\/\/ the second argument is the result.\n\t\tresponseArgs := request.Args.MustSliceOfLength(2)\n\n\t\t\/\/ The second argument is our result.\n\t\tresult = responseArgs[1]\n\n\t\t\/\/ This is error argument. Unmarshal panics if it is null.\n\t\tif responseArgs[0] == nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Read the error argument in response.\n\t\tvar kiteErr *Error\n\t\terr = responseArgs[0].Unmarshal(kiteErr)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = kiteErr\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\tr \"reflect\"\n\n\t\"strings\"\n\n\tsci \"github.com\/samuell\/scipipe\"\n)\n\nfunc main() {\n\tp := NewFooToBarReplacer()\n\tfmt.Println(\"Process: \", p)\n}\n\ntype FooToBarReplacer struct {\n\tsci.Process\n\tInnerProcess *sci.Process\n\tInFoo        chan *sci.FileTarget\n\tOutBar       chan *sci.FileTarget\n}\n\nfunc (p *FooToBarReplacer) Run() {\n\t\/\/ ...\n}\n\nfunc NewFooToBarReplacer() interface{} {\n\texecFunc := func(task *sci.ShellTask) {\n\t\tindata := task.InTargets[\"foo\"].Read()\n\t\tindataReplaced := bytes.Replace(indata, []byte(\"foo\"), []byte(\"bar\"), -1)\n\t\ttask.OutTargets[\"bar\"].WriteTempFile(indataReplaced)\n\t}\n\tpathFuncs := map[string]func(*sci.ShellTask) string{\n\t\t\"bar\": func(t *sci.ShellTask) string { return t.InTargets[\"foo\"].GetPath() + \".bar.txt\" },\n\t}\n\treturn NewProcessFromStruct(&FooToBarReplacer{}, execFunc, pathFuncs)\n}\n\nfunc NewProcessFromStruct(procStruct interface{}, execFunc func(*sci.ShellTask), pathFuncs map[string]func(*sci.ShellTask) string) interface{} {\n\t\/\/ Get in-ports of struct\n\tprocStructVal := r.ValueOf(procStruct).Elem()\n\tfor i := 0; i < procStructVal.NumField(); i++ {\n\t\tstructFieldName := procStructVal.Type().Field(i).Name\n\t\tstructFieldType := procStructVal.Type().Field(i).Type\n\t\texampleChan := make(chan *sci.FileTarget)\n\t\tif strings.HasPrefix(structFieldName, \"In\") && structFieldType == r.TypeOf(exampleChan) {\n\t\t\tfmt.Println(\"In-port:\", structFieldName)\n\t\t} else if strings.HasPrefix(structFieldName, \"Out\") && structFieldType == r.TypeOf(exampleChan) {\n\t\t\tfmt.Println(\"Out-port:\", structFieldName)\n\t\t}\n\t}\n\treturn procStruct\n}\n<commit_msg>Collecting in- and out-ports, in example 16<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\tr \"reflect\"\n\n\t\"strings\"\n\n\tsci \"github.com\/samuell\/scipipe\"\n)\n\nfunc main() {\n\tp := NewFooToBarReplacer()\n\tfmt.Println(\"Process: \", p)\n}\n\n\/\/ -------------------------------------------\n\/\/  Example of defining a new wrapper task\n\/\/ -------------------------------------------\n\ntype FooToBarReplacer struct {\n\tsci.Process\n\tInnerProcess *sci.Process\n\tRun          func(p *FooToBarReplacer)\n\tInFoo        chan *sci.FileTarget\n\tOutBar       chan *sci.FileTarget\n}\n\nfunc (p *FooToBarReplacer) Run() {\n\t\/\/ ...\n}\n\nfunc NewFooToBarReplacer() interface{} {\n\texecFunc := func(task *sci.ShellTask) {\n\t\tindata := task.InTargets[\"foo\"].Read()\n\t\tindataReplaced := bytes.Replace(indata, []byte(\"foo\"), []byte(\"bar\"), -1)\n\t\ttask.OutTargets[\"bar\"].WriteTempFile(indataReplaced)\n\t}\n\tpathFuncs := map[string]func(*sci.ShellTask) string{\n\t\t\"bar\": func(t *sci.ShellTask) string { return t.InTargets[\"foo\"].GetPath() + \".bar.txt\" },\n\t}\n\treturn NewProcessFromStruct(&FooToBarReplacer{}, execFunc, pathFuncs)\n}\n\n\/\/ -------------------------------------------\n\/\/  New helper methods\n\/\/ -------------------------------------------\n\nfunc NewProcessFromStruct(procStruct interface{}, execFunc func(*sci.ShellTask), pathFuncs map[string]func(*sci.ShellTask) string) interface{} {\n\t\/\/ Get in-ports of struct\n\tinPorts := map[string]chan *sci.FileTarget{}\n\toutPorts := map[string]chan *sci.FileTarget{}\n\n\tprocStructVal := r.ValueOf(procStruct).Elem()\n\tfor i := 0; i < procStructVal.NumField(); i++ {\n\t\tstructFieldName := procStructVal.Type().Field(i).Name\n\t\tstructFieldType := procStructVal.Type().Field(i).Type\n\t\texampleChan := make(chan *sci.FileTarget)\n\t\tif strings.HasPrefix(structFieldName, \"In\") && structFieldType == r.TypeOf(exampleChan) {\n\t\t\tfmt.Println(\"In-port:\", structFieldName)\n\t\t\tinPorts[strings.ToLower(structFieldName)] = exampleChan \/\/ TODO: Change this!\n\t\t} else if strings.HasPrefix(structFieldName, \"Out\") && structFieldType == r.TypeOf(exampleChan) {\n\t\t\tfmt.Println(\"Out-port:\", structFieldName)\n\t\t\toutPorts[strings.ToLower(structFieldName)] = exampleChan \/\/ TODO: Change this!\n\t\t}\n\t}\n\treturn procStruct\n}\n<|endoftext|>"}
{"text":"<commit_before>package payment\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/helpers\"\n\t\"sync\"\n\t\"time\"\n\n\t\"gopkg.in\/fatih\/set.v0\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\n\t\"github.com\/stripe\/stripe-go\"\n\t\"github.com\/stripe\/stripe-go\/customer\"\n\tstripeplan \"github.com\/stripe\/stripe-go\/plan\"\n\t\"github.com\/stripe\/stripe-go\/sub\"\n)\n\nvar (\n\t\/\/ ErrCustomerNotSubscribedToAnyPlans error for not subscribed users\n\tErrCustomerNotSubscribedToAnyPlans = errors.New(\"user is not subscribed to any plans\")\n\t\/\/ ErrCustomerNotExists error for not created users\n\tErrCustomerNotExists = errors.New(\"user is not created for subscription\")\n\t\/\/ ErrGroupAlreadyHasSub error when a group tries to create a sub and they try to create another\n\tErrGroupAlreadyHasSub = errors.New(\"group already has a subscription\")\n)\n\n\/\/ Usage holds current usage information, which will be calculated on the fly\ntype Usage struct {\n\tUser            *UserInfo\n\tExpectedPlan    *stripe.Plan\n\tDue             uint64\n\tNextBillingDate time.Time\n\tSubscription    *stripe.Sub\n}\n\n\/\/ UserInfo holds current info about team's user info\ntype UserInfo struct {\n\tTotal   int\n\tActive  int\n\tDeleted int\n}\n\n\/\/ DeleteCustomerForGroup deletes the customer for a given group. If customer is\n\/\/ not registered, returns error. If customer is already deleted, returns success.\nfunc DeleteCustomerForGroup(groupName string) error {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn ErrCustomerNotExists\n\t}\n\n\tif err := deleteCustomer(group.Payment.Customer.ID); err != nil {\n\t\treturn err\n\t}\n\n\treturn modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": group.Id},\n\t\tmodelhelper.Selector{\n\t\t\t\/\/ deleting customer deletes everything belong to that customer in stripe,\n\t\t\t\/\/ so say we all\n\t\t\t\"$unset\": modelhelper.Selector{\"payment\": \"\"},\n\t\t},\n\t)\n}\n\n\/\/ UpdateCustomerForGroup updates customer data of a group`\nfunc UpdateCustomerForGroup(username, groupName string, params *stripe.CustomerParams) (*stripe.Customer, error) {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn nil, ErrCustomerNotExists\n\t}\n\n\tparams, err = populateCustomerParams(username, groupName, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn customer.Update(group.Payment.Customer.ID, params)\n}\n\n\/\/ GetCustomerForGroup get the registered customer info of a group if exists\nfunc GetCustomerForGroup(groupName string) (*stripe.Customer, error) {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn nil, ErrCustomerNotExists\n\t}\n\n\treturn customer.Get(group.Payment.Customer.ID, nil)\n}\n\n\/\/ GetInfoForGroup get the current usage info of a group\nfunc GetInfoForGroup(group *models.Group) (*Usage, error) {\n\tusage, err := fetchParallelizableeUsageItems(group)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplan, err := getPlan(usage.Subscription, usage.User.Total)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusage.ExpectedPlan = plan\n\tusage.Due = uint64(usage.User.Total) * plan.Amount\n\n\treturn usage, nil\n\n}\n\nfunc fetchParallelizableeUsageItems(group *models.Group) (*Usage, error) {\n\tvar infoErr error\n\tvar errMu sync.Mutex\n\tvar wg sync.WaitGroup\n\n\twithCheck := func(f func() error) {\n\t\terrMu.Lock()\n\t\tif infoErr != nil {\n\t\t\terrMu.Unlock()\n\t\t\treturn\n\t\t}\n\t\terrMu.Unlock()\n\n\t\terr := f()\n\t\tif err != nil {\n\t\t\terrMu.Lock()\n\t\t\tinfoErr = err\n\t\t\terrMu.Unlock()\n\t\t}\n\t\twg.Done()\n\t}\n\n\tvar cus *stripe.Customer\n\twg.Add(1)\n\tgo withCheck(func() (err error) {\n\t\tif group.Payment.Customer.ID == \"\" {\n\t\t\treturn ErrCustomerNotExists\n\t\t}\n\n\t\tcus, err = customer.Get(group.Payment.Customer.ID, nil)\n\t\treturn err\n\t})\n\n\tvar subscription *stripe.Sub\n\twg.Add(1)\n\tgo withCheck(func() (err error) {\n\t\tif group.Payment.Subscription.ID == \"\" {\n\t\t\treturn ErrCustomerNotSubscribedToAnyPlans\n\t\t}\n\n\t\tsubscription, err = sub.Get(group.Payment.Subscription.ID, nil)\n\t\treturn err\n\t})\n\n\tvar activeCount int\n\twg.Add(1)\n\tgo withCheck(func() (err error) {\n\t\tactiveCount, err = calculateActiveUserCount(group.Id)\n\t\treturn err\n\t})\n\n\tvar deletedCount int\n\twg.Add(1)\n\tgo withCheck(func() (err error) {\n\t\tdeletedCount, err = modelhelper.GetDeletedMemberCountByGroupId(group.Id)\n\t\treturn err\n\t})\n\n\twg.Wait()\n\n\tif infoErr != nil {\n\t\treturn nil, infoErr\n\t}\n\n\ttotalCount := activeCount + deletedCount\n\n\t\/\/ if the team is in trialing period, and when we want to charge them, do\n\t\/\/ not include the deleted members\n\tif subscription.Status == \"trialing\" {\n\t\ttotalCount = activeCount\n\t}\n\n\tusage := &Usage{\n\t\tUser: &UserInfo{\n\t\t\tTotal:   totalCount,\n\t\t\tActive:  activeCount,\n\t\t\tDeleted: deletedCount,\n\t\t},\n\t\tExpectedPlan:    nil,\n\t\tDue:             0,\n\t\tNextBillingDate: time.Unix(subscription.PeriodEnd, 0),\n\t\tSubscription:    subscription,\n\t}\n\n\treturn usage, nil\n}\n\nfunc getPlan(subscription *stripe.Sub, totalCount int) (*stripe.Plan, error) {\n\tplan := subscription.Plan\n\n\tif plan.Amount == 0 { \/\/ we are on trial period\n\t\treturn plan, nil\n\t}\n\n\t\/\/ in the cases where the active subscription and the have-to-be\n\t\/\/ subscription is different, fetch the real plan from system. This can only\n\t\/\/ happen if the team got more members than the previous subscription's user\n\t\/\/ count in the current month. The subscription will be automatically fixed\n\t\/\/ on the next billing date. We do not change the subscription on each user\n\t\/\/ addition or deletion becasue Stripe charges the user whenever a\n\t\/\/ subscription change happens, so we only change the subscription on the\n\t\/\/ billing date with cancelling the previous subscription & invoice and\n\t\/\/ creating a new subscription with new requirement\n\tif plan.ID == GetPlanID(totalCount) {\n\t\treturn plan, nil\n\t}\n\n\treturn stripeplan.Get(GetPlanID(totalCount), nil)\n}\n\nfunc createFilter(groupID bson.ObjectId) modelhelper.Selector {\n\treturn modelhelper.Selector{\n\t\t\"as\":         modelhelper.Selector{\"$in\": []string{\"owner\", \"admin\", \"member\"}},\n\t\t\"targetName\": \"JAccount\",\n\t\t\"sourceName\": \"JGroup\",\n\t\t\"sourceId\":   groupID,\n\t}\n}\n\n\/\/ calculateActiveUserCount calculates the active user count from the\n\/\/ relationship collection. I tried using map-reduce first but that was so\n\/\/ magical from  engineering perspective and we dont have any other usage of it\n\/\/ in our system. Then i implemented it using \"aggregate\" framework, that worked\n\/\/ pretty well indeed but it is fetching all the records from database at once,\n\/\/ so decided to use our battle tested iter support, it handles iterations, bulk\n\/\/ operations, timeouts. We are actively using it for iterating over millions of\n\/\/ records without hardening on the database.\n\/\/\n\/\/\n\/\/ Sample aggregate function\n\/\/\n\/\/ db.relationships.aggregate([\n\/\/     { \"$match\": { as: { $in : [ \"owner\", \"admin\", \"member\" ] }, targetName:\"JAccount\", sourceName:\"JGroup\", sourceId: ObjectId(\"\") }},\n\/\/     \/\/ Count all occurrences\n\/\/     { \"$group\": {\n\/\/         \"_id\": {\n\/\/             \"targetId\": \"$targetId\"\n\/\/         },\n\/\/         \"count\": { \"$sum\": 1 }\n\/\/     }},\n\/\/     \/\/ Sum all occurrences and count distinct\n\/\/     { \"$group\": {\n\/\/         \"_id\": {\n\/\/             \"targetId\": \"$_id.targetId\"\n\/\/         },\n\/\/         \"totalCount\": { \"$sum\": \"$count\" },\n\/\/         \"distinctCount\": { \"$sum\": 1 }\n\/\/     }}\n\/\/ ])\n\/\/\nfunc calculateActiveUserCount(groupID bson.ObjectId) (int, error) {\n\taccounts := set.New()\n\n\titerOptions := helpers.NewIterOptions()\n\titerOptions.F = func(rel interface{}) error {\n\t\tresult, ok := rel.(*models.Relationship)\n\t\tif !ok {\n\t\t\treturn errors.New(\"not a relationship\")\n\t\t}\n\t\taccounts.Add(result.TargetId)\n\t\treturn nil\n\t}\n\titerOptions.CollectionName = modelhelper.RelationshipColl\n\titerOptions.Filter = createFilter(groupID)\n\titerOptions.Result = &models.Relationship{}\n\titerOptions.Limit = 0\n\titerOptions.Skip = 0\n\t\/\/ iterOptions.Log = log\n\n\terr := helpers.Iter(modelhelper.Mongo, iterOptions)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn accounts.Size(), nil\n}\n\n\/\/ CreateCustomerForGroup registers a customer for a group\nfunc CreateCustomerForGroup(username, groupName string, req *stripe.CustomerParams) (*stripe.Customer, error) {\n\treq, err := populateCustomerParams(username, groupName, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcus, err := customer.New(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": group.Id},\n\t\tmodelhelper.Selector{\n\t\t\t\"$set\": modelhelper.Selector{\n\t\t\t\t\"payment.customer.id\": cus.ID,\n\t\t\t},\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cus, nil\n}\n\n\/\/ deleteCustomer tries to make customer deletion idempotent\nfunc deleteCustomer(customerID string) error {\n\tcus, err := customer.Del(customerID)\n\tif cus != nil && cus.Deleted { \/\/ if customer is already deleted previously\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc populateCustomerParams(username, groupName string, initial *stripe.CustomerParams) (*stripe.CustomerParams, error) {\n\tif initial == nil {\n\t\tinitial = &stripe.CustomerParams{}\n\t}\n\n\t\/\/ whitelisted parameters\n\treq := &stripe.CustomerParams{\n\t\tToken:  initial.Token,\n\t\tCoupon: initial.Coupon,\n\t\tSource: initial.Source,\n\t\tDesc:   initial.Desc,\n\t\tEmail:  initial.Email,\n\t\tParams: initial.Params,\n\t\t\/\/ plan can not be updated by hand, do not add it to whilelist. It should\n\t\t\/\/ only be updated automatically on invoice applications\n\t\t\/\/ Plan: initial.Plan,\n\t}\n\n\tuser, err := modelhelper.GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req.Desc == \"\" {\n\t\treq.Desc = fmt.Sprintf(\"%s team\", groupName)\n\t}\n\tif req.Email == \"\" {\n\t\treq.Email = user.Email\n\t}\n\n\tif req.Params.Meta == nil {\n\t\treq.Params.Meta = make(map[string]string)\n\t}\n\treq.Params.Meta[\"groupName\"] = groupName\n\treq.Params.Meta[\"username\"] = username\n\n\treturn req, nil\n}\n<commit_msg>payment: fix for missing wg.Done() function call<commit_after>package payment\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/helpers\"\n\n\t\"gopkg.in\/fatih\/set.v0\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\n\t\"github.com\/stripe\/stripe-go\"\n\t\"github.com\/stripe\/stripe-go\/customer\"\n\tstripeplan \"github.com\/stripe\/stripe-go\/plan\"\n\t\"github.com\/stripe\/stripe-go\/sub\"\n\t\"golang.org\/x\/sync\/errgroup\"\n)\n\nvar (\n\t\/\/ ErrCustomerNotSubscribedToAnyPlans error for not subscribed users\n\tErrCustomerNotSubscribedToAnyPlans = errors.New(\"user is not subscribed to any plans\")\n\t\/\/ ErrCustomerNotExists error for not created users\n\tErrCustomerNotExists = errors.New(\"user is not created for subscription\")\n\t\/\/ ErrGroupAlreadyHasSub error when a group tries to create a sub and they try to create another\n\tErrGroupAlreadyHasSub = errors.New(\"group already has a subscription\")\n)\n\n\/\/ Usage holds current usage information, which will be calculated on the fly\ntype Usage struct {\n\tUser            *UserInfo\n\tExpectedPlan    *stripe.Plan\n\tDue             uint64\n\tNextBillingDate time.Time\n\tSubscription    *stripe.Sub\n}\n\n\/\/ UserInfo holds current info about team's user info\ntype UserInfo struct {\n\tTotal   int\n\tActive  int\n\tDeleted int\n}\n\n\/\/ DeleteCustomerForGroup deletes the customer for a given group. If customer is\n\/\/ not registered, returns error. If customer is already deleted, returns success.\nfunc DeleteCustomerForGroup(groupName string) error {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn ErrCustomerNotExists\n\t}\n\n\tif err := deleteCustomer(group.Payment.Customer.ID); err != nil {\n\t\treturn err\n\t}\n\n\treturn modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": group.Id},\n\t\tmodelhelper.Selector{\n\t\t\t\/\/ deleting customer deletes everything belong to that customer in stripe,\n\t\t\t\/\/ so say we all\n\t\t\t\"$unset\": modelhelper.Selector{\"payment\": \"\"},\n\t\t},\n\t)\n}\n\n\/\/ UpdateCustomerForGroup updates customer data of a group`\nfunc UpdateCustomerForGroup(username, groupName string, params *stripe.CustomerParams) (*stripe.Customer, error) {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn nil, ErrCustomerNotExists\n\t}\n\n\tparams, err = populateCustomerParams(username, groupName, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn customer.Update(group.Payment.Customer.ID, params)\n}\n\n\/\/ GetCustomerForGroup get the registered customer info of a group if exists\nfunc GetCustomerForGroup(groupName string) (*stripe.Customer, error) {\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif group.Payment.Customer.ID == \"\" {\n\t\treturn nil, ErrCustomerNotExists\n\t}\n\n\treturn customer.Get(group.Payment.Customer.ID, nil)\n}\n\n\/\/ GetInfoForGroup get the current usage info of a group\nfunc GetInfoForGroup(group *models.Group) (*Usage, error) {\n\tusage, err := fetchParallelizableeUsageItems(group)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplan, err := getPlan(usage.Subscription, usage.User.Total)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusage.ExpectedPlan = plan\n\tusage.Due = uint64(usage.User.Total) * plan.Amount\n\n\treturn usage, nil\n\n}\n\nfunc fetchParallelizableeUsageItems(group *models.Group) (*Usage, error) {\n\tvar g errgroup.Group\n\n\t\/\/ Stripe customer.\n\tvar cus *stripe.Customer\n\tg.Go(func() (err error) {\n\t\tif group.Payment.Customer.ID == \"\" {\n\t\t\treturn ErrCustomerNotExists\n\t\t}\n\n\t\tcus, err = customer.Get(group.Payment.Customer.ID, nil)\n\t\treturn err\n\t})\n\n\t\/\/ Stripe subscription.\n\tvar subscription *stripe.Sub\n\tg.Go(func() (err error) {\n\t\tif group.Payment.Subscription.ID == \"\" {\n\t\t\treturn ErrCustomerNotSubscribedToAnyPlans\n\t\t}\n\n\t\tsubscription, err = sub.Get(group.Payment.Subscription.ID, nil)\n\t\treturn err\n\t})\n\n\t\/\/ Active users count.\n\tvar activeCount int\n\tg.Go(func() (err error) {\n\t\tactiveCount, err = calculateActiveUserCount(group.Id)\n\t\treturn err\n\t})\n\n\t\/\/ Deleted members count.\n\tvar deletedCount int\n\tg.Go(func() (err error) {\n\t\tdeletedCount, err = modelhelper.GetDeletedMemberCountByGroupId(group.Id)\n\t\treturn err\n\t})\n\n\tif err := g.Wait(); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttotalCount := activeCount + deletedCount\n\n\t\/\/ if the team is in trialing period, and when we want to charge them, do\n\t\/\/ not include the deleted members\n\tif subscription.Status == \"trialing\" {\n\t\ttotalCount = activeCount\n\t}\n\n\tusage := &Usage{\n\t\tUser: &UserInfo{\n\t\t\tTotal:   totalCount,\n\t\t\tActive:  activeCount,\n\t\t\tDeleted: deletedCount,\n\t\t},\n\t\tExpectedPlan:    nil,\n\t\tDue:             0,\n\t\tNextBillingDate: time.Unix(subscription.PeriodEnd, 0),\n\t\tSubscription:    subscription,\n\t}\n\n\treturn usage, nil\n}\n\nfunc getPlan(subscription *stripe.Sub, totalCount int) (*stripe.Plan, error) {\n\tplan := subscription.Plan\n\n\tif plan.Amount == 0 { \/\/ we are on trial period\n\t\treturn plan, nil\n\t}\n\n\t\/\/ in the cases where the active subscription and the have-to-be\n\t\/\/ subscription is different, fetch the real plan from system. This can only\n\t\/\/ happen if the team got more members than the previous subscription's user\n\t\/\/ count in the current month. The subscription will be automatically fixed\n\t\/\/ on the next billing date. We do not change the subscription on each user\n\t\/\/ addition or deletion becasue Stripe charges the user whenever a\n\t\/\/ subscription change happens, so we only change the subscription on the\n\t\/\/ billing date with cancelling the previous subscription & invoice and\n\t\/\/ creating a new subscription with new requirement\n\tif plan.ID == GetPlanID(totalCount) {\n\t\treturn plan, nil\n\t}\n\n\treturn stripeplan.Get(GetPlanID(totalCount), nil)\n}\n\nfunc createFilter(groupID bson.ObjectId) modelhelper.Selector {\n\treturn modelhelper.Selector{\n\t\t\"as\":         modelhelper.Selector{\"$in\": []string{\"owner\", \"admin\", \"member\"}},\n\t\t\"targetName\": \"JAccount\",\n\t\t\"sourceName\": \"JGroup\",\n\t\t\"sourceId\":   groupID,\n\t}\n}\n\n\/\/ calculateActiveUserCount calculates the active user count from the\n\/\/ relationship collection. I tried using map-reduce first but that was so\n\/\/ magical from  engineering perspective and we dont have any other usage of it\n\/\/ in our system. Then i implemented it using \"aggregate\" framework, that worked\n\/\/ pretty well indeed but it is fetching all the records from database at once,\n\/\/ so decided to use our battle tested iter support, it handles iterations, bulk\n\/\/ operations, timeouts. We are actively using it for iterating over millions of\n\/\/ records without hardening on the database.\n\/\/\n\/\/\n\/\/ Sample aggregate function\n\/\/\n\/\/ db.relationships.aggregate([\n\/\/     { \"$match\": { as: { $in : [ \"owner\", \"admin\", \"member\" ] }, targetName:\"JAccount\", sourceName:\"JGroup\", sourceId: ObjectId(\"\") }},\n\/\/     \/\/ Count all occurrences\n\/\/     { \"$group\": {\n\/\/         \"_id\": {\n\/\/             \"targetId\": \"$targetId\"\n\/\/         },\n\/\/         \"count\": { \"$sum\": 1 }\n\/\/     }},\n\/\/     \/\/ Sum all occurrences and count distinct\n\/\/     { \"$group\": {\n\/\/         \"_id\": {\n\/\/             \"targetId\": \"$_id.targetId\"\n\/\/         },\n\/\/         \"totalCount\": { \"$sum\": \"$count\" },\n\/\/         \"distinctCount\": { \"$sum\": 1 }\n\/\/     }}\n\/\/ ])\n\/\/\nfunc calculateActiveUserCount(groupID bson.ObjectId) (int, error) {\n\taccounts := set.New()\n\n\titerOptions := helpers.NewIterOptions()\n\titerOptions.F = func(rel interface{}) error {\n\t\tresult, ok := rel.(*models.Relationship)\n\t\tif !ok {\n\t\t\treturn errors.New(\"not a relationship\")\n\t\t}\n\t\taccounts.Add(result.TargetId)\n\t\treturn nil\n\t}\n\titerOptions.CollectionName = modelhelper.RelationshipColl\n\titerOptions.Filter = createFilter(groupID)\n\titerOptions.Result = &models.Relationship{}\n\titerOptions.Limit = 0\n\titerOptions.Skip = 0\n\t\/\/ iterOptions.Log = log\n\n\terr := helpers.Iter(modelhelper.Mongo, iterOptions)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn accounts.Size(), nil\n}\n\n\/\/ CreateCustomerForGroup registers a customer for a group\nfunc CreateCustomerForGroup(username, groupName string, req *stripe.CustomerParams) (*stripe.Customer, error) {\n\treq, err := populateCustomerParams(username, groupName, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcus, err := customer.New(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgroup, err := modelhelper.GetGroup(groupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": group.Id},\n\t\tmodelhelper.Selector{\n\t\t\t\"$set\": modelhelper.Selector{\n\t\t\t\t\"payment.customer.id\": cus.ID,\n\t\t\t},\n\t\t},\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cus, nil\n}\n\n\/\/ deleteCustomer tries to make customer deletion idempotent\nfunc deleteCustomer(customerID string) error {\n\tcus, err := customer.Del(customerID)\n\tif cus != nil && cus.Deleted { \/\/ if customer is already deleted previously\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc populateCustomerParams(username, groupName string, initial *stripe.CustomerParams) (*stripe.CustomerParams, error) {\n\tif initial == nil {\n\t\tinitial = &stripe.CustomerParams{}\n\t}\n\n\t\/\/ whitelisted parameters\n\treq := &stripe.CustomerParams{\n\t\tToken:  initial.Token,\n\t\tCoupon: initial.Coupon,\n\t\tSource: initial.Source,\n\t\tDesc:   initial.Desc,\n\t\tEmail:  initial.Email,\n\t\tParams: initial.Params,\n\t\t\/\/ plan can not be updated by hand, do not add it to whilelist. It should\n\t\t\/\/ only be updated automatically on invoice applications\n\t\t\/\/ Plan: initial.Plan,\n\t}\n\n\tuser, err := modelhelper.GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif req.Desc == \"\" {\n\t\treq.Desc = fmt.Sprintf(\"%s team\", groupName)\n\t}\n\tif req.Email == \"\" {\n\t\treq.Email = user.Email\n\t}\n\n\tif req.Params.Meta == nil {\n\t\treq.Params.Meta = make(map[string]string)\n\t}\n\treq.Params.Meta[\"groupName\"] = groupName\n\treq.Params.Meta[\"username\"] = username\n\n\treturn req, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Go (cgo) interface to libgeoip *\/\npackage geoip\n\n\/*\n#cgo CFLAGS: -I\/opt\/local\/include -I\/usr\/local\/include -I\/usr\/include\n#cgo LDFLAGS: -lGeoIP -L\/opt\/local\/lib -L\/usr\/local\/lib -L\/usr\/lib\n#include <stdio.h>\n#include <errno.h>\n#include <GeoIP.h>\n\n\/\/typedef GeoIP* GeoIP_pnt\n*\/\nimport \"C\"\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"unsafe\"\n)\n\n\/\/ Set Quiet to true to silence warnings when the database can't be opened\n\/\/ (though libgeoip still prints to errout)\nvar Quiet bool = false\n\ntype GeoIP struct {\n\tdb *C.GeoIP\n}\n\n\/\/ Open opens a GeoIP database, all formats supported by libgeoip are supported though\n\/\/ there are only functions to access the country information in this API.\n\/\/ The database is opened in MEMORY_CACHE mode, if you need to optimize for memory\n\/\/ instead of performance you should change this.\n\/\/ If you don't pass a filename, it will try opening the database from\n\/\/ a list of common paths.\nfunc Open(files ...string) *GeoIP {\n\tif len(files) == 0 {\n\t\tfiles = []string{\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ Linux default\n\t\t\t\"\/usr\/share\/local\/GeoIP\/GeoIP.dat\", \/\/ source install?\n\t\t\t\"\/usr\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ FreeBSD\n\t\t\t\"\/opt\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ MacPorts\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ ArchLinux\n\t\t}\n\t}\n\n\tg := &GeoIP{}\n\n\tvar err error\n\n\tfor _, file := range files {\n\n\t\t\/\/ libgeoip prints errors if it can't open the file, so check first\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcbase := C.CString(file)\n\t\tg.db, err = C.GeoIP_open(cbase, C.GEOIP_MEMORY_CACHE)\n\t\tC.free(unsafe.Pointer(cbase))\n\t\tif g.db != nil && err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil && !Quiet {\n\t\tlog.Println(\"Error opening GeoIP database\", files, err)\n\t}\n\n\tif g.db != nil {\n\t\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\t\treturn g\n\t}\n\n\treturn nil\n}\n\n\/\/ GetOrg takes an IPv4 address string and returns the org name for that IP.\n\/\/ Requires the geoip org database\nfunc (gi *GeoIP) GetOrg(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tcname := C.GeoIP_name_by_addr(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif cname != nil {\n\t\trets := C.GoString(cname)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n\n\/\/ GetCountry takes an IPv4 address string and returns the country code for that IP.\nfunc (gi *GeoIP) GetCountry(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tccountry := C.GeoIP_country_code_by_addr(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif ccountry != nil {\n\t\trets := C.GoString(ccountry)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n\n\/\/ GetCountry_v6 works the same as GetCountry except for IPv6 addresses, be sure to\n\/\/ load a database with IPv6 data to get any results.\nfunc (gi *GeoIP) GetCountry_v6(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tccountry := C.GeoIP_country_code_by_addr_v6(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif ccountry != nil {\n\t\trets := C.GoString(ccountry)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n<commit_msg>Close GeoIP database when it goes out of scope<commit_after>\/* Go (cgo) interface to libgeoip *\/\npackage geoip\n\n\/*\n#cgo CFLAGS: -I\/opt\/local\/include -I\/usr\/local\/include -I\/usr\/include\n#cgo LDFLAGS: -lGeoIP -L\/opt\/local\/lib -L\/usr\/local\/lib -L\/usr\/lib\n#include <stdio.h>\n#include <errno.h>\n#include <GeoIP.h>\n\n\/\/typedef GeoIP* GeoIP_pnt\n*\/\nimport \"C\"\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\n\/\/ Set Quiet to true to silence warnings when the database can't be opened\n\/\/ (though libgeoip still prints to errout)\nvar Quiet bool = false\n\ntype GeoIP struct {\n\tdb *C.GeoIP\n}\n\nfunc (gi *GeoIP) Free() {\n\tif gi == nil {\n\t\treturn\n\t}\n\tif gi.db == nil {\n\t\tgi = nil\n\t\treturn\n\t}\n\tC.GeoIP_delete(gi.db)\n\tgi = nil\n\treturn\n}\n\n\/\/ Open opens a GeoIP database, all formats supported by libgeoip are supported though\n\/\/ there are only functions to access the country information in this API.\n\/\/ The database is opened in MEMORY_CACHE mode, if you need to optimize for memory\n\/\/ instead of performance you should change this.\n\/\/ If you don't pass a filename, it will try opening the database from\n\/\/ a list of common paths.\nfunc Open(files ...string) *GeoIP {\n\tif len(files) == 0 {\n\t\tfiles = []string{\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ Linux default\n\t\t\t\"\/usr\/share\/local\/GeoIP\/GeoIP.dat\", \/\/ source install?\n\t\t\t\"\/usr\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ FreeBSD\n\t\t\t\"\/opt\/local\/share\/GeoIP\/GeoIP.dat\", \/\/ MacPorts\n\t\t\t\"\/usr\/share\/GeoIP\/GeoIP.dat\",       \/\/ ArchLinux\n\t\t}\n\t}\n\n\tg := &GeoIP{}\n\truntime.SetFinalizer(g, (*GeoIP).Free)\n\n\tvar err error\n\n\tfor _, file := range files {\n\n\t\t\/\/ libgeoip prints errors if it can't open the file, so check first\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\tif os.IsExist(err) {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcbase := C.CString(file)\n\t\tg.db, err = C.GeoIP_open(cbase, C.GEOIP_MEMORY_CACHE)\n\t\tC.free(unsafe.Pointer(cbase))\n\t\tif g.db != nil && err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil && !Quiet {\n\t\tlog.Println(\"Error opening GeoIP database\", files, err)\n\t}\n\n\tif g.db != nil {\n\t\tC.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)\n\t\treturn g\n\t}\n\n\treturn nil\n}\n\n\/\/ GetOrg takes an IPv4 address string and returns the org name for that IP.\n\/\/ Requires the geoip org database\nfunc (gi *GeoIP) GetOrg(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tcname := C.GeoIP_name_by_addr(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif cname != nil {\n\t\trets := C.GoString(cname)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n\n\/\/ GetCountry takes an IPv4 address string and returns the country code for that IP.\nfunc (gi *GeoIP) GetCountry(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tccountry := C.GeoIP_country_code_by_addr(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif ccountry != nil {\n\t\trets := C.GoString(ccountry)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n\n\/\/ GetCountry_v6 works the same as GetCountry except for IPv6 addresses, be sure to\n\/\/ load a database with IPv6 data to get any results.\nfunc (gi *GeoIP) GetCountry_v6(ip string) string {\n\tif gi.db == nil {\n\t\treturn \"\"\n\t}\n\tcip := C.CString(ip)\n\tccountry := C.GeoIP_country_code_by_addr_v6(gi.db, cip)\n\tC.free(unsafe.Pointer(cip))\n\tif ccountry != nil {\n\t\trets := C.GoString(ccountry)\n\t\treturn rets\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"os\"\n\t\"syscall\"\n)\n\nvar daemonName = \"npserver\"\n\nfunc main() {\n\n\tinitFlags()\n\n\t\/\/ check permissions\n\tif os.Getuid() != 0 && os.Geteuid() != 0 {\n\t\tfmt.Printf(\"npserver-daemon should be run as root, have uid=%d and euid=%d\\n\", os.Getuid(), os.Geteuid())\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ check start || sto\n\tif flags.Start == flags.Stop {\n\t\tfmt.Println(\"need --start or --stop flag\")\n\t}\n\n\tif flags.Start {\n\t\tstartDaemon()\n\t}\n\tif flags.Stop {\n\t\tstopDaemon()\n\t}\n\n\t\/\/ all good :)\n}\n\nfunc startDaemon() {\n\t\/\/ setup args for daemon call\n\targs := []string{\n\t\tfmt.Sprintf(\"--name=%s\", daemonName),\n\t\t\"--noconfig\",\n\t\t\"--errlog=\/var\/log\/npserver-daemon.log\",\n\t\t\"--output=\/var\/log\/npserver.log\",\n\t\tfmt.Sprintf(\"--pidfile=%s\", flags.PIDFile),\n\t\t\"--unsafe\",\n\t\t\"--\",\n\t\t\"\/usr\/local\/bin\/npserver\",\n\t}\n\n\t\/\/ append extra args to args\n\targs = append(args, extraArgs...)\n\n\t\/\/ start process\n\tproc, err := os.StartProcess(\"\/usr\/bin\/daemon\", args, &os.ProcAttr{\n\t\tFiles: []*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\tSys: &syscall.SysProcAttr{\n\t\t\tCredential: &syscall.Credential{\n\t\t\t\tUid: uint32(os.Geteuid()),\n\t\t\t\tGid: uint32(os.Getegid()),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"os\/exec returned an error: '%s'\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ wait for daemon to be ready\n\t_, err = proc.Wait()\n\tif err != nil {\n\t\tfmt.Printf(\"proc.Wait() failed. %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc stopDaemon() {\n\t\/\/ stopping arguments\n\targs := []string{\n\t\t\"--stop\",\n\t\tfmt.Sprintf(\"--name=%s\", daemonName),\n\t\tfmt.Sprintf(\"--pidfile=%s\", flags.PIDFile),\n\t}\n\tspew.Dump(args)\n\n\t\/\/ start process\n\tproc, err := os.StartProcess(\"\/usr\/bin\/daemon\", args, &os.ProcAttr{\n\t\tFiles: []*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\tSys: &syscall.SysProcAttr{\n\t\t\tCredential: &syscall.Credential{\n\t\t\t\tUid: uint32(os.Geteuid()),\n\t\t\t\tGid: uint32(os.Getegid()),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"os\/exec returned an error: '%s'\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ wait for daemon to be ready\n\t_, err = proc.Wait()\n\tif err != nil {\n\t\tfmt.Printf(\"proc.Wait() failed. %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\t\/\/ \/\/ open pid file (if available)\n\t\/\/ pidFile, err := os.Open(flags.PIDFile)\n\t\/\/ if err != nil {\n\t\/\/ \tif os.IsNotExist(err) {\n\t\/\/ \t\tfmt.Printf(\"it looks like npserver is not running\")\n\t\/\/ \t\tos.Exit(0)\n\t\/\/ \t}\n\t\/\/ \tfmt.Printf(\"error on opening pidfile: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ read all file contents\n\t\/\/ pidFileContents, err := ioutil.ReadAll(pidFile)\n\t\/\/ pidFile.Close()\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error reading pidfile contents: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ pidFileContentsString := string(pidFileContents)\n\n\t\/\/ \/\/ strip eventual whitespace\n\t\/\/ pidFileContentsString = strings.TrimRight(pidFileContentsString, \" \\r\\n\\t\")\n\n\t\/\/ \/\/ convert pid string to pid int\n\t\/\/ pid, err := strconv.Atoi(pidFileContentsString)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error parsing pidfile contents: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ lookup process\n\t\/\/ proc, err := os.FindProcess(pid)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error finding process with pid %d: %s\\n\", pid, err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ signal process to stop\n\t\/\/ err = proc.Signal(os.Interrupt)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error sending interrupt signal to npserver: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ wait until process is done\n\t\/\/ state, err := proc.Wait()\n\t\/\/ if err != nil {\n\t\/\/ \tif err.Error() != \"wait: no child processes\" {\n\t\/\/ \t\tfmt.Printf(\"error waiting for process to stop: %s\\n\", err)\n\t\/\/ \t\tos.Exit(1)\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tif !state.Exited() || !state.Success() {\n\t\/\/ \t\tfmt.Printf(\"npserver process exited badly\")\n\t\/\/ \t\tos.Exit(1)\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ \/\/ remove pid file\n\t\/\/ err = os.Remove(flags.PIDFile)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error removing pid file: %s\\n\", err)\n\t\/\/ }\n}\n<commit_msg>killall...<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"syscall\"\n)\n\nvar daemonName = \"npserver\"\n\nfunc main() {\n\n\tinitFlags()\n\n\t\/\/ check permissions\n\tif os.Getuid() != 0 && os.Geteuid() != 0 {\n\t\tfmt.Printf(\"npserver-daemon should be run as root, have uid=%d and euid=%d\\n\", os.Getuid(), os.Geteuid())\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ check start || sto\n\tif flags.Start == flags.Stop {\n\t\tfmt.Println(\"need --start or --stop flag\")\n\t}\n\n\tif flags.Start {\n\t\tstartDaemon()\n\t}\n\tif flags.Stop {\n\t\tstopDaemon()\n\t}\n\n\t\/\/ all good :)\n}\n\nfunc startDaemon() {\n\t\/\/ setup args for daemon call\n\targs := []string{\n\t\tfmt.Sprintf(\"--name=%s\", daemonName),\n\t\t\"--noconfig\",\n\t\t\"--errlog=\/var\/log\/npserver-daemon.log\",\n\t\t\"--output=\/var\/log\/npserver.log\",\n\t\tfmt.Sprintf(\"--pidfile=%s\", flags.PIDFile),\n\t\t\"--unsafe\",\n\t\t\"--\",\n\t\t\"\/usr\/local\/bin\/npserver\",\n\t}\n\n\t\/\/ append extra args to args\n\targs = append(args, extraArgs...)\n\n\t\/\/ start process\n\tproc, err := os.StartProcess(\"\/usr\/bin\/daemon\", args, &os.ProcAttr{\n\t\tFiles: []*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\tSys: &syscall.SysProcAttr{\n\t\t\tCredential: &syscall.Credential{\n\t\t\t\tUid: uint32(os.Geteuid()),\n\t\t\t\tGid: uint32(os.Getegid()),\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"os\/exec returned an error: '%s'\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ wait for daemon to be ready\n\t_, err = proc.Wait()\n\tif err != nil {\n\t\tfmt.Printf(\"proc.Wait() failed. %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc stopDaemon() {\n\t\/\/ possibly racy.\n\t\/\/ no guarantee that npserver cleaned up before new npserver is being copied\/started\n\tcmd := exec.Command(\"killall\", \"-s\", \"SIGINT\", \"npserver\")\n\tcmd.Run()\n\n\t\/\/ \/\/ stopping arguments\n\t\/\/ args := []string{\n\t\/\/ \t\"--stop\",\n\t\/\/ \tfmt.Sprintf(\"--name=%s\", daemonName),\n\t\/\/ \tfmt.Sprintf(\"--pidfile=%s\", flags.PIDFile),\n\t\/\/ }\n\t\/\/ spew.Dump(args)\n\n\t\/\/ \/\/ start process\n\t\/\/ proc, err := os.StartProcess(\"\/usr\/bin\/daemon\", args, &os.ProcAttr{\n\t\/\/ \tFiles: []*os.File{os.Stdin, os.Stdout, os.Stderr},\n\t\/\/ \tSys: &syscall.SysProcAttr{\n\t\/\/ \t\tCredential: &syscall.Credential{\n\t\/\/ \t\t\tUid: uint32(os.Geteuid()),\n\t\/\/ \t\t\tGid: uint32(os.Getegid()),\n\t\/\/ \t\t},\n\t\/\/ \t},\n\t\/\/ })\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"os\/exec returned an error: '%s'\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ wait for daemon to be ready\n\t\/\/ _, err = proc.Wait()\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"proc.Wait() failed. %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ open pid file (if available)\n\t\/\/ pidFile, err := os.Open(flags.PIDFile)\n\t\/\/ if err != nil {\n\t\/\/ \tif os.IsNotExist(err) {\n\t\/\/ \t\tfmt.Printf(\"it looks like npserver is not running\")\n\t\/\/ \t\tos.Exit(0)\n\t\/\/ \t}\n\t\/\/ \tfmt.Printf(\"error on opening pidfile: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ read all file contents\n\t\/\/ pidFileContents, err := ioutil.ReadAll(pidFile)\n\t\/\/ pidFile.Close()\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error reading pidfile contents: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ pidFileContentsString := string(pidFileContents)\n\n\t\/\/ \/\/ strip eventual whitespace\n\t\/\/ pidFileContentsString = strings.TrimRight(pidFileContentsString, \" \\r\\n\\t\")\n\n\t\/\/ \/\/ convert pid string to pid int\n\t\/\/ pid, err := strconv.Atoi(pidFileContentsString)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error parsing pidfile contents: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ lookup process\n\t\/\/ proc, err := os.FindProcess(pid)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error finding process with pid %d: %s\\n\", pid, err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ signal process to stop\n\t\/\/ err = proc.Signal(os.Interrupt)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error sending interrupt signal to npserver: %s\\n\", err)\n\t\/\/ \tos.Exit(1)\n\t\/\/ }\n\n\t\/\/ \/\/ wait until process is done\n\t\/\/ state, err := proc.Wait()\n\t\/\/ if err != nil {\n\t\/\/ \tif err.Error() != \"wait: no child processes\" {\n\t\/\/ \t\tfmt.Printf(\"error waiting for process to stop: %s\\n\", err)\n\t\/\/ \t\tos.Exit(1)\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tif !state.Exited() || !state.Success() {\n\t\/\/ \t\tfmt.Printf(\"npserver process exited badly\")\n\t\/\/ \t\tos.Exit(1)\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ \/\/ remove pid file\n\t\/\/ err = os.Remove(flags.PIDFile)\n\t\/\/ if err != nil {\n\t\/\/ \tfmt.Printf(\"error removing pid file: %s\\n\", err)\n\t\/\/ }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 provides an extensive command line option parser.\n\/\/ The flags package is similar in functionality to the go builtin flag package\n\/\/ but provides more options and uses reflection to provide a convenient and\n\/\/ succinct way of specifying command line options.\n\/\/\n\/\/ Supported features:\n\/\/     Options with short names (-v)\n\/\/     Options with long names (--verbose)\n\/\/     Options with and without arguments (bool v.s. other type)\n\/\/     Options with optional arguments and default values\n\/\/     Multiple option groups each containing a set of options\n\/\/     Generate and print well-formatted help message\n\/\/     Passing remaining command line arguments after -- (optional)\n\/\/     Ignoring unknown command line options (optional)\n\/\/     Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n\/\/     Supports multiple short options -aux\n\/\/     Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n\/\/     Supports same option multiple times (can store in slice or last option counts)\n\/\/     Supports maps\n\/\/     Supports function callbacks\n\/\/\n\/\/ Additional features specific to Windows:\n\/\/     Options with short names (\/v)\n\/\/     Options with long names (\/verbose)\n\/\/     Windows-style options with arguments use a colon as the delimiter\n\/\/     Modify generated help message with Windows-style \/ options\n\/\/\n\/\/ The flags package uses structs, reflection and struct field tags\n\/\/ to allow users to specify command line options. This results in very simple\n\/\/ and consise specification of your application options. For example:\n\/\/\n\/\/     type Options struct {\n\/\/         Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n\/\/     }\n\/\/\n\/\/ This specifies one option with a short name -v and a long name --verbose.\n\/\/ When either -v or --verbose is found on the command line, a 'true' value\n\/\/ will be appended to the Verbose field. e.g. when specifying -vvv, the\n\/\/ resulting value of Verbose will be {[true, true, true]}.\n\/\/\n\/\/ Slice options work exactly the same as primitive type options, except that\n\/\/ whenever the option is encountered, a value is appended to the slice.\n\/\/\n\/\/ Map options from string to primitive type are also supported. On the command\n\/\/ line, you specify the value for such an option as key:value. For example\n\/\/\n\/\/     type Options struct {\n\/\/         AuthorInfo string[string] `short:\"a\"`\n\/\/     }\n\/\/\n\/\/ Then, the AuthorInfo map can be filled with something like\n\/\/ -a name:Jesse -a \"surname:van den Kieboom\".\n\/\/\n\/\/ Finally, for full control over the conversion between command line argument\n\/\/ values and options, user defined types can choose to implement the Marshaler\n\/\/ and Unmarshaler interfaces.\n\/\/\n\/\/ Available field tags:\n\/\/     short:          the short name of the option (single character)\n\/\/     long:           the long name of the option\n\/\/     description:    the description of the option (optional)\n\/\/     optional:       whether an argument of the option is optional (optional)\n\/\/     optional-value: the value of an optional option when the option occurs\n\/\/                     without an argument. This tag can be specified multiple\n\/\/                     times in the case of maps or slices (optional)\n\/\/     default:        the default value of an option. This tag can be specified\n\/\/                     multiple times in the case of slices or maps (optional).\n\/\/     default-mask:   when specified, this value will be displayed in the help\n\/\/                     instead of the actual default value. This is useful\n\/\/                     mostly for hiding otherwise sensitive information from\n\/\/                     showing up in the help. If default-mask takes the special\n\/\/                     value \"-\", then no default value will be shown at all\n\/\/                     (optional)\n\/\/     required:       whether an option is required to appear on the command\n\/\/                     line. If a required option is not present, the parser\n\/\/                     will return ErrRequired.\n\/\/     base:           a base (radix) used to convert strings to integer values,\n\/\/                     the default base is 10 (i.e. decimal) (optional)\n\/\/     value-name:     the name of the argument value (to be shown in the help,\n\/\/                     (optional)\n\/\/     group:          when specified on a struct field, makes the struct field\n\/\/                     a separate group with the given name (optional).\n\/\/     command:        when specified on a struct field, makes the struct field\n\/\/                     a (sub)command with the given name (optional).\n\/\/\n\/\/     subcommands-optional: when specified on a command struct field, makes\n\/\/                           any subcommands of that command optional.\n\/\/\n\/\/ Either short: or long: must be specified to make the field eligible as an\n\/\/ option.\n\/\/\n\/\/\n\/\/ Option groups:\n\/\/\n\/\/ Option groups are a simple way to semantically separate your options. The\n\/\/ only real difference is in how your options will appear in the builtin\n\/\/ generated help. All options in a particular group are shown together in the\n\/\/ help under the name of the group.\n\/\/\n\/\/ There are currently three ways to specify option groups.\n\/\/\n\/\/     1. Use NewNamedParser specifying the various option groups.\n\/\/     2. Use AddGroup to add a group to an existing parser.\n\/\/     3. Add a struct field to the toplevel options annotated with the\n\/\/        group:\"group-name\" tag.\n\/\/\n\/\/\n\/\/\n\/\/ Commands:\n\/\/\n\/\/ The flags package also has basic support for commands. Commands are often\n\/\/ used in monolithic applications that support various commands or actions.\n\/\/ Take git for example, all of the add, commit, checkout, etc. are called\n\/\/ commands. Using commands you can easily separate multiple functions of your\n\/\/ application.\n\/\/\n\/\/ There are currently two ways to specifiy a command.\n\/\/\n\/\/     1. Use AddCommand on an existing parser.\n\/\/     2. Add a struct field to your options struct annotated with the\n\/\/        command:\"command-name\" tag.\n\/\/\n\/\/ The most common, idiomatic way to implement commands is to define a global\n\/\/ parser instance and implement each command in a separate file. These\n\/\/ command files should define a go init function which calls AddCommand on\n\/\/ the global parser.\n\/\/\n\/\/ When parsing ends and there is an active command and that command implements\n\/\/ the Commander interface, then its Execute method will be run with the\n\/\/ remaining command line arguments.\n\/\/\n\/\/ Command structs can have options which become valid to parse after the\n\/\/ command has been specified on the command line. It is currently not valid\n\/\/ to specify options from the parent level of the command after the command\n\/\/ name has occurred. Thus, given a toplevel option \"-v\" and a command \"add\":\n\/\/\n\/\/     Valid:   .\/app -v add\n\/\/     Invalid: .\/app add -v\n\/\/\npackage flags\n<commit_msg>group field tags<commit_after>\/\/ Copyright 2012 Jesse van den Kieboom. All rights 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 provides an extensive command line option parser.\n\/\/ The flags package is similar in functionality to the go builtin flag package\n\/\/ but provides more options and uses reflection to provide a convenient and\n\/\/ succinct way of specifying command line options.\n\/\/\n\/\/ Supported features:\n\/\/     Options with short names (-v)\n\/\/     Options with long names (--verbose)\n\/\/     Options with and without arguments (bool v.s. other type)\n\/\/     Options with optional arguments and default values\n\/\/     Multiple option groups each containing a set of options\n\/\/     Generate and print well-formatted help message\n\/\/     Passing remaining command line arguments after -- (optional)\n\/\/     Ignoring unknown command line options (optional)\n\/\/     Supports -I\/usr\/include -I=\/usr\/include -I \/usr\/include option argument specification\n\/\/     Supports multiple short options -aux\n\/\/     Supports all primitive go types (string, int{8..64}, uint{8..64}, float)\n\/\/     Supports same option multiple times (can store in slice or last option counts)\n\/\/     Supports maps\n\/\/     Supports function callbacks\n\/\/\n\/\/ Additional features specific to Windows:\n\/\/     Options with short names (\/v)\n\/\/     Options with long names (\/verbose)\n\/\/     Windows-style options with arguments use a colon as the delimiter\n\/\/     Modify generated help message with Windows-style \/ options\n\/\/\n\/\/ The flags package uses structs, reflection and struct field tags\n\/\/ to allow users to specify command line options. This results in very simple\n\/\/ and consise specification of your application options. For example:\n\/\/\n\/\/     type Options struct {\n\/\/         Verbose []bool `short:\"v\" long:\"verbose\" description:\"Show verbose debug information\"`\n\/\/     }\n\/\/\n\/\/ This specifies one option with a short name -v and a long name --verbose.\n\/\/ When either -v or --verbose is found on the command line, a 'true' value\n\/\/ will be appended to the Verbose field. e.g. when specifying -vvv, the\n\/\/ resulting value of Verbose will be {[true, true, true]}.\n\/\/\n\/\/ Slice options work exactly the same as primitive type options, except that\n\/\/ whenever the option is encountered, a value is appended to the slice.\n\/\/\n\/\/ Map options from string to primitive type are also supported. On the command\n\/\/ line, you specify the value for such an option as key:value. For example\n\/\/\n\/\/     type Options struct {\n\/\/         AuthorInfo string[string] `short:\"a\"`\n\/\/     }\n\/\/\n\/\/ Then, the AuthorInfo map can be filled with something like\n\/\/ -a name:Jesse -a \"surname:van den Kieboom\".\n\/\/\n\/\/ Finally, for full control over the conversion between command line argument\n\/\/ values and options, user defined types can choose to implement the Marshaler\n\/\/ and Unmarshaler interfaces.\n\/\/\n\/\/ Available field tags:\n\/\/     short:       the short name of the option (single character)\n\/\/     long:        the long name of the option\n\/\/     required:    whether an option is required to appear on the command line.\n\/\/                  If a required option is not present, the parser will return\n\/\/                  ErrRequired.\n\/\/     description: the description of the option (optional)\n\/\/\n\/\/     optional:       whether an argument of the option is optional (optional)\n\/\/     optional-value: the value of an optional option when the option occurs\n\/\/                     without an argument. This tag can be specified multiple\n\/\/                     times in the case of maps or slices (optional)\n\/\/     default:        the default value of an option. This tag can be specified\n\/\/                     multiple times in the case of slices or maps (optional).\n\/\/     default-mask:   when specified, this value will be displayed in the help\n\/\/                     instead of the actual default value. This is useful\n\/\/                     mostly for hiding otherwise sensitive information from\n\/\/                     showing up in the help. If default-mask takes the special\n\/\/                     value \"-\", then no default value will be shown at all\n\/\/                     (optional)\n\/\/     value-name:     the name of the argument value (to be shown in the help,\n\/\/                     (optional)\n\/\/\n\/\/     base: a base (radix) used to convert strings to integer values, the default\n\/\/           base is 10 (i.e. decimal) (optional)\n\/\/\n\/\/     group:                when specified on a struct field, makes the struct\n\/\/                           field a separate group with the given name (optional).\n\/\/     command:              when specified on a struct field, makes the struct\n\/\/                           field a (sub)command with the given name (optional).\n\/\/     subcommands-optional: when specified on a command struct field, makes\n\/\/                           any subcommands of that command optional.\n\/\/\n\/\/ Either short: or long: must be specified to make the field eligible as an\n\/\/ option.\n\/\/\n\/\/\n\/\/ Option groups:\n\/\/\n\/\/ Option groups are a simple way to semantically separate your options. The\n\/\/ only real difference is in how your options will appear in the builtin\n\/\/ generated help. All options in a particular group are shown together in the\n\/\/ help under the name of the group.\n\/\/\n\/\/ There are currently three ways to specify option groups.\n\/\/\n\/\/     1. Use NewNamedParser specifying the various option groups.\n\/\/     2. Use AddGroup to add a group to an existing parser.\n\/\/     3. Add a struct field to the toplevel options annotated with the\n\/\/        group:\"group-name\" tag.\n\/\/\n\/\/\n\/\/\n\/\/ Commands:\n\/\/\n\/\/ The flags package also has basic support for commands. Commands are often\n\/\/ used in monolithic applications that support various commands or actions.\n\/\/ Take git for example, all of the add, commit, checkout, etc. are called\n\/\/ commands. Using commands you can easily separate multiple functions of your\n\/\/ application.\n\/\/\n\/\/ There are currently two ways to specifiy a command.\n\/\/\n\/\/     1. Use AddCommand on an existing parser.\n\/\/     2. Add a struct field to your options struct annotated with the\n\/\/        command:\"command-name\" tag.\n\/\/\n\/\/ The most common, idiomatic way to implement commands is to define a global\n\/\/ parser instance and implement each command in a separate file. These\n\/\/ command files should define a go init function which calls AddCommand on\n\/\/ the global parser.\n\/\/\n\/\/ When parsing ends and there is an active command and that command implements\n\/\/ the Commander interface, then its Execute method will be run with the\n\/\/ remaining command line arguments.\n\/\/\n\/\/ Command structs can have options which become valid to parse after the\n\/\/ command has been specified on the command line. It is currently not valid\n\/\/ to specify options from the parent level of the command after the command\n\/\/ name has occurred. Thus, given a toplevel option \"-v\" and a command \"add\":\n\/\/\n\/\/     Valid:   .\/app -v add\n\/\/     Invalid: .\/app add -v\n\/\/\npackage flags\n<|endoftext|>"}
{"text":"<commit_before>package runtime\n\nimport (\n\t\"testing\"\n\t\"time\"\n\t\"github.com\/devfeel\/dotweb\/test\"\n\t\"sync\"\n)\n\nconst (\n\tDefaultTestGCInterval = 2\n\n\tTEST_CACHE_KEY = \"joe\"\n\tTEST_CACHE_VALUE = \"zou\"\n\t\/\/int value\n\tTEST_CACHE_INT_VALUE = 1\n\n\t\/\/int64 value\n\tTEST_CACHE_INT64_VALUE = 1\n)\n\nfunc TestRuntimeCache_Get(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\t\/\/check value\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(4*time.Second)\n\t\tvalue,err:=cache.Get(TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,TEST_CACHE_VALUE,value)\n\t}(cache,t)\n\n\t\/\/check expired\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(5*time.Second)\n\t\tvalue,err:=cache.Exists(TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,true,value)\n\t}(cache,t)\n\n\ttime.Sleep(5*time.Second)\n}\n\n\nfunc TestRuntimeCache_GetInt(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_INT_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetInt(key)\n\t})\n}\n\n\nfunc TestRuntimeCache_GetInt64(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_INT64_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetInt64(key)\n\t})\n}\n\nfunc TestRuntimeCache_GetString(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetString(key)\n\t})\n}\n\nfunc testRuntimeCache(t *testing.T,insertValue interface{},f func(cache *RuntimeCache,key string)(interface{}, error)) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,insertValue,5)\n\t\/\/check value\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(4*time.Second)\n\t\tvalue,err:=f(cache,TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,insertValue,value)\n\t}(cache,t)\n\n\ttime.Sleep(5*time.Second)\n}\n\nfunc TestRuntimeCache_Delete(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\n\tvalue,e:=cache.Get(TEST_CACHE_KEY)\n\n\ttest.Nil(t,e)\n\ttest.Equal(t,TEST_CACHE_VALUE,value)\n\n\tcache.Delete(TEST_CACHE_KEY)\n\n\tvalue,e=cache.Get(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\ttest.Nil(t,value)\n}\n\nfunc TestRuntimeCache_ClearAll(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\tcache.Set(\"2\",TEST_CACHE_VALUE,5)\n\tcache.Set(\"3\",TEST_CACHE_VALUE,5)\n\n\tval_2, err := cache.GetString(\"2\")\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\ttest.Equal(t,TEST_CACHE_VALUE, val_2)\n\n\tcache.ClearAll()\n\texists_2, err := cache.Exists(\"2\")\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\tif exists_2{\n\t\tt.Error(\"exists 2 but need not exists\")\n\t}\n}\n\nfunc TestRuntimeCache_Incr(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Incr(TEST_CACHE_KEY)\n\t\t}\n\n\t\twg.Add(-1)\n\t}(cache)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Incr(TEST_CACHE_KEY)\n\t\t}\n\t\twg.Add(-1)\n\t}(cache)\n\n\twg.Wait()\n\n\tvalue,e:=cache.GetInt(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\n\ttest.Equal(t,100,value)\n}\n\nfunc TestRuntimeCache_Decr(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Decr(TEST_CACHE_KEY)\n\t\t}\n\n\t\twg.Add(-1)\n\t}(cache)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Decr(TEST_CACHE_KEY)\n\t\t}\n\t\twg.Add(-1)\n\t}(cache)\n\n\twg.Wait()\n\n\tvalue,e:=cache.GetInt(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\n\ttest.Equal(t,-100,value)\n}<commit_msg>#### Version 1.4.9.4 * 调整: dotweb.Classic移除自动UseRequestLog逻辑 * 调整：Session Redis模式时，新增sessionReExpire用于重置有效期，避免调用SessionUpdate导致不必要的redis数据交换 * 调整：Cache.Runtime调整map为sync.Map * 状态页：访问\/dotweb\/state时增加CurrentTime字段输出 * BUG： 修正Reponse自动释放时未重置body字段，导致内存溢出BUG * 2018-05-10 13:30<commit_after>package runtime\n\nimport (\n\t\"testing\"\n\t\"time\"\n\t\"github.com\/devfeel\/dotweb\/test\"\n\t\"sync\"\n)\n\nconst (\n\tDefaultTestGCInterval = 2\n\n\tTEST_CACHE_KEY = \"joe\"\n\tTEST_CACHE_VALUE = \"zou\"\n\t\/\/int value\n\tTEST_CACHE_INT_VALUE = 1\n\n\t\/\/int64 value\n\tTEST_CACHE_INT64_VALUE = 1\n)\n\nfunc TestRuntimeCache_Get(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\t\/\/check value\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(4*time.Second)\n\t\tvalue,err:=cache.Get(TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,TEST_CACHE_VALUE,value)\n\t}(cache,t)\n\n\t\/\/check expired\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(5*time.Second)\n\t\tvalue,err:=cache.Exists(TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,true,value)\n\t}(cache,t)\n\n\ttime.Sleep(5*time.Second)\n}\n\n\nfunc TestRuntimeCache_GetInt(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_INT_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetInt(key)\n\t})\n}\n\n\nfunc TestRuntimeCache_GetInt64(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_INT64_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetInt64(key)\n\t})\n}\n\nfunc TestRuntimeCache_GetString(t *testing.T) {\n\ttestRuntimeCache(t,TEST_CACHE_VALUE,func(cache *RuntimeCache,key string)(interface{}, error){\n\t\treturn cache.GetString(key)\n\t})\n}\n\nfunc testRuntimeCache(t *testing.T,insertValue interface{},f func(cache *RuntimeCache,key string)(interface{}, error)) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,insertValue,5)\n\t\/\/check value\n\tgo func(cache *RuntimeCache,t *testing.T) {\n\t\ttime.Sleep(4*time.Second)\n\t\tvalue,err:=f(cache,TEST_CACHE_KEY)\n\n\t\ttest.Nil(t,err)\n\t\ttest.Equal(t,insertValue,value)\n\t}(cache,t)\n\n\ttime.Sleep(5*time.Second)\n}\n\nfunc TestRuntimeCache_Delete(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\n\tvalue,e:=cache.Get(TEST_CACHE_KEY)\n\n\ttest.Nil(t,e)\n\ttest.Equal(t,TEST_CACHE_VALUE,value)\n\n\tcache.Delete(TEST_CACHE_KEY)\n\n\tvalue,e=cache.Get(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\ttest.Nil(t,value)\n}\n\nfunc TestRuntimeCache_ClearAll(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tcache.Set(TEST_CACHE_KEY,TEST_CACHE_VALUE,5)\n\tcache.Set(\"2\",TEST_CACHE_VALUE,5)\n\tcache.Set(\"3\",TEST_CACHE_VALUE,5)\n\n\tval2, err := cache.GetString(\"2\")\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\ttest.Equal(t,TEST_CACHE_VALUE, val2)\n\n\tcache.ClearAll()\n\texists2, err := cache.Exists(\"2\")\n\tif err != nil{\n\t\tt.Error(err)\n\t}\n\tif exists2{\n\t\tt.Error(\"exists 2 but need not exists\")\n\t}\n}\n\nfunc TestRuntimeCache_Incr(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Incr(TEST_CACHE_KEY)\n\t\t}\n\n\t\twg.Add(-1)\n\t}(cache)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Incr(TEST_CACHE_KEY)\n\t\t}\n\t\twg.Add(-1)\n\t}(cache)\n\n\twg.Wait()\n\n\tvalue,e:=cache.GetInt(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\n\ttest.Equal(t,100,value)\n}\n\nfunc TestRuntimeCache_Decr(t *testing.T) {\n\tcache:=NewRuntimeCache()\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Decr(TEST_CACHE_KEY)\n\t\t}\n\n\t\twg.Add(-1)\n\t}(cache)\n\n\tgo func(cache *RuntimeCache) {\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tcache.Decr(TEST_CACHE_KEY)\n\t\t}\n\t\twg.Add(-1)\n\t}(cache)\n\n\twg.Wait()\n\n\tvalue,e:=cache.GetInt(TEST_CACHE_KEY)\n\ttest.Nil(t,e)\n\n\ttest.Equal(t,-100,value)\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 objectpath_test\n\nimport (\n\t\"bytes\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"testing\"\n\n\t\"golang.org\/x\/tools\/go\/buildutil\"\n\t\"golang.org\/x\/tools\/go\/gcexportdata\"\n\t\"golang.org\/x\/tools\/go\/loader\"\n\t\"golang.org\/x\/tools\/go\/types\/objectpath\"\n)\n\nfunc TestPaths(t *testing.T) {\n\tpkgs := map[string]map[string]string{\n\t\t\"b\": {\"b.go\": `\npackage b\n\nimport \"a\"\n\nconst C = a.Int(0)\n\nfunc F(a, b, c int, d a.T)\n\ntype T struct{ A int; b int; a.T }\n\nfunc (T) M() *interface{ f() }\n\ntype U T\n\ntype A = struct{ x int }\n\nvar V []*a.T\n\ntype M map[struct{x int}]struct{y int}\n\nfunc unexportedFunc()\ntype unexportedType struct{}\n`},\n\t\t\"a\": {\"a.go\": `\npackage a\n\ntype Int int\n\ntype T struct{x, y int}\n\n`},\n\t}\n\tconf := loader.Config{Build: buildutil.FakeContext(pkgs)}\n\tconf.Import(\"a\")\n\tconf.Import(\"b\")\n\tprog, err := conf.Load()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ta := prog.Imported[\"a\"].Pkg\n\tb := prog.Imported[\"b\"].Pkg\n\n\t\/\/ We test objectpath by enumerating a set of paths\n\t\/\/ and ensuring that Path(pkg, Object(pkg, path)) == path.\n\t\/\/\n\t\/\/ It might seem more natural to invert the test:\n\t\/\/ identify a set of objects and for each one,\n\t\/\/ ensure that Object(pkg, Path(pkg, obj)) == obj.\n\t\/\/ However, for most interesting test cases there is no\n\t\/\/ easy way to identify the object short of applying\n\t\/\/ a series of destructuring operations to pkg---which\n\t\/\/ is essentially what objectpath.Object does.\n\t\/\/ (We do a little of that when testing bad paths, below.)\n\t\/\/\n\t\/\/ The downside is that the test depends on the path encoding.\n\t\/\/ The upside is that the test exercises the encoding.\n\n\t\/\/ good paths\n\tfor _, test := range []struct {\n\t\tpkg     *types.Package\n\t\tpath    objectpath.Path\n\t\twantobj string\n\t}{\n\t\t{b, \"C\", \"const b.C a.Int\"},\n\t\t{b, \"F\", \"func b.F(a int, b int, c int, d a.T)\"},\n\t\t{b, \"F.PA0\", \"var a int\"},\n\t\t{b, \"F.PA1\", \"var b int\"},\n\t\t{b, \"F.PA2\", \"var c int\"},\n\t\t{b, \"F.PA3\", \"var d a.T\"},\n\t\t{b, \"T\", \"type b.T struct{A int; b int; a.T}\"},\n\t\t{b, \"T.O\", \"type b.T struct{A int; b int; a.T}\"},\n\t\t{b, \"T.UF0\", \"field A int\"},\n\t\t{b, \"T.UF1\", \"field b int\"},\n\t\t{b, \"T.UF2\", \"field T a.T\"},\n\t\t{b, \"U.UF2\", \"field T a.T\"}, \/\/ U.U... are aliases for T.U...\n\t\t{b, \"A\", \"type b.A = struct{x int}\"},\n\t\t{b, \"A.F0\", \"field x int\"},\n\t\t{b, \"V\", \"var b.V []*a.T\"},\n\t\t{b, \"M\", \"type b.M map[struct{x int}]struct{y int}\"},\n\t\t{b, \"M.UKF0\", \"field x int\"},\n\t\t{b, \"M.UEF0\", \"field y int\"},\n\t\t{b, \"T.M0\", \"func (b.T).M() *interface{f()}\"}, \/\/ concrete method\n\t\t{b, \"T.M0.RA0\", \"var  *interface{f()}\"},       \/\/ parameter\n\t\t{b, \"T.M0.RA0.EM0\", \"func (interface).f()\"},   \/\/ interface method\n\t\t{b, \"unexportedType\", \"type b.unexportedType struct{}\"},\n\t\t{a, \"T\", \"type a.T struct{x int; y int}\"},\n\t\t{a, \"T.UF0\", \"field x int\"},\n\t} {\n\t\t\/\/ check path -> object\n\t\tobj, err := objectpath.Object(test.pkg, test.path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q) failed: %v\",\n\t\t\t\ttest.pkg.Path(), test.path, err)\n\t\t\tcontinue\n\t\t}\n\t\tif obj.String() != test.wantobj {\n\t\t\tt.Errorf(\"Object(%s, %q) = %v, want %s\",\n\t\t\t\ttest.pkg.Path(), test.path, obj, test.wantobj)\n\t\t\tcontinue\n\t\t}\n\t\tif obj.Pkg() != test.pkg {\n\t\t\tt.Errorf(\"Object(%s, %q) = %v, which belongs to package %s\",\n\t\t\t\ttest.pkg.Path(), test.path, obj, obj.Pkg().Path())\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ check object -> path\n\t\tpath2, err := objectpath.For(obj)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"For(%v) failed: %v, want %q\", obj, err, test.path)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ We do not require that test.path == path2. Aliases are legal.\n\t\t\/\/ But we do require that Object(path2) finds the same object.\n\t\tobj2, err := objectpath.Object(test.pkg, path2)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q) failed: %v (roundtrip from %q)\",\n\t\t\t\ttest.pkg.Path(), path2, err, test.path)\n\t\t\tcontinue\n\t\t}\n\t\tif obj2 != obj {\n\t\t\tt.Errorf(\"Object(%s, For(obj)) != obj: got %s, obj is %s (path1=%q, path2=%q)\",\n\t\t\t\ttest.pkg.Path(), obj2, obj, test.path, path2)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t\/\/ bad paths (all relative to package b)\n\tfor _, test := range []struct {\n\t\tpkg     *types.Package\n\t\tpath    objectpath.Path\n\t\twantErr string\n\t}{\n\t\t{b, \"\", \"empty path\"},\n\t\t{b, \"missing\", `package b does not contain \"missing\"`},\n\t\t{b, \"F.U\", \"invalid path: ends with 'U', want [AFMO]\"},\n\t\t{b, \"F.PA3.O\", \"path denotes type a.T struct{x int; y int}, which belongs to a different package\"},\n\t\t{b, \"F.PA!\", `invalid path: bad numeric operand \"\" for code 'A'`},\n\t\t{b, \"F.PA3.UF0\", \"path denotes field x int, which belongs to a different package\"},\n\t\t{b, \"F.PA3.UF5\", \"field index 5 out of range [0-2)\"},\n\t\t{b, \"V.EE\", \"invalid path: ends with 'E', want [AFMO]\"},\n\t\t{b, \"F..O\", \"invalid path: unexpected '.' in type context\"},\n\t\t{b, \"T.OO\", \"invalid path: code 'O' in object context\"},\n\t\t{b, \"T.EO\", \"cannot apply 'E' to b.T (got *types.Named, want pointer, slice, array, chan or map)\"},\n\t\t{b, \"A.O\", \"cannot apply 'O' to struct{x int} (got struct{x int}, want named)\"},\n\t\t{b, \"A.UF0\", \"cannot apply 'U' to struct{x int} (got struct{x int}, want named)\"},\n\t\t{b, \"M.UPO\", \"cannot apply 'P' to map[struct{x int}]struct{y int} (got *types.Map, want signature)\"},\n\t\t{b, \"C.O\", \"path denotes type a.Int int, which belongs to a different package\"},\n\t} {\n\t\tobj, err := objectpath.Object(test.pkg, test.path)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Object(%s, %q) = %s, want error\",\n\t\t\t\ttest.pkg.Path(), test.path, obj)\n\t\t\tcontinue\n\t\t}\n\t\tif err.Error() != test.wantErr {\n\t\t\tt.Errorf(\"Object(%s, %q) error was %q, want %q\",\n\t\t\t\ttest.pkg.Path(), test.path, err, test.wantErr)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t\/\/ bad objects\n\tbInfo := prog.Imported[\"b\"]\n\tfor _, test := range []struct {\n\t\tobj     types.Object\n\t\twantErr string\n\t}{\n\t\t{types.Universe.Lookup(\"nil\"), \"predeclared nil has no path\"},\n\t\t{types.Universe.Lookup(\"len\"), \"predeclared builtin len has no path\"},\n\t\t{types.Universe.Lookup(\"int\"), \"predeclared type int has no path\"},\n\t\t{bInfo.Info.Implicits[bInfo.Files[0].Imports[0]], \"no path for package a\"}, \/\/ import \"a\"\n\t\t{b.Scope().Lookup(\"unexportedFunc\"), \"no path for non-exported func b.unexportedFunc()\"},\n\t} {\n\t\tpath, err := objectpath.For(test.obj)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Object(%s) = %q, want error\", test.obj, path)\n\t\t\tcontinue\n\t\t}\n\t\tif err.Error() != test.wantErr {\n\t\t\tt.Errorf(\"Object(%s) error was %q, want %q\", test.obj, err, test.wantErr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\/\/ TestSourceAndExportData uses objectpath to compute a correspondence\n\/\/ of objects between two versions of the same package, one loaded from\n\/\/ source, the other from export data.\nfunc TestSourceAndExportData(t *testing.T) {\n\tconst src = `\npackage p\n\ntype I int\n\nfunc (I) F() *struct{ X, Y int } {\n\treturn nil\n}\n\ntype Foo interface {\n\tMethod() (string, func(int) struct{ X int })\n}\n\nvar X chan struct{ Z int }\nvar Z map[string]struct{ A int }\n`\n\n\t\/\/ Parse source file and type-check it as a package, \"src\".\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"src.go\", src, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tconf := types.Config{Importer: importer.For(\"source\", nil)}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t}\n\tsrcpkg, err := conf.Check(\"src\/p\", fset, []*ast.File{f}, info)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Export binary export data then reload it as a new package, \"bin\".\n\tvar buf bytes.Buffer\n\tif err := gcexportdata.Write(&buf, fset, srcpkg); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\timports := make(map[string]*types.Package)\n\tbinpkg, err := gcexportdata.Read(&buf, fset, imports, \"bin\/p\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Now find the correspondences between them.\n\tfor _, srcobj := range info.Defs {\n\t\tif srcobj == nil {\n\t\t\tcontinue \/\/ e.g. package declaration\n\t\t}\n\t\tif _, ok := srcobj.(*types.PkgName); ok {\n\t\t\tcontinue \/\/ PkgName has no objectpath\n\t\t}\n\n\t\tpath, err := objectpath.For(srcobj)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"For(%v): %v\", srcobj, err)\n\t\t\tcontinue\n\t\t}\n\t\tbinobj, err := objectpath.Object(binpkg, path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q): %v\", binpkg.Path(), path, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Check the object strings match.\n\t\t\/\/ (We can't check that types are identical because the\n\t\t\/\/ objects belong to different type-checker realms.)\n\t\tsrcstr := types.ObjectString(srcobj, (*types.Package).Name)\n\t\tbinstr := types.ObjectString(binobj, (*types.Package).Name)\n\t\tif srcstr != binstr {\n\t\t\tt.Errorf(\"ObjectStrings do not match: Object(For(%q)) = %s, want %s\",\n\t\t\t\tpath, srcstr, binstr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n<commit_msg>go\/types\/objectpath: fix tests for pre-go1.11<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 objectpath_test\n\nimport (\n\t\"bytes\"\n\t\"go\/ast\"\n\t\"go\/importer\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"golang.org\/x\/tools\/go\/buildutil\"\n\t\"golang.org\/x\/tools\/go\/gcexportdata\"\n\t\"golang.org\/x\/tools\/go\/loader\"\n\t\"golang.org\/x\/tools\/go\/types\/objectpath\"\n)\n\nfunc TestPaths(t *testing.T) {\n\tpkgs := map[string]map[string]string{\n\t\t\"b\": {\"b.go\": `\npackage b\n\nimport \"a\"\n\nconst C = a.Int(0)\n\nfunc F(a, b, c int, d a.T)\n\ntype T struct{ A int; b int; a.T }\n\nfunc (T) M() *interface{ f() }\n\ntype U T\n\ntype A = struct{ x int }\n\nvar V []*a.T\n\ntype M map[struct{x int}]struct{y int}\n\nfunc unexportedFunc()\ntype unexportedType struct{}\n`},\n\t\t\"a\": {\"a.go\": `\npackage a\n\ntype Int int\n\ntype T struct{x, y int}\n\n`},\n\t}\n\tconf := loader.Config{Build: buildutil.FakeContext(pkgs)}\n\tconf.Import(\"a\")\n\tconf.Import(\"b\")\n\tprog, err := conf.Load()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ta := prog.Imported[\"a\"].Pkg\n\tb := prog.Imported[\"b\"].Pkg\n\n\t\/\/ We test objectpath by enumerating a set of paths\n\t\/\/ and ensuring that Path(pkg, Object(pkg, path)) == path.\n\t\/\/\n\t\/\/ It might seem more natural to invert the test:\n\t\/\/ identify a set of objects and for each one,\n\t\/\/ ensure that Object(pkg, Path(pkg, obj)) == obj.\n\t\/\/ However, for most interesting test cases there is no\n\t\/\/ easy way to identify the object short of applying\n\t\/\/ a series of destructuring operations to pkg---which\n\t\/\/ is essentially what objectpath.Object does.\n\t\/\/ (We do a little of that when testing bad paths, below.)\n\t\/\/\n\t\/\/ The downside is that the test depends on the path encoding.\n\t\/\/ The upside is that the test exercises the encoding.\n\n\t\/\/ good paths\n\tfor _, test := range []struct {\n\t\tpkg     *types.Package\n\t\tpath    objectpath.Path\n\t\twantobj string\n\t}{\n\t\t{b, \"C\", \"const b.C a.Int\"},\n\t\t{b, \"F\", \"func b.F(a int, b int, c int, d a.T)\"},\n\t\t{b, \"F.PA0\", \"var a int\"},\n\t\t{b, \"F.PA1\", \"var b int\"},\n\t\t{b, \"F.PA2\", \"var c int\"},\n\t\t{b, \"F.PA3\", \"var d a.T\"},\n\t\t{b, \"T\", \"type b.T struct{A int; b int; a.T}\"},\n\t\t{b, \"T.O\", \"type b.T struct{A int; b int; a.T}\"},\n\t\t{b, \"T.UF0\", \"field A int\"},\n\t\t{b, \"T.UF1\", \"field b int\"},\n\t\t{b, \"T.UF2\", \"field T a.T\"},\n\t\t{b, \"U.UF2\", \"field T a.T\"}, \/\/ U.U... are aliases for T.U...\n\t\t{b, \"A\", \"type b.A = struct{x int}\"},\n\t\t{b, \"A.F0\", \"field x int\"},\n\t\t{b, \"V\", \"var b.V []*a.T\"},\n\t\t{b, \"M\", \"type b.M map[struct{x int}]struct{y int}\"},\n\t\t{b, \"M.UKF0\", \"field x int\"},\n\t\t{b, \"M.UEF0\", \"field y int\"},\n\t\t{b, \"T.M0\", \"func (b.T).M() *interface{f()}\"}, \/\/ concrete method\n\t\t{b, \"T.M0.RA0\", \"var  *interface{f()}\"},       \/\/ parameter\n\t\t{b, \"T.M0.RA0.EM0\", \"func (interface).f()\"},   \/\/ interface method\n\t\t{b, \"unexportedType\", \"type b.unexportedType struct{}\"},\n\t\t{a, \"T\", \"type a.T struct{x int; y int}\"},\n\t\t{a, \"T.UF0\", \"field x int\"},\n\t} {\n\t\t\/\/ check path -> object\n\t\tobj, err := objectpath.Object(test.pkg, test.path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q) failed: %v\",\n\t\t\t\ttest.pkg.Path(), test.path, err)\n\t\t\tcontinue\n\t\t}\n\t\tif obj.String() != test.wantobj {\n\t\t\tt.Errorf(\"Object(%s, %q) = %v, want %s\",\n\t\t\t\ttest.pkg.Path(), test.path, obj, test.wantobj)\n\t\t\tcontinue\n\t\t}\n\t\tif obj.Pkg() != test.pkg {\n\t\t\tt.Errorf(\"Object(%s, %q) = %v, which belongs to package %s\",\n\t\t\t\ttest.pkg.Path(), test.path, obj, obj.Pkg().Path())\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ check object -> path\n\t\tpath2, err := objectpath.For(obj)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"For(%v) failed: %v, want %q\", obj, err, test.path)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ We do not require that test.path == path2. Aliases are legal.\n\t\t\/\/ But we do require that Object(path2) finds the same object.\n\t\tobj2, err := objectpath.Object(test.pkg, path2)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q) failed: %v (roundtrip from %q)\",\n\t\t\t\ttest.pkg.Path(), path2, err, test.path)\n\t\t\tcontinue\n\t\t}\n\t\tif obj2 != obj {\n\t\t\tt.Errorf(\"Object(%s, For(obj)) != obj: got %s, obj is %s (path1=%q, path2=%q)\",\n\t\t\t\ttest.pkg.Path(), obj2, obj, test.path, path2)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t\/\/ bad paths (all relative to package b)\n\tfor _, test := range []struct {\n\t\tpkg     *types.Package\n\t\tpath    objectpath.Path\n\t\twantErr string\n\t}{\n\t\t{b, \"\", \"empty path\"},\n\t\t{b, \"missing\", `package b does not contain \"missing\"`},\n\t\t{b, \"F.U\", \"invalid path: ends with 'U', want [AFMO]\"},\n\t\t{b, \"F.PA3.O\", \"path denotes type a.T struct{x int; y int}, which belongs to a different package\"},\n\t\t{b, \"F.PA!\", `invalid path: bad numeric operand \"\" for code 'A'`},\n\t\t{b, \"F.PA3.UF0\", \"path denotes field x int, which belongs to a different package\"},\n\t\t{b, \"F.PA3.UF5\", \"field index 5 out of range [0-2)\"},\n\t\t{b, \"V.EE\", \"invalid path: ends with 'E', want [AFMO]\"},\n\t\t{b, \"F..O\", \"invalid path: unexpected '.' in type context\"},\n\t\t{b, \"T.OO\", \"invalid path: code 'O' in object context\"},\n\t\t{b, \"T.EO\", \"cannot apply 'E' to b.T (got *types.Named, want pointer, slice, array, chan or map)\"},\n\t\t{b, \"A.O\", \"cannot apply 'O' to struct{x int} (got struct{x int}, want named)\"},\n\t\t{b, \"A.UF0\", \"cannot apply 'U' to struct{x int} (got struct{x int}, want named)\"},\n\t\t{b, \"M.UPO\", \"cannot apply 'P' to map[struct{x int}]struct{y int} (got *types.Map, want signature)\"},\n\t\t{b, \"C.O\", \"path denotes type a.Int int, which belongs to a different package\"},\n\t} {\n\t\tobj, err := objectpath.Object(test.pkg, test.path)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Object(%s, %q) = %s, want error\",\n\t\t\t\ttest.pkg.Path(), test.path, obj)\n\t\t\tcontinue\n\t\t}\n\t\tif err.Error() != test.wantErr {\n\t\t\tt.Errorf(\"Object(%s, %q) error was %q, want %q\",\n\t\t\t\ttest.pkg.Path(), test.path, err, test.wantErr)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t\/\/ bad objects\n\tbInfo := prog.Imported[\"b\"]\n\tfor _, test := range []struct {\n\t\tobj     types.Object\n\t\twantErr string\n\t}{\n\t\t{types.Universe.Lookup(\"nil\"), \"predeclared nil has no path\"},\n\t\t{types.Universe.Lookup(\"len\"), \"predeclared builtin len has no path\"},\n\t\t{types.Universe.Lookup(\"int\"), \"predeclared type int has no path\"},\n\t\t{bInfo.Info.Implicits[bInfo.Files[0].Imports[0]], \"no path for package a\"}, \/\/ import \"a\"\n\t\t{b.Scope().Lookup(\"unexportedFunc\"), \"no path for non-exported func b.unexportedFunc()\"},\n\t} {\n\t\tpath, err := objectpath.For(test.obj)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Object(%s) = %q, want error\", test.obj, path)\n\t\t\tcontinue\n\t\t}\n\t\tif err.Error() != test.wantErr {\n\t\t\tt.Errorf(\"Object(%s) error was %q, want %q\", test.obj, err, test.wantErr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\/\/ TestSourceAndExportData uses objectpath to compute a correspondence\n\/\/ of objects between two versions of the same package, one loaded from\n\/\/ source, the other from export data.\nfunc TestSourceAndExportData(t *testing.T) {\n\tconst src = `\npackage p\n\ntype I int\n\nfunc (I) F() *struct{ X, Y int } {\n\treturn nil\n}\n\ntype Foo interface {\n\tMethod() (string, func(int) struct{ X int })\n}\n\nvar X chan struct{ Z int }\nvar Z map[string]struct{ A int }\n`\n\n\t\/\/ Parse source file and type-check it as a package, \"src\".\n\tfset := token.NewFileSet()\n\tf, err := parser.ParseFile(fset, \"src.go\", src, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tconf := types.Config{Importer: importer.For(\"source\", nil)}\n\tinfo := &types.Info{\n\t\tDefs: make(map[*ast.Ident]types.Object),\n\t}\n\tsrcpkg, err := conf.Check(\"src\/p\", fset, []*ast.File{f}, info)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Export binary export data then reload it as a new package, \"bin\".\n\tvar buf bytes.Buffer\n\tif err := gcexportdata.Write(&buf, fset, srcpkg); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\timports := make(map[string]*types.Package)\n\tbinpkg, err := gcexportdata.Read(&buf, fset, imports, \"bin\/p\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Now find the correspondences between them.\n\tfor _, srcobj := range info.Defs {\n\t\tif srcobj == nil {\n\t\t\tcontinue \/\/ e.g. package declaration\n\t\t}\n\t\tif _, ok := srcobj.(*types.PkgName); ok {\n\t\t\tcontinue \/\/ PkgName has no objectpath\n\t\t}\n\n\t\tpath, err := objectpath.For(srcobj)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"For(%v): %v\", srcobj, err)\n\t\t\tcontinue\n\t\t}\n\t\tbinobj, err := objectpath.Object(binpkg, path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Object(%s, %q): %v\", binpkg.Path(), path, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Check the object strings match.\n\t\t\/\/ (We can't check that types are identical because the\n\t\t\/\/ objects belong to different type-checker realms.)\n\t\tsrcstr := objectString(srcobj)\n\t\tbinstr := objectString(binobj)\n\t\tif srcstr != binstr {\n\t\t\tt.Errorf(\"ObjectStrings do not match: Object(For(%q)) = %s, want %s\",\n\t\t\t\tpath, srcstr, binstr)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc objectString(obj types.Object) string {\n\ts := types.ObjectString(obj, (*types.Package).Name)\n\n\t\/\/ The printing of interface methods changed in go1.11.\n\t\/\/ This work-around makes the specific test pass with earlier versions.\n\ts = strings.Replace(s, \"func (interface).Method\", \"func (p.Foo).Method\", -1)\n\n\treturn s\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>gocolor -> gxlog<commit_after><|endoftext|>"}
{"text":"<commit_before>package kontrolhelper\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/streadway\/amqp\"\n\t\"io\/ioutil\"\n\t\"koding\/tools\/config\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Producer struct {\n\tConn    *amqp.Connection\n\tChannel *amqp.Channel\n\tName    string\n\tDone    chan error\n}\n\nfunc NewProducer(name string) *Producer {\n\treturn &Producer{\n\t\tConn:    nil,\n\t\tChannel: nil,\n\t\tName:    name,\n\t\tDone:    make(chan error),\n\t}\n}\n\nfunc CreateAmqpConnection() *amqp.Connection {\n\tuser := config.Current.Kontrold.RabbitMq.Login\n\tpassword := config.Current.Kontrold.RabbitMq.Password\n\thost := config.Current.Kontrold.RabbitMq.Host\n\tport := config.Current.Kontrold.RabbitMq.Port\n\n\tif port == \"\" {\n\t\tport = \"5672\" \/\/ default RABBITMQ_NODE_PORT\n\t}\n\n\turl := \"amqp:\/\/\" + user + \":\" + password + \"@\" + host + \":\" + port\n\tconn, err := amqp.Dial(url)\n\tif err != nil {\n\t\tlog.Fatalln(\"AMQP dial: \", err)\n\t}\n\n\tgo func() {\n\t\tfor err := range conn.NotifyClose(make(chan *amqp.Error)) {\n\t\t\tlog.Fatalf(\"AMQP connection: %s\" + err.Error())\n\t\t}\n\t}()\n\n\treturn conn\n}\n\nfunc CreateChannel(conn *amqp.Connection) *amqp.Channel {\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\tfor err := range channel.NotifyClose(make(chan *amqp.Error)) {\n\t\t\tlog.Fatalf(\"AMQP channel: %s\" + err.Error())\n\t\t}\n\t}()\n\treturn channel\n}\n\nfunc CreateStream(channel *amqp.Channel, kind, exchange, queue, key string, durable, autoDelete bool) <-chan amqp.Delivery {\n\tif err := channel.ExchangeDeclare(exchange, kind, durable, autoDelete, false, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif _, err := channel.QueueDeclare(queue, true, false, false, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := channel.QueueBind(queue, key, exchange, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream, err := channel.Consume(queue, \"\", true, true, false, false, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn stream\n}\n\nfunc CustomHostname() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn hostname\n}\n\nfunc ReadVersion() string {\n\tfile, err := ioutil.ReadFile(\"VERSION\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn strings.TrimSpace(string(file))\n}\n\nfunc ReadFile(config string) string {\n\tfile, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn strings.TrimSpace(string(file))\n}\n\nfunc CreateProducer(name string) (*Producer, error) {\n\tp := NewProducer(name)\n\tlog.Printf(\"creating connection for sending %s messages\", p.Name)\n\tp.Conn = CreateAmqpConnection()\n\tp.Channel = CreateChannel(p.Conn)\n\n\treturn p, nil\n}\n\nfunc RegisterToKontrol(name, uuid string, port int) error {\n\tconnection := CreateAmqpConnection()\n\tchannel := CreateChannel(connection)\n\n\ttype workerMessage struct {\n\t\tCommand string\n\t\tOption  string\n\t\tResult  string\n\t}\n\n\ttype workerMain struct {\n\t\tName     string\n\t\tUuid     string\n\t\tHostname string\n\t\tMessage  workerMessage\n\t\tPort     int\n\t}\n\n\tcmd := workerMain{\n\t\tName:     name,\n\t\tUuid:     uuid,\n\t\tHostname: CustomHostname(),\n\t\tMessage: workerMessage{\n\t\t\tCommand: \"addWithProxy\",\n\t\t\tOption:  \"many\",\n\t\t},\n\t\tPort: port,\n\t}\n\n\ttype Wrap struct{ Worker workerMain }\n\n\tdata, err := json.Marshal(&Wrap{cmd})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg := amqp.Publishing{\n\t\tHeaders:         amqp.Table{},\n\t\tContentType:     \"text\/plain\",\n\t\tContentEncoding: \"\",\n\t\tBody:            data,\n\t\tDeliveryMode:    1, \/\/ 1=non-persistent, 2=persistent\n\t\tAppId:           uuid,\n\t}\n\n\terr = channel.Publish(\"workerExchange\", \"input.worker\", false, false, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = channel.Close()\n\tif err != nil {\n\t\tlog.Println(\"could not close kontrold publisher amqp channel\", err)\n\t}\n\n\treturn nil\n}\n<commit_msg>kontrolhelper: create exchange if it doesn't exist<commit_after>package kontrolhelper\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/streadway\/amqp\"\n\t\"io\/ioutil\"\n\t\"koding\/tools\/config\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Producer struct {\n\tConn    *amqp.Connection\n\tChannel *amqp.Channel\n\tName    string\n\tDone    chan error\n}\n\nfunc NewProducer(name string) *Producer {\n\treturn &Producer{\n\t\tConn:    nil,\n\t\tChannel: nil,\n\t\tName:    name,\n\t\tDone:    make(chan error),\n\t}\n}\n\nfunc CreateAmqpConnection() *amqp.Connection {\n\tuser := config.Current.Kontrold.RabbitMq.Login\n\tpassword := config.Current.Kontrold.RabbitMq.Password\n\thost := config.Current.Kontrold.RabbitMq.Host\n\tport := config.Current.Kontrold.RabbitMq.Port\n\n\tif port == \"\" {\n\t\tport = \"5672\" \/\/ default RABBITMQ_NODE_PORT\n\t}\n\n\turl := \"amqp:\/\/\" + user + \":\" + password + \"@\" + host + \":\" + port\n\tconn, err := amqp.Dial(url)\n\tif err != nil {\n\t\tlog.Fatalln(\"AMQP dial: \", err)\n\t}\n\n\tgo func() {\n\t\tfor err := range conn.NotifyClose(make(chan *amqp.Error)) {\n\t\t\tlog.Fatalf(\"AMQP connection: %s\" + err.Error())\n\t\t}\n\t}()\n\n\treturn conn\n}\n\nfunc CreateChannel(conn *amqp.Connection) *amqp.Channel {\n\tchannel, err := conn.Channel()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgo func() {\n\t\tfor err := range channel.NotifyClose(make(chan *amqp.Error)) {\n\t\t\tlog.Fatalf(\"AMQP channel: %s\" + err.Error())\n\t\t}\n\t}()\n\treturn channel\n}\n\nfunc CreateStream(channel *amqp.Channel, kind, exchange, queue, key string, durable, autoDelete bool) <-chan amqp.Delivery {\n\tif err := channel.ExchangeDeclare(exchange, kind, durable, autoDelete, false, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif _, err := channel.QueueDeclare(queue, true, false, false, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := channel.QueueBind(queue, key, exchange, false, nil); err != nil {\n\t\tpanic(err)\n\t}\n\n\tstream, err := channel.Consume(queue, \"\", true, true, false, false, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn stream\n}\n\nfunc CustomHostname() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn hostname\n}\n\nfunc ReadVersion() string {\n\tfile, err := ioutil.ReadFile(\"VERSION\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn strings.TrimSpace(string(file))\n}\n\nfunc ReadFile(config string) string {\n\tfile, err := ioutil.ReadFile(config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn strings.TrimSpace(string(file))\n}\n\nfunc CreateProducer(name string) (*Producer, error) {\n\tp := NewProducer(name)\n\tlog.Printf(\"creating connection for sending %s messages\", p.Name)\n\tp.Conn = CreateAmqpConnection()\n\tp.Channel = CreateChannel(p.Conn)\n\n\treturn p, nil\n}\n\nfunc RegisterToKontrol(name, uuid string, port int) error {\n\tconnection := CreateAmqpConnection()\n\tchannel := CreateChannel(connection)\n\n\ttype workerMessage struct {\n\t\tCommand string\n\t\tOption  string\n\t\tResult  string\n\t}\n\n\ttype workerMain struct {\n\t\tName     string\n\t\tUuid     string\n\t\tHostname string\n\t\tMessage  workerMessage\n\t\tPort     int\n\t}\n\n\tcmd := workerMain{\n\t\tName:     name,\n\t\tUuid:     uuid,\n\t\tHostname: CustomHostname(),\n\t\tMessage: workerMessage{\n\t\t\tCommand: \"addWithProxy\",\n\t\t\tOption:  \"many\",\n\t\t},\n\t\tPort: port,\n\t}\n\n\ttype Wrap struct{ Worker workerMain }\n\n\tdata, err := json.Marshal(&Wrap{cmd})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsg := amqp.Publishing{\n\t\tHeaders:         amqp.Table{},\n\t\tContentType:     \"text\/plain\",\n\t\tContentEncoding: \"\",\n\t\tBody:            data,\n\t\tDeliveryMode:    1, \/\/ 1=non-persistent, 2=persistent\n\t\tAppId:           uuid,\n\t}\n\n\tif err := channel.ExchangeDeclare(\"workerExchange\", \"topic\", true, false, false, false, nil); err != nil {\n\t\treturn err\n\t}\n\n\terr = channel.Publish(\"workerExchange\", \"input.worker\", false, false, msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = channel.Close()\n\tif err != nil {\n\t\tlog.Println(\"could not close kontrold publisher amqp channel\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/maxmind\/geoipupdate\/v4\/pkg\/geoipupdate\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestMultipleDatabaseDownload(t *testing.T) {\n\tdatabaseContent := \"database content goes here\"\n\n\tserver := httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rw http.ResponseWriter, r *http.Request) {\n\t\t\t\terr := r.ParseForm()\n\t\t\t\trequire.NoError(t, err, \"parse form\")\n\n\t\t\t\tif strings.HasPrefix(r.URL.Path, \"\/geoip\/databases\") {\n\t\t\t\t\tbuf := &bytes.Buffer{}\n\t\t\t\t\tgzWriter := gzip.NewWriter(buf)\n\t\t\t\t\tmd5Writer := md5.New()\n\t\t\t\t\tmultiWriter := io.MultiWriter(gzWriter, md5Writer)\n\t\t\t\t\t_, err := multiWriter.Write([]byte(\n\t\t\t\t\t\tdatabaseContent + \" \" + r.URL.Path,\n\t\t\t\t\t))\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\terr = gzWriter.Close()\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\trw.Header().Set(\n\t\t\t\t\t\t\"X-Database-MD5\",\n\t\t\t\t\t\tfmt.Sprintf(\"%x\", md5Writer.Sum(nil)),\n\t\t\t\t\t)\n\t\t\t\t\trw.Header().Set(\"Last-Modified\", time.Now().Format(time.RFC1123))\n\n\t\t\t\t\t_, err = rw.Write(buf.Bytes())\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif r.URL.Path == \"\/app\/update_getfilename\" {\n\t\t\t\t\t_, err := rw.Write([]byte(r.Form.Get(\"product_id\") + \".mmdb\"))\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\t},\n\t\t),\n\t)\n\tdefer server.Close()\n\n\tclient := server.Client()\n\n\ttempDir, err := ioutil.TempDir(\"\", \"gutest-\")\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\terr := os.RemoveAll(tempDir)\n\t\trequire.NoError(t, err)\n\t}()\n\n\tconfig := &geoipupdate.Config{\n\t\tAccountID:         123,\n\t\tDatabaseDirectory: tempDir,\n\t\tEditionIDs:        []string{\"GeoLite2-City\", \"GeoLite2-Country\"},\n\t\tLicenseKey:        \"testing\",\n\t\tLockFile:          filepath.Join(tempDir, \".geoipupdate.lock\"),\n\t\tURL:               server.URL,\n\t}\n\n\tlogOutput := &bytes.Buffer{}\n\tlog.SetOutput(logOutput)\n\n\terr = run(client, config)\n\tassert.NoError(t, err, \"run successfully\")\n\n\tassert.Equal(t, \"\", logOutput.String(), \"no logged output\")\n\n\tfor _, editionID := range config.EditionIDs {\n\t\tpath := filepath.Join(config.DatabaseDirectory, editionID+\".mmdb\")\n\t\tbuf, err := ioutil.ReadFile(path) \/\/nolint:gosec\n\t\trequire.NoError(t, err, \"read file\")\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\tdatabaseContent+\" \/geoip\/databases\/\"+editionID+\"\/update\",\n\t\t\tstring(buf),\n\t\t\t\"correct database\",\n\t\t)\n\t}\n}\n<commit_msg>Use filepath.Clean instance of nolint<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/maxmind\/geoipupdate\/v4\/pkg\/geoipupdate\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestMultipleDatabaseDownload(t *testing.T) {\n\tdatabaseContent := \"database content goes here\"\n\n\tserver := httptest.NewServer(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(rw http.ResponseWriter, r *http.Request) {\n\t\t\t\terr := r.ParseForm()\n\t\t\t\trequire.NoError(t, err, \"parse form\")\n\n\t\t\t\tif strings.HasPrefix(r.URL.Path, \"\/geoip\/databases\") {\n\t\t\t\t\tbuf := &bytes.Buffer{}\n\t\t\t\t\tgzWriter := gzip.NewWriter(buf)\n\t\t\t\t\tmd5Writer := md5.New()\n\t\t\t\t\tmultiWriter := io.MultiWriter(gzWriter, md5Writer)\n\t\t\t\t\t_, err := multiWriter.Write([]byte(\n\t\t\t\t\t\tdatabaseContent + \" \" + r.URL.Path,\n\t\t\t\t\t))\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\terr = gzWriter.Close()\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\trw.Header().Set(\n\t\t\t\t\t\t\"X-Database-MD5\",\n\t\t\t\t\t\tfmt.Sprintf(\"%x\", md5Writer.Sum(nil)),\n\t\t\t\t\t)\n\t\t\t\t\trw.Header().Set(\"Last-Modified\", time.Now().Format(time.RFC1123))\n\n\t\t\t\t\t_, err = rw.Write(buf.Bytes())\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif r.URL.Path == \"\/app\/update_getfilename\" {\n\t\t\t\t\t_, err := rw.Write([]byte(r.Form.Get(\"product_id\") + \".mmdb\"))\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\t},\n\t\t),\n\t)\n\tdefer server.Close()\n\n\tclient := server.Client()\n\n\ttempDir, err := ioutil.TempDir(\"\", \"gutest-\")\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\terr := os.RemoveAll(tempDir)\n\t\trequire.NoError(t, err)\n\t}()\n\n\tconfig := &geoipupdate.Config{\n\t\tAccountID:         123,\n\t\tDatabaseDirectory: tempDir,\n\t\tEditionIDs:        []string{\"GeoLite2-City\", \"GeoLite2-Country\"},\n\t\tLicenseKey:        \"testing\",\n\t\tLockFile:          filepath.Join(tempDir, \".geoipupdate.lock\"),\n\t\tURL:               server.URL,\n\t}\n\n\tlogOutput := &bytes.Buffer{}\n\tlog.SetOutput(logOutput)\n\n\terr = run(client, config)\n\tassert.NoError(t, err, \"run successfully\")\n\n\tassert.Equal(t, \"\", logOutput.String(), \"no logged output\")\n\n\tfor _, editionID := range config.EditionIDs {\n\t\tpath := filepath.Join(config.DatabaseDirectory, editionID+\".mmdb\")\n\t\tbuf, err := ioutil.ReadFile(filepath.Clean(path))\n\t\trequire.NoError(t, err, \"read file\")\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\tdatabaseContent+\" \/geoip\/databases\/\"+editionID+\"\/update\",\n\t\t\tstring(buf),\n\t\t\t\"correct database\",\n\t\t)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package oskite\n\nimport (\n\t\"fmt\"\n\t\"koding\/virt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\tredigo \"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/koding\/redis\"\n)\n\nvar (\n\toskites   = make(map[string]*OskiteInfo)\n\toskitesMu sync.Mutex\n)\n\nfunc (o *Oskite) loadBalancer(correlationName, username, deadService string) string {\n\tblog := func(v interface{}) {\n\t\tlog.Info(\"oskite loadbalancer for [correlationName: '%s' user: '%s' deadService: '%s'] results in --> %v.\", correlationName, username, deadService, v)\n\t}\n\n\tresultOskite := o.ServiceUniquename\n\tlowestOskite := lowestOskiteLoad()\n\tif lowestOskite != \"\" {\n\t\tif deadService == lowestOskite {\n\t\t\tresultOskite = o.ServiceUniquename\n\t\t} else {\n\t\t\tresultOskite = lowestOskite\n\t\t}\n\t}\n\n\tvar vm *virt.VM\n\tif bson.IsObjectIdHex(correlationName) {\n\t\tmongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.FindId(bson.ObjectIdHex(correlationName)).One(&vm)\n\t\t})\n\t}\n\n\tif vm == nil {\n\t\tif err := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Find(bson.M{\"hostnameAlias\": correlationName}).One(&vm)\n\t\t}); err != nil {\n\t\t\tblog(fmt.Sprintf(\"no hostnameAlias found, returning %s\", resultOskite))\n\t\t\treturn resultOskite \/\/ no vm was found, return this oskite\n\t\t}\n\t}\n\n\tif vm.PinnedToHost != \"\" {\n\t\tblog(fmt.Sprintf(\"returning pinnedHost '%s'\", vm.PinnedToHost))\n\t\treturn vm.PinnedToHost\n\t}\n\n\tif vm.HostKite == \"\" {\n\t\t\/\/ also set hoskite to prevent race condition between terminal and\n\t\t\/\/ oskite. Because if we set it now, the \"kite.who\" method of terminal\n\t\t\/\/ will not reply with an empty response.\n\t\terr := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Update(bson.M{\"_id\": vm.Id, \"hostKite\": nil}, bson.M{\"$set\": bson.M{\"hostKite\": resultOskite}})\n\t\t})\n\n\t\tblog(fmt.Sprintf(\"hostkite is empty returning '%s. (update err: %s)\", resultOskite, err))\n\t\treturn resultOskite\n\t}\n\n\t\/\/ maintenance and banned will be handled again in valideVM() function,\n\t\/\/ which will return a permission error.\n\tif vm.HostKite == \"(maintenance)\" || vm.HostKite == \"(banned)\" {\n\t\tblog(fmt.Sprintf(\"hostkite is %s returning '%s'\", vm.HostKite, resultOskite))\n\t\treturn resultOskite\n\t}\n\n\t\/\/ Set hostkite to nil if we detect a dead service. On the next call,\n\t\/\/ Oskite will point to an health service in validateVM function()\n\t\/\/ because it will detect that the hostkite is nil and change it to the\n\t\/\/ healthy service given by the client, which is the returned\n\t\/\/ k.ServiceUniqueName.\n\tif vm.HostKite == deadService {\n\t\tblog(fmt.Sprintf(\"dead service detected %s returning '%s'\", vm.HostKite, o.ServiceUniquename))\n\t\tif err := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Update(bson.M{\"_id\": vm.Id}, bson.M{\"$set\": bson.M{\"hostKite\": nil}})\n\t\t}); err != nil {\n\t\t\tlog.LogError(err, 0, vm.Id.Hex())\n\t\t}\n\n\t\treturn resultOskite\n\t}\n\n\tblog(fmt.Sprintf(\"returning existing hostkite '%s'\", vm.HostKite))\n\treturn vm.HostKite\n}\n\nfunc (o *Oskite) setupRedis() {\n\tif o.RedisSession != nil {\n\t\treturn\n\t}\n\n\tsession, err := redis.NewRedisSession(conf.Redis)\n\tif err != nil {\n\t\tlog.Error(\"redis SADD kontainers. err: %v\", err.Error())\n\t}\n\n\to.RedisSession = session\n\n\t\/\/ oskite:production:sj:\n\to.RedisPrefix = \"oskite:\" + conf.Environment + \":\" + o.Region + \":\"\n\n\t\/\/ kontainers-production-sj\n\to.RedisKontainerSet = \"kontainers-\" + conf.Environment + \"-\" + o.Region\n\n\t\/\/ oskite:production:sj:kite-os-sj|kontainer3_sj_koding_com\n\to.RedisKontainerKey = o.RedisPrefix + o.ServiceUniquename\n\n\to.RedisSession.SetPrefix(\"oskite\")\n}\n\nfunc (o *Oskite) redisBalancer() {\n\to.setupRedis()\n\n\tlog.Info(\"Connected to Redis with %s\", o.RedisKontainerKey)\n\t_, err := redigo.Int(o.RedisSession.Do(\"SADD\", o.RedisKontainerSet, o.RedisKontainerKey))\n\tif err != nil {\n\t\tlog.Error(\"redis SADD kontainers. err: %v\", err.Error())\n\t}\n\n\t\/\/ update regularly our VMS info\n\tgo func() {\n\t\texpireDuration := time.Second * 5\n\t\tfor _ = range time.Tick(2 * time.Second) {\n\t\t\toskiteInfo := o.GetOskiteInfo()\n\n\t\t\tif _, err := o.RedisSession.Do(\"HMSET\", redigo.Args{o.RedisKontainerKey}.AddFlat(oskiteInfo)...); err != nil {\n\t\t\t\tlog.Error(\"redis HMSET err: %v\", err.Error())\n\t\t\t}\n\n\t\t\treply, err := redigo.Int(o.RedisSession.Do(\"EXPIRE\", o.RedisKontainerKey, expireDuration.Seconds()))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"redis SET Expire %v. reply: %v err: %v\", o.RedisKontainerKey, reply, err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ get oskite statuses from others every 2 seconds\n\tfor _ = range time.Tick(2 * time.Second) {\n\t\tkontainers, err := redigo.Strings(o.RedisSession.Do(\"SMEMBERS\", o.RedisKontainerSet))\n\t\tif err != nil {\n\t\t\tlog.Error(\"redis SMEMBER kontainers. err: %v\", err.Error())\n\t\t}\n\n\t\tfor _, kontainerHostname := range kontainers {\n\t\t\t\/\/ convert to o.ServiceUniquename format\n\t\t\tremoteOskite := strings.TrimPrefix(kontainerHostname, o.RedisPrefix)\n\n\t\t\tvalues, err := redigo.Values(o.RedisSession.Do(\"HGETALL\", kontainerHostname))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"redis HTGETALL %s. err: %v\", kontainerHostname, err.Error())\n\n\t\t\t\t\/\/ kontainer might be dead, key gets than expired, continue with the next one\n\n\t\t\t\toskitesMu.Lock()\n\t\t\t\tdelete(oskites, remoteOskite)\n\t\t\t\toskitesMu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ cleanup members from the set if the key expires. Usually that\n\t\t\t\/\/ might due a host who added itself to the kontainer set but then\n\t\t\t\/\/ just died or added a wrong set name.\n\t\t\tif len(values) == 0 && kontainerHostname != o.RedisKontainerKey {\n\t\t\t\t_, err := redigo.Int(o.RedisSession.Do(\"SREM\", o.RedisKontainerSet, kontainerHostname))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"redis SREM kontainers. err: %v\", err.Error())\n\t\t\t\t}\n\n\t\t\t\toskitesMu.Lock()\n\t\t\t\tdelete(oskites, remoteOskite)\n\t\t\t\toskitesMu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toskiteInfo := new(OskiteInfo)\n\t\t\tif err := redigo.ScanStruct(values, oskiteInfo); err != nil {\n\t\t\t\tlog.Error(\"redis ScanStruct err: %v\", err.Error())\n\t\t\t}\n\n\t\t\toskitesMu.Lock()\n\t\t\toskites[remoteOskite] = oskiteInfo\n\t\t\toskitesMu.Unlock()\n\t\t}\n\t}\n}\n\nfunc lowestOskiteLoad() (serviceUniquename string) {\n\toskitesMu.Lock()\n\tdefer oskitesMu.Unlock()\n\n\toskitesSlice := make([]*OskiteInfo, 0, len(oskites))\n\n\tfor s, v := range oskites {\n\t\tv.ServiceUniquename = s\n\t\toskitesSlice = append(oskitesSlice, v)\n\t}\n\n\tsort.Sort(ByVM(oskitesSlice))\n\n\tmiddle := len(oskitesSlice) \/ 2\n\tif middle == 0 {\n\t\treturn \"\"\n\t}\n\n\t\/\/ return randomly one of the lowest\n\tl := oskitesSlice[rand.Intn(middle)]\n\n\t\/\/ also pick up the highest to log information\n\th := oskitesSlice[len(oskitesSlice)-1]\n\n\tlog.Info(\"oskite picked up as lowest load %s with %d VMs (highest was: %d \/ %s)\",\n\t\tl.ServiceUniquename, l.ActiveVMs, h.ActiveVMs, h.ServiceUniquename)\n\n\treturn l.ServiceUniquename\n}\n<commit_msg>oskite: only remove from internal map, it get's removed when oskite shuts down<commit_after>package oskite\n\nimport (\n\t\"fmt\"\n\t\"koding\/virt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\tredigo \"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/koding\/redis\"\n)\n\nvar (\n\toskites   = make(map[string]*OskiteInfo)\n\toskitesMu sync.Mutex\n)\n\nfunc (o *Oskite) loadBalancer(correlationName, username, deadService string) string {\n\tblog := func(v interface{}) {\n\t\tlog.Info(\"oskite loadbalancer for [correlationName: '%s' user: '%s' deadService: '%s'] results in --> %v.\", correlationName, username, deadService, v)\n\t}\n\n\tresultOskite := o.ServiceUniquename\n\tlowestOskite := lowestOskiteLoad()\n\tif lowestOskite != \"\" {\n\t\tif deadService == lowestOskite {\n\t\t\tresultOskite = o.ServiceUniquename\n\t\t} else {\n\t\t\tresultOskite = lowestOskite\n\t\t}\n\t}\n\n\tvar vm *virt.VM\n\tif bson.IsObjectIdHex(correlationName) {\n\t\tmongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.FindId(bson.ObjectIdHex(correlationName)).One(&vm)\n\t\t})\n\t}\n\n\tif vm == nil {\n\t\tif err := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Find(bson.M{\"hostnameAlias\": correlationName}).One(&vm)\n\t\t}); err != nil {\n\t\t\tblog(fmt.Sprintf(\"no hostnameAlias found, returning %s\", resultOskite))\n\t\t\treturn resultOskite \/\/ no vm was found, return this oskite\n\t\t}\n\t}\n\n\tif vm.PinnedToHost != \"\" {\n\t\tblog(fmt.Sprintf(\"returning pinnedHost '%s'\", vm.PinnedToHost))\n\t\treturn vm.PinnedToHost\n\t}\n\n\tif vm.HostKite == \"\" {\n\t\t\/\/ also set hoskite to prevent race condition between terminal and\n\t\t\/\/ oskite. Because if we set it now, the \"kite.who\" method of terminal\n\t\t\/\/ will not reply with an empty response.\n\t\terr := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Update(bson.M{\"_id\": vm.Id, \"hostKite\": nil}, bson.M{\"$set\": bson.M{\"hostKite\": resultOskite}})\n\t\t})\n\n\t\tblog(fmt.Sprintf(\"hostkite is empty returning '%s. (update err: %s)\", resultOskite, err))\n\t\treturn resultOskite\n\t}\n\n\t\/\/ maintenance and banned will be handled again in valideVM() function,\n\t\/\/ which will return a permission error.\n\tif vm.HostKite == \"(maintenance)\" || vm.HostKite == \"(banned)\" {\n\t\tblog(fmt.Sprintf(\"hostkite is %s returning '%s'\", vm.HostKite, resultOskite))\n\t\treturn resultOskite\n\t}\n\n\t\/\/ Set hostkite to nil if we detect a dead service. On the next call,\n\t\/\/ Oskite will point to an health service in validateVM function()\n\t\/\/ because it will detect that the hostkite is nil and change it to the\n\t\/\/ healthy service given by the client, which is the returned\n\t\/\/ k.ServiceUniqueName.\n\tif vm.HostKite == deadService {\n\t\tblog(fmt.Sprintf(\"dead service detected %s returning '%s'\", vm.HostKite, o.ServiceUniquename))\n\t\tif err := mongodbConn.Run(\"jVMs\", func(c *mgo.Collection) error {\n\t\t\treturn c.Update(bson.M{\"_id\": vm.Id}, bson.M{\"$set\": bson.M{\"hostKite\": nil}})\n\t\t}); err != nil {\n\t\t\tlog.LogError(err, 0, vm.Id.Hex())\n\t\t}\n\n\t\treturn resultOskite\n\t}\n\n\tblog(fmt.Sprintf(\"returning existing hostkite '%s'\", vm.HostKite))\n\treturn vm.HostKite\n}\n\nfunc (o *Oskite) setupRedis() {\n\tif o.RedisSession != nil {\n\t\treturn\n\t}\n\n\tsession, err := redis.NewRedisSession(conf.Redis)\n\tif err != nil {\n\t\tlog.Error(\"redis SADD kontainers. err: %v\", err.Error())\n\t}\n\n\to.RedisSession = session\n\n\t\/\/ oskite:production:sj:\n\to.RedisPrefix = \"oskite:\" + conf.Environment + \":\" + o.Region + \":\"\n\n\t\/\/ kontainers-production-sj\n\to.RedisKontainerSet = \"kontainers-\" + conf.Environment + \"-\" + o.Region\n\n\t\/\/ oskite:production:sj:kite-os-sj|kontainer3_sj_koding_com\n\to.RedisKontainerKey = o.RedisPrefix + o.ServiceUniquename\n\n\to.RedisSession.SetPrefix(\"oskite\")\n}\n\nfunc (o *Oskite) redisBalancer() {\n\to.setupRedis()\n\n\tlog.Info(\"Connected to Redis with %s\", o.RedisKontainerKey)\n\t_, err := redigo.Int(o.RedisSession.Do(\"SADD\", o.RedisKontainerSet, o.RedisKontainerKey))\n\tif err != nil {\n\t\tlog.Error(\"redis SADD kontainers. err: %v\", err.Error())\n\t}\n\n\t\/\/ update regularly our VMS info\n\tgo func() {\n\t\texpireDuration := time.Second * 5\n\t\tfor _ = range time.Tick(2 * time.Second) {\n\t\t\toskiteInfo := o.GetOskiteInfo()\n\n\t\t\tif _, err := o.RedisSession.Do(\"HMSET\", redigo.Args{o.RedisKontainerKey}.AddFlat(oskiteInfo)...); err != nil {\n\t\t\t\tlog.Error(\"redis HMSET err: %v\", err.Error())\n\t\t\t}\n\n\t\t\treply, err := redigo.Int(o.RedisSession.Do(\"EXPIRE\", o.RedisKontainerKey, expireDuration.Seconds()))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"redis SET Expire %v. reply: %v err: %v\", o.RedisKontainerKey, reply, err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ get oskite statuses from others every 2 seconds\n\tfor _ = range time.Tick(2 * time.Second) {\n\t\tkontainers, err := redigo.Strings(o.RedisSession.Do(\"SMEMBERS\", o.RedisKontainerSet))\n\t\tif err != nil {\n\t\t\tlog.Error(\"redis SMEMBER kontainers. err: %v\", err.Error())\n\t\t}\n\n\t\tfor _, kontainerHostname := range kontainers {\n\t\t\t\/\/ convert to o.ServiceUniquename format\n\t\t\tremoteOskite := strings.TrimPrefix(kontainerHostname, o.RedisPrefix)\n\n\t\t\tvalues, err := redigo.Values(o.RedisSession.Do(\"HGETALL\", kontainerHostname))\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"redis HTGETALL %s. err: %v\", kontainerHostname, err.Error())\n\n\t\t\t\t\/\/ kontainer might be dead, key gets than expired, continue with the next one\n\n\t\t\t\toskitesMu.Lock()\n\t\t\t\tdelete(oskites, remoteOskite)\n\t\t\t\toskitesMu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ cleanup members from the map if the key expires. Usually that\n\t\t\t\/\/ might due a host who added itself to the kontainer set but then\n\t\t\t\/\/ just died or added a wrong set name. If the kontainer comes up\n\t\t\t\/\/ again we do add it below again.\n\t\t\tif len(values) == 0 {\n\t\t\t\toskitesMu.Lock()\n\t\t\t\tdelete(oskites, remoteOskite)\n\t\t\t\toskitesMu.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toskiteInfo := new(OskiteInfo)\n\t\t\tif err := redigo.ScanStruct(values, oskiteInfo); err != nil {\n\t\t\t\tlog.Error(\"redis ScanStruct err: %v\", err.Error())\n\t\t\t}\n\n\t\t\toskitesMu.Lock()\n\t\t\toskites[remoteOskite] = oskiteInfo\n\t\t\toskitesMu.Unlock()\n\t\t}\n\t}\n}\n\nfunc lowestOskiteLoad() (serviceUniquename string) {\n\toskitesMu.Lock()\n\tdefer oskitesMu.Unlock()\n\n\toskitesSlice := make([]*OskiteInfo, 0, len(oskites))\n\n\tfor s, v := range oskites {\n\t\tv.ServiceUniquename = s\n\t\toskitesSlice = append(oskitesSlice, v)\n\t}\n\n\tsort.Sort(ByVM(oskitesSlice))\n\n\tmiddle := len(oskitesSlice) \/ 2\n\tif middle == 0 {\n\t\treturn \"\"\n\t}\n\n\t\/\/ return randomly one of the lowest\n\tl := oskitesSlice[rand.Intn(middle)]\n\n\t\/\/ also pick up the highest to log information\n\th := oskitesSlice[len(oskitesSlice)-1]\n\n\tlog.Info(\"oskite picked up as lowest load %s with %d VMs (highest was: %d \/ %s)\",\n\t\tl.ServiceUniquename, l.ActiveVMs, h.ActiveVMs, h.ServiceUniquename)\n\n\treturn l.ServiceUniquename\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/MJKWoolnough\/byteio\"\n\t\"github.com\/MJKWoolnough\/minecraft\"\n\t\"github.com\/MJKWoolnough\/minecraft\/nbt\"\n\t\"github.com\/MJKWoolnough\/ora\"\n)\n\nfunc (t Transfer) generate(name string, _ *byteio.StickyReader, w *byteio.StickyWriter, f *os.File, size int64) error {\n\to, err := ora.Open(f, size)\n\tif err != nil {\n\t\treturn err\n\t}\n\tterrain := o.Layer(\"terrain\")\n\tif terrain == nil {\n\t\treturn layerError{\"terrain\"}\n\t}\n\theight := o.Layer(\"height\")\n\tif height == nil {\n\t\treturn layerError{\"height\"}\n\t}\n\tmp := t.c.NewMap()\n\tif mp == nil {\n\t\treturn errors.New(\"failed to create map\")\n\t}\n\n\tdone := false\n\tdefer func() {\n\t\tif !done {\n\t\t\tt.c.RemoveMap(mp.ID)\n\t\t}\n\t\tgo t.c.Save()\n\t}()\n\n\tmp.Lock()\n\tmp.Name = name\n\tmapPath := mp.Path\n\tmp.Server = -2\n\tmp.Unlock()\n\n\tms := DefaultMapSettings()\n\tms[\"level-type\"] = minecraft.FlatGenerator\n\tms[\"generator-settings\"] = \"0\"\n\tms[\"motd\"] = name\n\n\tpf, err := os.Create(path.Join(mapPath, \"properties.map\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = ms.WriteTo(pf); err != nil {\n\t\treturn err\n\t}\n\tpf.Close()\n\n\tb := o.Bounds()\n\tw.WriteUint8(2)\n\tw.WriteInt32(int32(b.Max.X) >> 4)\n\tw.WriteInt32(int32(b.Max.Y) >> 4)\n\tc := make(chan paint, 1024)\n\tm := make(chan string, 4)\n\te := make(chan struct{}, 0)\n\tdefer close(e)\n\tgo func() {\n\t\tdefer close(c)\n\t\tdefer close(m)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message := <-m:\n\t\t\t\tw.WriteUint8(3)\n\t\t\t\twriteString(w, message)\n\t\t\tcase p := <-c:\n\t\t\t\tw.WriteUint8(4)\n\t\t\t\tw.WriteInt32(p.X)\n\t\t\t\tw.WriteInt32(p.Y)\n\t\t\t\tr, g, b, a := p.RGBA()\n\t\t\t\tw.WriteUint8(uint8(r >> 8))\n\t\t\t\tw.WriteUint8(uint8(g >> 8))\n\t\t\t\tw.WriteUint8(uint8(b >> 8))\n\t\t\t\tw.WriteUint8(uint8(a >> 8))\n\t\t\tcase <-e:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tsTerrain := image.NewPaletted(o.Bounds(), terrainColours)\n\tterrainI, err := terrain.Image()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdraw.Draw(sTerrain, image.Rect(terrain.X, terrain.Y, sTerrain.Bounds().Max.X, sTerrain.Bounds().Max.Y), terrainI, image.Point{}, draw.Src)\n\tterrainI = nil\n\tsHeight := image.NewGray(o.Bounds())\n\theightI, err := height.Image()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdraw.Draw(sHeight, image.Rect(height.X, height.Y, sTerrain.Bounds().Max.X, sTerrain.Bounds().Max.Y), heightI, image.Point{}, draw.Src)\n\theightI = nil\n\n\tp, err := minecraft.NewFilePath(mapPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlevel, err := minecraft.NewLevel(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlevel.LevelName(name)\n\n\tm <- \"Building Terrain\"\n\tif err := buildTerrain(p, level, sTerrain, sHeight, c); err != nil {\n\t\treturn err\n\t}\n\n\tlevel.LevelName(name)\n\tlevel.MobSpawning(false)\n\tlevel.KeepInventory(true)\n\tlevel.FireTick(false)\n\tlevel.DayLightCycle(false)\n\tlevel.MobGriefing(false)\n\tlevel.Spawn(10, 250, 10)\n\tlevel.Generator(minecraft.FlatGenerator)\n\tlevel.GeneratorOptions(\"0\")\n\tlevel.GameMode(minecraft.Creative)\n\tlevel.AllowCommands(true)\n\n\tm <- \"Exporting\"\n\tlevel.Save()\n\tlevel.Close()\n\tdone = true\n\tmp.Lock()\n\tmp.Server = -1\n\tmp.Unlock()\n\n\treturn nil\n}\n\ntype paint struct {\n\tcolor.Color\n\tX, Y int32\n}\n\ntype layerError struct {\n\tname string\n}\n\nfunc (l layerError) Error() string {\n\treturn \"missing layer: \" + l.name\n}\n\ntype terrain struct {\n\tBase, Top minecraft.Block\n\tTopLevel  uint8\n}\n\nvar (\n\tterrainColours = color.Palette{\n\t\tcolor.RGBA{},\n\t\tcolor.RGBA{255, 255, 0, 255},   \/\/ Yellow - Sand\n\t\tcolor.RGBA{0, 255, 0, 255},     \/\/ Green - Grass\n\t\tcolor.RGBA{87, 59, 12, 255},    \/\/ Brown - Dirt\n\t\tcolor.RGBA{255, 128, 0, 255},   \/\/ Orange - Farm\n\t\tcolor.RGBA{128, 128, 128, 255}, \/\/ Grey - Stone\n\t\tcolor.RGBA{255, 255, 255, 255}, \/\/ White - Snow\n\t}\n\tterrainBlocks = []terrain{\n\t\t{},\n\t\t{minecraft.Block{ID: 24, Data: 2}, minecraft.Block{ID: 12}, 5}, \/\/ Sandstone - Sand\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 2}, 1},            \/\/ Dirt - Grass\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 3}, 0},            \/\/ Dirt - Dirt\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 60, Data: 7}, 1},  \/\/ Dirt - Farmland\n\t\t{minecraft.Block{ID: 1}, minecraft.Block{ID: 1}, 0},            \/\/ Stone - Stone\n\t\t{minecraft.Block{ID: 1}, minecraft.Block{ID: 80}, 3},           \/\/ Stone - Snow\n\t}\n)\n\nfunc modeTerrain(p *image.Paletted) uint8 {\n\tb := p.Bounds()\n\tmodeMap := make([]uint16, len(terrainColours))\n\tmost := uint16(0)\n\tmode := uint8(0)\n\tfor i := b.Min.X; i < b.Max.X; i++ {\n\t\tfor j := b.Min.Y; j < b.Max.Y; j++ {\n\t\t\tpos := p.ColorIndexAt(i, j)\n\t\t\tmodeMap[pos]++\n\t\t\tif m := modeMap[pos]; m > most {\n\t\t\t\tmost = m\n\t\t\t\tmode = pos\n\t\t\t}\n\t\t}\n\t}\n\treturn mode\n}\n\nfunc meanHeight(g *image.Gray) uint8 {\n\tb := g.Bounds()\n\tvar total int64\n\tfor i := b.Min.X; i < b.Max.X; i++ {\n\t\tfor j := b.Min.Y; j < b.Max.Y; j++ {\n\t\t\ttotal += int64(g.GrayAt(i, j).Y)\n\t\t}\n\t}\n\treturn uint8(total \/ int64((b.Dx() * b.Dy())))\n}\n\ntype chunkCache struct {\n\tmem   *minecraft.MemPath\n\tlevel *minecraft.Level\n\tclear nbt.Tag\n\tcache map[uint16]nbt.Tag\n}\n\nfunc newCache() *chunkCache {\n\tmem := minecraft.NewMemPath()\n\tl, _ := minecraft.NewLevel(mem)\n\n\tbedrock := minecraft.Block{ID: 7}\n\n\tl.SetBlock(0, 0, 0, minecraft.Block{})\n\tl.Save()\n\tl.Close()\n\tclearChunk, _ := mem.GetChunk(0, 0)\n\n\tfor i := int32(-16); i < 16; i++ {\n\t\tfor j := int32(0); j < 255; j++ {\n\t\t\tfor k := int32(-16); j < 16; j++ {\n\t\t\t\tl.SetBlock(i, j, k, bedrock)\n\t\t\t}\n\t\t}\n\t}\n\tl.Save()\n\tl.Close()\n\tmem.SetChunk(clearChunk)\n\treturn &chunkCache{\n\t\tmem,\n\t\tl,\n\t\tclearChunk,\n\t\tmake(map[uint16]nbt.Tag),\n\t}\n}\n\nfunc (c *chunkCache) getFromCache(x, z int32, terrain uint8, height int32) nbt.Tag {\n\tcacheID := uint16(terrain)<<8 | uint16(height)\n\tchunk, ok := c.cache[cacheID]\n\tif !ok {\n\t\tb := terrainBlocks[terrain].Base\n\t\tfor j := int32(0); j < height; j++ {\n\t\t\tfor i := int32(0); i < 16; i++ {\n\t\t\t\tfor k := int32(0); k < 16; k++ {\n\t\t\t\t\tc.level.SetBlock(i, j, k, b)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tc.level.Save()\n\t\tc.level.Close()\n\t\tchunk, _ = c.mem.GetChunk(0, 0)\n\t\tc.mem.SetChunk(c.clear)\n\t\tc.cache[cacheID] = chunk\n\t}\n\tld := chunk.Data().(nbt.Compound).Get(\"Level\").Data().(nbt.Compound)\n\tld.Set(nbt.NewTag(\"xPos\", nbt.Int(x)))\n\tld.Set(nbt.NewTag(\"zPos\", nbt.Int(z)))\n\treturn chunk\n}\n\nfunc buildTerrain(mpath minecraft.Path, level *minecraft.Level, terrain *image.Paletted, height *image.Gray, c chan paint) error {\n\tb := terrain.Bounds()\n\tproceed := make(chan struct{}, 10)\n\terrChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(proceed)\n\t\tcc := newCache()\n\t\tfor j := 0; j < b.Max.Y; j += 16 {\n\t\t\tchunkZ := int32(j >> 4)\n\t\t\tfor i := 0; i < b.Max.X; i += 16 {\n\t\t\t\tchunkX := int32(i >> 4)\n\t\t\t\tp := terrain.SubImage(image.Rect(i, j, i+16, j+16)).(*image.Paletted)\n\t\t\t\tg := height.SubImage(image.Rect(i, j, i+16, j+16)).(*image.Gray)\n\t\t\t\tt := modeTerrain(p)\n\t\t\t\th := int32(meanHeight(g))\n\t\t\t\terr := mpath.SetChunk(cc.getFromCache(chunkX, chunkZ, t, h))\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\tc <- paint{\n\t\t\t\t\tterrainColours[t],\n\t\t\t\t\tchunkX, chunkZ,\n\t\t\t\t}\n\t\t\t\tproceed <- struct{}{}\n\t\t\t}\n\t\t}\n\t}()\n\tfor i := 0; i < (b.Max.X>>4)+2; i++ {\n\t\t<-proceed \/\/ get far enough ahead so all chunks are surrounded before shaping, to get correct lighting\n\t}\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tdefault:\n\t}\n\tfor j := int32(0); j < int32(b.Max.Y); j += 16 {\n\t\tchunkZ := j >> 4\n\t\tfor i := int32(0); i < int32(b.Max.X); i += 16 {\n\t\t\tchunkX := i >> 4\n\t\t\tvar totalHeight int32\n\t\t\tfor x := i; x < i+16; x++ {\n\t\t\t\tfor z := j; z < j+16; z++ {\n\t\t\t\t\th := int32(height.GrayAt(int(x), int(z)).Y)\n\t\t\t\t\tmin := h\n\t\t\t\t\tfor mz := int(z) - 1; mz <= int(z)+1; mz++ {\n\t\t\t\t\t\tif mz < 0 || mz >= b.Max.Y {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor mx := int(x) - 1; mx <= int(x)+1; mx++ {\n\t\t\t\t\t\t\tif mx < 0 || mx >= b.Max.X {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif mh := int32(height.GrayAt(mx, mz).Y); mh < min {\n\t\t\t\t\t\t\t\tmin = mh\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\ttotalHeight += h\n\t\t\t\t\ty, err := level.GetHeight(x, z)\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\tfor ; y > h; y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, minecraft.Block{})\n\t\t\t\t\t}\n\t\t\t\t\tt := terrainBlocks[terrain.ColorIndexAt(int(x), int(z))]\n\t\t\t\t\tfor ; y > h-int32(t.TopLevel); y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, t.Top)\n\t\t\t\t\t}\n\t\t\t\t\tfor ; y >= min; y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, t.Base)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- paint{\n\t\t\t\tcolor.Alpha{uint8(totalHeight >> 8)},\n\t\t\t\tchunkX, chunkZ,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-proceed:\n\t\t\tcase err := <-errChan:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Added initial code to support biomes in generation<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/MJKWoolnough\/byteio\"\n\t\"github.com\/MJKWoolnough\/minecraft\"\n\t\"github.com\/MJKWoolnough\/minecraft\/nbt\"\n\t\"github.com\/MJKWoolnough\/ora\"\n)\n\nfunc (t Transfer) generate(name string, _ *byteio.StickyReader, w *byteio.StickyWriter, f *os.File, size int64) error {\n\to, err := ora.Open(f, size)\n\tif err != nil {\n\t\treturn err\n\t}\n\tterrain := o.Layer(\"terrain\")\n\tif terrain == nil {\n\t\treturn layerError{\"terrain\"}\n\t}\n\theight := o.Layer(\"height\")\n\tif height == nil {\n\t\treturn layerError{\"height\"}\n\t}\n\tmp := t.c.NewMap()\n\tif mp == nil {\n\t\treturn errors.New(\"failed to create map\")\n\t}\n\n\tdone := false\n\tdefer func() {\n\t\tif !done {\n\t\t\tt.c.RemoveMap(mp.ID)\n\t\t}\n\t\tgo t.c.Save()\n\t}()\n\n\tmp.Lock()\n\tmp.Name = name\n\tmapPath := mp.Path\n\tmp.Server = -2\n\tmp.Unlock()\n\n\tms := DefaultMapSettings()\n\tms[\"level-type\"] = minecraft.FlatGenerator\n\tms[\"generator-settings\"] = \"0\"\n\tms[\"motd\"] = name\n\n\tpf, err := os.Create(path.Join(mapPath, \"properties.map\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = ms.WriteTo(pf); err != nil {\n\t\treturn err\n\t}\n\tpf.Close()\n\n\tb := o.Bounds()\n\tw.WriteUint8(2)\n\tw.WriteInt32(int32(b.Max.X) >> 4)\n\tw.WriteInt32(int32(b.Max.Y) >> 4)\n\tc := make(chan paint, 1024)\n\tm := make(chan string, 4)\n\te := make(chan struct{}, 0)\n\tdefer close(e)\n\tgo func() {\n\t\tdefer close(c)\n\t\tdefer close(m)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message := <-m:\n\t\t\t\tw.WriteUint8(3)\n\t\t\t\twriteString(w, message)\n\t\t\tcase p := <-c:\n\t\t\t\tw.WriteUint8(4)\n\t\t\t\tw.WriteInt32(p.X)\n\t\t\t\tw.WriteInt32(p.Y)\n\t\t\t\tr, g, b, a := p.RGBA()\n\t\t\t\tw.WriteUint8(uint8(r >> 8))\n\t\t\t\tw.WriteUint8(uint8(g >> 8))\n\t\t\t\tw.WriteUint8(uint8(b >> 8))\n\t\t\t\tw.WriteUint8(uint8(a >> 8))\n\t\t\tcase <-e:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tsTerrain := image.NewPaletted(o.Bounds(), terrainColours)\n\tterrainI, err := terrain.Image()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdraw.Draw(sTerrain, image.Rect(terrain.X, terrain.Y, sTerrain.Bounds().Max.X, sTerrain.Bounds().Max.Y), terrainI, image.Point{}, draw.Src)\n\tterrainI = nil\n\tsHeight := image.NewGray(o.Bounds())\n\theightI, err := height.Image()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdraw.Draw(sHeight, image.Rect(height.X, height.Y, sTerrain.Bounds().Max.X, sTerrain.Bounds().Max.Y), heightI, image.Point{}, draw.Src)\n\theightI = nil\n\n\tp, err := minecraft.NewFilePath(mapPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlevel, err := minecraft.NewLevel(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlevel.LevelName(name)\n\n\tm <- \"Building Terrain\"\n\tif err := buildTerrain(p, level, sTerrain, nil, sHeight, c); err != nil {\n\t\treturn err\n\t}\n\n\tlevel.LevelName(name)\n\tlevel.MobSpawning(false)\n\tlevel.KeepInventory(true)\n\tlevel.FireTick(false)\n\tlevel.DayLightCycle(false)\n\tlevel.MobGriefing(false)\n\tlevel.Spawn(10, 250, 10)\n\tlevel.Generator(minecraft.FlatGenerator)\n\tlevel.GeneratorOptions(\"0\")\n\tlevel.GameMode(minecraft.Creative)\n\tlevel.AllowCommands(true)\n\n\tm <- \"Exporting\"\n\tlevel.Save()\n\tlevel.Close()\n\tdone = true\n\tmp.Lock()\n\tmp.Server = -1\n\tmp.Unlock()\n\n\treturn nil\n}\n\ntype paint struct {\n\tcolor.Color\n\tX, Y int32\n}\n\ntype layerError struct {\n\tname string\n}\n\nfunc (l layerError) Error() string {\n\treturn \"missing layer: \" + l.name\n}\n\ntype terrain struct {\n\tBase, Top minecraft.Block\n\tTopLevel  uint8\n}\n\nvar (\n\tterrainColours = color.Palette{\n\t\tcolor.RGBA{},\n\t\tcolor.RGBA{255, 255, 0, 255},   \/\/ Yellow - Sand\n\t\tcolor.RGBA{0, 255, 0, 255},     \/\/ Green - Grass\n\t\tcolor.RGBA{87, 59, 12, 255},    \/\/ Brown - Dirt\n\t\tcolor.RGBA{255, 128, 0, 255},   \/\/ Orange - Farm\n\t\tcolor.RGBA{128, 128, 128, 255}, \/\/ Grey - Stone\n\t\tcolor.RGBA{255, 255, 255, 255}, \/\/ White - Snow\n\t}\n\tterrainBlocks = []terrain{\n\t\t{},\n\t\t{minecraft.Block{ID: 24, Data: 2}, minecraft.Block{ID: 12}, 5}, \/\/ Sandstone - Sand\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 2}, 1},            \/\/ Dirt - Grass\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 3}, 0},            \/\/ Dirt - Dirt\n\t\t{minecraft.Block{ID: 3}, minecraft.Block{ID: 60, Data: 7}, 1},  \/\/ Dirt - Farmland\n\t\t{minecraft.Block{ID: 1}, minecraft.Block{ID: 1}, 0},            \/\/ Stone - Stone\n\t\t{minecraft.Block{ID: 1}, minecraft.Block{ID: 80}, 3},           \/\/ Stone - Snow\n\t}\n\tbiomePalette = color.Palette{}\n\tbiomeList    = []minecraft.Biome{}\n)\n\nfunc modeTerrain(p *image.Paletted) uint8 {\n\tb := p.Bounds()\n\tmodeMap := make([]uint16, len(terrainColours))\n\tmost := uint16(0)\n\tmode := uint8(0)\n\tfor i := b.Min.X; i < b.Max.X; i++ {\n\t\tfor j := b.Min.Y; j < b.Max.Y; j++ {\n\t\t\tpos := p.ColorIndexAt(i, j)\n\t\t\tmodeMap[pos]++\n\t\t\tif m := modeMap[pos]; m > most {\n\t\t\t\tmost = m\n\t\t\t\tmode = pos\n\t\t\t}\n\t\t}\n\t}\n\treturn mode\n}\n\nfunc meanHeight(g *image.Gray) uint8 {\n\tb := g.Bounds()\n\tvar total int64\n\tfor i := b.Min.X; i < b.Max.X; i++ {\n\t\tfor j := b.Min.Y; j < b.Max.Y; j++ {\n\t\t\ttotal += int64(g.GrayAt(i, j).Y)\n\t\t}\n\t}\n\treturn uint8(total \/ int64((b.Dx() * b.Dy())))\n}\n\ntype chunkCache struct {\n\tmem   *minecraft.MemPath\n\tlevel *minecraft.Level\n\tclear nbt.Tag\n\tcache map[uint16]nbt.Tag\n}\n\nfunc newCache() *chunkCache {\n\tmem := minecraft.NewMemPath()\n\tl, _ := minecraft.NewLevel(mem)\n\n\tbedrock := minecraft.Block{ID: 7}\n\n\tl.SetBlock(0, 0, 0, minecraft.Block{})\n\tl.Save()\n\tl.Close()\n\tclearChunk, _ := mem.GetChunk(0, 0)\n\n\tfor i := int32(-16); i < 16; i++ {\n\t\tfor j := int32(0); j < 255; j++ {\n\t\t\tfor k := int32(-16); j < 16; j++ {\n\t\t\t\tl.SetBlock(i, j, k, bedrock)\n\t\t\t}\n\t\t}\n\t}\n\tl.Save()\n\tl.Close()\n\tmem.SetChunk(clearChunk)\n\treturn &chunkCache{\n\t\tmem,\n\t\tl,\n\t\tclearChunk,\n\t\tmake(map[uint16]nbt.Tag),\n\t}\n}\n\nfunc (c *chunkCache) getFromCache(x, z int32, terrain uint8, height int32) nbt.Tag {\n\tcacheID := uint16(terrain)<<8 | uint16(height)\n\tchunk, ok := c.cache[cacheID]\n\tif !ok {\n\t\tb := terrainBlocks[terrain].Base\n\t\tfor j := int32(0); j < height; j++ {\n\t\t\tfor i := int32(0); i < 16; i++ {\n\t\t\t\tfor k := int32(0); k < 16; k++ {\n\t\t\t\t\tc.level.SetBlock(i, j, k, b)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tc.level.Save()\n\t\tc.level.Close()\n\t\tchunk, _ = c.mem.GetChunk(0, 0)\n\t\tc.mem.SetChunk(c.clear)\n\t\tc.cache[cacheID] = chunk\n\t}\n\tld := chunk.Data().(nbt.Compound).Get(\"Level\").Data().(nbt.Compound)\n\tld.Set(nbt.NewTag(\"xPos\", nbt.Int(x)))\n\tld.Set(nbt.NewTag(\"zPos\", nbt.Int(z)))\n\treturn chunk\n}\n\nfunc buildTerrain(mpath minecraft.Path, level *minecraft.Level, terrain, biomes *image.Paletted, height *image.Gray, c chan paint) error {\n\tb := terrain.Bounds()\n\tproceed := make(chan struct{}, 10)\n\terrChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer close(proceed)\n\t\tcc := newCache()\n\t\tfor j := 0; j < b.Max.Y; j += 16 {\n\t\t\tchunkZ := int32(j >> 4)\n\t\t\tfor i := 0; i < b.Max.X; i += 16 {\n\t\t\t\tchunkX := int32(i >> 4)\n\t\t\t\tp := terrain.SubImage(image.Rect(i, j, i+16, j+16)).(*image.Paletted)\n\t\t\t\tg := height.SubImage(image.Rect(i, j, i+16, j+16)).(*image.Gray)\n\t\t\t\tt := modeTerrain(p)\n\t\t\t\th := int32(meanHeight(g))\n\t\t\t\terr := mpath.SetChunk(cc.getFromCache(chunkX, chunkZ, t, h))\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\tc <- paint{\n\t\t\t\t\tterrainColours[t],\n\t\t\t\t\tchunkX, chunkZ,\n\t\t\t\t}\n\t\t\t\tproceed <- struct{}{}\n\t\t\t}\n\t\t}\n\t}()\n\tfor i := 0; i < (b.Max.X>>4)+2; i++ {\n\t\t<-proceed \/\/ get far enough ahead so all chunks are surrounded before shaping, to get correct lighting\n\t}\n\tselect {\n\tcase err := <-errChan:\n\t\treturn err\n\tdefault:\n\t}\n\tfor j := int32(0); j < int32(b.Max.Y); j += 16 {\n\t\tchunkZ := j >> 4\n\t\tfor i := int32(0); i < int32(b.Max.X); i += 16 {\n\t\t\tchunkX := i >> 4\n\t\t\tvar totalHeight int32\n\t\t\tfor x := i; x < i+16; x++ {\n\t\t\t\tfor z := j; z < j+16; z++ {\n\t\t\t\t\tif biomes != nil {\n\t\t\t\t\t\tlevel.SetBiome(x, z, biomeList[biomePalette.ColorIndexAt(int(x), int(z))])\n\t\t\t\t\t}\n\t\t\t\t\th := int32(height.GrayAt(int(x), int(z)).Y)\n\t\t\t\t\tmin := h\n\t\t\t\t\tfor mz := int(z) - 1; mz <= int(z)+1; mz++ {\n\t\t\t\t\t\tif mz < 0 || mz >= b.Max.Y {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor mx := int(x) - 1; mx <= int(x)+1; mx++ {\n\t\t\t\t\t\t\tif mx < 0 || mx >= b.Max.X {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif mh := int32(height.GrayAt(mx, mz).Y); mh < min {\n\t\t\t\t\t\t\t\tmin = mh\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\ttotalHeight += h\n\t\t\t\t\ty, err := level.GetHeight(x, z)\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\tfor ; y > h; y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, minecraft.Block{})\n\t\t\t\t\t}\n\t\t\t\t\tt := terrainBlocks[terrain.ColorIndexAt(int(x), int(z))]\n\t\t\t\t\tfor ; y > h-int32(t.TopLevel); y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, t.Top)\n\t\t\t\t\t}\n\t\t\t\t\tfor ; y >= min; y-- {\n\t\t\t\t\t\tlevel.SetBlock(x, y, z, t.Base)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tc <- paint{\n\t\t\t\tcolor.Alpha{uint8(totalHeight >> 8)},\n\t\t\t\tchunkX, chunkZ,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-proceed:\n\t\t\tcase err := <-errChan:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn 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: Aaron Meihm ameihm@mozilla.com [:alm]\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mig.ninja\/mig\"\n\t\"mig.ninja\/mig\/client\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n)\n\nfunc getResultsStoragePath(nm string) (rdir string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getResultsStoragePath() -> %v\", e)\n\t\t}\n\t}()\n\ttstamp := time.Now().UTC().Format(\"20060102\")\n\trdir = path.Join(ctx.Runner.RunDirectory, nm, \"results\", tstamp)\n\n\t_, err = os.Stat(rdir)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = os.MkdirAll(rdir, 0755)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn rdir, nil\n}\n\nfunc getResults(r mig.RunnerResult) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getResults() -> %v\", e)\n\t\t}\n\t}()\n\n\tmlog(\"fetching results for %v\/%.0f\", r.EntityName, r.Action.ID)\n\n\tcli, err := client.NewClient(ctx.ClientConf, \"mig-runner-results\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresults, err := cli.FetchActionResults(r.Action)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Store the results\n\toutpath, err := getResultsStoragePath(r.EntityName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toutpath = path.Join(outpath, fmt.Sprintf(\"%.0f\", r.Action.ID))\n\tfd, err := os.Create(outpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fd.Close()\n\n\tr.Commands = results\n\tbuf, err := json.Marshal(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = fd.Write(buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmlog(\"wrote results for %.0f to %v\", r.Action.ID, outpath)\n\n\t\/\/ If a plugin has been configured on the result set, call the\n\t\/\/ plugin on the data.\n\tif r.UsePlugin != \"\" {\n\t\terr = runPlugin(r)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tmlog(\"no output plugin for %.0f, skipping plugin processing\", r.Action.ID)\n\t}\n\n\treturn nil\n}\n\nfunc processResults() {\n\tmlog(\"results processing routine started\")\n\n\treslist := make([]mig.RunnerResult, 0)\n\n\tfor {\n\t\ttimeout := false\n\t\tselect {\n\t\tcase nr := <-ctx.Channels.Results:\n\t\t\tmlog(\"monitoring result for %v\/%.0f\", nr.EntityName, nr.Action.ID)\n\t\t\treslist = append(reslist, nr)\n\t\tcase <-time.After(time.Duration(5) * time.Second):\n\t\t\ttimeout = true\n\t\t}\n\t\tif !timeout {\n\t\t\t\/\/ Only attempt action results fetch if we are idle\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ See if any actions have expired, if so grab the results\n\t\toldres := reslist\n\t\treslist = reslist[:0]\n\t\tfor _, x := range oldres {\n\t\t\tif time.Now().After(x.Action.ExpireAfter) {\n\t\t\t\terr := getResults(x)\n\t\t\t\tif err != nil {\n\t\t\t\t\tmlog(\"results error for %v: %v\", x.EntityName, err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treslist = append(reslist, x)\n\t\t}\n\t}\n}\n<commit_msg>[minor] add additional logging on results fetch<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: Aaron Meihm ameihm@mozilla.com [:alm]\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"mig.ninja\/mig\"\n\t\"mig.ninja\/mig\/client\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n)\n\nfunc getResultsStoragePath(nm string) (rdir string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getResultsStoragePath() -> %v\", e)\n\t\t}\n\t}()\n\ttstamp := time.Now().UTC().Format(\"20060102\")\n\trdir = path.Join(ctx.Runner.RunDirectory, nm, \"results\", tstamp)\n\n\t_, err = os.Stat(rdir)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tpanic(err)\n\t\t}\n\t\terr = os.MkdirAll(rdir, 0755)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn rdir, nil\n}\n\nfunc getResults(r mig.RunnerResult) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getResults() -> %v\", e)\n\t\t}\n\t}()\n\n\tmlog(\"fetching results for %v\/%.0f\", r.EntityName, r.Action.ID)\n\n\tcli, err := client.NewClient(ctx.ClientConf, \"mig-runner-results\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tresults, err := cli.FetchActionResults(r.Action)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmlog(\"%v\/%.0f: fetched results, %v commands returned\", r.EntityName, r.Action.ID, len(results))\n\n\t\/\/ Store the results\n\toutpath, err := getResultsStoragePath(r.EntityName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toutpath = path.Join(outpath, fmt.Sprintf(\"%.0f\", r.Action.ID))\n\tfd, err := os.Create(outpath)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer fd.Close()\n\n\tr.Commands = results\n\tbuf, err := json.Marshal(r)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = fd.Write(buf)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmlog(\"wrote results for %.0f to %v\", r.Action.ID, outpath)\n\n\t\/\/ If a plugin has been configured on the result set, call the\n\t\/\/ plugin on the data.\n\tif r.UsePlugin != \"\" {\n\t\terr = runPlugin(r)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tmlog(\"no output plugin for %.0f, skipping plugin processing\", r.Action.ID)\n\t}\n\n\treturn nil\n}\n\nfunc processResults() {\n\tmlog(\"results processing routine started\")\n\n\treslist := make([]mig.RunnerResult, 0)\n\n\tfor {\n\t\ttimeout := false\n\t\tselect {\n\t\tcase nr := <-ctx.Channels.Results:\n\t\t\tmlog(\"monitoring result for %v\/%.0f\", nr.EntityName, nr.Action.ID)\n\t\t\treslist = append(reslist, nr)\n\t\tcase <-time.After(time.Duration(5) * time.Second):\n\t\t\ttimeout = true\n\t\t}\n\t\tif !timeout {\n\t\t\t\/\/ Only attempt action results fetch if we are idle\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ See if any actions have expired, if so grab the results\n\t\toldres := reslist\n\t\treslist = reslist[:0]\n\t\tfor _, x := range oldres {\n\t\t\tif time.Now().After(x.Action.ExpireAfter) {\n\t\t\t\terr := getResults(x)\n\t\t\t\tif err != nil {\n\t\t\t\t\tmlog(\"results error for %v: %v\", x.EntityName, err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treslist = append(reslist, x)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package usl provides functionality to build Universal Scalability Law models\n\/\/ from sets of observed measurements.\npackage usl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com\/maorshutman\/lm\"\n)\n\nvar (\n\t\/\/ ErrInsufficientMeasurements is returned when fewer than 6 measurements were provided.\n\tErrInsufficientMeasurements = errors.New(\"usl: need at least 6 measurements\")\n)\n\n\/\/ Model is a Universal Scalability Law model.\ntype Model struct {\n\tSigma  float64 \/\/ The model's coefficient of contention, σ.\n\tKappa  float64 \/\/ The model's coefficient of crosstalk\/coherency, κ.\n\tLambda float64 \/\/ The model's coefficient of performance, λ.\n}\n\nfunc (m *Model) String() string {\n\treturn fmt.Sprintf(\"Model{σ=%v, κ=%v, λ=%v}\", m.Sigma, m.Kappa, m.Lambda)\n}\n\n\/\/ ThroughputAtConcurrency returns the expected throughput given a number of concurrent workers,\n\/\/ Concurrency(N).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 3\".\nfunc (m *Model) ThroughputAtConcurrency(n float64) float64 {\n\treturn (m.Lambda * n) \/ (1 + (m.Sigma * (n - 1)) + (m.Kappa * n * (n - 1)))\n}\n\n\/\/ LatencyAtConcurrency returns the expected mean latency given a number of concurrent workers,\n\/\/ R(N).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 6\".\nfunc (m *Model) LatencyAtConcurrency(n float64) float64 {\n\treturn (1 + (m.Sigma * (n - 1)) + (m.Kappa * n * (n - 1))) \/ m.Lambda\n}\n\n\/\/ MaxConcurrency returns the maximum expected number of concurrent workers the system can handle,\n\/\/ Nmax.\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 4\".\nfunc (m *Model) MaxConcurrency() float64 {\n\treturn math.Floor(math.Sqrt((1 - m.Sigma) \/ m.Kappa))\n}\n\n\/\/ MaxThroughput returns the maximum expected throughput the system can handle, Xmax.\nfunc (m Model) MaxThroughput() float64 {\n\treturn m.ThroughputAtConcurrency(m.MaxConcurrency())\n}\n\n\/\/ LatencyAtThroughput returns the expected mean latency given a throughput, R(X).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 8\".\nfunc (m *Model) LatencyAtThroughput(x float64) float64 {\n\treturn (m.Sigma - 1) \/ (m.Sigma*x - m.Lambda)\n}\n\n\/\/ ThroughputAtLatency returns the expected throughput given a mean latency, X(R).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 9\".\nfunc (m *Model) ThroughputAtLatency(r float64) float64 {\n\ta := 2 * m.Kappa * (2*m.Lambda*r + m.Sigma - 2)\n\tb := math.Sqrt(math.Pow(m.Sigma, 2) + math.Pow(m.Kappa, 2) + a)\n\n\treturn (b - m.Kappa + m.Sigma) \/ (2.0 * m.Kappa * r)\n}\n\n\/\/ ConcurrencyAtLatency returns the expected number of concurrent workers given a mean latency,\n\/\/ N(R).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 10\".\nfunc (m *Model) ConcurrencyAtLatency(r float64) float64 {\n\ta := 2 * m.Kappa * ((2 * m.Lambda * r) + m.Sigma - 2)\n\tb := math.Sqrt(math.Pow(m.Sigma, 2) + math.Pow(m.Kappa, 2) + a)\n\n\treturn (m.Kappa - m.Sigma + b) \/ (2 * m.Kappa)\n}\n\n\/\/ ConcurrencyAtThroughput returns the expected number of concurrent workers at a particular\n\/\/ throughput, N(X).\nfunc (m *Model) ConcurrencyAtThroughput(x float64) float64 {\n\treturn m.LatencyAtThroughput(x) * x\n}\n\n\/\/ ContentionConstrained returns true if the system is constrained by contention.\nfunc (m *Model) ContentionConstrained() bool {\n\treturn m.Sigma > m.Kappa\n}\n\n\/\/ CoherencyConstrained returns true if the system is constrained by coherency costs.\nfunc (m *Model) CoherencyConstrained() bool {\n\treturn m.Sigma < m.Kappa\n}\n\n\/\/ Limitless returns true if the system is linearly scalable.\nfunc (m *Model) Limitless() bool {\n\treturn m.Kappa == 0\n}\n\nconst minMeasurements = 6\n\n\/\/ Build returns a model whose parameters are generated from the given measurements.\n\/\/\n\/\/ Finds a set of coefficients for the equation y = λx\/(1+σ(x-1)+κx(x-1)) which best fit the\n\/\/ observed values using unconstrained least-squares regression. The resulting values for λ, κ, and\n\/\/ σ are the parameters of the returned model.\nfunc Build(measurements []Measurement) (m *Model, err error) {\n\tif len(measurements) < minMeasurements {\n\t\treturn nil, ErrInsufficientMeasurements\n\t}\n\n\t\/\/ Calculate an initial guess at the model parameters.\n\tinit := []float64{0.1, 0.01, 0}\n\n\t\/\/ Use max(x\/n) as initial lambda.\n\tfor _, m := range measurements {\n\t\tv := m.Throughput \/ m.Concurrency\n\t\tif v > init[2] {\n\t\t\tinit[2] = v\n\t\t}\n\t}\n\n\t\/\/ Calculate the residuals of a possible model.\n\tf := func(dst, x []float64) {\n\t\tmodel := Model{Sigma: x[0], Kappa: x[1], Lambda: x[2]}\n\n\t\tfor i, v := range measurements {\n\t\t\tdst[i] = v.Throughput - model.ThroughputAtConcurrency(v.Concurrency)\n\t\t}\n\t}\n\tj := lm.NumJac{Func: f}\n\n\t\/\/ Formulate an LM problem.\n\tp := lm.LMProblem{\n\t\tDim:        3,                 \/\/ Three parameters in the model.\n\t\tSize:       len(measurements), \/\/ Use all measurements to calculate residuals.\n\t\tFunc:       f,                 \/\/ Reduce the residuals of model predictions to observations.\n\t\tJac:        j.Jac,             \/\/ Use the default Jaccardian formula.\n\t\tInitParams: init,              \/\/ Use our initial guesses at parameters.\n\t\tTau:        1e-6,              \/\/ Need a non-zero initial damping factor.\n\t\tEps1:       1e-8,              \/\/ Small but non-zero values here prevent singular matrices.\n\t\tEps2:       1e-8,\n\t}\n\n\t\/\/ Calculate the model parameters.\n\tresults, err := lm.LM(p, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Return the model.\n\treturn &Model{\n\t\tSigma:  results.X[0],\n\t\tKappa:  results.X[1],\n\t\tLambda: results.X[2],\n\t}, nil\n}\n<commit_msg>docfix<commit_after>\/\/ Package usl provides functionality to build Universal Scalability Law models\n\/\/ from sets of observed measurements.\npackage usl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\n\t\"github.com\/maorshutman\/lm\"\n)\n\nvar (\n\t\/\/ ErrInsufficientMeasurements is returned when fewer than 6 measurements were provided.\n\tErrInsufficientMeasurements = errors.New(\"usl: need at least 6 measurements\")\n)\n\n\/\/ Model is a Universal Scalability Law model.\ntype Model struct {\n\tSigma  float64 \/\/ The model's coefficient of contention, σ.\n\tKappa  float64 \/\/ The model's coefficient of crosstalk\/coherency, κ.\n\tLambda float64 \/\/ The model's coefficient of performance, λ.\n}\n\nfunc (m *Model) String() string {\n\treturn fmt.Sprintf(\"Model{σ=%v, κ=%v, λ=%v}\", m.Sigma, m.Kappa, m.Lambda)\n}\n\n\/\/ ThroughputAtConcurrency returns the expected throughput given a number of concurrent workers,\n\/\/ Concurrency(N).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 3\".\nfunc (m *Model) ThroughputAtConcurrency(n float64) float64 {\n\treturn (m.Lambda * n) \/ (1 + (m.Sigma * (n - 1)) + (m.Kappa * n * (n - 1)))\n}\n\n\/\/ LatencyAtConcurrency returns the expected mean latency given a number of concurrent workers,\n\/\/ R(N).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 6\".\nfunc (m *Model) LatencyAtConcurrency(n float64) float64 {\n\treturn (1 + (m.Sigma * (n - 1)) + (m.Kappa * n * (n - 1))) \/ m.Lambda\n}\n\n\/\/ MaxConcurrency returns the maximum expected number of concurrent workers the system can handle,\n\/\/ Nmax.\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 4\".\nfunc (m *Model) MaxConcurrency() float64 {\n\treturn math.Floor(math.Sqrt((1 - m.Sigma) \/ m.Kappa))\n}\n\n\/\/ MaxThroughput returns the maximum expected throughput the system can handle, Xmax.\nfunc (m Model) MaxThroughput() float64 {\n\treturn m.ThroughputAtConcurrency(m.MaxConcurrency())\n}\n\n\/\/ LatencyAtThroughput returns the expected mean latency given a throughput, R(X).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 8\".\nfunc (m *Model) LatencyAtThroughput(x float64) float64 {\n\treturn (m.Sigma - 1) \/ (m.Sigma*x - m.Lambda)\n}\n\n\/\/ ThroughputAtLatency returns the expected throughput given a mean latency, X(R).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 9\".\nfunc (m *Model) ThroughputAtLatency(r float64) float64 {\n\ta := 2 * m.Kappa * (2*m.Lambda*r + m.Sigma - 2)\n\tb := math.Sqrt(math.Pow(m.Sigma, 2) + math.Pow(m.Kappa, 2) + a)\n\n\treturn (b - m.Kappa + m.Sigma) \/ (2.0 * m.Kappa * r)\n}\n\n\/\/ ConcurrencyAtLatency returns the expected number of concurrent workers given a mean latency,\n\/\/ N(R).\n\/\/\n\/\/ See \"Practical Scalability Analysis with the Universal Scalability Law, Equation 10\".\nfunc (m *Model) ConcurrencyAtLatency(r float64) float64 {\n\ta := 2 * m.Kappa * ((2 * m.Lambda * r) + m.Sigma - 2)\n\tb := math.Sqrt(math.Pow(m.Sigma, 2) + math.Pow(m.Kappa, 2) + a)\n\n\treturn (m.Kappa - m.Sigma + b) \/ (2 * m.Kappa)\n}\n\n\/\/ ConcurrencyAtThroughput returns the expected number of concurrent workers at a particular\n\/\/ throughput, N(X).\nfunc (m *Model) ConcurrencyAtThroughput(x float64) float64 {\n\treturn m.LatencyAtThroughput(x) * x\n}\n\n\/\/ ContentionConstrained returns true if the system is constrained by contention.\nfunc (m *Model) ContentionConstrained() bool {\n\treturn m.Sigma > m.Kappa\n}\n\n\/\/ CoherencyConstrained returns true if the system is constrained by coherency costs.\nfunc (m *Model) CoherencyConstrained() bool {\n\treturn m.Sigma < m.Kappa\n}\n\n\/\/ Limitless returns true if the system is linearly scalable.\nfunc (m *Model) Limitless() bool {\n\treturn m.Kappa == 0\n}\n\nconst minMeasurements = 6\n\n\/\/ Build returns a model whose parameters are generated from the given measurements.\n\/\/\n\/\/ Finds a set of coefficients for the equation y = λx\/(1+σ(x-1)+κx(x-1)) which best fit the\n\/\/ observed values using unconstrained least-squares regression. The resulting values for λ, κ, and\n\/\/ σ are the parameters of the returned model.\nfunc Build(measurements []Measurement) (m *Model, err error) {\n\tif len(measurements) < minMeasurements {\n\t\treturn nil, ErrInsufficientMeasurements\n\t}\n\n\t\/\/ Calculate an initial guess at the model parameters.\n\tinit := []float64{0.1, 0.01, 0}\n\n\t\/\/ Use max(x\/n) as initial lambda.\n\tfor _, m := range measurements {\n\t\tv := m.Throughput \/ m.Concurrency\n\t\tif v > init[2] {\n\t\t\tinit[2] = v\n\t\t}\n\t}\n\n\t\/\/ Calculate the residuals of a possible model.\n\tf := func(dst, x []float64) {\n\t\tmodel := Model{Sigma: x[0], Kappa: x[1], Lambda: x[2]}\n\n\t\tfor i, v := range measurements {\n\t\t\tdst[i] = v.Throughput - model.ThroughputAtConcurrency(v.Concurrency)\n\t\t}\n\t}\n\tj := lm.NumJac{Func: f}\n\n\t\/\/ Formulate an LM problem.\n\tp := lm.LMProblem{\n\t\tDim:        3,                 \/\/ Three parameters in the model.\n\t\tSize:       len(measurements), \/\/ Use all measurements to calculate residuals.\n\t\tFunc:       f,                 \/\/ Reduce the residuals of model predictions to observations.\n\t\tJac:        j.Jac,             \/\/ Approximate the Jacobian by finite differences.\n\t\tInitParams: init,              \/\/ Use our initial guesses at parameters.\n\t\tTau:        1e-6,              \/\/ Need a non-zero initial damping factor.\n\t\tEps1:       1e-8,              \/\/ Small but non-zero values here prevent singular matrices.\n\t\tEps2:       1e-8,\n\t}\n\n\t\/\/ Calculate the model parameters.\n\tresults, err := lm.LM(p, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Return the model.\n\treturn &Model{\n\t\tSigma:  results.X[0],\n\t\tKappa:  results.X[1],\n\t\tLambda: results.X[2],\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport \"testing\"\n\nfunc Test_DoRequest(t *testing.T) {\n\treq := &AliyunRequest{\n\t\t\"http:\/\/weibo.com\",\n\t}\n\t_, err := req.DoGetRequest()\n\tif err != nil {\n\t\tt.Error(\"Request failed.\")\n\t}\n}\n\nfunc Test_GetQueryFromMap(t *testing.T) {\n\tparams := map[string]string{\n\t\t\"user\": \"root\",\n\t\t\"pass\": \"test\",\n\t}\n\tquery := GetQueryFromMap(params)\n\tif query != \"user=root&pass=test\" && query != \"pass=test&user=root\" {\n\t\tt.Error(query + \"Query string is incorrect.\")\n\t}\n}\n<commit_msg>\tmodified:   util\/request_test.go<commit_after>package util\n\nimport \"testing\"\n\nfunc Test_DoRequest(t *testing.T) {\n\treq := &AliyunRequest{\n\t\t\"http:\/\/weibo.com\",\n\t}\n\t_, err := req.DoGetRequest()\n\tif err != nil {\n\t\tt.Error(\"Request failed.\")\n\t}\n}\n\nfunc Test_GetQueryFromMap(t *testing.T) {\n\tparams := map[string]string{\n\t\t\"user\": \"root\",\n\t\t\"pass\": \"test\",\n\t}\n\tquery := GetQueryFromMap(params)\n\tif query != \"user=root&pass=test\" && query != \"pass=test&user=root\" {\n\t\tt.Error(\"Query string is incorrect.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package idxfile\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"sort\"\n\n\tencbin \"encoding\/binary\"\n\n\t\"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n)\n\nconst (\n\t\/\/ VersionSupported is the only idx version supported.\n\tVersionSupported = 2\n\n\tnoMapping = -1\n)\n\nvar (\n\tidxHeader = []byte{255, 't', 'O', 'c'}\n)\n\n\/\/ Index represents an index of a packfile.\ntype Index interface {\n\t\/\/ Contains checks whether the given hash is in the index.\n\tContains(h plumbing.Hash) (bool, error)\n\t\/\/ FindOffset finds the offset in the packfile for the object with\n\t\/\/ the given hash.\n\tFindOffset(h plumbing.Hash) (int64, error)\n\t\/\/ FindCRC32 finds the CRC32 of the object with the given hash.\n\tFindCRC32(h plumbing.Hash) (uint32, error)\n\t\/\/ FindHash finds the hash for the object with the given offset.\n\tFindHash(o int64) (plumbing.Hash, error)\n\t\/\/ Count returns the number of entries in the index.\n\tCount() (int64, error)\n\t\/\/ Entries returns an iterator to retrieve all index entries.\n\tEntries() (EntryIter, error)\n\t\/\/ EntriesByOffset returns an iterator to retrieve all index entries ordered\n\t\/\/ by offset.\n\tEntriesByOffset() (EntryIter, error)\n}\n\n\/\/ MemoryIndex is the in memory representation of an idx file.\ntype MemoryIndex struct {\n\tVersion uint32\n\tFanout  [256]uint32\n\t\/\/ FanoutMapping maps the position in the fanout table to the position\n\t\/\/ in the Names, Offset32 and CRC32 slices. This improves the memory\n\t\/\/ usage by not needing an array with unnecessary empty slots.\n\tFanoutMapping    [256]int\n\tNames            [][]byte\n\tOffset32         [][]byte\n\tCRC32            [][]byte\n\tOffset64         []byte\n\tPackfileChecksum [20]byte\n\tIdxChecksum      [20]byte\n\n\toffsetHash       map[int64]plumbing.Hash\n\toffsetHashIsFull bool\n}\n\nvar _ Index = (*MemoryIndex)(nil)\n\n\/\/ NewMemoryIndex returns an instance of a new MemoryIndex.\nfunc NewMemoryIndex() *MemoryIndex {\n\treturn &MemoryIndex{}\n}\n\nfunc (idx *MemoryIndex) findHashIndex(h plumbing.Hash) (int, bool) {\n\tk := idx.FanoutMapping[h[0]]\n\tif k == noMapping {\n\t\treturn 0, false\n\t}\n\n\tif len(idx.Names) <= k {\n\t\treturn 0, false\n\t}\n\n\tdata := idx.Names[k]\n\thigh := uint64(len(idx.Offset32[k])) >> 2\n\tif high == 0 {\n\t\treturn 0, false\n\t}\n\n\tlow := uint64(0)\n\tfor {\n\t\tmid := (low + high) >> 1\n\t\toffset := mid * objectIDLength\n\n\t\tcmp := bytes.Compare(h[:], data[offset:offset+objectIDLength])\n\t\tif cmp < 0 {\n\t\t\thigh = mid\n\t\t} else if cmp == 0 {\n\t\t\treturn int(mid), true\n\t\t} else {\n\t\t\tlow = mid + 1\n\t\t}\n\n\t\tif low >= high {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn 0, false\n}\n\n\/\/ Contains implements the Index interface.\nfunc (idx *MemoryIndex) Contains(h plumbing.Hash) (bool, error) {\n\t_, ok := idx.findHashIndex(h)\n\treturn ok, nil\n}\n\n\/\/ FindOffset implements the Index interface.\nfunc (idx *MemoryIndex) FindOffset(h plumbing.Hash) (int64, error) {\n\tif len(idx.FanoutMapping) <= int(h[0]) {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\tk := idx.FanoutMapping[h[0]]\n\ti, ok := idx.findHashIndex(h)\n\tif !ok {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\toffset := idx.getOffset(k, i)\n\n\tif !idx.offsetHashIsFull {\n\t\t\/\/ Save the offset for reverse lookup\n\t\tif idx.offsetHash == nil {\n\t\t\tidx.offsetHash = make(map[int64]plumbing.Hash)\n\t\t}\n\t\tidx.offsetHash[int64(offset)] = h\n\t}\n\n\treturn int64(offset), nil\n}\n\nconst isO64Mask = uint64(1) << 31\n\nfunc (idx *MemoryIndex) getOffset(firstLevel, secondLevel int) uint64 {\n\toffset := secondLevel << 2\n\tofs := encbin.BigEndian.Uint32(idx.Offset32[firstLevel][offset : offset+4])\n\n\tif (uint64(ofs) & isO64Mask) != 0 {\n\t\toffset := 8 * (uint64(ofs) & ^isO64Mask)\n\t\tn := encbin.BigEndian.Uint64(idx.Offset64[offset : offset+8])\n\t\treturn n\n\t}\n\n\treturn uint64(ofs)\n}\n\n\/\/ FindCRC32 implements the Index interface.\nfunc (idx *MemoryIndex) FindCRC32(h plumbing.Hash) (uint32, error) {\n\tk := idx.FanoutMapping[h[0]]\n\ti, ok := idx.findHashIndex(h)\n\tif !ok {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\treturn idx.getCRC32(k, i), nil\n}\n\nfunc (idx *MemoryIndex) getCRC32(firstLevel, secondLevel int) uint32 {\n\toffset := secondLevel << 2\n\treturn encbin.BigEndian.Uint32(idx.CRC32[firstLevel][offset : offset+4])\n}\n\n\/\/ FindHash implements the Index interface.\nfunc (idx *MemoryIndex) FindHash(o int64) (plumbing.Hash, error) {\n\tvar hash plumbing.Hash\n\tvar ok bool\n\n\tif idx.offsetHash != nil {\n\t\tif hash, ok = idx.offsetHash[o]; ok {\n\t\t\treturn hash, nil\n\t\t}\n\t}\n\n\t\/\/ Lazily generate the reverse offset\/hash map if required.\n\tif !idx.offsetHashIsFull || idx.offsetHash == nil {\n\t\tif err := idx.genOffsetHash(); err != nil {\n\t\t\treturn plumbing.ZeroHash, err\n\t\t}\n\n\t\thash, ok = idx.offsetHash[o]\n\t}\n\n\tif !ok {\n\t\treturn plumbing.ZeroHash, plumbing.ErrObjectNotFound\n\t}\n\n\treturn hash, nil\n}\n\n\/\/ genOffsetHash generates the offset\/hash mapping for reverse search.\nfunc (idx *MemoryIndex) genOffsetHash() error {\n\tcount, err := idx.Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.offsetHash = make(map[int64]plumbing.Hash, count)\n\tidx.offsetHashIsFull = true\n\n\titer, err := idx.Entries()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\tentry, err := iter.Next()\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\tidx.offsetHash[int64(entry.Offset)] = entry.Hash\n\t}\n}\n\n\/\/ Count implements the Index interface.\nfunc (idx *MemoryIndex) Count() (int64, error) {\n\treturn int64(idx.Fanout[fanout-1]), nil\n}\n\n\/\/ Entries implements the Index interface.\nfunc (idx *MemoryIndex) Entries() (EntryIter, error) {\n\treturn &idxfileEntryIter{idx, 0, 0, 0}, nil\n}\n\n\/\/ EntriesByOffset implements the Index interface.\nfunc (idx *MemoryIndex) EntriesByOffset() (EntryIter, error) {\n\tcount, err := idx.Count()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titer := &idxfileEntryOffsetIter{\n\t\tentries: make(entriesByOffset, count),\n\t}\n\n\tentries, err := idx.Entries()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor pos := 0; int64(pos) < count; pos++ {\n\t\tentry, err := entries.Next()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\titer.entries[pos] = entry\n\t}\n\n\tsort.Sort(iter.entries)\n\n\treturn iter, nil\n}\n\n\/\/ EntryIter is an iterator that will return the entries in a packfile index.\ntype EntryIter interface {\n\t\/\/ Next returns the next entry in the packfile index.\n\tNext() (*Entry, error)\n\t\/\/ Close closes the iterator.\n\tClose() error\n}\n\ntype idxfileEntryIter struct {\n\tidx                     *MemoryIndex\n\ttotal                   int\n\tfirstLevel, secondLevel int\n}\n\nfunc (i *idxfileEntryIter) Next() (*Entry, error) {\n\tfor {\n\t\tif i.firstLevel >= fanout {\n\t\t\treturn nil, io.EOF\n\t\t}\n\n\t\tif i.total >= int(i.idx.Fanout[i.firstLevel]) {\n\t\t\ti.firstLevel++\n\t\t\ti.secondLevel = 0\n\t\t\tcontinue\n\t\t}\n\n\t\tentry := new(Entry)\n\t\tofs := i.secondLevel * objectIDLength\n\t\tcopy(entry.Hash[:], i.idx.Names[i.idx.FanoutMapping[i.firstLevel]][ofs:])\n\n\t\tpos := i.idx.FanoutMapping[entry.Hash[0]]\n\n\t\tentry.Offset = i.idx.getOffset(pos, i.secondLevel)\n\t\tentry.CRC32 = i.idx.getCRC32(pos, i.secondLevel)\n\n\t\ti.secondLevel++\n\t\ti.total++\n\n\t\treturn entry, nil\n\t}\n}\n\nfunc (i *idxfileEntryIter) Close() error {\n\ti.firstLevel = fanout\n\treturn nil\n}\n\n\/\/ Entry is the in memory representation of an object entry in the idx file.\ntype Entry struct {\n\tHash   plumbing.Hash\n\tCRC32  uint32\n\tOffset uint64\n}\n\ntype idxfileEntryOffsetIter struct {\n\tentries entriesByOffset\n\tpos     int\n}\n\nfunc (i *idxfileEntryOffsetIter) Next() (*Entry, error) {\n\tif i.pos >= len(i.entries) {\n\t\treturn nil, io.EOF\n\t}\n\n\tentry := i.entries[i.pos]\n\ti.pos++\n\n\treturn entry, nil\n}\n\nfunc (i *idxfileEntryOffsetIter) Close() error {\n\ti.pos = len(i.entries) + 1\n\treturn nil\n}\n\ntype entriesByOffset []*Entry\n\nfunc (o entriesByOffset) Len() int {\n\treturn len(o)\n}\n\nfunc (o entriesByOffset) Less(i int, j int) bool {\n\treturn o[i].Offset < o[j].Offset\n}\n\nfunc (o entriesByOffset) Swap(i int, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n<commit_msg>plumbing: format\/idxfile, save another 18% of time in genOffsetHash by not using iterator and not loading CRC<commit_after>package idxfile\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"sort\"\n\n\tencbin \"encoding\/binary\"\n\n\t\"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n)\n\nconst (\n\t\/\/ VersionSupported is the only idx version supported.\n\tVersionSupported = 2\n\n\tnoMapping = -1\n)\n\nvar (\n\tidxHeader = []byte{255, 't', 'O', 'c'}\n)\n\n\/\/ Index represents an index of a packfile.\ntype Index interface {\n\t\/\/ Contains checks whether the given hash is in the index.\n\tContains(h plumbing.Hash) (bool, error)\n\t\/\/ FindOffset finds the offset in the packfile for the object with\n\t\/\/ the given hash.\n\tFindOffset(h plumbing.Hash) (int64, error)\n\t\/\/ FindCRC32 finds the CRC32 of the object with the given hash.\n\tFindCRC32(h plumbing.Hash) (uint32, error)\n\t\/\/ FindHash finds the hash for the object with the given offset.\n\tFindHash(o int64) (plumbing.Hash, error)\n\t\/\/ Count returns the number of entries in the index.\n\tCount() (int64, error)\n\t\/\/ Entries returns an iterator to retrieve all index entries.\n\tEntries() (EntryIter, error)\n\t\/\/ EntriesByOffset returns an iterator to retrieve all index entries ordered\n\t\/\/ by offset.\n\tEntriesByOffset() (EntryIter, error)\n}\n\n\/\/ MemoryIndex is the in memory representation of an idx file.\ntype MemoryIndex struct {\n\tVersion uint32\n\tFanout  [256]uint32\n\t\/\/ FanoutMapping maps the position in the fanout table to the position\n\t\/\/ in the Names, Offset32 and CRC32 slices. This improves the memory\n\t\/\/ usage by not needing an array with unnecessary empty slots.\n\tFanoutMapping    [256]int\n\tNames            [][]byte\n\tOffset32         [][]byte\n\tCRC32            [][]byte\n\tOffset64         []byte\n\tPackfileChecksum [20]byte\n\tIdxChecksum      [20]byte\n\n\toffsetHash       map[int64]plumbing.Hash\n\toffsetHashIsFull bool\n}\n\nvar _ Index = (*MemoryIndex)(nil)\n\n\/\/ NewMemoryIndex returns an instance of a new MemoryIndex.\nfunc NewMemoryIndex() *MemoryIndex {\n\treturn &MemoryIndex{}\n}\n\nfunc (idx *MemoryIndex) findHashIndex(h plumbing.Hash) (int, bool) {\n\tk := idx.FanoutMapping[h[0]]\n\tif k == noMapping {\n\t\treturn 0, false\n\t}\n\n\tif len(idx.Names) <= k {\n\t\treturn 0, false\n\t}\n\n\tdata := idx.Names[k]\n\thigh := uint64(len(idx.Offset32[k])) >> 2\n\tif high == 0 {\n\t\treturn 0, false\n\t}\n\n\tlow := uint64(0)\n\tfor {\n\t\tmid := (low + high) >> 1\n\t\toffset := mid * objectIDLength\n\n\t\tcmp := bytes.Compare(h[:], data[offset:offset+objectIDLength])\n\t\tif cmp < 0 {\n\t\t\thigh = mid\n\t\t} else if cmp == 0 {\n\t\t\treturn int(mid), true\n\t\t} else {\n\t\t\tlow = mid + 1\n\t\t}\n\n\t\tif low >= high {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn 0, false\n}\n\n\/\/ Contains implements the Index interface.\nfunc (idx *MemoryIndex) Contains(h plumbing.Hash) (bool, error) {\n\t_, ok := idx.findHashIndex(h)\n\treturn ok, nil\n}\n\n\/\/ FindOffset implements the Index interface.\nfunc (idx *MemoryIndex) FindOffset(h plumbing.Hash) (int64, error) {\n\tif len(idx.FanoutMapping) <= int(h[0]) {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\tk := idx.FanoutMapping[h[0]]\n\ti, ok := idx.findHashIndex(h)\n\tif !ok {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\toffset := idx.getOffset(k, i)\n\n\tif !idx.offsetHashIsFull {\n\t\t\/\/ Save the offset for reverse lookup\n\t\tif idx.offsetHash == nil {\n\t\t\tidx.offsetHash = make(map[int64]plumbing.Hash)\n\t\t}\n\t\tidx.offsetHash[int64(offset)] = h\n\t}\n\n\treturn int64(offset), nil\n}\n\nconst isO64Mask = uint64(1) << 31\n\nfunc (idx *MemoryIndex) getOffset(firstLevel, secondLevel int) uint64 {\n\toffset := secondLevel << 2\n\tofs := encbin.BigEndian.Uint32(idx.Offset32[firstLevel][offset : offset+4])\n\n\tif (uint64(ofs) & isO64Mask) != 0 {\n\t\toffset := 8 * (uint64(ofs) & ^isO64Mask)\n\t\tn := encbin.BigEndian.Uint64(idx.Offset64[offset : offset+8])\n\t\treturn n\n\t}\n\n\treturn uint64(ofs)\n}\n\n\/\/ FindCRC32 implements the Index interface.\nfunc (idx *MemoryIndex) FindCRC32(h plumbing.Hash) (uint32, error) {\n\tk := idx.FanoutMapping[h[0]]\n\ti, ok := idx.findHashIndex(h)\n\tif !ok {\n\t\treturn 0, plumbing.ErrObjectNotFound\n\t}\n\n\treturn idx.getCRC32(k, i), nil\n}\n\nfunc (idx *MemoryIndex) getCRC32(firstLevel, secondLevel int) uint32 {\n\toffset := secondLevel << 2\n\treturn encbin.BigEndian.Uint32(idx.CRC32[firstLevel][offset : offset+4])\n}\n\n\/\/ FindHash implements the Index interface.\nfunc (idx *MemoryIndex) FindHash(o int64) (plumbing.Hash, error) {\n\tvar hash plumbing.Hash\n\tvar ok bool\n\n\tif idx.offsetHash != nil {\n\t\tif hash, ok = idx.offsetHash[o]; ok {\n\t\t\treturn hash, nil\n\t\t}\n\t}\n\n\t\/\/ Lazily generate the reverse offset\/hash map if required.\n\tif !idx.offsetHashIsFull || idx.offsetHash == nil {\n\t\tif err := idx.genOffsetHash(); err != nil {\n\t\t\treturn plumbing.ZeroHash, err\n\t\t}\n\n\t\thash, ok = idx.offsetHash[o]\n\t}\n\n\tif !ok {\n\t\treturn plumbing.ZeroHash, plumbing.ErrObjectNotFound\n\t}\n\n\treturn hash, nil\n}\n\n\/\/ genOffsetHash generates the offset\/hash mapping for reverse search.\nfunc (idx *MemoryIndex) genOffsetHash() error {\n\tcount, err := idx.Count()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tidx.offsetHash = make(map[int64]plumbing.Hash, count)\n\tidx.offsetHashIsFull = true\n\n\tvar hash plumbing.Hash\n\ti := uint32(0)\n\tfor firstLevel, fanoutValue := range idx.Fanout {\n\t\tpos := idx.FanoutMapping[firstLevel]\n\t\tfor secondLevel := uint32(0); i < fanoutValue; i++ {\n\t\t\tcopy(hash[:], idx.Names[pos][secondLevel*objectIDLength:])\n\t\t\toffset := int64(idx.getOffset(pos, int(secondLevel)))\n\t\t\tidx.offsetHash[offset] = hash\n\t\t\tsecondLevel++\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Count implements the Index interface.\nfunc (idx *MemoryIndex) Count() (int64, error) {\n\treturn int64(idx.Fanout[fanout-1]), nil\n}\n\n\/\/ Entries implements the Index interface.\nfunc (idx *MemoryIndex) Entries() (EntryIter, error) {\n\treturn &idxfileEntryIter{idx, 0, 0, 0}, nil\n}\n\n\/\/ EntriesByOffset implements the Index interface.\nfunc (idx *MemoryIndex) EntriesByOffset() (EntryIter, error) {\n\tcount, err := idx.Count()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titer := &idxfileEntryOffsetIter{\n\t\tentries: make(entriesByOffset, count),\n\t}\n\n\tentries, err := idx.Entries()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor pos := 0; int64(pos) < count; pos++ {\n\t\tentry, err := entries.Next()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\titer.entries[pos] = entry\n\t}\n\n\tsort.Sort(iter.entries)\n\n\treturn iter, nil\n}\n\n\/\/ EntryIter is an iterator that will return the entries in a packfile index.\ntype EntryIter interface {\n\t\/\/ Next returns the next entry in the packfile index.\n\tNext() (*Entry, error)\n\t\/\/ Close closes the iterator.\n\tClose() error\n}\n\ntype idxfileEntryIter struct {\n\tidx                     *MemoryIndex\n\ttotal                   int\n\tfirstLevel, secondLevel int\n}\n\nfunc (i *idxfileEntryIter) Next() (*Entry, error) {\n\tfor {\n\t\tif i.firstLevel >= fanout {\n\t\t\treturn nil, io.EOF\n\t\t}\n\n\t\tif i.total >= int(i.idx.Fanout[i.firstLevel]) {\n\t\t\ti.firstLevel++\n\t\t\ti.secondLevel = 0\n\t\t\tcontinue\n\t\t}\n\n\t\tentry := new(Entry)\n\t\tofs := i.secondLevel * objectIDLength\n\t\tcopy(entry.Hash[:], i.idx.Names[i.idx.FanoutMapping[i.firstLevel]][ofs:])\n\n\t\tpos := i.idx.FanoutMapping[entry.Hash[0]]\n\n\t\tentry.Offset = i.idx.getOffset(pos, i.secondLevel)\n\t\tentry.CRC32 = i.idx.getCRC32(pos, i.secondLevel)\n\n\t\ti.secondLevel++\n\t\ti.total++\n\n\t\treturn entry, nil\n\t}\n}\n\nfunc (i *idxfileEntryIter) Close() error {\n\ti.firstLevel = fanout\n\treturn nil\n}\n\n\/\/ Entry is the in memory representation of an object entry in the idx file.\ntype Entry struct {\n\tHash   plumbing.Hash\n\tCRC32  uint32\n\tOffset uint64\n}\n\ntype idxfileEntryOffsetIter struct {\n\tentries entriesByOffset\n\tpos     int\n}\n\nfunc (i *idxfileEntryOffsetIter) Next() (*Entry, error) {\n\tif i.pos >= len(i.entries) {\n\t\treturn nil, io.EOF\n\t}\n\n\tentry := i.entries[i.pos]\n\ti.pos++\n\n\treturn entry, nil\n}\n\nfunc (i *idxfileEntryOffsetIter) Close() error {\n\ti.pos = len(i.entries) + 1\n\treturn nil\n}\n\ntype entriesByOffset []*Entry\n\nfunc (o entriesByOffset) Len() int {\n\treturn len(o)\n}\n\nfunc (o entriesByOffset) Less(i int, j int) bool {\n\treturn o[i].Offset < o[j].Offset\n}\n\nfunc (o entriesByOffset) Swap(i int, j int) {\n\to[i], o[j] = o[j], o[i]\n}\n<|endoftext|>"}
{"text":"<commit_before>package queue\n\nimport (\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc TestStorage(t *testing.T) {\n\tvar (\n\t\tdirectory   = path.Join(os.TempDir(), uuid.New())\n\t\tdata        = []byte(\"test\")\n\t\tnumMessages = 5\n\t\tmessageIDs  = make([]string, numMessages)\n\t\tm           = &Message{}\n\t)\n\tif err := os.MkdirAll(directory, 0755); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(directory)\n\tif s, messages, err := NewStorage(directory); err == nil {\n\t\tif len(messages) != 0 {\n\t\t\tt.Fatalf(\"%d != 0\", len(messages))\n\t\t}\n\t\tif w, id, err := s.NewBody(); err == nil {\n\t\t\tif _, err := w.Write(data); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tm.Body = id\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfor i := 0; i < numMessages; i++ {\n\t\t\tif id, err := s.NewMessage(m); err == nil {\n\t\t\t\tmessageIDs[i] = id\n\t\t\t} else {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tt.Fatal(err)\n\t}\n\tif s, messages, err := NewStorage(directory); err == nil {\n\t\tif len(messages) != numMessages {\n\t\t\tt.Fatalf(\"%d != %d\", len(messages), numMessages)\n\t\t}\n\t\tfor _, id := range messageIDs {\n\t\t\tif err := s.DeleteMessage(id); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t\tif _, err := s.GetBody(m.Body); err != InvalidID {\n\t\t\tt.Fatalf(\"%v != %v\", err, InvalidID)\n\t\t}\n\t} else {\n\t\tt.Fatal(err)\n\t}\n}\n<commit_msg>Switched Storage tests to using TempDir.<commit_after>package queue\n\nimport (\n\t\"github.com\/nathan-osman\/go-cannon\/util\"\n\n\t\"testing\"\n)\n\nfunc TestStorage(t *testing.T) {\n\tvar (\n\t\tdata        = []byte(\"test\")\n\t\tnumMessages = 5\n\t\tmessageIDs  = make([]string, numMessages)\n\t\tm           = &Message{}\n\t)\n\tif d, err := util.NewTempDir(); err == nil {\n\t\tdefer d.Delete()\n\t\tif s, messages, err := NewStorage(d.Path); err == nil {\n\t\t\tif len(messages) != 0 {\n\t\t\t\tt.Fatalf(\"%d != 0\", len(messages))\n\t\t\t}\n\t\t\tif w, id, err := s.NewBody(); err == nil {\n\t\t\t\tif _, err := w.Write(data); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tif err := w.Close(); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tm.Body = id\n\t\t\t} else {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tfor i := 0; i < numMessages; i++ {\n\t\t\t\tif id, err := s.NewMessage(m); err == nil {\n\t\t\t\t\tmessageIDs[i] = id\n\t\t\t\t} else {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif s, messages, err := NewStorage(d.Path); err == nil {\n\t\t\tif len(messages) != numMessages {\n\t\t\t\tt.Fatalf(\"%d != %d\", len(messages), numMessages)\n\t\t\t}\n\t\t\tfor _, id := range messageIDs {\n\t\t\t\tif err := s.DeleteMessage(id); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, err := s.GetBody(m.Body); err != InvalidID {\n\t\t\t\tt.Fatalf(\"%v != %v\", err, InvalidID)\n\t\t\t}\n\t\t} else {\n\t\t\tt.Fatal(err)\n\t\t}\n\t} else {\n\t\tt.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package main implements a (prototype-quality) review wizard.\n\/\/\n\/\/ The code is organized into three packages:\n\/\/\n\/\/    entity\n\/\/      ^   ^\n\/\/      |    \\\n\/\/      |    persist\n\/\/      |     ^\n\/\/      |    \/\n\/\/      main\n\/\/\n\/\/ The entity package contains domain syntax: Reviews, (Question) Profiles, Responses, etc.\n\/\/ The persist package implements the *Repo interfaces defined in the entity model.\n\/\/ The main package defines the web UI and calls the entity and persist code.\n\/\/\n\/\/ For more information on this architecture, see\n\/\/\n\/\/     http:\/\/manuel.kiessling.net\/2012\/09\/28\/applying-the-clean-architecture-to-go-applications\/\n\/\/\n\/\/ Next, a note about naming: the convention used below is that App* is\n\/\/ newtype-wrapper that ServeHTTP calls that it receives to a corresponding\n\/\/ Handle* method on its embedded App struct. In turn, Handle*Set will parse\n\/\/ the request URL and method and will delegate to a more specific\n\/\/ Handle*(Set)?(Get|Post)() method. Thus, one typical handling chain might be:\n\/\/\n\/\/   GET \/reviews\/\n\/\/      -> ReviewSetApp.ServeHTTP()\n\/\/      -> App.HandleReviewSet()\n\/\/      -> App.HandleReviewSetGet()\n\/\/\n\/\/ while another might be:\n\/\/\n\/\/   POST \/reviews\/acme-1.2.0\n\/\/      -> ReviewSetApp.ServeHTTP()\n\/\/      -> App.HandleReviewSet()\n\/\/      -> App.HandleReviewPost(..., \"acme-1.2.0\")\npackage main\n\nimport (\n\t\"entity\"\n\t\"fmt\"\n\t\"html\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"persist\"\n\t\"regexp\"\n\n\/\/ revel, pat, gorilla\n\/\/ gorp, json, xml\n)\n\ntype App struct {\n\tidChan chan int\n\tentity.ProfileRepo\n\tentity.QuestionRepo\n\tentity.ReviewRepo\n}\n\ntype ReviewSetApp struct {\n\t*App\n}\n\ntype RootApp struct {\n\t*App\n}\n\ntype ProfileSetApp struct {\n\t*App\n}\n\nfunc (self *ReviewSetApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer recoverHTTP(w, r)\n\tself.HandleReviewSet(w, r)\n}\n\nfunc (self *ProfileSetApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer recoverHTTP(w, r)\n\tself.HandleProfileSet(w, r)\n}\n\nfunc (self *RootApp) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdefer recoverHTTP(w, r)\n\tself.HandleRoot(w, r)\n}\n\nfunc recoverHTTP(w http.ResponseWriter, r *http.Request) {\n\tif rec := recover(); rec != nil {\n\t\tswitch err := rec.(type) {\n\t\tcase error:\n\t\t\tlog.Printf(\"error: %v, req: %v\", err, r)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown error: %v, req: %v\", err, r)\n\t\t\thttp.Error(w, \"unknown error\", http.StatusInternalServerError)\n\t\t}\n\t}\n}\n\nfunc checkHTTP(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (self *App) HandleReviewPost(w http.ResponseWriter, r *http.Request, reviewName string) {\n\tlog.Printf(\"HandleReviewPost(): reviewName: %v\\n\", reviewName)\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\n\/\/ BUG(mistone): CSRF!\nfunc (self *App) HandleReviewSetPost(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"\/reviews\/\" {\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Bad Path %q %q\\n\",\n\t\t\t\thtml.EscapeString(r.Method),\n\t\t\t\thtml.EscapeString(r.URL.Path)),\n\t\t\thttp.StatusBadRequest)\n\t} else {\n\t\t\/\/ parse body\n\t\treviewName := r.FormValue(\"review\")\n\n\t\treviewVer, err := entity.NewVersionFromString(reviewName)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): reviewVer: %v\\n\", reviewVer)\n\n\t\t\/\/ extract profile\n\t\tprofileName := r.FormValue(\"profile\")\n\n\t\tprofileVer, err := entity.NewVersionFromString(profileName)\n\t\tcheckHTTP(err)\n\n\t\tprofile, err := self.GetProfileById(*profileVer)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): profile: %v\\n\", profile)\n\n\t\t\/\/ make a new Review\n\t\treview := &entity.Review{\n\t\t\tVersion:   *reviewVer,\n\t\t\tProfile:   profile,\n\t\t\tResponses: make([]*entity.Response, len(profile.Questions)),\n\t\t}\n\n\t\t\/\/ make appropriate Responses based on the Questions\n\t\t\/\/   contained in the indicated Profile\n\t\tfor idx, q := range profile.Questions {\n\t\t\treview.Responses[idx] = &entity.Response{\n\t\t\t\tQuestion: q,\n\t\t\t\tAnswer:   nil,\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"HandleReviewSetPost(): created review: %v\\n\", review)\n\n\t\t\/\/ persist the new review\n\t\terr = self.ReviewRepo.AddReview(review)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): redirecting to: .\/%s\\n\", reviewVer)\n\t\thttp.Redirect(w, r, fmt.Sprintf(\".\/%s\", reviewVer), http.StatusSeeOther)\n\t}\n}\n\nfunc (self *App) HandleReviewGet(w http.ResponseWriter, r *http.Request, reviewName string) {\n\tlog.Printf(\"HandleReviewGet(): reviewName: %v\\n\", reviewName)\n\n\treviewVer, err := entity.NewVersionFromString(reviewName)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleReviewGet(): reviewVer: %v\\n\", reviewVer)\n\n\treview, err := self.ReviewRepo.GetReviewById(*reviewVer)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleReviewGet(): review: %v\\n\", review)\n\n\trenderTemplate(w, \"review\", review)\n}\n\nfunc (self *App) HandleReviewSetGet(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleReviewSetGet()\\n\")\n\t\/\/ ...\n\t\/\/ list links to all (current?) reviews?\n\treviews, err := self.GetAllReviews()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\trenderTemplate(w, \"review_set\", reviews)\n}\n\nvar reviewPat *regexp.Regexp = regexp.MustCompile(`^\/reviews\/([^-]+-\\d+\\.\\d+\\.\\d+)?$`)\n\nfunc (self *App) HandleReviewSet(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleReviewSet()\\n\")\n\tms := reviewPat.FindStringSubmatch(r.URL.Path)\n\tlog.Printf(\"HandleReviewSet(): ms: %s, len: %d\", ms, len(ms))\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tif len(ms[1]) == 0 {\n\t\t\tself.HandleReviewSetPost(w, r)\n\t\t} else {\n\t\t\tself.HandleReviewPost(w, r, ms[1])\n\t\t}\n\tcase \"GET\":\n\t\tif len(ms[1]) == 0 {\n\t\t\tself.HandleReviewSetGet(w, r)\n\t\t} else {\n\t\t\tself.HandleReviewGet(w, r, ms[1])\n\t\t}\n\tdefault:\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Unknown Method %q %q\\n\",\n\t\t\t\thtml.EscapeString(r.Method),\n\t\t\t\thtml.EscapeString(r.URL.Path)),\n\t\t\thttp.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (self *App) HandleProfilePost(w http.ResponseWriter, r *http.Request, profileName string) {\n\tlog.Printf(\"HandleProfilePost()\\n\")\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\nfunc (self *App) HandleProfileGet(w http.ResponseWriter, r *http.Request, profileName string) {\n\tlog.Printf(\"HandleProfileGet(): profileName: %v\\n\", profileName)\n\n\tprofileVer, err := entity.NewVersionFromString(profileName)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleProfileGet(): profileVer: %v\\n\", profileVer)\n\n\tprofile, err := self.ProfileRepo.GetProfileById(*profileVer)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleProfileGet(): profile: %v\\n\", profile)\n\n\trenderTemplate(w, \"profile\", profile)\n}\n\nfunc (self *App) HandleProfileSetPost(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleProfileSetPost()\\n\")\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\nfunc (self *App) HandleProfileSetGet(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleProfileSetGet()\\n\")\n\t\/\/ ...\n\t\/\/ list links to all (current?) profiles?\n\tprofiles, err := self.GetAllProfiles()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\trenderTemplate(w, \"profile_set\", profiles)\n}\n\nvar profilePat *regexp.Regexp = regexp.MustCompile(`^\/profiles\/([^-]+-\\d+\\.\\d+\\.\\d+)?$`)\n\nfunc (self *App) HandleProfileSet(w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleProfileSet()\\n\")\n\tms := profilePat.FindStringSubmatch(r.URL.Path)\n\tlog.Printf(\"HandleProfileSet(): ms: %s, len: %d\", ms, len(ms))\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tif len(ms[1]) == 0 {\n\t\t\tself.HandleProfileSetPost(w, r)\n\t\t} else {\n\t\t\tself.HandleProfilePost(w, r, ms[1])\n\t\t}\n\tcase \"GET\":\n\t\tif len(ms[1]) == 0 {\n\t\t\tself.HandleProfileSetGet(w, r)\n\t\t} else {\n\t\t\tself.HandleProfileGet(w, r, ms[1])\n\t\t}\n\tdefault:\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Unknown Method %q %q\\n\",\n\t\t\t\thtml.EscapeString(r.Method),\n\t\t\t\thtml.EscapeString(r.URL.Path)),\n\t\t\thttp.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (self *App) HandleRootGet(w http.ResponseWriter, r *http.Request) {\n\trenderTemplate(w, \"root\", nil)\n}\n\nfunc (self *App) HandleRoot(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\tself.HandleRootGet(w, r)\n\tdefault:\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Unknown Method %q %q\\n\",\n\t\t\t\thtml.EscapeString(r.Method),\n\t\t\t\thtml.EscapeString(r.URL.Path)),\n\t\t\thttp.StatusMethodNotAllowed)\n\t}\n\n}\n\nvar templates = template.Must(template.ParseFiles(\n\t\"src\/root.html\",\n\t\"src\/review.html\",\n\t\"src\/review_set.html\",\n\t\"src\/profile.html\",\n\t\"src\/profile_set.html\"))\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p interface{}) {\n\terr := templates.ExecuteTemplate(w, tmpl+\".html\", p)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc main() {\n\t\/\/ Create a supply of ids.\n\tidChan := make(chan int)\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tidChan <- i\n\t\t}\n\t}()\n\n\tpersist := new(persist.PersistMem)\n\n\tapp := &App{\n\t\tidChan:       idChan,\n\t\tProfileRepo:  entity.ProfileRepo(persist),\n\t\tQuestionRepo: entity.QuestionRepo(persist),\n\t\tReviewRepo:   entity.ReviewRepo(persist),\n\t}\n\n\tfmt.Printf(\"Hi.\\n\")\n\thttp.Handle(\"\/reviews\/\",\n\t\t&ReviewSetApp{app})\n\thttp.Handle(\"\/profiles\/\",\n\t\t&ProfileSetApp{app})\n\thttp.Handle(\"\/\",\n\t\t&RootApp{app})\n\tlog.Fatal(http.ListenAndServe(\"127.0.0.1:3001\", nil))\n}\n<commit_msg>Switch to gorilla\/mux and wrapped functions.<commit_after>\/\/ Package main implements a (prototype-quality) review wizard.\n\/\/\n\/\/ The code is organized into three packages:\n\/\/\n\/\/    entity\n\/\/      ^   ^\n\/\/      |    \\\n\/\/      |    persist\n\/\/      |     ^\n\/\/      |    \/\n\/\/      main\n\/\/\n\/\/ The entity package contains domain syntax: Reviews, (Question) Profiles, Responses, etc.\n\/\/ The persist package implements the *Repo interfaces defined in the entity model.\n\/\/ The main package defines the web UI and calls the entity and persist code.\n\/\/\n\/\/ For more information on this architecture, see\n\/\/\n\/\/     http:\/\/manuel.kiessling.net\/2012\/09\/28\/applying-the-clean-architecture-to-go-applications\/\n\/\/\npackage main\n\nimport (\n\t\"entity\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"html\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"persist\"\n\/\/ revel, pat, gorilla\n\/\/ gorp, json, xml\n)\n\ntype App struct {\n\tidChan chan int\n\tentity.ProfileRepo\n\tentity.QuestionRepo\n\tentity.ReviewRepo\n}\n\nfunc recoverHTTP(w http.ResponseWriter, r *http.Request) {\n\tif rec := recover(); rec != nil {\n\t\tswitch err := rec.(type) {\n\t\tcase error:\n\t\t\tlog.Printf(\"error: %v, req: %v\", err, r)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tdefault:\n\t\t\tlog.Printf(\"unknown error: %v, req: %v\", err, r)\n\t\t\thttp.Error(w, \"unknown error\", http.StatusInternalServerError)\n\t\t}\n\t}\n}\n\nfunc checkHTTP(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc HandleReviewSetGet(self *App, w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleReviewSetGet()\\n\")\n\t\/\/ ...\n\t\/\/ list links to all (current?) reviews?\n\treviews, err := self.GetAllReviews()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\trenderTemplate(w, \"review_set\", reviews)\n}\n\n\/\/ BUG(mistone): CSRF!\nfunc HandleReviewSetPost(self *App, w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path != \"\/reviews\/\" {\n\t\thttp.Error(w,\n\t\t\tfmt.Sprintf(\"Bad Path %q %q\\n\",\n\t\t\t\thtml.EscapeString(r.Method),\n\t\t\t\thtml.EscapeString(r.URL.Path)),\n\t\t\thttp.StatusBadRequest)\n\t} else {\n\t\t\/\/ parse body\n\t\treviewName := r.FormValue(\"review\")\n\n\t\treviewVer, err := entity.NewVersionFromString(reviewName)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): reviewVer: %v\\n\", reviewVer)\n\n\t\t\/\/ extract profile\n\t\tprofileName := r.FormValue(\"profile\")\n\n\t\tprofileVer, err := entity.NewVersionFromString(profileName)\n\t\tcheckHTTP(err)\n\n\t\tprofile, err := self.GetProfileById(*profileVer)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): profile: %v\\n\", profile)\n\n\t\t\/\/ make a new Review\n\t\treview := &entity.Review{\n\t\t\tVersion:   *reviewVer,\n\t\t\tProfile:   profile,\n\t\t\tResponses: make([]*entity.Response, len(profile.Questions)),\n\t\t}\n\n\t\t\/\/ make appropriate Responses based on the Questions\n\t\t\/\/   contained in the indicated Profile\n\t\tfor idx, q := range profile.Questions {\n\t\t\treview.Responses[idx] = &entity.Response{\n\t\t\t\tQuestion: q,\n\t\t\t\tAnswer:   nil,\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"HandleReviewSetPost(): created review: %v\\n\", review)\n\n\t\t\/\/ persist the new review\n\t\terr = self.ReviewRepo.AddReview(review)\n\t\tcheckHTTP(err)\n\n\t\tlog.Printf(\"HandleReviewSetPost(): redirecting to: .\/%s\\n\", reviewVer)\n\t\thttp.Redirect(w, r, fmt.Sprintf(\".\/%s\", reviewVer), http.StatusSeeOther)\n\t}\n}\n\nfunc HandleReviewGet(self *App, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\treviewName := vars[\"review_name\"]\n\tlog.Printf(\"HandleReviewGet(): reviewName: %v\\n\", reviewName)\n\n\treviewVer, err := entity.NewVersionFromString(reviewName)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleReviewGet(): reviewVer: %v\\n\", reviewVer)\n\n\treview, err := self.ReviewRepo.GetReviewById(*reviewVer)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleReviewGet(): review: %v\\n\", review)\n\n\trenderTemplate(w, \"review\", review)\n}\n\nfunc HandleReviewPost(self *App, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\treviewName := vars[\"review_name\"]\n\tlog.Printf(\"HandleReviewPost(): reviewName: %v\\n\", reviewName)\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\nfunc HandleProfileSetGet(self *App, w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleProfileSetGet()\\n\")\n\t\/\/ ...\n\t\/\/ list links to all (current?) profiles?\n\tprofiles, err := self.GetAllProfiles()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\trenderTemplate(w, \"profile_set\", profiles)\n}\n\nfunc HandleProfileSetPost(self *App, w http.ResponseWriter, r *http.Request) {\n\tlog.Printf(\"HandleProfileSetPost()\\n\")\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\nfunc HandleProfileGet(self *App, w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tprofileName := vars[\"profile_name\"]\n\tlog.Printf(\"HandleProfileGet(): profileName: %v\\n\", profileName)\n\n\tprofileVer, err := entity.NewVersionFromString(profileName)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleProfileGet(): profileVer: %v\\n\", profileVer)\n\n\tprofile, err := self.ProfileRepo.GetProfileById(*profileVer)\n\tcheckHTTP(err)\n\tlog.Printf(\"HandleProfileGet(): profile: %v\\n\", profile)\n\n\trenderTemplate(w, \"profile\", profile)\n}\n\nfunc HandleProfilePost(self *App, w http.ResponseWriter, r *http.Request, profileName string) {\n\tlog.Printf(\"HandleProfilePost()\\n\")\n\thttp.Error(w, \"Not implemented.\", http.StatusNotImplemented)\n}\n\nfunc HandleRootGet(self *App, w http.ResponseWriter, r *http.Request) {\n\trenderTemplate(w, \"root\", nil)\n}\n\nvar templates = template.Must(template.ParseFiles(\n\t\"src\/root.html\",\n\t\"src\/review.html\",\n\t\"src\/review_set.html\",\n\t\"src\/profile.html\",\n\t\"src\/profile_set.html\"))\n\nfunc renderTemplate(w http.ResponseWriter, tmpl string, p interface{}) {\n\terr := templates.ExecuteTemplate(w, tmpl+\".html\", p)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\nfunc main() {\n\t\/\/ Create a supply of ids.\n\tidChan := make(chan int)\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tidChan <- i\n\t\t}\n\t}()\n\n\tpersist := new(persist.PersistMem)\n\n\tapp := &App{\n\t\tidChan:       idChan,\n\t\tProfileRepo:  entity.ProfileRepo(persist),\n\t\tQuestionRepo: entity.QuestionRepo(persist),\n\t\tReviewRepo:   entity.ReviewRepo(persist),\n\t}\n\n\twrap := func(fn func(*App, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {\n\t\treturn (func(w http.ResponseWriter, r *http.Request) {\n\t\t\tdefer recoverHTTP(w, r)\n\t\t\tfn(app, w, r)\n\t\t})\n\t}\n\n\tfmt.Printf(\"Hi.\\n\")\n\tr := mux.NewRouter()\n\n\ts := r.PathPrefix(\"\/reviews\").Subrouter()\n\ts.HandleFunc(\"\/\", wrap(HandleReviewSetGet)).Methods(\"GET\").Name(\"review_set\")\n\ts.HandleFunc(\"\/\", wrap(HandleReviewSetPost)).Methods(\"POST\")\n\ts.HandleFunc(\"\/{review_name}\", wrap(HandleReviewGet)).Methods(\"GET\").Name(\"review\")\n\n\ts = r.PathPrefix(\"\/profiles\").Subrouter()\n\ts.HandleFunc(\"\/\", wrap(HandleProfileSetGet)).Methods(\"GET\").Name(\"profile_set\")\n\ts.HandleFunc(\"\/\", wrap(HandleProfileSetPost)).Methods(\"POST\")\n\ts.HandleFunc(\"\/{profile_name}\", wrap(HandleProfileGet)).Methods(\"GET\").Name(\"profile\")\n\n\tr.HandleFunc(\"\/\", wrap(HandleRootGet)).Methods(\"GET\").Name(\"root\")\n\n\thttp.Handle(\"\/\", r)\n\tlog.Fatal(http.ListenAndServe(\"127.0.0.1:3001\", nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package dnsclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\n\t\"koding\/kites\/kloud\/awscompat\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/route53\"\n\t\"github.com\/dchest\/validator\"\n\t\"github.com\/koding\/logging\"\n\toldaws \"github.com\/mitchellh\/goamz\/aws\"\n)\n\nvar ErrNoRecord = errors.New(\"no records available\")\n\ntype Route53 struct {\n\t*route53.Route53\n\thostedZone string\n\tZoneId     string\n\tLog        logging.Logger\n}\n\n\/\/ NewRoute53Client initializes a new DNSClient interface instance based on AWS Route53\nfunc NewRoute53Client(hostedZone string, auth oldaws.Auth) *Route53 {\n\tdns := route53.New(\n\t\tawscompat.NewSession(auth),\n\t\taws.NewConfig().WithRegion(\"us-east-1\"), \/\/ our route53 is based on this region, so we use it\n\t)\n\tdns.Client.Retryer = awscompat.Retry\n\n\tparams := &route53.ListHostedZonesInput{\n\t\tMaxItems: aws.String(\"100\"),\n\t}\n\thostedZones, err := dns.ListHostedZones(params)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar zoneId string\n\tvar dnsName = hostedZone + \".\" \/\/ DNS name ends with a \".\", e.g. \"dev.koding.io.\"\n\tfor _, h := range hostedZones.HostedZones {\n\t\tif aws.StringValue(h.Name) == dnsName {\n\t\t\t\/\/ The h.Id looks like \"\/hostedzone\/Z2T644TMIB2JZM\", we're interested\n\t\t\t\/\/ only in the last part - \"Z2T644TMIB2JZM\".\n\t\t\tif s := aws.StringValue(h.Id); s != \"\" {\n\t\t\t\tzoneId = path.Base(s)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif zoneId == \"\" {\n\t\tpanic(fmt.Sprintf(\"Hosted zone with the name '%s' doesn't exist\", hostedZone))\n\t}\n\n\treturn &Route53{\n\t\tRoute53:    dns,\n\t\thostedZone: hostedZone,\n\t\tZoneId:     zoneId,\n\t\tLog:        logging.NewLogger(\"kloud-dns\"),\n\t}\n}\n\n\/\/ Upsert creates or updates a the domain record with the given ip address. If\n\/\/ the record already exists, the record is updated with the new IP.\nfunc (r *Route53) Upsert(domain string, newIP string) error {\n\tr.Log.Debug(\"upserting domain name: %s to be associated with following ip: %v\", domain, newIP)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Upserting domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"UPSERT\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(domain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(30),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(newIP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\t_, err := r.ChangeResourceRecordSets(params)\n\tif err != nil {\n\t\treturn r.errorf(\"could not upsert domain %q: \", domain, err)\n\t}\n\treturn nil\n}\n\n\/\/ Domain retrieves the record set for the given domain name\nfunc (r *Route53) Get(domain string) (*Record, error) {\n\tr.Log.Debug(\"fetching domain record for domain: %s\", domain)\n\tresp, err := r.get(domain)\n\tif err != nil {\n\t\treturn nil, r.error(err)\n\t}\n\n\tvar dnsName = domain + \".\" \/\/ DNS name ends with a \".\", e.g. \"dev.koding.io.\"\n\tfor _, r := range resp {\n\t\tif aws.StringValue(r.Name) == dnsName {\n\t\t\treturn &Record{\n\t\t\t\tName: aws.StringValue(r.Name),\n\t\t\t\tIP:   aws.StringValue(r.ResourceRecords[0].Value),\n\t\t\t\tTTL:  int(aws.Int64Value(r.TTL)),\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn nil, r.error(ErrNoRecord)\n}\n\n\/\/ GetAll retrieves all records from the hostedzone. Because of the limitation\n\/\/ of Route53 it only returns up to 100 records. Subsequent calls retrieve the\n\/\/ first 100.\nfunc (r *Route53) GetAll(name string) ([]*Record, error) {\n\tr.Log.Debug(\"fetching domain records for name: %s\", name)\n\tresp, err := r.get(name)\n\tif err != nil {\n\t\treturn nil, r.error(err)\n\t}\n\n\trecords := make([]*Record, len(resp))\n\n\tfor i, r := range resp {\n\t\trecords[i] = &Record{\n\t\t\tName: aws.StringValue(r.Name),\n\t\t\tIP:   aws.StringValue(r.ResourceRecords[0].Value),\n\t\t\tTTL:  int(aws.Int64Value(r.TTL)),\n\t\t}\n\t}\n\n\treturn records, nil\n}\n\nfunc (r *Route53) get(name string) ([]*route53.ResourceRecordSet, error) {\n\tparams := &route53.ListResourceRecordSetsInput{\n\t\tHostedZoneId:    aws.String(r.ZoneId),\n\t\tStartRecordName: aws.String(name),\n\t}\n\tresp, err := r.ListResourceRecordSets(params)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not fetch records for name %q: %s\", name, err)\n\t}\n\tif len(resp.ResourceRecordSets) == 0 {\n\t\treturn nil, ErrNoRecord\n\t}\n\treturn resp.ResourceRecordSets, nil\n}\n\n\/\/ Rename changes the domain from oldDomain to newDomain in a single transaction\nfunc (r *Route53) Rename(oldDomain, newDomain string) error {\n\trecord, err := r.Get(oldDomain)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Log.Debug(\"updating domain name of IP %s from %q to %q\", record.IP, oldDomain, newDomain)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Renaming domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"DELETE\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(oldDomain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}, {\n\t\t\t\tAction: aws.String(\"UPSERT\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(newDomain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tif _, err = r.ChangeResourceRecordSets(params); err != nil {\n\t\treturn r.errorf(\"could not rename domain %q to %q: %s\", oldDomain, newDomain, err)\n\t}\n\treturn nil\n}\n\n\/\/ DeleteDomain deletes a domain record for the given domain\nfunc (r *Route53) Delete(domain string) error {\n\t\/\/ fetch correct TTL value, instead of relying on a hardcoded value for TTL\n\t\/\/ and IP\n\trecord, err := r.Get(domain)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Log.Debug(\"deleting domain name: %s which was associated to following ip: %s\", domain, record.IP)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Renaming domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"DELETE\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(domain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tif _, err = r.ChangeResourceRecordSets(params); err != nil {\n\t\treturn r.errorf(\"could not delete domain %q: %s\", domain, err)\n\t}\n\treturn nil\n}\n\nfunc (r *Route53) HostedZone() string {\n\treturn r.hostedZone\n}\n\nfunc (r *Route53) Validate(domain, username string) error {\n\thostedZone := r.hostedZone\n\n\tif domain == \"\" {\n\t\treturn r.errorf(\"Domain name argument is empty\")\n\t}\n\n\tif domain == hostedZone {\n\t\treturn r.errorf(\"Domain '%s' can't be the same as top-level domain '%s'\", domain, hostedZone)\n\t}\n\n\tif !strings.Contains(domain, hostedZone) {\n\t\treturn r.errorf(\"Domain doesn't contain hostedzone '%s'\", hostedZone)\n\t}\n\n\trest := strings.TrimSuffix(domain, \".\"+hostedZone)\n\tif rest == domain {\n\t\treturn r.errorf(\"Domain is invalid (1) '%s'\", domain)\n\t}\n\n\tif split := strings.Split(rest, \".\"); split[len(split)-1] != username {\n\t\treturn r.errorf(\"Domain doesn't contain username '%s'\", username)\n\t}\n\n\tif !validator.IsValidDomain(domain) {\n\t\treturn r.errorf(\"Domain is invalid (2) '%s'\", domain)\n\t}\n\n\treturn nil\n}\n\nfunc (r *Route53) errorf(format string, v ...interface{}) error {\n\terr := fmt.Errorf(format, v...)\n\tr.Log.Error(err.Error())\n\treturn err\n}\n\nfunc (r *Route53) error(err error) error {\n\tr.Log.Error(err.Error())\n\treturn err\n}\n<commit_msg>dnsclient: fix fetching all records<commit_after>package dnsclient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\n\t\"koding\/kites\/kloud\/awscompat\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/route53\"\n\t\"github.com\/dchest\/validator\"\n\t\"github.com\/koding\/logging\"\n\toldaws \"github.com\/mitchellh\/goamz\/aws\"\n)\n\nvar ErrNoRecord = errors.New(\"no records available\")\n\ntype Route53 struct {\n\t*route53.Route53\n\thostedZone string\n\tZoneId     string\n\tLog        logging.Logger\n}\n\n\/\/ NewRoute53Client initializes a new DNSClient interface instance based on AWS Route53\nfunc NewRoute53Client(hostedZone string, auth oldaws.Auth) *Route53 {\n\tdns := route53.New(\n\t\tawscompat.NewSession(auth),\n\t\taws.NewConfig().WithRegion(\"us-east-1\"), \/\/ our route53 is based on this region, so we use it\n\t)\n\tdns.Client.Retryer = awscompat.Retry\n\n\tparams := &route53.ListHostedZonesInput{\n\t\tMaxItems: aws.String(\"100\"),\n\t}\n\thostedZones, err := dns.ListHostedZones(params)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar zoneId string\n\tvar dnsName = hostedZone + \".\" \/\/ DNS name ends with a \".\", e.g. \"dev.koding.io.\"\n\tfor _, h := range hostedZones.HostedZones {\n\t\tif aws.StringValue(h.Name) == dnsName {\n\t\t\t\/\/ The h.Id looks like \"\/hostedzone\/Z2T644TMIB2JZM\", we're interested\n\t\t\t\/\/ only in the last part - \"Z2T644TMIB2JZM\".\n\t\t\tif s := aws.StringValue(h.Id); s != \"\" {\n\t\t\t\tzoneId = path.Base(s)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif zoneId == \"\" {\n\t\tpanic(fmt.Sprintf(\"Hosted zone with the name '%s' doesn't exist\", hostedZone))\n\t}\n\n\treturn &Route53{\n\t\tRoute53:    dns,\n\t\thostedZone: hostedZone,\n\t\tZoneId:     zoneId,\n\t\tLog:        logging.NewLogger(\"kloud-dns\"),\n\t}\n}\n\n\/\/ Upsert creates or updates a the domain record with the given ip address. If\n\/\/ the record already exists, the record is updated with the new IP.\nfunc (r *Route53) Upsert(domain string, newIP string) error {\n\tr.Log.Debug(\"upserting domain name: %s to be associated with following ip: %v\", domain, newIP)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Upserting domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"UPSERT\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(domain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(30),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(newIP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\t_, err := r.ChangeResourceRecordSets(params)\n\tif err != nil {\n\t\treturn r.errorf(\"could not upsert domain %q: \", domain, err)\n\t}\n\treturn nil\n}\n\n\/\/ Domain retrieves the record set for the given domain name\nfunc (r *Route53) Get(domain string) (*Record, error) {\n\tr.Log.Debug(\"fetching domain record for domain: %s\", domain)\n\tresp, err := r.get(domain)\n\tif err != nil {\n\t\treturn nil, r.error(err)\n\t}\n\n\tvar dnsName = domain + \".\" \/\/ DNS name ends with a \".\", e.g. \"dev.koding.io.\"\n\tfor _, r := range resp {\n\t\tif aws.StringValue(r.Name) == dnsName {\n\t\t\treturn &Record{\n\t\t\t\tName: aws.StringValue(r.Name),\n\t\t\t\tIP:   aws.StringValue(r.ResourceRecords[0].Value),\n\t\t\t\tTTL:  int(aws.Int64Value(r.TTL)),\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn nil, r.error(ErrNoRecord)\n}\n\n\/\/ GetAll retrieves all records from the hostedzone. Because of the limitation\n\/\/ of Route53 it only returns up to 100 records. Subsequent calls retrieve the\n\/\/ first 100.\nfunc (r *Route53) GetAll(name string) ([]*Record, error) {\n\tr.Log.Debug(\"fetching domain records for name: %s\", name)\n\tresp, err := r.get(name)\n\tif err != nil {\n\t\treturn nil, r.error(err)\n\t}\n\n\trecords := make([]*Record, len(resp))\n\n\tfor i, r := range resp {\n\t\trecords[i] = &Record{\n\t\t\tName: aws.StringValue(r.Name),\n\t\t\tIP:   aws.StringValue(r.ResourceRecords[0].Value),\n\t\t\tTTL:  int(aws.Int64Value(r.TTL)),\n\t\t}\n\t}\n\n\treturn records, nil\n}\n\nfunc (r *Route53) get(name string) ([]*route53.ResourceRecordSet, error) {\n\tparams := &route53.ListResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t}\n\tif name != \"\" {\n\t\tparams.StartRecordName = aws.String(name)\n\t}\n\tresp, err := r.ListResourceRecordSets(params)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not fetch records for name %q: %s\", name, err)\n\t}\n\tif len(resp.ResourceRecordSets) == 0 {\n\t\treturn nil, ErrNoRecord\n\t}\n\treturn resp.ResourceRecordSets, nil\n}\n\n\/\/ Rename changes the domain from oldDomain to newDomain in a single transaction\nfunc (r *Route53) Rename(oldDomain, newDomain string) error {\n\trecord, err := r.Get(oldDomain)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Log.Debug(\"updating domain name of IP %s from %q to %q\", record.IP, oldDomain, newDomain)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Renaming domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"DELETE\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(oldDomain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}, {\n\t\t\t\tAction: aws.String(\"UPSERT\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(newDomain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tif _, err = r.ChangeResourceRecordSets(params); err != nil {\n\t\treturn r.errorf(\"could not rename domain %q to %q: %s\", oldDomain, newDomain, err)\n\t}\n\treturn nil\n}\n\n\/\/ DeleteDomain deletes a domain record for the given domain\nfunc (r *Route53) Delete(domain string) error {\n\t\/\/ fetch correct TTL value, instead of relying on a hardcoded value for TTL\n\t\/\/ and IP\n\trecord, err := r.Get(domain)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Log.Debug(\"deleting domain name: %s which was associated to following ip: %s\", domain, record.IP)\n\tparams := &route53.ChangeResourceRecordSetsInput{\n\t\tHostedZoneId: aws.String(r.ZoneId),\n\t\tChangeBatch: &route53.ChangeBatch{\n\t\t\tComment: aws.String(\"Renaming domain\"),\n\t\t\tChanges: []*route53.Change{{\n\t\t\t\tAction: aws.String(\"DELETE\"),\n\t\t\t\tResourceRecordSet: &route53.ResourceRecordSet{\n\t\t\t\t\tName: aws.String(domain),\n\t\t\t\t\tType: aws.String(\"A\"),\n\t\t\t\t\tTTL:  aws.Int64(int64(record.TTL)),\n\t\t\t\t\tResourceRecords: []*route53.ResourceRecord{{\n\t\t\t\t\t\tValue: aws.String(record.IP),\n\t\t\t\t\t}},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tif _, err = r.ChangeResourceRecordSets(params); err != nil {\n\t\treturn r.errorf(\"could not delete domain %q: %s\", domain, err)\n\t}\n\treturn nil\n}\n\nfunc (r *Route53) HostedZone() string {\n\treturn r.hostedZone\n}\n\nfunc (r *Route53) Validate(domain, username string) error {\n\thostedZone := r.hostedZone\n\n\tif domain == \"\" {\n\t\treturn r.errorf(\"Domain name argument is empty\")\n\t}\n\n\tif domain == hostedZone {\n\t\treturn r.errorf(\"Domain '%s' can't be the same as top-level domain '%s'\", domain, hostedZone)\n\t}\n\n\tif !strings.Contains(domain, hostedZone) {\n\t\treturn r.errorf(\"Domain doesn't contain hostedzone '%s'\", hostedZone)\n\t}\n\n\trest := strings.TrimSuffix(domain, \".\"+hostedZone)\n\tif rest == domain {\n\t\treturn r.errorf(\"Domain is invalid (1) '%s'\", domain)\n\t}\n\n\tif split := strings.Split(rest, \".\"); split[len(split)-1] != username {\n\t\treturn r.errorf(\"Domain doesn't contain username '%s'\", username)\n\t}\n\n\tif !validator.IsValidDomain(domain) {\n\t\treturn r.errorf(\"Domain is invalid (2) '%s'\", domain)\n\t}\n\n\treturn nil\n}\n\nfunc (r *Route53) errorf(format string, v ...interface{}) error {\n\terr := fmt.Errorf(format, v...)\n\tr.Log.Error(err.Error())\n\treturn err\n}\n\nfunc (r *Route53) error(err error) error {\n\tr.Log.Error(err.Error())\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 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 amqp\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/types\"\n\t. \"github.com\/smartystreets\/assertions\"\n\tAMQP \"github.com\/streadway\/amqp\"\n)\n\nvar host string\n\nfunc init() {\n\thost = os.Getenv(\"AMQP_ADDRESS\")\n\tif host == \"\" {\n\t\thost = \"localhost:5672\"\n\t}\n}\n\nfunc TestNewClient(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestNewClient\"), \"guest\", \"guest\", host)\n\ta.So(c, ShouldNotBeNil)\n}\n\nfunc TestConnect(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestConnect\"), \"guest\", \"guest\", host)\n\terr := c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldBeNil)\n\n\t\/\/ Connecting while already connected should not change anything\n\terr = c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldBeNil)\n}\n\nfunc TestConnectInvalidAddress(t *testing.T) {\n\ta := New(t)\n\tConnectRetries = 2\n\tConnectRetryDelay = 50 * time.Millisecond\n\tc := NewClient(getLogger(t, \"TestConnectInvalidAddress\"), \"guest\", \"guest\", \"localhost:56720\")\n\terr := c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldNotBeNil)\n}\n\nfunc TestIsConnected(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestIsConnected\"), \"guest\", \"guest\", host)\n\n\ta.So(c.IsConnected(), ShouldBeFalse)\n\n\tc.Connect()\n\tdefer c.Disconnect()\n\n\ta.So(c.IsConnected(), ShouldBeTrue)\n}\n\nfunc TestDisconnect(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestDisconnect\"), \"guest\", \"guest\", host)\n\n\t\/\/ Disconnecting when not connected should not change anything\n\tc.Disconnect()\n\ta.So(c.IsConnected(), ShouldBeFalse)\n\n\tc.Connect()\n\tdefer c.Disconnect()\n\tc.Disconnect()\n\n\ta.So(c.IsConnected(), ShouldBeFalse)\n}\n\nfunc TestReopenChannelClient(t *testing.T) {\n\ta := New(t)\n\tctx := getLogger(t, \"TestReopenChannelClient\")\n\tc := NewClient(ctx, \"guest\", \"guest\", host).(*DefaultClient)\n\tclosed, err := c.connect(false)\n\ta.So(err, ShouldBeNil)\n\tdefer c.Disconnect()\n\n\tpublisher := c.NewPublisher(\"\")\n\terr = publisher.Open()\n\ta.So(err, ShouldBeNil)\n\tdefer publisher.Close()\n\n\ttest := func() error {\n\t\tctx.Debug(\"Testing publish\")\n\t\treturn publisher.PublishDownlink(types.DownlinkMessage{\n\t\t\tAppID: \"app\",\n\t\t})\n\t}\n\n\t\/\/ First attempt should be OK\n\terr = test()\n\ta.So(err, ShouldBeNil)\n\n\t\/\/ Make sure that the old channel is closed\n\tpublisher.(*DefaultPublisher).channel.Close()\n\n\t\/\/ Simulate a connection close so a new channel should be opened\n\tclosed <- AMQP.ErrClosed\n\n\t\/\/ Give the reconnect some time\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Second attempt should be OK as well and will only work on a new channel\n\terr = test()\n\ta.So(err, ShouldBeNil)\n}\n<commit_msg>Use Subscriber to test that publish actually works<commit_after>\/\/ Copyright © 2017 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 amqp\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"sync\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/types\"\n\t. \"github.com\/smartystreets\/assertions\"\n\tAMQP \"github.com\/streadway\/amqp\"\n)\n\nvar host string\n\nfunc init() {\n\thost = os.Getenv(\"AMQP_ADDRESS\")\n\tif host == \"\" {\n\t\thost = \"localhost:5672\"\n\t}\n}\n\nfunc TestNewClient(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestNewClient\"), \"guest\", \"guest\", host)\n\ta.So(c, ShouldNotBeNil)\n}\n\nfunc TestConnect(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestConnect\"), \"guest\", \"guest\", host)\n\terr := c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldBeNil)\n\n\t\/\/ Connecting while already connected should not change anything\n\terr = c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldBeNil)\n}\n\nfunc TestConnectInvalidAddress(t *testing.T) {\n\ta := New(t)\n\tConnectRetries = 2\n\tConnectRetryDelay = 50 * time.Millisecond\n\tc := NewClient(getLogger(t, \"TestConnectInvalidAddress\"), \"guest\", \"guest\", \"localhost:56720\")\n\terr := c.Connect()\n\tdefer c.Disconnect()\n\ta.So(err, ShouldNotBeNil)\n}\n\nfunc TestIsConnected(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestIsConnected\"), \"guest\", \"guest\", host)\n\n\ta.So(c.IsConnected(), ShouldBeFalse)\n\n\tc.Connect()\n\tdefer c.Disconnect()\n\n\ta.So(c.IsConnected(), ShouldBeTrue)\n}\n\nfunc TestDisconnect(t *testing.T) {\n\ta := New(t)\n\tc := NewClient(getLogger(t, \"TestDisconnect\"), \"guest\", \"guest\", host)\n\n\t\/\/ Disconnecting when not connected should not change anything\n\tc.Disconnect()\n\ta.So(c.IsConnected(), ShouldBeFalse)\n\n\tc.Connect()\n\tdefer c.Disconnect()\n\tc.Disconnect()\n\n\ta.So(c.IsConnected(), ShouldBeFalse)\n}\n\nfunc TestReopenChannelClient(t *testing.T) {\n\ta := New(t)\n\tctx := getLogger(t, \"TestReopenChannelClient\")\n\tc := NewClient(ctx, \"guest\", \"guest\", host).(*DefaultClient)\n\tclosed, err := c.connect(false)\n\ta.So(err, ShouldBeNil)\n\tdefer c.Disconnect()\n\n\tpublisher := c.NewPublisher(\"amq.topic\")\n\terr = publisher.Open()\n\ta.So(err, ShouldBeNil)\n\tdefer publisher.Close()\n\n\tsubscriber := c.NewSubscriber(\"amq.topic\", \"\", false, true)\n\terr = subscriber.Open()\n\ta.So(err, ShouldBeNil)\n\tdefer subscriber.Close()\n\n\twg := sync.WaitGroup{}\n\terr = subscriber.SubscribeDownlink(func(_ Subscriber, appID string, _ string, _ types.DownlinkMessage) {\n\t\ta.So(appID, ShouldEqual, \"app\")\n\t\tctx.Debugf(\"Got downlink message\")\n\t\twg.Done()\n\t})\n\ta.So(err, ShouldBeNil)\n\n\ttest := func() error {\n\t\tctx.Debug(\"Testing publish\")\n\t\treturn publisher.PublishDownlink(types.DownlinkMessage{\n\t\t\tAppID: \"app\",\n\t\t})\n\t}\n\n\t\/\/ First attempt should be OK\n\twg.Add(1)\n\terr = test()\n\ta.So(err, ShouldBeNil)\n\twg.Wait()\n\n\t\/\/ Make sure that the old channel is closed\n\tpublisher.(*DefaultPublisher).channel.Close()\n\n\t\/\/ Simulate a connection close so a new channel should be opened\n\tclosed <- AMQP.ErrClosed\n\n\t\/\/ Give the reconnect some time\n\ttime.Sleep(100 * time.Millisecond)\n\n\t\/\/ Second attempt should be OK as well and will only work on a new channel\n\terr = test()\n\ta.So(err, ShouldBeNil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/ant0ine\/go-json-rest\/rest\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"bufio\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"net\/http\/httputil\"\n\t\"net\"\n\t\"io\"\n)\n\ntype PassedParams struct {\n\tImage_name string\n\tUsername   string\n\tPassword   string\n\tEmail      string\n\tDockerfile string\n\tTarUrl \t   string\n}\n\ntype PushAuth struct {\n\tUsername      string `json:\"username\"`\n\tPassword      string `json:\"password\"`\n\tServeraddress string `json:\"serveraddress\"`\n\tEmail         string `json:\"email\"`\n}\n\ntype JobID struct {\n\tJobIdentifier string\n}\n\ntype JobStatus struct {\n\tStatus string\n}\n\ntype JobLogs struct {\n\tLogs string\n}\n\ntype StreamCatcher struct {\n\tErrorDetail ErrorCatcher `json:\"errorDetail\"`\n\tStream      string `json:\"stream\"`\n}\n\ntype ErrorCatcher struct {\n\tMessage \tstring `json:\"message\"`\n\tError \t\tstring `json:\"error\"`\n}\n\nfunc main() {\n\n\thandler := rest.ResourceHandler{\n\t\tEnableRelaxedContentType: true,\n\t}\n\n\thandler.SetRoutes(\n\t\t&rest.Route{\"POST\", \"\/api\/v1\/build\", BuildImageFromDockerfile},\n\t\t&rest.Route{\"GET\", \"\/api\/v1\/:jobid\/status\", GetStatusForJobID},\n\t\t&rest.Route{\"GET\", \"\/api\/v1\/:jobid\/logs\", GetLogsForJobID},\n\t)\n\n\t\/\/Use the environment variable PORT, else default.\n\tvar port string\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tport = os.Getenv(\"PORT\")\n\t} else {\n\t\tport = \":8080\"\n\t}\n\thttp.ListenAndServe(port, &handler)\n\n}\n\n\/\/3 steps.  Unpack the jobId that came in.  Open the redis connection and get the right status.  Then write the status back.\nfunc GetStatusForJobID(w rest.ResponseWriter, r *rest.Request) {\n\tjobid := r.PathParam(\"jobid\")\n\n\t\/\/Open a redis connection.  c is type redis.Conn\n\tc := RedisConnection()\n\tdefer c.Close()\n\n\t\/\/First check if the key and field exist.\n\texists, err := redis.Bool(c.Do(\"HEXISTS\", jobid, \"status\")) \n\tif exists == true {\n\t\tvar status JobStatus\n\t\tstatus.Status, err = redis.String(c.Do(\"HGET\", jobid, \"status\"))\n\t\tif err != nil {\n\t\t\trest.Error(w, \"Redis Cache Error\", 404)\n\t\t}\n\t\tw.WriteJson(status)\n\t} else {\n\t\trest.Error(w, \"Jobid doesn't exist in the cache.  Bad request.\", 404)\n\t}\n}\n\n\n\n\/\/3 steps.  Unpack the jobId that came in.  Open the redis connection and get the logs.  Then write the logs back.\nfunc GetLogsForJobID(w rest.ResponseWriter, r *rest.Request) {\n\tjobid := r.PathParam(\"jobid\")\n\n\t\/\/Open a redis connection.  c is type redis.Conn\n\tc := RedisConnection()\n\tdefer c.Close()\n\n\t\/\/First check if the key and field exist.\n\texists, err := redis.Bool(c.Do(\"HEXISTS\", jobid, \"logs\"))\n\tif exists == true {\n\t\tvar logs JobLogs\n\t\tlogs.Logs, err = redis.String(c.Do(\"HGET\", jobid, \"logs\"))\n\t\tif err != nil {\n\t\t\trest.Error(w, \"Redis Cache Error\", 404)\n\t\t}\n\t\tw.WriteJson(logs)\n\t} else {\n\t\trest.Error(w, \"Jobid doesn't exist in the cache.  Bad request.\", 404)\n\t}\n}\n\n\/\/Builds the image in a docker node.\nfunc BuildImageFromDockerfile(w rest.ResponseWriter, r *rest.Request) {\n\n\t\/\/Unpack the params that come in.\n\tpassedParams := PassedParams{}\n\terr := r.DecodeJsonPayload(&passedParams)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\n\tif Validate(passedParams) {\n\t\t\/\/Create a uuid for the specific job.\n\t\tvar jobid JobID\n\t\tjobid.JobIdentifier = JobUUIDString()\n\n\t\t\/\/Open a redis connection.  c is type redis.Conn\n\t\tc := RedisConnection()\n\n\t\t\/\/Set the status to building in the cache.\n\t\tc.Do(\"HSET\", jobid.JobIdentifier, \"status\", \"Building\")\n\n\t\t\/\/Launch a goroutine to build, push, and delete.  Updates the cache as the process goes on.\n\t\tgo BuildPushAndDeleteImage(jobid.JobIdentifier, passedParams, c)\n\n\t\t\/\/Write the jobid back\n\t\tw.WriteJson(jobid)\n\t} else {\n\t\t\/\/Params didn't validate.  Bad Request.\n\t\trest.Error(w, \"Insufficient Information.  Must provide at least an Image Name and a Dockerfile\/Tarurl.\", 400)\n\t}\n\n\n}\n\nfunc BuildPushAndDeleteImage(jobid string, passedParams PassedParams, c redis.Conn) {\n\n\t\/\/Parse the image name if it has a . in it.  Differentiate between private and docker repos.\n\t\/\/Will cut quay.io\/ichaboddee\/ubuntu into quay.io AND ichaboddee\/ubuntu.\n\t\/\/If there is no . in it, then splitImageName[0-1] will be nil.  Code relies on that for logic later.\n\tsplitImageName := make([]string, 2)\n\tif strings.Contains(passedParams.Image_name, \".\") {\n\t\tsplitImageName = strings.SplitN(passedParams.Image_name, \"\/\", 2)\n\t}\n\n\t\/\/Create the post request to build.  Query Param t=image name is the tag.\n\tbuildUrl := (\"\/v1.10\/build?t=\" + passedParams.Image_name)\n\n\t\/\/Open connection to docker and build.  The request will depend on whether a dockerfile was passed or a url to a zip.\n\tdockerDial := Dial()\n\tdockerConnection := httputil.NewClientConn(dockerDial, nil)\n\tbuildReq, err := http.NewRequest(\"POST\", buildUrl, ReaderForInputType(passedParams))\n    buildResponse, err := dockerConnection.Do(buildReq)\n    defer buildResponse.Body.Close()\n\tbuildReader := bufio.NewReader(buildResponse.Body)\n\tif err != nil {\n\t\tc.Do(\"HSET\", jobid, \"status\", err)\n\t\treturn\n\t}\n\n\tvar logsString string\n\t\/\/Loop through.  If stream is there append it to the logsString and update the cache.\n\tfor {\n\t\t\/\/Breaks when there is nothing left to read.\n\t\tline, err := buildReader.ReadBytes('\\r')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\n\t\t\/\/Unmarshal the json in to my structure.\n\t\tvar stream StreamCatcher\n\t\terr = json.Unmarshal(line, &stream)\n\n\t\t\/\/This if catches the error from docker and puts it in logs in the cache, then fails.\n\t\tif stream.ErrorDetail.Message != \"\" {\n\t\t\tbuildLogsSlice := []byte(logsString)\n\t\t\tbuildLogsSlice = append(buildLogsSlice, []byte(stream.ErrorDetail.Message)...)\n\t\t\tlogsString = string(buildLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\t\t\tCacheBuildError := \"Error: \" + stream.ErrorDetail.Message\n\t\t\tc.Do(\"HSET\", jobid, \"status\", CacheBuildError)\n\t\t\treturn\n\t\t}\n\n\t\tif stream.Stream != \"\" {\n\t\t\tbuildLogsSlice := []byte(logsString)\n\t\t\tbuildLogsSlice = append(buildLogsSlice, []byte(stream.Stream)...)\n\t\t\tlogsString = string(buildLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\t\t}\n\t}\n\t\n\t\/\/Update status in the cache, then start the push process.\n\tc.Do(\"HSET\", jobid, \"status\", \"Pushing\")\n\n\tpushUrl := (\"\/v1.10\/images\/\" + passedParams.Image_name + \"\/push\")\n\t\/\/ pushConnection := httputil.NewClientConn(dockerDial, nil)\n\tpushReq, err := http.NewRequest(\"POST\", pushUrl, nil)\n\tpushReq.Header.Add(\"X-Registry-Auth\", StringEncAuth(passedParams, ServerAddress(splitImageName[0])))\n    pushResponse, err := dockerConnection.Do(pushReq)\n\tpushReader := bufio.NewReader(pushResponse.Body)\n\tif err != nil {\n\t\tc.Do(\"HSET\", jobid, \"status\", err)\n\t\treturn\n\t}\n\n\t\/\/Loop through.  Only concerned with catching the error.  Append it to logsString if it exists.\n\tfor {\n\t\t\/\/Breaks when there is nothing left to read.\n\t\tline, err := pushReader.ReadBytes('\\r')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\n\t\t\/\/Unmarshal the json in to my structure.\n\t\tvar stream StreamCatcher\n\t\terr = json.Unmarshal(line, &stream)\n\n\t\t\/\/This if catches the error from docker and puts it in logs and status in the cache, then fails.\n\t\tif stream.ErrorDetail.Message != \"\" {\n\t\t\tpushLogsSlice := []byte(logsString)\n\t\t\tpushLogsSlice = append(pushLogsSlice, []byte(stream.ErrorDetail.Message)...)\n\t\t\tlogsString = string(pushLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\t\t\tCachePushError := \"Error: \" + stream.ErrorDetail.Message\n\t\t\tc.Do(\"HSET\", jobid, \"status\", CachePushError)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/Finished.  Update status in the cache and close.\n\tc.Do(\"HSET\", jobid, \"status\", \"Finished\")\n\tc.Close()\n\n\t\/\/Delete it from the docker node.  Save space.  \n\tdeleteUrl := (\"\/v1.10\/images\/\" + passedParams.Image_name)\n\tdeleteReq, err := http.NewRequest(\"DELETE\", deleteUrl, nil)\n    dockerConnection.Do(deleteReq)\n\tdockerConnection.Close()\n}\n\nfunc Validate(passedParams PassedParams) bool {\n\/\/Must have an image name and either a Dockerfile or TarUrl.\n\tswitch {\n\t\tcase passedParams.Dockerfile == \"\" && passedParams.TarUrl == \"\": \n\t\t\treturn false\n\t\tcase passedParams.Image_name == \"\": \n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t}\n}\n\n\/\/String encode the info required for X-AUTH.  Username, Password, Email, Serveraddress.\nfunc StringEncAuth(passedParams PassedParams, serveraddress string) string {\n\t\/\/Encoder the needed data to pass as the X-RegistryAuth Header\n\tvar data PushAuth\n\tdata.Username = passedParams.Username\n\tdata.Password = passedParams.Password\n\tdata.Email = passedParams.Email\n\tdata.Serveraddress = serveraddress\n\n\tjsonData, err := json.Marshal(data)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tsEnc := base64.StdEncoding.EncodeToString([]byte(jsonData))\n\treturn sEnc\n}\n\n\/\/Essentially docker_node := os.Getenv(\"DOCKER_NODE\") | default_node\nfunc DockerNode() string {\n\n\tvar docker_node string\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tdocker_node = os.Getenv(\"DOCKER_HOST\")\n\t} else {\n\t\tdocker_node = \"http:\/\/127.0.0.1:4243\"\n\t}\n\treturn docker_node\n}\n\n\nfunc Dial() net.Conn {\n\tvar docker_proto string\n\tvar docker_host string\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tdockerHost := os.Getenv(\"DOCKER_HOST\")\n\t\tsplitStrings := strings.SplitN(dockerHost, \":\/\/\", 2)\n\t\tdocker_proto = splitStrings[0]\n\t\tdocker_host = splitStrings[1]\n\t} else {\n\t\tdocker_proto = \"tcp\"\n\t\tdocker_host = \"localhost:4243\"\n\t}\n\n\tdockerDial, err := net.Dial(docker_proto, docker_host)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn dockerDial\n}\n\n\/\/Open a redis connection.\nfunc RedisConnection() redis.Conn {\n\tc, err := redis.Dial(\"tcp\", CachePort())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif os.Getenv(\"CACHE_PASSWORD\") != \"\" {\n\t\tc.Do(\"AUTH\", os.Getenv(\"CACHE_PASSWORD\"))\n\t}\n\n\treturn c\n}\n\n\/\/create a Unique JobID and return it as a string.\nfunc JobUUIDString() string {\n\tuniqueJobId, uuidErr := uuid.NewV4()\n\tif uuidErr != nil {\n\t\tlog.Fatal(uuidErr)\n\t}\n\ts := uniqueJobId.String()\n\treturn s\n\n}\n\n\/\/Env variables can be used to set the CACHE_PORT\nfunc CachePort() string {\n\n\tvar cacheTCPAddress string\n\tif os.Getenv(\"CACHE_1_PORT_6379_TCP_ADDR\") != \"\" {\n\t\tcacheTCPAddress = os.Getenv(\"CACHE_1_PORT_6379_TCP_ADDR\")\n\t} else {\n\t\tcacheTCPAddress = \"\"\n\t}\n\n\tvar cachePort string\n\tif os.Getenv(\"CACHE_1_PORT_6379_TCP_PORT\") != \"\" {\n\t\tcachePort = os.Getenv(\"CACHE_1_PORT_6379_TCP_PORT\")\n\t} else {\n\t\tcachePort = \"6379\"\n\t}\n\treturn cacheTCPAddress + \":\" + cachePort\n}\n\nfunc ServerAddress(privateRepo string) string {\n\n\t\/\/The server address is different for a private repo.\n\tvar serveraddress string\n\tif privateRepo != \"\" {\n\t\tserveraddress = (\"https:\/\/\" + privateRepo + \"\/v1\/\")\n\t} else {\n\t\tserveraddress = \"https:\/\/index.docker.io\/v1\/\"\n\t}\n\treturn serveraddress\n\n}\n\n\/\/Reader will read from either the zip made from the dockerfile passed in or the zip from the url passed in.\nfunc ReaderForInputType(passedParams PassedParams) io.Reader {\n\t\n\tif passedParams.Dockerfile != \"\" {\n\t\treturn TarzipBufferFromDockerfile(passedParams.Dockerfile)\n\t} else {\n\t\treturn ResponseZipFromURL(passedParams.TarUrl)\n\t}\n\n}\n\n\n\/\/URL example = https:\/\/github.com\/tutumcloud\/docker-hello-world\/archive\/v1.0.tar.gz\nfunc ResponseZipFromURL(url string) io.ReadCloser {\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\treturn response.Body\n\n}\n\n\nfunc TarzipBufferFromDockerfile(dockerfile string) *bytes.Buffer {\n\n\t\/\/ Create a buffer to write our archive to.\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ Create a new tar archive.\n\ttw := tar.NewWriter(buf)\n\n\t\/\/ Add the dockerfile to the archive.\n\tvar files = []struct {\n\t\tName, Body string\n\t}{\n\t\t{\"Dockerfile\", dockerfile},\n\t}\n\tfor _, file := range files {\n\t\thdr := &tar.Header{\n\t\t\tName: file.Name,\n\t\t\tSize: int64(len(file.Body)),\n\t\t}\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(file.Body)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/Check the error on Close.\n\tif err := tw.Close(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn buf\n}\n<commit_msg>Fixed the parameter error response code and the failed push error message.<commit_after>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/ant0ine\/go-json-rest\/rest\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"bufio\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"net\/http\/httputil\"\n\t\"net\"\n\t\"io\"\n)\n\ntype PassedParams struct {\n\tImage_name string\n\tUsername   string\n\tPassword   string\n\tEmail      string\n\tDockerfile string\n\tTarUrl \t   string\n}\n\ntype PushAuth struct {\n\tUsername      string `json:\"username\"`\n\tPassword      string `json:\"password\"`\n\tServeraddress string `json:\"serveraddress\"`\n\tEmail         string `json:\"email\"`\n}\n\ntype JobID struct {\n\tJobIdentifier string\n}\n\ntype JobStatus struct {\n\tStatus string\n}\n\ntype JobLogs struct {\n\tLogs string\n}\n\ntype StreamCatcher struct {\n\tErrorDetail ErrorCatcher `json:\"errorDetail\"`\n\tStream      string `json:\"stream\"`\n}\n\ntype ErrorCatcher struct {\n\tMessage \tstring `json:\"message\"`\n\tError \t\tstring `json:\"error\"`\n}\n\nfunc main() {\n\n\thandler := rest.ResourceHandler{\n\t\tEnableRelaxedContentType: true,\n\t}\n\n\thandler.SetRoutes(\n\t\t&rest.Route{\"POST\", \"\/api\/v1\/build\", BuildImageFromDockerfile},\n\t\t&rest.Route{\"GET\", \"\/api\/v1\/:jobid\/status\", GetStatusForJobID},\n\t\t&rest.Route{\"GET\", \"\/api\/v1\/:jobid\/logs\", GetLogsForJobID},\n\t)\n\n\t\/\/Use the environment variable PORT, else default.\n\tvar port string\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tport = os.Getenv(\"PORT\")\n\t} else {\n\t\tport = \":8080\"\n\t}\n\thttp.ListenAndServe(port, &handler)\n\n}\n\n\/\/3 steps.  Unpack the jobId that came in.  Open the redis connection and get the right status.  Then write the status back.\nfunc GetStatusForJobID(w rest.ResponseWriter, r *rest.Request) {\n\tjobid := r.PathParam(\"jobid\")\n\n\t\/\/Open a redis connection.  c is type redis.Conn\n\tc := RedisConnection()\n\tdefer c.Close()\n\n\t\/\/First check if the key and field exist.\n\texists, err := redis.Bool(c.Do(\"HEXISTS\", jobid, \"status\")) \n\tif exists == true {\n\t\tvar status JobStatus\n\t\tstatus.Status, err = redis.String(c.Do(\"HGET\", jobid, \"status\"))\n\t\tif err != nil {\n\t\t\trest.Error(w, \"Redis Cache Error\", 404)\n\t\t}\n\t\tw.WriteJson(status)\n\t} else {\n\t\trest.Error(w, \"Jobid doesn't exist in the cache.  Bad request.\", 404)\n\t}\n}\n\n\n\n\/\/3 steps.  Unpack the jobId that came in.  Open the redis connection and get the logs.  Then write the logs back.\nfunc GetLogsForJobID(w rest.ResponseWriter, r *rest.Request) {\n\tjobid := r.PathParam(\"jobid\")\n\n\t\/\/Open a redis connection.  c is type redis.Conn\n\tc := RedisConnection()\n\tdefer c.Close()\n\n\t\/\/First check if the key and field exist.\n\texists, err := redis.Bool(c.Do(\"HEXISTS\", jobid, \"logs\"))\n\tif exists == true {\n\t\tvar logs JobLogs\n\t\tlogs.Logs, err = redis.String(c.Do(\"HGET\", jobid, \"logs\"))\n\t\tif err != nil {\n\t\t\trest.Error(w, \"Redis Cache Error\", 404)\n\t\t}\n\t\tw.WriteJson(logs)\n\t} else {\n\t\trest.Error(w, \"Jobid doesn't exist in the cache.  Bad request.\", 404)\n\t}\n}\n\n\/\/Builds the image in a docker node.\nfunc BuildImageFromDockerfile(w rest.ResponseWriter, r *rest.Request) {\n\n\t\/\/Unpack the params that come in.\n\tpassedParams := PassedParams{}\n\terr := r.DecodeJsonPayload(&passedParams)\n\tif err != nil {\n\t\trest.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\n\n\tif Validate(passedParams) {\n\t\t\/\/Create a uuid for the specific job.\n\t\tvar jobid JobID\n\t\tjobid.JobIdentifier = JobUUIDString()\n\n\t\t\/\/Open a redis connection.  c is type redis.Conn\n\t\tc := RedisConnection()\n\n\t\t\/\/Set the status to building in the cache.\n\t\tc.Do(\"HSET\", jobid.JobIdentifier, \"status\", \"Building\")\n\n\t\t\/\/Launch a goroutine to build, push, and delete.  Updates the cache as the process goes on.\n\t\tgo BuildPushAndDeleteImage(jobid.JobIdentifier, passedParams, c)\n\n\t\t\/\/Write the jobid back\n\t\tw.WriteJson(jobid)\n\t} else {\n\t\t\/\/Params didn't validate.  Bad Request.\n\t\trest.Error(w, \"Insufficient Information.  Must provide at least an Image Name and a Dockerfile\/Tarurl.\", 400)\n\t}\n\n\n}\n\nfunc BuildPushAndDeleteImage(jobid string, passedParams PassedParams, c redis.Conn) {\n\n\t\/\/Parse the image name if it has a . in it.  Differentiate between private and docker repos.\n\t\/\/Will cut quay.io\/ichaboddee\/ubuntu into quay.io AND ichaboddee\/ubuntu.\n\t\/\/If there is no . in it, then splitImageName[0-1] will be nil.  Code relies on that for logic later.\n\tsplitImageName := make([]string, 2)\n\tif strings.Contains(passedParams.Image_name, \".\") {\n\t\tsplitImageName = strings.SplitN(passedParams.Image_name, \"\/\", 2)\n\t}\n\n\t\/\/Create the post request to build.  Query Param t=image name is the tag.\n\tbuildUrl := (\"\/v1.10\/build?t=\" + passedParams.Image_name)\n\n\t\/\/Open connection to docker and build.  The request will depend on whether a dockerfile was passed or a url to a zip.\n\tdockerDial := Dial()\n\tdockerConnection := httputil.NewClientConn(dockerDial, nil)\n\tbuildReq, err := http.NewRequest(\"POST\", buildUrl, ReaderForInputType(passedParams))\n    buildResponse, err := dockerConnection.Do(buildReq)\n    defer buildResponse.Body.Close()\n\tbuildReader := bufio.NewReader(buildResponse.Body)\n\tif err != nil {\n\t\tc.Do(\"HSET\", jobid, \"status\", err)\n\t\treturn\n\t}\n\n\tvar logsString string\n\t\/\/Loop through.  If stream is there append it to the logsString and update the cache.\n\tfor {\n\t\t\/\/Breaks when there is nothing left to read.\n\t\tline, err := buildReader.ReadBytes('\\r')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\n\t\t\/\/Unmarshal the json in to my structure.\n\t\tvar stream StreamCatcher\n\t\terr = json.Unmarshal(line, &stream)\n\n\t\t\/\/This if catches the error from docker and puts it in logs in the cache, then fails.\n\t\tif stream.ErrorDetail.Message != \"\" {\n\t\t\tbuildLogsSlice := []byte(logsString)\n\t\t\tbuildLogsSlice = append(buildLogsSlice, []byte(stream.ErrorDetail.Message)...)\n\t\t\tlogsString = string(buildLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\n\t\t\tCacheBuildError := \"Failed: \" + stream.ErrorDetail.Message\n\t\t\tc.Do(\"HSET\", jobid, \"status\", CacheBuildError)\n\t\t\treturn\n\t\t}\n\n\t\tif stream.Stream != \"\" {\n\t\t\tbuildLogsSlice := []byte(logsString)\n\t\t\tbuildLogsSlice = append(buildLogsSlice, []byte(stream.Stream)...)\n\t\t\tlogsString = string(buildLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\t\t}\n\t}\n\t\n\t\/\/Update status in the cache, then start the push process.\n\tc.Do(\"HSET\", jobid, \"status\", \"Pushing\")\n\n\tpushUrl := (\"\/v1.10\/images\/\" + passedParams.Image_name + \"\/push\")\n\t\/\/ pushConnection := httputil.NewClientConn(dockerDial, nil)\n\tpushReq, err := http.NewRequest(\"POST\", pushUrl, nil)\n\tpushReq.Header.Add(\"X-Registry-Auth\", StringEncAuth(passedParams, ServerAddress(splitImageName[0])))\n    pushResponse, err := dockerConnection.Do(pushReq)\n\tpushReader := bufio.NewReader(pushResponse.Body)\n\tif err != nil {\n\t\tc.Do(\"HSET\", jobid, \"status\", err)\n\t\treturn\n\t}\n\n\t\/\/Loop through.  Only concerned with catching the error.  Append it to logsString if it exists.\n\tfor {\n\t\t\/\/Breaks when there is nothing left to read.\n\t\tline, err := pushReader.ReadBytes('\\r')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\n\t\t\/\/Unmarshal the json in to my structure.\n\t\tvar stream StreamCatcher\n\t\terr = json.Unmarshal(line, &stream)\n\n\t\t\/\/This if catches the error from docker and puts it in logs and status in the cache, then fails.\n\t\tif stream.ErrorDetail.Message != \"\" {\n\t\t\tpushLogsSlice := []byte(logsString)\n\t\t\tpushLogsSlice = append(pushLogsSlice, []byte(stream.ErrorDetail.Message)...)\n\t\t\tlogsString = string(pushLogsSlice)\n\t\t\tc.Do(\"HSET\", jobid, \"logs\", logsString)\n\t\t\tCachePushError := \"Failed: \" + stream.ErrorDetail.Message\n\t\t\tc.Do(\"HSET\", jobid, \"status\", CachePushError)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/Finished.  Update status in the cache and close.\n\tc.Do(\"HSET\", jobid, \"status\", \"Finished\")\n\tc.Close()\n\n\t\/\/Delete it from the docker node.  Save space.  \n\tdeleteUrl := (\"\/v1.10\/images\/\" + passedParams.Image_name)\n\tdeleteReq, err := http.NewRequest(\"DELETE\", deleteUrl, nil)\n    dockerConnection.Do(deleteReq)\n\tdockerConnection.Close()\n}\n\nfunc Validate(passedParams PassedParams) bool {\n\/\/Must have an image name and either a Dockerfile or TarUrl.\n\tswitch {\n\t\tcase passedParams.Dockerfile == \"\" && passedParams.TarUrl == \"\": \n\t\t\treturn false\n\t\tcase passedParams.Image_name == \"\": \n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t}\n}\n\n\/\/String encode the info required for X-AUTH.  Username, Password, Email, Serveraddress.\nfunc StringEncAuth(passedParams PassedParams, serveraddress string) string {\n\t\/\/Encoder the needed data to pass as the X-RegistryAuth Header\n\tvar data PushAuth\n\tdata.Username = passedParams.Username\n\tdata.Password = passedParams.Password\n\tdata.Email = passedParams.Email\n\tdata.Serveraddress = serveraddress\n\n\tjsonData, err := json.Marshal(data)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tsEnc := base64.StdEncoding.EncodeToString([]byte(jsonData))\n\treturn sEnc\n}\n\n\/\/Essentially docker_node := os.Getenv(\"DOCKER_NODE\") | default_node\nfunc DockerNode() string {\n\n\tvar docker_node string\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tdocker_node = os.Getenv(\"DOCKER_HOST\")\n\t} else {\n\t\tdocker_node = \"http:\/\/127.0.0.1:4243\"\n\t}\n\treturn docker_node\n}\n\n\nfunc Dial() net.Conn {\n\tvar docker_proto string\n\tvar docker_host string\n\tif os.Getenv(\"DOCKER_HOST\") != \"\" {\n\t\tdockerHost := os.Getenv(\"DOCKER_HOST\")\n\t\tsplitStrings := strings.SplitN(dockerHost, \":\/\/\", 2)\n\t\tdocker_proto = splitStrings[0]\n\t\tdocker_host = splitStrings[1]\n\t} else {\n\t\tdocker_proto = \"tcp\"\n\t\tdocker_host = \"localhost:4243\"\n\t}\n\n\tdockerDial, err := net.Dial(docker_proto, docker_host)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn dockerDial\n}\n\n\/\/Open a redis connection.\nfunc RedisConnection() redis.Conn {\n\tc, err := redis.Dial(\"tcp\", CachePort())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif os.Getenv(\"CACHE_PASSWORD\") != \"\" {\n\t\tc.Do(\"AUTH\", os.Getenv(\"CACHE_PASSWORD\"))\n\t}\n\n\treturn c\n}\n\n\/\/create a Unique JobID and return it as a string.\nfunc JobUUIDString() string {\n\tuniqueJobId, uuidErr := uuid.NewV4()\n\tif uuidErr != nil {\n\t\tlog.Fatal(uuidErr)\n\t}\n\ts := uniqueJobId.String()\n\treturn s\n\n}\n\n\/\/Env variables can be used to set the CACHE_PORT\nfunc CachePort() string {\n\n\tvar cacheTCPAddress string\n\tif os.Getenv(\"CACHE_1_PORT_6379_TCP_ADDR\") != \"\" {\n\t\tcacheTCPAddress = os.Getenv(\"CACHE_1_PORT_6379_TCP_ADDR\")\n\t} else {\n\t\tcacheTCPAddress = \"\"\n\t}\n\n\tvar cachePort string\n\tif os.Getenv(\"CACHE_1_PORT_6379_TCP_PORT\") != \"\" {\n\t\tcachePort = os.Getenv(\"CACHE_1_PORT_6379_TCP_PORT\")\n\t} else {\n\t\tcachePort = \"6379\"\n\t}\n\treturn cacheTCPAddress + \":\" + cachePort\n}\n\nfunc ServerAddress(privateRepo string) string {\n\n\t\/\/The server address is different for a private repo.\n\tvar serveraddress string\n\tif privateRepo != \"\" {\n\t\tserveraddress = (\"https:\/\/\" + privateRepo + \"\/v1\/\")\n\t} else {\n\t\tserveraddress = \"https:\/\/index.docker.io\/v1\/\"\n\t}\n\treturn serveraddress\n\n}\n\n\/\/Reader will read from either the zip made from the dockerfile passed in or the zip from the url passed in.\nfunc ReaderForInputType(passedParams PassedParams) io.Reader {\n\t\n\tif passedParams.Dockerfile != \"\" {\n\t\treturn TarzipBufferFromDockerfile(passedParams.Dockerfile)\n\t} else {\n\t\treturn ResponseZipFromURL(passedParams.TarUrl)\n\t}\n\n}\n\n\n\/\/URL example = https:\/\/github.com\/tutumcloud\/docker-hello-world\/archive\/v1.0.tar.gz\nfunc ResponseZipFromURL(url string) io.ReadCloser {\n\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\treturn response.Body\n\n}\n\n\nfunc TarzipBufferFromDockerfile(dockerfile string) *bytes.Buffer {\n\n\t\/\/ Create a buffer to write our archive to.\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ Create a new tar archive.\n\ttw := tar.NewWriter(buf)\n\n\t\/\/ Add the dockerfile to the archive.\n\tvar files = []struct {\n\t\tName, Body string\n\t}{\n\t\t{\"Dockerfile\", dockerfile},\n\t}\n\tfor _, file := range files {\n\t\thdr := &tar.Header{\n\t\t\tName: file.Name,\n\t\t\tSize: int64(len(file.Body)),\n\t\t}\n\t\tif err := tw.WriteHeader(hdr); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tif _, err := tw.Write([]byte(file.Body)); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\t\/\/Check the error on Close.\n\tif err := tw.Close(); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn buf\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>调整输出格式，用字符串保证时间正确以及数据精度<commit_after><|endoftext|>"}
{"text":"<commit_before>package spawn\n\n\/*\nPackage spawn implements methods and interfaces used in downloading and spawning the underlying thrust core binary.\n*\/\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t. \"github.com\/miketheprogrammer\/go-thrust\/common\"\n\t\"github.com\/miketheprogrammer\/go-thrust\/connection\"\n)\n\nconst (\n\tthrustVersion = \"0.7.5\"\n)\n\nvar base string\n\n\/*\nSetBaseDirectory sets the base directory used in the other helper methods\n*\/\nfunc SetBaseDirectory(dir string) error {\n\tif len(dir) == 0 {\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Println(usr.HomeDir)\n\t\tdir = usr.HomeDir\n\t}\n\tdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\tfmt.Println(\"Could not calculate absolute path\", err)\n\t\treturn err\n\t}\n\tbase = dir\n\n\treturn nil\n}\n\n\/*\nThe SpawnThrustCore method is a bootstrap and run method.\nIt will try to detect an installation of thrust, if it cannot find it\nit will download the version of Thrust detailed in the \"common\" package.\nOnce downloaded, it will launch a process.\nGo-Thrust and all *-Thrust packages communicate with Thrust Core via Stdin\/Stdout.\nusing -log=debug as a command switch will give you the most information about what is going on. -log=info will give you notices that stuff is happening.\nAny log level higher than that will output nothing.\n*\/\nfunc Run() {\n\tif Log == nil {\n\t\tInitLogger(\"debug\")\n\t}\n\tif base == \"\" {\n\t\tSetBaseDirectory(\"\") \/\/ Default to usr.homedir.\n\t}\n\n\tthrustExecPath := GetExecutablePath()\n\tif len(thrustExecPath) > 0 {\n\n\t\tif provisioner == nil {\n\t\t\tSetProvisioner(NewThrustProvisioner())\n\t\t}\n\t\tif err := provisioner.Provision(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthrustExecPath = GetExecutablePath()\n\n\t\tLog.Info(\"Attempting to start Thrust Core\")\n\t\tLog.Debug(\"CMD:\", thrustExecPath)\n\t\tcmd := exec.Command(thrustExecPath)\n\t\tcmdIn, e1 := cmd.StdinPipe()\n\t\tcmdOut, e2 := cmd.StdoutPipe()\n\n\t\tif e1 != nil {\n\t\t\tfmt.Println(e1)\n\t\t\tos.Exit(2) \/\/ need to improve exit codes\n\t\t}\n\n\t\tif e2 != nil {\n\t\t\tfmt.Println(e2)\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\tif Log.LogDebug() {\n\t\t\tcmd.Stderr = os.Stdout\n\t\t}\n\n\t\tif err = cmd.Start(); err != nil {\n\t\t\tLog.Emergency(\"Could not start Thrust Core\")\n\t\t\tpanic(\"Thrust Core not started.\")\n\t\t}\n\n\t\tLog.Info(\"Thrust Core started.\")\n\n\t\t\/\/ Setup our Connection.\n\t\tconnection.Stdout = cmdOut\n\t\tconnection.Stdin = cmdIn\n\t\tconnection.ExecCommand = cmd\n\t\tconnection.InitializeThreads()\n\t\treturn\n\t} else {\n\t\tfmt.Println(\"===============WARNING================\")\n\t\tfmt.Println(\"Current operating system not supported\", runtime.GOOS)\n\t\tfmt.Println(\"===============END====================\")\n\t}\n\treturn\n}\n<commit_msg>Fix err not defined in spawn<commit_after>package spawn\n\n\/*\nPackage spawn implements methods and interfaces used in downloading and spawning the underlying thrust core binary.\n*\/\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t. \"github.com\/miketheprogrammer\/go-thrust\/common\"\n\t\"github.com\/miketheprogrammer\/go-thrust\/connection\"\n)\n\nconst (\n\tthrustVersion = \"0.7.5\"\n)\n\nvar base string\n\n\/*\nSetBaseDirectory sets the base directory used in the other helper methods\n*\/\nfunc SetBaseDirectory(dir string) error {\n\tif len(dir) == 0 {\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tfmt.Println(usr.HomeDir)\n\t\tdir = usr.HomeDir\n\t}\n\tdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\tfmt.Println(\"Could not calculate absolute path\", err)\n\t\treturn err\n\t}\n\tbase = dir\n\n\treturn nil\n}\n\n\/*\nThe SpawnThrustCore method is a bootstrap and run method.\nIt will try to detect an installation of thrust, if it cannot find it\nit will download the version of Thrust detailed in the \"common\" package.\nOnce downloaded, it will launch a process.\nGo-Thrust and all *-Thrust packages communicate with Thrust Core via Stdin\/Stdout.\nusing -log=debug as a command switch will give you the most information about what is going on. -log=info will give you notices that stuff is happening.\nAny log level higher than that will output nothing.\n*\/\nfunc Run() {\n\tif Log == nil {\n\t\tInitLogger(\"debug\")\n\t}\n\tif base == \"\" {\n\t\tSetBaseDirectory(\"\") \/\/ Default to usr.homedir.\n\t}\n\n\tthrustExecPath := GetExecutablePath()\n\tif len(thrustExecPath) > 0 {\n\n\t\tif provisioner == nil {\n\t\t\tSetProvisioner(NewThrustProvisioner())\n\t\t}\n\t\tif err := provisioner.Provision(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tthrustExecPath = GetExecutablePath()\n\n\t\tLog.Info(\"Attempting to start Thrust Core\")\n\t\tLog.Debug(\"CMD:\", thrustExecPath)\n\t\tcmd := exec.Command(thrustExecPath)\n\t\tcmdIn, e1 := cmd.StdinPipe()\n\t\tcmdOut, e2 := cmd.StdoutPipe()\n\n\t\tif e1 != nil {\n\t\t\tfmt.Println(e1)\n\t\t\tos.Exit(2) \/\/ need to improve exit codes\n\t\t}\n\n\t\tif e2 != nil {\n\t\t\tfmt.Println(e2)\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\tif Log.LogDebug() {\n\t\t\tcmd.Stderr = os.Stdout\n\t\t}\n\n\t\tif err := cmd.Start(); err != nil {\n\t\t\tLog.Emergency(\"Could not start Thrust Core\")\n\t\t\tpanic(\"Thrust Core not started.\")\n\t\t}\n\n\t\tLog.Info(\"Thrust Core started.\")\n\n\t\t\/\/ Setup our Connection.\n\t\tconnection.Stdout = cmdOut\n\t\tconnection.Stdin = cmdIn\n\t\tconnection.ExecCommand = cmd\n\t\tconnection.InitializeThreads()\n\t\treturn\n\t} else {\n\t\tfmt.Println(\"===============WARNING================\")\n\t\tfmt.Println(\"Current operating system not supported\", runtime.GOOS)\n\t\tfmt.Println(\"===============END====================\")\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package tiff\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/big\"\n)\n\n\/* Field type definitions\nFrom [TIFF6]:\n\t1-12: Field types 1 - 12 are described in [TIFF6].\n\n\t1  = BYTE\t8-bit unsigned integer.\n\t2  = ASCII\t8-bit byte that contains a 7-bit ASCII code; the last byte must be NUL (binary zero).\n\t3  = SHORT\t16-bit (2-byte) unsigned integer.\n\t4  = LONG\t32-bit (4-byte) unsigned integer.\n\t5  = RATIONAL\tTwo LONGs: the first represents the numerator of a fraction; the second, the denominator.\n\t6  = SBYTE\tAn 8-bit signed (twos-complement) integer.\n\t7  = UNDEFINED\tAn 8-bit byte that may contain anything, depending on the definition of the field.\n\t8  = SSHORT\tA 16-bit (2-byte) signed (twos-complement) integer.\n\t9  = SLONG\tA 32-bit (4-byte) signed (twos-complement) integer.\n\t10 = SRATIONAL\tTwo SLONG’s: the first represents the numerator of a fraction, the second the denominator.\n\t11 = FLOAT\tSingle precision (4-byte) IEEE format.\n\t12 = DOUBLE\tDouble precision (8-byte) IEEE format.\nFrom [BIGTIFFDESIGN]:\n\t13-15: Field Type IDs 13 - 15 are mentioned in [BIGTIFFDESIGN], but only\n\t\tto explain why values 13 - 15 were skipped when identifying new\n\t\tField Types for BigTIFF. These are meant to be used with regular\n\t\tTIFF, but were apparently not properly documented prior to the\n\t\tBigTIFF design discussion.\n\n\t13 = IFD\t?? 32-bit unsigned integer offset value ??\n\t14 = UNICODE\t??\n\t15 = COMPLEX\t??\n*\/\n\n\/\/ Default set of Field types.  These are exported for others to use in\n\/\/ registering custom tags.\nvar (\n\tFTByte      = NewFieldType(1, \"BYTE\", 1, false, reprByte)\n\tFTAscii     = NewFieldType(2, \"ASCII\", 1, false, reprASCII)\n\tFTShort     = NewFieldType(3, \"SHORT\", 2, false, reprShort)\n\tFTLong      = NewFieldType(4, \"LONG\", 4, false, reprLong)\n\tFTRational  = NewFieldType(5, \"RATIONAL\", 8, false, reprRational)\n\tFTSByte     = NewFieldType(6, \"SBYTE\", 1, true, reprSByte)\n\tFTUndefined = NewFieldType(7, \"UNDEFINED\", 1, false, reprByte)\n\tFTSShort    = NewFieldType(8, \"SSHORT\", 2, true, reprSShort)\n\tFTSLong     = NewFieldType(9, \"SLONG\", 4, true, reprSLong)\n\tFTSRational = NewFieldType(10, \"SRATIONAL\", 8, true, reprSRational)\n\tFTFloat     = NewFieldType(11, \"FLOAT\", 4, true, reprFloat)\n\tFTDouble    = NewFieldType(12, \"DOUBLE\", 8, true, reprDouble)\n\tFTIFD       = NewFieldType(13, \"IFD\", 4, false, reprLong)\n\tFTUnicode   = NewFieldType(14, \"UNICODE\", 4, false, nil)\n\tFTComplex   = NewFieldType(15, \"COMPLEX\", 8, true, nil)\n)\n\n\/\/ These functions provide string representations of values based on field types.\nfunc reprByte(in []byte, bo binary.ByteOrder) string   { return fmt.Sprintf(\"%d\", in[0]) }\nfunc reprSByte(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", int8(in[0])) }\nfunc reprASCII(in []byte, bo binary.ByteOrder) string  { return string(in) }\nfunc reprShort(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", bo.Uint16(in)) }\nfunc reprSShort(in []byte, bo binary.ByteOrder) string { return fmt.Sprintf(\"%d\", int16(bo.Uint16(in))) }\nfunc reprLong(in []byte, bo binary.ByteOrder) string   { return fmt.Sprintf(\"%d\", bo.Uint32(in)) }\nfunc reprSLong(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", int32(bo.Uint32(in))) }\nfunc reprRational(in []byte, bo binary.ByteOrder) string {\n\treturn big.NewRat(int64(bo.Uint32(in)), int64(bo.Uint32(in[4:]))).String()\n}\nfunc reprSRational(in []byte, bo binary.ByteOrder) string {\n\treturn big.NewRat(int64(int32(bo.Uint32(in))), int64(int32(bo.Uint32(in[4:])))).String()\n}\nfunc reprFloat(in []byte, bo binary.ByteOrder) string {\n\treturn fmt.Sprintf(\"%f\", math.Float32frombits(bo.Uint32(in)))\n}\nfunc reprDouble(in []byte, bo binary.ByteOrder) string {\n\treturn fmt.Sprintf(\"%f\", math.Float64frombits(bo.Uint64(in)))\n}\n\n\/\/ DefaultFieldTypeSet is the default set of field types supported by this\n\/\/ package.  A user is free to create their own FieldTypeSet from which to\n\/\/ support extended functionality or to provide a substitute representation for\n\/\/ known types.  Most users will be fine with the default set defined here.\nvar DefaultFieldTypeSet = NewFieldTypeSet(\"Default\")\n\nfunc init() {\n\tDefaultFieldTypeSet.Register(FTByte)\n\tDefaultFieldTypeSet.Register(FTAscii)\n\tDefaultFieldTypeSet.Register(FTShort)\n\tDefaultFieldTypeSet.Register(FTLong)\n\tDefaultFieldTypeSet.Register(FTRational)\n\tDefaultFieldTypeSet.Register(FTSByte)\n\tDefaultFieldTypeSet.Register(FTUndefined)\n\tDefaultFieldTypeSet.Register(FTSShort)\n\tDefaultFieldTypeSet.Register(FTSLong)\n\tDefaultFieldTypeSet.Register(FTSRational)\n\tDefaultFieldTypeSet.Register(FTFloat)\n\tDefaultFieldTypeSet.Register(FTDouble)\n\tDefaultFieldTypeSet.Register(FTIFD)\n\tDefaultFieldTypeSet.Register(FTUnicode)\n\tDefaultFieldTypeSet.Register(FTComplex)\n\n\t\/\/ Prevent further registration in the DefaultFieldTypeSet.  Others should\n\t\/\/ add to the DefaultFieldTypeSpace instead of the core set.\n\tDefaultFieldTypeSet.Lock()\n\n\tDefaultFieldTypeSpace.RegisterFieldTypeSet(DefaultFieldTypeSet)\n}\n<commit_msg>Change how Rational and SRational are printed in their representation functions to prevent divide by 0 panics<commit_after>package tiff\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"math\"\n)\n\n\/* Field type definitions\nFrom [TIFF6]:\n\t1-12: Field types 1 - 12 are described in [TIFF6].\n\n\t1  = BYTE\t8-bit unsigned integer.\n\t2  = ASCII\t8-bit byte that contains a 7-bit ASCII code; the last byte must be NUL (binary zero).\n\t3  = SHORT\t16-bit (2-byte) unsigned integer.\n\t4  = LONG\t32-bit (4-byte) unsigned integer.\n\t5  = RATIONAL\tTwo LONGs: the first represents the numerator of a fraction; the second, the denominator.\n\t6  = SBYTE\tAn 8-bit signed (twos-complement) integer.\n\t7  = UNDEFINED\tAn 8-bit byte that may contain anything, depending on the definition of the field.\n\t8  = SSHORT\tA 16-bit (2-byte) signed (twos-complement) integer.\n\t9  = SLONG\tA 32-bit (4-byte) signed (twos-complement) integer.\n\t10 = SRATIONAL\tTwo SLONG’s: the first represents the numerator of a fraction, the second the denominator.\n\t11 = FLOAT\tSingle precision (4-byte) IEEE format.\n\t12 = DOUBLE\tDouble precision (8-byte) IEEE format.\nFrom [BIGTIFFDESIGN]:\n\t13-15: Field Type IDs 13 - 15 are mentioned in [BIGTIFFDESIGN], but only\n\t\tto explain why values 13 - 15 were skipped when identifying new\n\t\tField Types for BigTIFF. These are meant to be used with regular\n\t\tTIFF, but were apparently not properly documented prior to the\n\t\tBigTIFF design discussion.\n\n\t13 = IFD\t?? 32-bit unsigned integer offset value ??\n\t14 = UNICODE\t??\n\t15 = COMPLEX\t??\n*\/\n\n\/\/ Default set of Field types.  These are exported for others to use in\n\/\/ registering custom tags.\nvar (\n\tFTByte      = NewFieldType(1, \"BYTE\", 1, false, reprByte)\n\tFTAscii     = NewFieldType(2, \"ASCII\", 1, false, reprASCII)\n\tFTShort     = NewFieldType(3, \"SHORT\", 2, false, reprShort)\n\tFTLong      = NewFieldType(4, \"LONG\", 4, false, reprLong)\n\tFTRational  = NewFieldType(5, \"RATIONAL\", 8, false, reprRational)\n\tFTSByte     = NewFieldType(6, \"SBYTE\", 1, true, reprSByte)\n\tFTUndefined = NewFieldType(7, \"UNDEFINED\", 1, false, reprByte)\n\tFTSShort    = NewFieldType(8, \"SSHORT\", 2, true, reprSShort)\n\tFTSLong     = NewFieldType(9, \"SLONG\", 4, true, reprSLong)\n\tFTSRational = NewFieldType(10, \"SRATIONAL\", 8, true, reprSRational)\n\tFTFloat     = NewFieldType(11, \"FLOAT\", 4, true, reprFloat)\n\tFTDouble    = NewFieldType(12, \"DOUBLE\", 8, true, reprDouble)\n\tFTIFD       = NewFieldType(13, \"IFD\", 4, false, reprLong)\n\tFTUnicode   = NewFieldType(14, \"UNICODE\", 4, false, nil)\n\tFTComplex   = NewFieldType(15, \"COMPLEX\", 8, true, nil)\n)\n\n\/\/ These functions provide string representations of values based on field types.\nfunc reprByte(in []byte, bo binary.ByteOrder) string   { return fmt.Sprintf(\"%d\", in[0]) }\nfunc reprSByte(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", int8(in[0])) }\nfunc reprASCII(in []byte, bo binary.ByteOrder) string  { return string(in) }\nfunc reprShort(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", bo.Uint16(in)) }\nfunc reprSShort(in []byte, bo binary.ByteOrder) string { return fmt.Sprintf(\"%d\", int16(bo.Uint16(in))) }\nfunc reprLong(in []byte, bo binary.ByteOrder) string   { return fmt.Sprintf(\"%d\", bo.Uint32(in)) }\nfunc reprSLong(in []byte, bo binary.ByteOrder) string  { return fmt.Sprintf(\"%d\", int32(bo.Uint32(in))) }\nfunc reprRational(in []byte, bo binary.ByteOrder) string {\n\t\/\/ Print the representation directly to prevent panics from divide by\n\t\/\/ zero errors when using big.NewRat().\n\treturn fmt.Sprintf(\"%d\/%d\", int64(bo.Uint32(in)), int64(bo.Uint32(in[4:])))\n}\nfunc reprSRational(in []byte, bo binary.ByteOrder) string {\n\t\/\/ Print the representation directly to prevent panics from divide by\n\t\/\/ zero errors when using big.NewRat()\n\treturn fmt.Sprintf(\"%d\/%d\", int64(int32(bo.Uint32(in))), int64(int32(bo.Uint32(in[4:]))))\n}\nfunc reprFloat(in []byte, bo binary.ByteOrder) string {\n\treturn fmt.Sprintf(\"%f\", math.Float32frombits(bo.Uint32(in)))\n}\nfunc reprDouble(in []byte, bo binary.ByteOrder) string {\n\treturn fmt.Sprintf(\"%f\", math.Float64frombits(bo.Uint64(in)))\n}\n\n\/\/ DefaultFieldTypeSet is the default set of field types supported by this\n\/\/ package.  A user is free to create their own FieldTypeSet from which to\n\/\/ support extended functionality or to provide a substitute representation for\n\/\/ known types.  Most users will be fine with the default set defined here.\nvar DefaultFieldTypeSet = NewFieldTypeSet(\"Default\")\n\nfunc init() {\n\tDefaultFieldTypeSet.Register(FTByte)\n\tDefaultFieldTypeSet.Register(FTAscii)\n\tDefaultFieldTypeSet.Register(FTShort)\n\tDefaultFieldTypeSet.Register(FTLong)\n\tDefaultFieldTypeSet.Register(FTRational)\n\tDefaultFieldTypeSet.Register(FTSByte)\n\tDefaultFieldTypeSet.Register(FTUndefined)\n\tDefaultFieldTypeSet.Register(FTSShort)\n\tDefaultFieldTypeSet.Register(FTSLong)\n\tDefaultFieldTypeSet.Register(FTSRational)\n\tDefaultFieldTypeSet.Register(FTFloat)\n\tDefaultFieldTypeSet.Register(FTDouble)\n\tDefaultFieldTypeSet.Register(FTIFD)\n\tDefaultFieldTypeSet.Register(FTUnicode)\n\tDefaultFieldTypeSet.Register(FTComplex)\n\n\t\/\/ Prevent further registration in the DefaultFieldTypeSet.  Others should\n\t\/\/ add to the DefaultFieldTypeSpace instead of the core set.\n\tDefaultFieldTypeSet.Lock()\n\n\tDefaultFieldTypeSpace.RegisterFieldTypeSet(DefaultFieldTypeSet)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"os\"\n\t\"fmt\"\n)\n\nvar executable = flag.String(\"executable\", \"\", \"name of the app executable\")\nvar destination = flag.String(\"destination\", \"\", \"where to put the executable deps\")\n\nvar knownDeps = []string{\n\t\"libQt\",\n\t\"libPoco\",\n\t\"libbugsnag\",\n\t\"libTogglDesktop\",\n\t\"libicu\",\n\t\"libjson\",\n\t\"libssl\",\n\t\"libcrypto\",\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(*executable) == 0 {\n\t\tfmt.Println(\"executable parameter is required\")\n\t\tos.Exit(1)\n\t}\n\tif len(*destination) == 0 {\n\t\tfmt.Println(\"destination parameter is required\")\n\t\tos.Exit(1)\n\t}\n\n\tb, err := exec.Command(\"ldd\", *executable).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Println(err, string(b))\n\t\tos.Exit(1)\n\t}\n\n\tdeps := strings.Split(string(b), \"\\n\")\n\n\tfmt.Println(len(deps), \"dependencies found\")\n\n\tfor _, s := range deps {\n\t\tif !strings.Contains(s, \"=>\") {\n\t\t\tcontinue\n\t\t}\n\t\tname := strings.Split(s, \"=> \")[1]\n\t\tname = strings.Split(name, \" (\")[0]\n\t\tif len(name) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name == \"not found\" {\n\t\t\tfmt.Println(s)\n\t\t\tfmt.Println(\"Library dependency not found\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\t\n\t\trequired := false\n\t\tfor _, depName := range knownDeps {\n\t\t\tif strings.Contains(name, depName) {\n\t\t\t\trequired = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !required {\n\t\t\tcontinue\n\t\t}\n\t\t_, err := exec.Command(\"cp\", name, *destination).CombinedOutput()\n\t\tif err != nil {\n\t\t\tfmt.Println(err, string(b))\n\t\t\tfmt.Println(\"cp subcommand failed\")\n\t\t\tfmt.Println(\"cp\", name, *destination)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tfmt.Println(len(deps), \"dependencies copied\")\n\n\tos.Exit(0)\n}\n<commit_msg>Copy libxcb dependencies (linux)<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"os\"\n\t\"fmt\"\n)\n\nvar executable = flag.String(\"executable\", \"\", \"name of the app executable\")\nvar destination = flag.String(\"destination\", \"\", \"where to put the executable deps\")\n\nvar knownDeps = []string{\n\t\"libQt\",\n\t\"libPoco\",\n\t\"libbugsnag\",\n\t\"libTogglDesktop\",\n\t\"libicu\",\n\t\"libjson\",\n\t\"libssl\",\n\t\"libcrypto\",\n\t\"libxcb\",\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(*executable) == 0 {\n\t\tfmt.Println(\"executable parameter is required\")\n\t\tos.Exit(1)\n\t}\n\tif len(*destination) == 0 {\n\t\tfmt.Println(\"destination parameter is required\")\n\t\tos.Exit(1)\n\t}\n\n\tb, err := exec.Command(\"ldd\", *executable).CombinedOutput()\n\tif err != nil {\n\t\tfmt.Println(err, string(b))\n\t\tos.Exit(1)\n\t}\n\n\tdeps := strings.Split(string(b), \"\\n\")\n\n\tfmt.Println(len(deps), \"dependencies found\")\n\n\tcopied := 0\n\n\tfor _, s := range deps {\n\t\tif !strings.Contains(s, \"=>\") {\n\t\t\tcontinue\n\t\t}\n\t\tname := strings.Split(s, \"=> \")[1]\n\t\tname = strings.Split(name, \" (\")[0]\n\t\tif len(name) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif name == \"not found\" {\n\t\t\tfmt.Println(s)\n\t\t\tfmt.Println(\"Library dependency not found\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\t\n\t\trequired := false\n\t\tfor _, depName := range knownDeps {\n\t\t\tif strings.Contains(name, depName) {\n\t\t\t\trequired = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !required {\n\t\t\tcontinue\n\t\t}\n\t\tcopied += 1\n\t\t_, err := exec.Command(\"cp\", name, *destination).CombinedOutput()\n\t\tif err != nil {\n\t\t\tfmt.Println(err, string(b))\n\t\t\tfmt.Println(\"cp subcommand failed\")\n\t\t\tfmt.Println(\"cp\", name, *destination)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tfmt.Println(copied, \"dependencies copied\")\n\n\tos.Exit(0)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 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 cloud\n\nimport (\n\t\"google.golang.org\/cloud\/datastore\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ Use installs the cloud services implementation into the supplied Context.\n\/\/\n\/\/ This includes:\n\/\/\t- github.com\/luci\/gae\/service\/info\n\/\/\t- github.com\/luci\/gae\/service\/datastore\n\/\/\n\/\/ This is built around the ability to use cloud datastore.\nfunc Use(c context.Context, client *datastore.Client) context.Context {\n\tcds := cloudDatastore{\n\t\tclient: client,\n\t}\n\n\treturn cds.use(useInfo(c))\n}\n<commit_msg>Add an option to install just Cloud Datastore.<commit_after>\/\/ Copyright 2016 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 cloud\n\nimport (\n\t\"google.golang.org\/cloud\/datastore\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ Use installs the cloud services implementation into the supplied Context.\n\/\/\n\/\/ This includes:\n\/\/\t- github.com\/luci\/gae\/service\/info\n\/\/\t- github.com\/luci\/gae\/service\/datastore\n\/\/\n\/\/ This is built around the ability to use cloud datastore.\nfunc Use(c context.Context, client *datastore.Client) context.Context {\n\treturn UseDS(useInfo(c), client)\n}\n\n\/\/ UseDS installs the cloud datastore implementation into the supplied Context.\nfunc UseDS(c context.Context, client *datastore.Client) context.Context {\n\tcds := cloudDatastore{\n\t\tclient: client,\n\t}\n\treturn cds.use(c)\n}\n<|endoftext|>"}
{"text":"<commit_before>package bridge\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/libnetwork\/iptables\"\n\t\"github.com\/docker\/libnetwork\/netutils\"\n)\n\n\/\/ DockerChain: DOCKER iptable chain name\nconst (\n\tDockerChain    = \"DOCKER\"\n\tIsolationChain = \"DOCKER-ISOLATION\"\n)\n\nfunc setupIPChains(config *configuration) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) {\n\t\/\/ Sanity check.\n\tif config.EnableIPTables == false {\n\t\treturn nil, nil, nil, fmt.Errorf(\"cannot create new chains, EnableIPTable is disabled\")\n\t}\n\n\thairpinMode := !config.EnableUserlandProxy\n\n\tnatChain, err := iptables.NewChain(DockerChain, iptables.Nat, hairpinMode)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create NAT chain: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {\n\t\t\t\tlogrus.Warnf(\"failed on removing iptables NAT chain on cleanup: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfilterChain, err := iptables.NewChain(DockerChain, iptables.Filter, false)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create FILTER chain: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := iptables.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {\n\t\t\t\tlogrus.Warnf(\"failed on removing iptables FILTER chain on cleanup: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tisolationChain, err := iptables.NewChain(IsolationChain, iptables.Filter, false)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create FILTER isolation chain: %v\", err)\n\t}\n\n\tif err := addReturnRule(IsolationChain); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn natChain, filterChain, isolationChain, nil\n}\n\nfunc (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInterface) error {\n\td := n.driver\n\td.Lock()\n\tdriverConfig := d.config\n\td.Unlock()\n\n\t\/\/ Sanity check.\n\tif driverConfig.EnableIPTables == false {\n\t\treturn fmt.Errorf(\"Cannot program chains, EnableIPTable is disabled\")\n\t}\n\n\t\/\/ Pickup this configuraton option from driver\n\thairpinMode := !driverConfig.EnableUserlandProxy\n\n\taddrv4, _, err := netutils.GetIfaceAddr(config.BridgeName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to setup IP tables, cannot acquire Interface address: %s\", err.Error())\n\t}\n\tipnet := addrv4.(*net.IPNet)\n\tmaskedAddrv4 := &net.IPNet{\n\t\tIP:   ipnet.IP.Mask(ipnet.Mask),\n\t\tMask: ipnet.Mask,\n\t}\n\tif config.Internal {\n\t\tif err = setupInternalNetworkRules(config.BridgeName, maskedAddrv4, true); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to Setup IP tables: %s\", err.Error())\n\t\t}\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn setupInternalNetworkRules(config.BridgeName, maskedAddrv4, false)\n\t\t})\n\t} else {\n\t\tif err = setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to Setup IP tables: %s\", err.Error())\n\t\t}\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)\n\t\t})\n\t\tnatChain, filterChain, _, err := n.getDriverChains()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to setup IP tables, cannot acquire chain info %s\", err.Error())\n\t\t}\n\n\t\terr = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to program NAT chain: %s\", err.Error())\n\t\t}\n\n\t\terr = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to program FILTER chain: %s\", err.Error())\n\t\t}\n\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)\n\t\t})\n\n\t\tn.portMapper.SetIptablesChain(filterChain, n.getNetworkBridgeName())\n\t}\n\n\tif err := ensureJumpRule(\"FORWARD\", IsolationChain); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\ntype iptRule struct {\n\ttable   iptables.Table\n\tchain   string\n\tpreArgs []string\n\targs    []string\n}\n\nfunc setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {\n\n\tvar (\n\t\taddress   = addr.String()\n\t\tnatRule   = iptRule{table: iptables.Nat, chain: \"POSTROUTING\", preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-s\", address, \"!\", \"-o\", bridgeIface, \"-j\", \"MASQUERADE\"}}\n\t\thpNatRule = iptRule{table: iptables.Nat, chain: \"POSTROUTING\", preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-m\", \"addrtype\", \"--src-type\", \"LOCAL\", \"-o\", bridgeIface, \"-j\", \"MASQUERADE\"}}\n\t\tskipDNAT  = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-i\", bridgeIface, \"-j\", \"RETURN\"}}\n\t\toutRule   = iptRule{table: iptables.Filter, chain: \"FORWARD\", args: []string{\"-i\", bridgeIface, \"!\", \"-o\", bridgeIface, \"-j\", \"ACCEPT\"}}\n\t\tinRule    = iptRule{table: iptables.Filter, chain: \"FORWARD\", args: []string{\"-o\", bridgeIface, \"-m\", \"conntrack\", \"--ctstate\", \"RELATED,ESTABLISHED\", \"-j\", \"ACCEPT\"}}\n\t)\n\n\t\/\/ Set NAT.\n\tif ipmasq {\n\t\tif err := programChainRule(natRule, \"NAT\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := programChainRule(skipDNAT, \"SKIP DNAT\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ In hairpin mode, masquerade traffic from localhost\n\tif hairpin {\n\t\tif err := programChainRule(hpNatRule, \"MASQ LOCAL HOST\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Set Inter Container Communication.\n\tif err := setIcc(bridgeIface, icc, enable); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set Accept on all non-intercontainer outgoing packets.\n\tif err := programChainRule(outRule, \"ACCEPT NON_ICC OUTGOING\", enable); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set Accept on incoming packets for existing connections.\n\tif err := programChainRule(inRule, \"ACCEPT INCOMING\", enable); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc programChainRule(rule iptRule, ruleDescr string, insert bool) error {\n\tvar (\n\t\tprefix    []string\n\t\toperation string\n\t\tcondition bool\n\t\tdoesExist = iptables.Exists(rule.table, rule.chain, rule.args...)\n\t)\n\n\tif insert {\n\t\tcondition = !doesExist\n\t\tprefix = []string{\"-I\", rule.chain}\n\t\toperation = \"enable\"\n\t} else {\n\t\tcondition = doesExist\n\t\tprefix = []string{\"-D\", rule.chain}\n\t\toperation = \"disable\"\n\t}\n\tif rule.preArgs != nil {\n\t\tprefix = append(rule.preArgs, prefix...)\n\t}\n\n\tif condition {\n\t\tif err := iptables.RawCombinedOutput(append(prefix, rule.args...)...); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to %s %s rule: %s\", operation, ruleDescr, err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc setIcc(bridgeIface string, iccEnable, insert bool) error {\n\tvar (\n\t\ttable      = iptables.Filter\n\t\tchain      = \"FORWARD\"\n\t\targs       = []string{\"-i\", bridgeIface, \"-o\", bridgeIface, \"-j\"}\n\t\tacceptArgs = append(args, \"ACCEPT\")\n\t\tdropArgs   = append(args, \"DROP\")\n\t)\n\n\tif insert {\n\t\tif !iccEnable {\n\t\t\tiptables.Raw(append([]string{\"-D\", chain}, acceptArgs...)...)\n\n\t\t\tif !iptables.Exists(table, chain, dropArgs...) {\n\t\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-A\", chain}, dropArgs...)...); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Unable to prevent intercontainer communication: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tiptables.Raw(append([]string{\"-D\", chain}, dropArgs...)...)\n\n\t\t\tif !iptables.Exists(table, chain, acceptArgs...) {\n\t\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, acceptArgs...)...); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Unable to allow intercontainer communication: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ Remove any ICC rule.\n\t\tif !iccEnable {\n\t\t\tif iptables.Exists(table, chain, dropArgs...) {\n\t\t\t\tiptables.Raw(append([]string{\"-D\", chain}, dropArgs...)...)\n\t\t\t}\n\t\t} else {\n\t\t\tif iptables.Exists(table, chain, acceptArgs...) {\n\t\t\t\tiptables.Raw(append([]string{\"-D\", chain}, acceptArgs...)...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Control Inter Network Communication. Install\/remove only if it is not\/is present.\nfunc setINC(iface1, iface2 string, enable bool) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\tchain = IsolationChain\n\t\targs  = [2][]string{{\"-i\", iface1, \"-o\", iface2, \"-j\", \"DROP\"}, {\"-i\", iface2, \"-o\", iface1, \"-j\", \"DROP\"}}\n\t)\n\n\tif enable {\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tif iptables.Exists(table, chain, args[i]...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, args[i]...)...); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to add inter-network communication rule: %v\", err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tif !iptables.Exists(table, chain, args[i]...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-D\", chain}, args[i]...)...); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to remove inter-network communication rule: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc addReturnRule(chain string) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\targs  = []string{\"-j\", \"RETURN\"}\n\t)\n\n\tif iptables.Exists(table, chain, args...) {\n\t\treturn nil\n\t}\n\n\terr := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, args...)...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to add return rule in %s chain: %s\", chain, err.Error())\n\t}\n\n\treturn nil\n}\n\n\/\/ Ensure the jump rule is on top\nfunc ensureJumpRule(fromChain, toChain string) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\targs  = []string{\"-j\", toChain}\n\t)\n\n\tif iptables.Exists(table, fromChain, args...) {\n\t\terr := iptables.RawCombinedOutput(append([]string{\"-D\", fromChain}, args...)...)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to remove jump to %s rule in %s chain: %s\", toChain, fromChain, err.Error())\n\t\t}\n\t}\n\n\terr := iptables.RawCombinedOutput(append([]string{\"-I\", fromChain}, args...)...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to insert jump to %s rule in %s chain: %s\", toChain, fromChain, err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc removeIPChains() {\n\tfor _, chainInfo := range []iptables.ChainInfo{\n\t\t{Name: DockerChain, Table: iptables.Nat},\n\t\t{Name: DockerChain, Table: iptables.Filter},\n\t\t{Name: IsolationChain, Table: iptables.Filter},\n\t} {\n\t\tif err := chainInfo.Remove(); err != nil {\n\t\t\tlogrus.Warnf(\"Failed to remove existing iptables entries in table %s chain %s : %v\", chainInfo.Table, chainInfo.Name, err)\n\t\t}\n\t}\n}\n\nfunc setupInternalNetworkRules(bridgeIface string, addr net.Addr, insert bool) error {\n\tvar (\n\t\tinDropRule  = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{\"-i\", bridgeIface, \"!\", \"-d\", addr.String(), \"-j\", \"DROP\"}}\n\t\toutDropRule = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{\"-o\", bridgeIface, \"!\", \"-s\", addr.String(), \"-j\", \"DROP\"}}\n\t)\n\tif err := programChainRule(inDropRule, \"DROP INCOMING\", insert); err != nil {\n\t\treturn err\n\t}\n\tif err := programChainRule(outDropRule, \"DROP OUTGOING\", insert); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Register natChain with portmapper<commit_after>package bridge\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/libnetwork\/iptables\"\n\t\"github.com\/docker\/libnetwork\/netutils\"\n)\n\n\/\/ DockerChain: DOCKER iptable chain name\nconst (\n\tDockerChain    = \"DOCKER\"\n\tIsolationChain = \"DOCKER-ISOLATION\"\n)\n\nfunc setupIPChains(config *configuration) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) {\n\t\/\/ Sanity check.\n\tif config.EnableIPTables == false {\n\t\treturn nil, nil, nil, fmt.Errorf(\"cannot create new chains, EnableIPTable is disabled\")\n\t}\n\n\thairpinMode := !config.EnableUserlandProxy\n\n\tnatChain, err := iptables.NewChain(DockerChain, iptables.Nat, hairpinMode)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create NAT chain: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {\n\t\t\t\tlogrus.Warnf(\"failed on removing iptables NAT chain on cleanup: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfilterChain, err := iptables.NewChain(DockerChain, iptables.Filter, false)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create FILTER chain: %v\", err)\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif err := iptables.RemoveExistingChain(DockerChain, iptables.Filter); err != nil {\n\t\t\t\tlogrus.Warnf(\"failed on removing iptables FILTER chain on cleanup: %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tisolationChain, err := iptables.NewChain(IsolationChain, iptables.Filter, false)\n\tif err != nil {\n\t\treturn nil, nil, nil, fmt.Errorf(\"failed to create FILTER isolation chain: %v\", err)\n\t}\n\n\tif err := addReturnRule(IsolationChain); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\treturn natChain, filterChain, isolationChain, nil\n}\n\nfunc (n *bridgeNetwork) setupIPTables(config *networkConfiguration, i *bridgeInterface) error {\n\td := n.driver\n\td.Lock()\n\tdriverConfig := d.config\n\td.Unlock()\n\n\t\/\/ Sanity check.\n\tif driverConfig.EnableIPTables == false {\n\t\treturn fmt.Errorf(\"Cannot program chains, EnableIPTable is disabled\")\n\t}\n\n\t\/\/ Pickup this configuraton option from driver\n\thairpinMode := !driverConfig.EnableUserlandProxy\n\n\taddrv4, _, err := netutils.GetIfaceAddr(config.BridgeName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to setup IP tables, cannot acquire Interface address: %s\", err.Error())\n\t}\n\tipnet := addrv4.(*net.IPNet)\n\tmaskedAddrv4 := &net.IPNet{\n\t\tIP:   ipnet.IP.Mask(ipnet.Mask),\n\t\tMask: ipnet.Mask,\n\t}\n\tif config.Internal {\n\t\tif err = setupInternalNetworkRules(config.BridgeName, maskedAddrv4, true); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to Setup IP tables: %s\", err.Error())\n\t\t}\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn setupInternalNetworkRules(config.BridgeName, maskedAddrv4, false)\n\t\t})\n\t} else {\n\t\tif err = setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, true); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to Setup IP tables: %s\", err.Error())\n\t\t}\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn setupIPTablesInternal(config.BridgeName, maskedAddrv4, config.EnableICC, config.EnableIPMasquerade, hairpinMode, false)\n\t\t})\n\t\tnatChain, filterChain, _, err := n.getDriverChains()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to setup IP tables, cannot acquire chain info %s\", err.Error())\n\t\t}\n\n\t\terr = iptables.ProgramChain(natChain, config.BridgeName, hairpinMode, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to program NAT chain: %s\", err.Error())\n\t\t}\n\n\t\terr = iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, true)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to program FILTER chain: %s\", err.Error())\n\t\t}\n\n\t\tn.registerIptCleanFunc(func() error {\n\t\t\treturn iptables.ProgramChain(filterChain, config.BridgeName, hairpinMode, false)\n\t\t})\n\n\t\tn.portMapper.SetIptablesChain(natChain, n.getNetworkBridgeName())\n\t}\n\n\tif err := ensureJumpRule(\"FORWARD\", IsolationChain); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\ntype iptRule struct {\n\ttable   iptables.Table\n\tchain   string\n\tpreArgs []string\n\targs    []string\n}\n\nfunc setupIPTablesInternal(bridgeIface string, addr net.Addr, icc, ipmasq, hairpin, enable bool) error {\n\n\tvar (\n\t\taddress   = addr.String()\n\t\tnatRule   = iptRule{table: iptables.Nat, chain: \"POSTROUTING\", preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-s\", address, \"!\", \"-o\", bridgeIface, \"-j\", \"MASQUERADE\"}}\n\t\thpNatRule = iptRule{table: iptables.Nat, chain: \"POSTROUTING\", preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-m\", \"addrtype\", \"--src-type\", \"LOCAL\", \"-o\", bridgeIface, \"-j\", \"MASQUERADE\"}}\n\t\tskipDNAT  = iptRule{table: iptables.Nat, chain: DockerChain, preArgs: []string{\"-t\", \"nat\"}, args: []string{\"-i\", bridgeIface, \"-j\", \"RETURN\"}}\n\t\toutRule   = iptRule{table: iptables.Filter, chain: \"FORWARD\", args: []string{\"-i\", bridgeIface, \"!\", \"-o\", bridgeIface, \"-j\", \"ACCEPT\"}}\n\t\tinRule    = iptRule{table: iptables.Filter, chain: \"FORWARD\", args: []string{\"-o\", bridgeIface, \"-m\", \"conntrack\", \"--ctstate\", \"RELATED,ESTABLISHED\", \"-j\", \"ACCEPT\"}}\n\t)\n\n\t\/\/ Set NAT.\n\tif ipmasq {\n\t\tif err := programChainRule(natRule, \"NAT\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif ipmasq && !hairpin {\n\t\tif err := programChainRule(skipDNAT, \"SKIP DNAT\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ In hairpin mode, masquerade traffic from localhost\n\tif hairpin {\n\t\tif err := programChainRule(hpNatRule, \"MASQ LOCAL HOST\", enable); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Set Inter Container Communication.\n\tif err := setIcc(bridgeIface, icc, enable); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set Accept on all non-intercontainer outgoing packets.\n\tif err := programChainRule(outRule, \"ACCEPT NON_ICC OUTGOING\", enable); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set Accept on incoming packets for existing connections.\n\tif err := programChainRule(inRule, \"ACCEPT INCOMING\", enable); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc programChainRule(rule iptRule, ruleDescr string, insert bool) error {\n\tvar (\n\t\tprefix    []string\n\t\toperation string\n\t\tcondition bool\n\t\tdoesExist = iptables.Exists(rule.table, rule.chain, rule.args...)\n\t)\n\n\tif insert {\n\t\tcondition = !doesExist\n\t\tprefix = []string{\"-I\", rule.chain}\n\t\toperation = \"enable\"\n\t} else {\n\t\tcondition = doesExist\n\t\tprefix = []string{\"-D\", rule.chain}\n\t\toperation = \"disable\"\n\t}\n\tif rule.preArgs != nil {\n\t\tprefix = append(rule.preArgs, prefix...)\n\t}\n\n\tif condition {\n\t\tif err := iptables.RawCombinedOutput(append(prefix, rule.args...)...); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to %s %s rule: %s\", operation, ruleDescr, err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc setIcc(bridgeIface string, iccEnable, insert bool) error {\n\tvar (\n\t\ttable      = iptables.Filter\n\t\tchain      = \"FORWARD\"\n\t\targs       = []string{\"-i\", bridgeIface, \"-o\", bridgeIface, \"-j\"}\n\t\tacceptArgs = append(args, \"ACCEPT\")\n\t\tdropArgs   = append(args, \"DROP\")\n\t)\n\n\tif insert {\n\t\tif !iccEnable {\n\t\t\tiptables.Raw(append([]string{\"-D\", chain}, acceptArgs...)...)\n\n\t\t\tif !iptables.Exists(table, chain, dropArgs...) {\n\t\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-A\", chain}, dropArgs...)...); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Unable to prevent intercontainer communication: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tiptables.Raw(append([]string{\"-D\", chain}, dropArgs...)...)\n\n\t\t\tif !iptables.Exists(table, chain, acceptArgs...) {\n\t\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, acceptArgs...)...); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Unable to allow intercontainer communication: %s\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ Remove any ICC rule.\n\t\tif !iccEnable {\n\t\t\tif iptables.Exists(table, chain, dropArgs...) {\n\t\t\t\tiptables.Raw(append([]string{\"-D\", chain}, dropArgs...)...)\n\t\t\t}\n\t\t} else {\n\t\t\tif iptables.Exists(table, chain, acceptArgs...) {\n\t\t\t\tiptables.Raw(append([]string{\"-D\", chain}, acceptArgs...)...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Control Inter Network Communication. Install\/remove only if it is not\/is present.\nfunc setINC(iface1, iface2 string, enable bool) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\tchain = IsolationChain\n\t\targs  = [2][]string{{\"-i\", iface1, \"-o\", iface2, \"-j\", \"DROP\"}, {\"-i\", iface2, \"-o\", iface1, \"-j\", \"DROP\"}}\n\t)\n\n\tif enable {\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tif iptables.Exists(table, chain, args[i]...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, args[i]...)...); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to add inter-network communication rule: %v\", err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tif !iptables.Exists(table, chain, args[i]...) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := iptables.RawCombinedOutput(append([]string{\"-D\", chain}, args[i]...)...); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to remove inter-network communication rule: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc addReturnRule(chain string) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\targs  = []string{\"-j\", \"RETURN\"}\n\t)\n\n\tif iptables.Exists(table, chain, args...) {\n\t\treturn nil\n\t}\n\n\terr := iptables.RawCombinedOutput(append([]string{\"-I\", chain}, args...)...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to add return rule in %s chain: %s\", chain, err.Error())\n\t}\n\n\treturn nil\n}\n\n\/\/ Ensure the jump rule is on top\nfunc ensureJumpRule(fromChain, toChain string) error {\n\tvar (\n\t\ttable = iptables.Filter\n\t\targs  = []string{\"-j\", toChain}\n\t)\n\n\tif iptables.Exists(table, fromChain, args...) {\n\t\terr := iptables.RawCombinedOutput(append([]string{\"-D\", fromChain}, args...)...)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to remove jump to %s rule in %s chain: %s\", toChain, fromChain, err.Error())\n\t\t}\n\t}\n\n\terr := iptables.RawCombinedOutput(append([]string{\"-I\", fromChain}, args...)...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to insert jump to %s rule in %s chain: %s\", toChain, fromChain, err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc removeIPChains() {\n\tfor _, chainInfo := range []iptables.ChainInfo{\n\t\t{Name: DockerChain, Table: iptables.Nat},\n\t\t{Name: DockerChain, Table: iptables.Filter},\n\t\t{Name: IsolationChain, Table: iptables.Filter},\n\t} {\n\t\tif err := chainInfo.Remove(); err != nil {\n\t\t\tlogrus.Warnf(\"Failed to remove existing iptables entries in table %s chain %s : %v\", chainInfo.Table, chainInfo.Name, err)\n\t\t}\n\t}\n}\n\nfunc setupInternalNetworkRules(bridgeIface string, addr net.Addr, insert bool) error {\n\tvar (\n\t\tinDropRule  = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{\"-i\", bridgeIface, \"!\", \"-d\", addr.String(), \"-j\", \"DROP\"}}\n\t\toutDropRule = iptRule{table: iptables.Filter, chain: IsolationChain, args: []string{\"-o\", bridgeIface, \"!\", \"-s\", addr.String(), \"-j\", \"DROP\"}}\n\t)\n\tif err := programChainRule(inDropRule, \"DROP INCOMING\", insert); err != nil {\n\t\treturn err\n\t}\n\tif err := programChainRule(outDropRule, \"DROP OUTGOING\", insert); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package game\n\nimport (\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/quad\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n\n\t\"github.com\/ghthor\/gospec\"\n\t. \"github.com\/ghthor\/gospec\"\n)\n\nfunc DescribeCollision(c gospec.Context) {\n\tcell := func(x, y int) coord.Cell { return coord.Cell{x, y} }\n\tpa := func(start, speed int64, origin, dest coord.Cell) *coord.PathAction {\n\t\treturn &coord.PathAction{\n\t\t\tSpan: stime.NewSpan(stime.Time(start), stime.Time(start+speed)),\n\t\t\tOrig: origin,\n\t\t\tDest: dest,\n\t\t}\n\t}\n\n\tc.Specify(\"a collision between\", func() {\n\t\tc.Specify(\"2 actors\", func() {\n\t\t\tc.Specify(\"that are both moving\", func() {\n\t\t\t\tc.Specify(\"in the same direction\", func() {\n\t\t\t\t\tpa0 := pa(0, 5, cell(0, 0), cell(0, 1))\n\t\t\t\t\tpa1 := pa(0, 10, cell(0, 1), cell(0, 2))\n\n\t\t\t\t\tindex := actorIndex{\n\t\t\t\t\t\t0: &actor{\n\t\t\t\t\t\t\tactorEntity: actorEntity{\n\t\t\t\t\t\t\t\tid: 0,\n\n\t\t\t\t\t\t\t\tcell:   pa0.Orig,\n\t\t\t\t\t\t\t\tfacing: pa0.Direction(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t1: &actor{\n\t\t\t\t\t\t\tactorEntity: actorEntity{\n\t\t\t\t\t\t\t\tid: 1,\n\n\t\t\t\t\t\t\t\tcell:   pa1.Orig,\n\t\t\t\t\t\t\t\tfacing: pa1.Direction(),\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\tindex[0].applyPathAction(pa0)\n\t\t\t\t\tindex[1].applyPathAction(pa1)\n\n\t\t\t\t\tphase := narrowPhase{index}\n\n\t\t\t\t\ttestCases := []struct {\n\t\t\t\t\t\tspec string\n\t\t\t\t\t\tcgrp quad.CollisionGroup\n\t\t\t\t\t}{{\n\t\t\t\t\t\t\"AB\", quad.CollisionGroup{}.AddCollision(quad.Collision{\n\t\t\t\t\t\t\tindex[0].Entity(),\n\t\t\t\t\t\t\tindex[1].Entity(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t}, {\n\t\t\t\t\t\t\"BA\", quad.CollisionGroup{}.AddCollision(quad.Collision{\n\t\t\t\t\t\t\tindex[1].Entity(),\n\t\t\t\t\t\t\tindex[0].Entity(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t}}\n\n\t\t\t\t\tfor _, testCase := range testCases {\n\t\t\t\t\t\tc.Specify(testCase.spec, func() {\n\t\t\t\t\t\t\tstillExisting, removed := phase.ResolveCollisions(&testCase.cgrp, 0)\n\t\t\t\t\t\t\tc.Assume(len(stillExisting), Equals, 2)\n\t\t\t\t\t\t\tc.Assume(len(removed), Equals, 0)\n\n\t\t\t\t\t\t\tc.Expect(index[0].pathAction, IsNil)\n\t\t\t\t\t\t\tc.Expect(*index[1].pathAction, Equals, *pa1)\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>[game] refactor collision specifications<commit_after>package game\n\nimport (\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/quad\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n\n\t\"github.com\/ghthor\/gospec\"\n\t. \"github.com\/ghthor\/gospec\"\n)\n\ntype spec_2moving struct {\n\tspec         string\n\tpaths        []coord.PathAction\n\texpectations func(spec_2moving, actorIndex, gospec.Context)\n}\n\nfunc (t spec_2moving) runSpec(c gospec.Context) {\n\tpa0 := t.paths[0]\n\tpa1 := t.paths[1]\n\n\tindex := actorIndex{\n\t\t0: &actor{\n\t\t\tactorEntity: actorEntity{\n\t\t\t\tid: 0,\n\n\t\t\t\tcell:   pa0.Orig,\n\t\t\t\tfacing: pa0.Direction(),\n\t\t\t},\n\t\t},\n\n\t\t1: &actor{\n\t\t\tactorEntity: actorEntity{\n\t\t\t\tid: 1,\n\n\t\t\t\tcell:   pa1.Orig,\n\t\t\t\tfacing: pa1.Direction(),\n\t\t\t},\n\t\t},\n\t}\n\n\tindex[0].applyPathAction(&pa0)\n\tindex[1].applyPathAction(&pa1)\n\n\tphase := narrowPhase{index}\n\ttestCases := []struct {\n\t\tspec string\n\t\tcgrp quad.CollisionGroup\n\t}{{\n\t\t\"AB\", quad.CollisionGroup{}.AddCollision(quad.Collision{\n\t\t\tindex[0].Entity(),\n\t\t\tindex[1].Entity(),\n\t\t}),\n\t}, {\n\t\t\"BA\", quad.CollisionGroup{}.AddCollision(quad.Collision{\n\t\t\tindex[1].Entity(),\n\t\t\tindex[0].Entity(),\n\t\t}),\n\t}}\n\n\tc.Specify(t.spec, func() {\n\t\tfor _, testCase := range testCases {\n\t\t\tc.Specify(testCase.spec, func() {\n\t\t\t\tstillExisting, removed := phase.ResolveCollisions(&testCase.cgrp, 0)\n\t\t\t\tc.Assume(len(stillExisting), Equals, 2)\n\t\t\t\tc.Assume(len(removed), Equals, 0)\n\n\t\t\t\tt.expectations(t, index, c)\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc DescribeCollision(c gospec.Context) {\n\tcell := func(x, y int) coord.Cell { return coord.Cell{x, y} }\n\tpa := func(start, speed int64, origin, dest coord.Cell) coord.PathAction {\n\t\treturn coord.PathAction{\n\t\t\tSpan: stime.NewSpan(stime.Time(start), stime.Time(start+speed)),\n\t\t\tOrig: origin,\n\t\t\tDest: dest,\n\t\t}\n\t}\n\n\tc.Specify(\"a collision between\", func() {\n\t\tc.Specify(\"2 actors\", func() {\n\n\t\t\tc.Specify(\"that are both moving\", func() {\n\t\t\t\ttestCases := []spec_2moving{{\n\t\t\t\t\tspec: \"in the same direction\",\n\t\t\t\t\tpaths: []coord.PathAction{\n\t\t\t\t\t\tpa(0, 5, cell(0, 0), cell(0, 1)),\n\t\t\t\t\t\tpa(0, 10, cell(0, 1), cell(0, 2)),\n\t\t\t\t\t},\n\t\t\t\t\texpectations: func(testCase spec_2moving, index actorIndex, c gospec.Context) {\n\t\t\t\t\t\tc.Expect(index[0].pathAction, IsNil)\n\t\t\t\t\t\tc.Expect(*index[1].pathAction, Equals, testCase.paths[1])\n\t\t\t\t\t}},\n\t\t\t\t}\n\n\t\t\t\tfor _, testCase := range testCases {\n\t\t\t\t\ttestCase.runSpec(c)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package extensions\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"github.com\/pawelszydlo\/papa-bot\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"github.com\/pawelszydlo\/papa-bot\/events\"\n)\n\n\/*\nExtensionWolfram - query Wolfram Alpha.\n\nUsed custom variables:\n- WolframKey - Your Wolfram Alpha AppID key.\n*\/\ntype ExtensionWolfram struct {\n\tannounced map[string]bool\n\tTexts     *extensionWolframTexts\n\tbot       *papaBot.Bot\n}\n\ntype extensionWolframTexts struct {\n\tNoResult string\n\tOr       string\n}\n\n\/\/ Structs for Wolfram responses.\ntype queryResult struct {\n\tSuccess bool  `xml:\"success,attr\"`\n\tError   bool  `xml:\"error,attr\"`\n\tPods    []pod `xml:\"pod\"`\n}\n\ntype pod struct {\n\tTitle   string `xml:\"title,attr\"`\n\tScanner string `xml:\"scanner,attr\"`\n\tId      string `xml:\"id,attr\"`\n\n\tSubpods []subPod `xml:\"subpod\"`\n}\n\ntype subPod struct {\n\tTitle     string `xml:\"title,attr\"`\n\tPlainText string `xml:\"plaintext\"`\n}\n\n\/\/ Init inits the extension.\nfunc (ext *ExtensionWolfram) Init(bot *papaBot.Bot) error {\n\t\/\/ Init variables.\n\text.announced = map[string]bool{}\n\t\/\/ Load texts.\n\ttexts := &extensionWolframTexts{}\n\tif err := bot.LoadTexts(\"wolfram\", texts); err != nil {\n\t\treturn err\n\t}\n\text.Texts = texts\n\t\/\/ Register new command.\n\tbot.RegisterCommand(&papaBot.BotCommand{\n\t\t[]string{\"wa\", \"wolfram\"},\n\t\tfalse, false, false,\n\t\t\"<query>\", \"Search Wolfram Alpha for <query>.\",\n\t\text.commandWolfram})\n\text.bot = bot\n\treturn nil\n}\n\nfunc (ext *ExtensionWolfram) queryWolfram(query string, format events.Formatting) string {\n\tappId := ext.bot.GetVar(\"WolframKey\")\n\tif appId == \"\" {\n\t\text.bot.Log.Error(\"Wolfram Alpha AppID key not set! Set the 'WolframKey' variable in the bot.\")\n\t\treturn \"\"\n\t}\n\n\terr, _, body := ext.bot.GetPageBody(\n\t\tfmt.Sprintf(\n\t\t\t\"http:\/\/api.wolframalpha.com\/v2\/query?format=plaintext&appid=%s&podindex=1,2&input=%s\",\n\t\t\tappId, strings.Replace(url.QueryEscape(query), \"+\", \"%20\", -1),\n\t\t), nil)\n\tif err != nil {\n\t\text.bot.Log.Warningf(\"Error getting Wolfram data: %s\", err)\n\t\treturn \"\"\n\t}\n\n\t\/\/ Parse XML.\n\tdata := new(queryResult)\n\tif err := xml.Unmarshal(body, &data); err != nil {\n\t\text.bot.Log.Errorf(\"Error parsing Wolfram data: %s\", err)\n\t\treturn \"\"\n\t}\n\n\t\/\/ Did the query succeed?\n\tif data.Error || !data.Success {\n\t\treturn ext.Texts.NoResult\n\t}\n\n\tinput := \"\"\n\tresult := []string{} \/\/ Result can have multiple forms.\n\n\tfor _, pod := range data.Pods {\n\t\t\/\/ Get the input interpretation.\n\t\tif pod.Id == \"Input\" {\n\t\t\tfor _, subpod := range pod.Subpods {\n\t\t\t\tinput = subpod.PlainText\n\t\t\t}\n\t\t}\n\t\t\/\/ Get the result.\n\t\tif pod.Id == \"Result\" || pod.Id == \"Value\" {\n\t\t\tfor _, subpod := range pod.Subpods {\n\t\t\t\tif format == events.FormatMarkdown {\n\t\t\t\t\tresult = append(result, \"**\"+subpod.PlainText+\"**\")\n\t\t\t\t} else if format == events.FormatIRC {\n\t\t\t\t\tresult = append(result, \"\\x0308\"+subpod.PlainText+\"\\x03\")\n\t\t\t\t} else {\n\t\t\t\t\tresult = append(result, subpod.PlainText)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%s = %s\", input, strings.Join(result, ext.Texts.Or))\n}\n\n\/\/ commandMovie is a command for manually searching for movies.\nfunc (ext *ExtensionWolfram) commandWolfram(bot *papaBot.Bot, sourceEvent *events.EventMessage, params []string) {\n\tif len(params) < 1 {\n\t\treturn\n\t}\n\tsearch := strings.Join(params, \" \")\n\n\t\/\/ Announce each article only once.\n\tif ext.announced[sourceEvent.Channel+search] {\n\t\treturn\n\t}\n\n\tcontent := ext.queryWolfram(search, sourceEvent.TransportFormatting)\n\n\t\/\/ Error occured.\n\tif content == \"\" {\n\t\treturn\n\t}\n\n\tmaxLen := 300\n\tif sourceEvent.TransportFormatting == events.FormatMarkdown {\n\t\tmaxLen = 3000\n\t}\n\n\t\/\/ Announce.\n\tcontentPreview := content\n\tcontentFull := \"\"\n\tif len(content) > maxLen {\n\t\tcontentPreview = content[:maxLen] + \"…\"\n\t\tcontentFull = content\n\t}\n\n\tnotice := fmt.Sprintf(\"%s, %s\", sourceEvent.Nick, contentPreview)\n\tbot.SendMessage(sourceEvent, notice)\n\text.announced[sourceEvent.Channel+search] = true\n\n\tif contentFull != \"\" {\n\t\tbot.AddMoreInfo(sourceEvent.TransportName, sourceEvent.Channel, contentFull)\n\t}\n}\n<commit_msg>WolframAlpha result caching.<commit_after>package extensions\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"github.com\/pawelszydlo\/papa-bot\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"github.com\/pawelszydlo\/papa-bot\/events\"\n)\n\n\/*\nExtensionWolfram - query Wolfram Alpha.\n\nUsed custom variables:\n- WolframKey - Your Wolfram Alpha AppID key.\n*\/\ntype ExtensionWolfram struct {\n\tannounced map[string]string\n\tTexts     *extensionWolframTexts\n\tbot       *papaBot.Bot\n}\n\ntype extensionWolframTexts struct {\n\tNoResult string\n\tOr       string\n}\n\n\/\/ Structs for Wolfram responses.\ntype queryResult struct {\n\tSuccess bool  `xml:\"success,attr\"`\n\tError   bool  `xml:\"error,attr\"`\n\tPods    []pod `xml:\"pod\"`\n}\n\ntype pod struct {\n\tTitle   string `xml:\"title,attr\"`\n\tScanner string `xml:\"scanner,attr\"`\n\tId      string `xml:\"id,attr\"`\n\n\tSubpods []subPod `xml:\"subpod\"`\n}\n\ntype subPod struct {\n\tTitle     string `xml:\"title,attr\"`\n\tPlainText string `xml:\"plaintext\"`\n}\n\n\/\/ Init inits the extension.\nfunc (ext *ExtensionWolfram) Init(bot *papaBot.Bot) error {\n\t\/\/ Init variables.\n\text.announced = map[string]string{}\n\t\/\/ Load texts.\n\ttexts := &extensionWolframTexts{}\n\tif err := bot.LoadTexts(\"wolfram\", texts); err != nil {\n\t\treturn err\n\t}\n\text.Texts = texts\n\t\/\/ Register new command.\n\tbot.RegisterCommand(&papaBot.BotCommand{\n\t\t[]string{\"wa\", \"wolfram\"},\n\t\tfalse, false, false,\n\t\t\"<query>\", \"Search Wolfram Alpha for <query>.\",\n\t\text.commandWolfram})\n\text.bot = bot\n\treturn nil\n}\n\nfunc (ext *ExtensionWolfram) queryWolfram(query string, format events.Formatting) string {\n\tappId := ext.bot.GetVar(\"WolframKey\")\n\tif appId == \"\" {\n\t\text.bot.Log.Error(\"Wolfram Alpha AppID key not set! Set the 'WolframKey' variable in the bot.\")\n\t\treturn \"\"\n\t}\n\n\text.bot.Log.Debugf(\"Querying WolframAlpha for %s...\", query)\n\terr, _, body := ext.bot.GetPageBody(\n\t\tfmt.Sprintf(\n\t\t\t\"http:\/\/api.wolframalpha.com\/v2\/query?format=plaintext&appid=%s&podindex=1,2&input=%s\",\n\t\t\tappId, strings.Replace(url.QueryEscape(query), \"+\", \"%20\", -1),\n\t\t), nil)\n\tif err != nil {\n\t\text.bot.Log.Warningf(\"Error getting Wolfram data: %s\", err)\n\t\treturn \"\"\n\t}\n\n\t\/\/ Parse XML.\n\tdata := new(queryResult)\n\tif err := xml.Unmarshal(body, &data); err != nil {\n\t\text.bot.Log.Errorf(\"Error parsing Wolfram data: %s\", err)\n\t\treturn \"\"\n\t}\n\n\t\/\/ Did the query succeed?\n\tif data.Error || !data.Success {\n\t\treturn ext.Texts.NoResult\n\t}\n\n\tinput := \"\"\n\tresult := []string{} \/\/ Result can have multiple forms.\n\n\tfor _, pod := range data.Pods {\n\t\t\/\/ Get the input interpretation.\n\t\tif pod.Id == \"Input\" {\n\t\t\tfor _, subpod := range pod.Subpods {\n\t\t\t\tinput = subpod.PlainText\n\t\t\t}\n\t\t}\n\t\t\/\/ Get the result.\n\t\tif pod.Id == \"Result\" || pod.Id == \"Value\" {\n\t\t\tfor _, subpod := range pod.Subpods {\n\t\t\t\tif format == events.FormatMarkdown {\n\t\t\t\t\tresult = append(result, \"**\"+subpod.PlainText+\"**\")\n\t\t\t\t} else if format == events.FormatIRC {\n\t\t\t\t\tresult = append(result, \"\\x0308\"+subpod.PlainText+\"\\x03\")\n\t\t\t\t} else {\n\t\t\t\t\tresult = append(result, subpod.PlainText)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"%s = %s\", input, strings.Join(result, ext.Texts.Or))\n}\n\n\/\/ commandMovie is a command for manually searching for movies.\nfunc (ext *ExtensionWolfram) commandWolfram(bot *papaBot.Bot, sourceEvent *events.EventMessage, params []string) {\n\tif len(params) < 1 {\n\t\treturn\n\t}\n\tsearch := strings.Join(params, \" \")\n\n\t\/\/ Check if we have the result cached.\n\tif val, exists := ext.announced[sourceEvent.Channel+search]; exists {\n\t\tbot.SendMessage(sourceEvent, fmt.Sprintf(\"%s, %s\", sourceEvent.Nick, val))\n\t\treturn\n\t}\n\n\tcontent := ext.queryWolfram(search, sourceEvent.TransportFormatting)\n\n\t\/\/ Error occured.\n\tif content == \"\" {\n\t\treturn\n\t}\n\n\tmaxLen := 300\n\tif sourceEvent.TransportFormatting == events.FormatMarkdown {\n\t\tmaxLen = 3000\n\t}\n\n\t\/\/ Announce.\n\tcontentPreview := content\n\tcontentFull := \"\"\n\tif len(content) > maxLen {\n\t\tcontentPreview = content[:maxLen] + \"…\"\n\t\tcontentFull = content\n\t}\n\n\tbot.SendMessage(sourceEvent, fmt.Sprintf(\"%s, %s\", sourceEvent.Nick, contentPreview))\n\text.announced[sourceEvent.Channel+search] = contentPreview\n\n\tif contentFull != \"\" {\n\t\tbot.AddMoreInfo(sourceEvent.TransportName, sourceEvent.Channel, contentFull)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\tcq_config \"go.chromium.org\/luci\/cq\/api\/config\/v2\"\n\t\"go.skia.org\/infra\/go\/auth\"\n\t\"go.skia.org\/infra\/go\/common\"\n\t\"go.skia.org\/infra\/go\/cq\"\n\t\"go.skia.org\/infra\/go\/gerrit\"\n\t\"go.skia.org\/infra\/go\/gitiles\"\n\t\"go.skia.org\/infra\/go\/httputils\"\n\t\"go.skia.org\/infra\/go\/sklog\"\n\t\"go.skia.org\/infra\/go\/supported_branches\"\n\t\"go.skia.org\/infra\/go\/util\"\n)\n\nvar (\n\t\/\/ Flags.\n\tbranch         = flag.String(\"branch\", \"\", \"Name of the new branch, without refs\/heads prefix.\")\n\tdeleteBranch   = flag.String(\"delete\", \"\", \"Name of an existing branch to delete, without refs\/heads prefix.\")\n\texcludeTrybots = common.NewMultiStringFlag(\"exclude-trybots\", nil, \"Regular expressions for trybot names to exclude.\")\n\towner          = flag.String(\"owner\", \"\", \"Owner of the new branch.\")\n\trepoUrl        = flag.String(\"repo\", common.REPO_SKIA, \"URL of the git repository.\")\n\tsubmit         = flag.Bool(\"submit\", false, \"If set, automatically submit the CL to update the CQ and supported branches.\")\n)\n\nfunc main() {\n\tcommon.Init()\n\n\tif *branch == \"\" {\n\t\tsklog.Fatal(\"--branch is required.\")\n\t}\n\tnewRef := fmt.Sprintf(\"refs\/heads\/%s\", *branch)\n\tif *owner == \"\" {\n\t\tsklog.Fatal(\"--owner is required.\")\n\t}\n\texcludeTrybotRegexp := make([]*regexp.Regexp, 0, len(*excludeTrybots))\n\tfor _, excludeTrybot := range *excludeTrybots {\n\t\tre, err := regexp.Compile(excludeTrybot)\n\t\tif err != nil {\n\t\t\tsklog.Fatalf(\"Failed to compile regular expression from %q; %s\", excludeTrybot, err)\n\t\t}\n\t\texcludeTrybotRegexp = append(excludeTrybotRegexp, re)\n\t}\n\n\t\/\/ Setup.\n\twd, err := ioutil.TempDir(\"\", \"new-branch\")\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tdefer util.RemoveAll(wd)\n\n\tts, err := auth.NewDefaultTokenSource(true, auth.SCOPE_GERRIT)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tclient := httputils.DefaultClientConfig().WithTokenSource(ts).Client()\n\tgUrl := strings.Split(*repoUrl, \".googlesource.com\")[0] + \"-review.googlesource.com\"\n\tg, err := gerrit.NewGerrit(gUrl, client)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\trepo := gitiles.NewRepo(*repoUrl, client)\n\tctx := context.Background()\n\tbaseCommitInfo, err := repo.Details(ctx, cq.CQ_CFG_REF)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tbaseCommit := baseCommitInfo.Hash\n\n\t\/\/ Download the CQ config file and modify it.\n\tvar buf bytes.Buffer\n\tif err := repo.ReadFileAtRef(ctx, cq.CQ_CFG_FILE, baseCommit, &buf); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tnewCfgBytes, err := cq.WithUpdateCQConfig(buf.Bytes(), func(cfg *cq_config.Config) error {\n\t\tcg, _, _, err := cq.MatchConfigGroup(cfg, newRef)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif cg != nil {\n\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"Already have %s in %s; not adding a duplicate.\\n\", newRef, cq.CQ_CFG_FILE)\n\t\t} else {\n\t\t\tif err := cq.CloneBranch(cfg, \"master\", *branch, false, false, excludeTrybotRegexp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *deleteBranch != \"\" {\n\t\t\tif err := cq.DeleteBranch(cfg, *deleteBranch); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Download and modify the supported-branches.json file.\n\tbuf = bytes.Buffer{}\n\tif err := repo.ReadFileAtRef(ctx, supported_branches.SUPPORTED_BRANCHES_FILE, baseCommit, &buf); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tsbc, err := supported_branches.DecodeConfig(&buf)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tdeleteRef := \"\"\n\tif *deleteBranch != \"\" {\n\t\tdeleteRef = fmt.Sprintf(\"refs\/heads\/%s\", *deleteBranch)\n\t}\n\tfoundNewRef := false\n\tnewBranches := make([]*supported_branches.SupportedBranch, 0, len(sbc.Branches)+1)\n\tfor _, sb := range sbc.Branches {\n\t\tif deleteRef == \"\" || deleteRef != sb.Ref {\n\t\t\tnewBranches = append(newBranches, sb)\n\t\t}\n\t\tif sb.Ref == newRef {\n\t\t\tfoundNewRef = true\n\t\t}\n\t}\n\tif foundNewRef {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Already have %s in %s; not adding a duplicate.\\n\", newRef, supported_branches.SUPPORTED_BRANCHES_FILE)\n\t} else {\n\t\tnewBranches = append(newBranches, &supported_branches.SupportedBranch{\n\t\t\tRef:   newRef,\n\t\t\tOwner: *owner,\n\t\t})\n\t}\n\tsbc.Branches = newBranches\n\tbuf = bytes.Buffer{}\n\tif err := supported_branches.EncodeConfig(&buf, sbc); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\n\t\/\/ Create the Gerrit CL.\n\tcommitMsg := fmt.Sprintf(\"Add supported branch %s\", *branch)\n\tif *deleteBranch != \"\" {\n\t\tcommitMsg += fmt.Sprintf(\", remove %s\", *deleteBranch)\n\t}\n\trepoSplit := strings.Split(*repoUrl, \"\/\")\n\tproject := strings.TrimSuffix(repoSplit[len(repoSplit)-1], \".git\")\n\tci, err := gerrit.CreateAndEditChange(ctx, g, project, cq.CQ_CFG_REF, commitMsg, baseCommit, func(ctx context.Context, g gerrit.GerritInterface, ci *gerrit.ChangeInfo) error {\n\t\tif err := g.EditFile(ctx, ci, cq.CQ_CFG_FILE, string(newCfgBytes)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := g.EditFile(ctx, ci, supported_branches.SUPPORTED_BRANCHES_FILE, string(buf.Bytes())); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tfmt.Println(fmt.Sprintf(\"Uploaded change https:\/\/skia-review.googlesource.com\/%d\", ci.Issue))\n\tif *submit {\n\t\tif err := g.SetReadyForReview(ctx, ci); err != nil {\n\t\t\tsklog.Fatalf(\"Failed to set ready for review: %s\", err)\n\t\t}\n\t\tif err := g.SetReview(ctx, ci, \"\", gerrit.CONFIG_CHROMIUM.SelfApproveLabels, nil); err != nil {\n\t\t\tsklog.Fatalf(\"Failed to set Code-Review+1: %s\", err)\n\t\t}\n\t\tif err := g.Submit(ctx, ci); err != nil {\n\t\t\tsklog.Fatalf(\"Failed to submit CL: %s\", err)\n\t\t}\n\t}\n}\n<commit_msg>[chrome branch] Only set ready-for-review if the CL is WIP<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\tcq_config \"go.chromium.org\/luci\/cq\/api\/config\/v2\"\n\t\"go.skia.org\/infra\/go\/auth\"\n\t\"go.skia.org\/infra\/go\/common\"\n\t\"go.skia.org\/infra\/go\/cq\"\n\t\"go.skia.org\/infra\/go\/gerrit\"\n\t\"go.skia.org\/infra\/go\/gitiles\"\n\t\"go.skia.org\/infra\/go\/httputils\"\n\t\"go.skia.org\/infra\/go\/sklog\"\n\t\"go.skia.org\/infra\/go\/supported_branches\"\n\t\"go.skia.org\/infra\/go\/util\"\n)\n\nvar (\n\t\/\/ Flags.\n\tbranch         = flag.String(\"branch\", \"\", \"Name of the new branch, without refs\/heads prefix.\")\n\tdeleteBranch   = flag.String(\"delete\", \"\", \"Name of an existing branch to delete, without refs\/heads prefix.\")\n\texcludeTrybots = common.NewMultiStringFlag(\"exclude-trybots\", nil, \"Regular expressions for trybot names to exclude.\")\n\towner          = flag.String(\"owner\", \"\", \"Owner of the new branch.\")\n\trepoUrl        = flag.String(\"repo\", common.REPO_SKIA, \"URL of the git repository.\")\n\tsubmit         = flag.Bool(\"submit\", false, \"If set, automatically submit the CL to update the CQ and supported branches.\")\n)\n\nfunc main() {\n\tcommon.Init()\n\n\tif *branch == \"\" {\n\t\tsklog.Fatal(\"--branch is required.\")\n\t}\n\tnewRef := fmt.Sprintf(\"refs\/heads\/%s\", *branch)\n\tif *owner == \"\" {\n\t\tsklog.Fatal(\"--owner is required.\")\n\t}\n\texcludeTrybotRegexp := make([]*regexp.Regexp, 0, len(*excludeTrybots))\n\tfor _, excludeTrybot := range *excludeTrybots {\n\t\tre, err := regexp.Compile(excludeTrybot)\n\t\tif err != nil {\n\t\t\tsklog.Fatalf(\"Failed to compile regular expression from %q; %s\", excludeTrybot, err)\n\t\t}\n\t\texcludeTrybotRegexp = append(excludeTrybotRegexp, re)\n\t}\n\n\t\/\/ Setup.\n\twd, err := ioutil.TempDir(\"\", \"new-branch\")\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tdefer util.RemoveAll(wd)\n\n\tts, err := auth.NewDefaultTokenSource(true, auth.SCOPE_GERRIT)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tclient := httputils.DefaultClientConfig().WithTokenSource(ts).Client()\n\tgUrl := strings.Split(*repoUrl, \".googlesource.com\")[0] + \"-review.googlesource.com\"\n\tg, err := gerrit.NewGerrit(gUrl, client)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\trepo := gitiles.NewRepo(*repoUrl, client)\n\tctx := context.Background()\n\tbaseCommitInfo, err := repo.Details(ctx, cq.CQ_CFG_REF)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tbaseCommit := baseCommitInfo.Hash\n\n\t\/\/ Download the CQ config file and modify it.\n\tvar buf bytes.Buffer\n\tif err := repo.ReadFileAtRef(ctx, cq.CQ_CFG_FILE, baseCommit, &buf); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tnewCfgBytes, err := cq.WithUpdateCQConfig(buf.Bytes(), func(cfg *cq_config.Config) error {\n\t\tcg, _, _, err := cq.MatchConfigGroup(cfg, newRef)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif cg != nil {\n\t\t\t_, _ = fmt.Fprintf(os.Stderr, \"Already have %s in %s; not adding a duplicate.\\n\", newRef, cq.CQ_CFG_FILE)\n\t\t} else {\n\t\t\tif err := cq.CloneBranch(cfg, \"master\", *branch, false, false, excludeTrybotRegexp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *deleteBranch != \"\" {\n\t\t\tif err := cq.DeleteBranch(cfg, *deleteBranch); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Download and modify the supported-branches.json file.\n\tbuf = bytes.Buffer{}\n\tif err := repo.ReadFileAtRef(ctx, supported_branches.SUPPORTED_BRANCHES_FILE, baseCommit, &buf); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tsbc, err := supported_branches.DecodeConfig(&buf)\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tdeleteRef := \"\"\n\tif *deleteBranch != \"\" {\n\t\tdeleteRef = fmt.Sprintf(\"refs\/heads\/%s\", *deleteBranch)\n\t}\n\tfoundNewRef := false\n\tnewBranches := make([]*supported_branches.SupportedBranch, 0, len(sbc.Branches)+1)\n\tfor _, sb := range sbc.Branches {\n\t\tif deleteRef == \"\" || deleteRef != sb.Ref {\n\t\t\tnewBranches = append(newBranches, sb)\n\t\t}\n\t\tif sb.Ref == newRef {\n\t\t\tfoundNewRef = true\n\t\t}\n\t}\n\tif foundNewRef {\n\t\t_, _ = fmt.Fprintf(os.Stderr, \"Already have %s in %s; not adding a duplicate.\\n\", newRef, supported_branches.SUPPORTED_BRANCHES_FILE)\n\t} else {\n\t\tnewBranches = append(newBranches, &supported_branches.SupportedBranch{\n\t\t\tRef:   newRef,\n\t\t\tOwner: *owner,\n\t\t})\n\t}\n\tsbc.Branches = newBranches\n\tbuf = bytes.Buffer{}\n\tif err := supported_branches.EncodeConfig(&buf, sbc); err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\n\t\/\/ Create the Gerrit CL.\n\tcommitMsg := fmt.Sprintf(\"Add supported branch %s\", *branch)\n\tif *deleteBranch != \"\" {\n\t\tcommitMsg += fmt.Sprintf(\", remove %s\", *deleteBranch)\n\t}\n\trepoSplit := strings.Split(*repoUrl, \"\/\")\n\tproject := strings.TrimSuffix(repoSplit[len(repoSplit)-1], \".git\")\n\tci, err := gerrit.CreateAndEditChange(ctx, g, project, cq.CQ_CFG_REF, commitMsg, baseCommit, func(ctx context.Context, g gerrit.GerritInterface, ci *gerrit.ChangeInfo) error {\n\t\tif err := g.EditFile(ctx, ci, cq.CQ_CFG_FILE, string(newCfgBytes)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := g.EditFile(ctx, ci, supported_branches.SUPPORTED_BRANCHES_FILE, string(buf.Bytes())); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tsklog.Fatal(err)\n\t}\n\tfmt.Println(fmt.Sprintf(\"Uploaded change https:\/\/skia-review.googlesource.com\/%d\", ci.Issue))\n\tif *submit {\n\t\tif ci.WorkInProgress {\n\t\t\tif err := g.SetReadyForReview(ctx, ci); err != nil {\n\t\t\t\tsklog.Fatalf(\"Failed to set ready for review: %s\", err)\n\t\t\t}\n\t\t}\n\t\tif err := g.SetReview(ctx, ci, \"\", gerrit.CONFIG_CHROMIUM.SelfApproveLabels, nil); err != nil {\n\t\t\tsklog.Fatalf(\"Failed to set Code-Review+1: %s\", err)\n\t\t}\n\t\tif err := g.Submit(ctx, ci); err != nil {\n\t\t\tsklog.Fatalf(\"Failed to submit CL: %s\", err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ geomi, 거미, is a basic spider for crawling specific webs. It was designed to crawl\n\/\/ either a site, or a subset of a site, indexing the pages and where they link to.\n\/\/ Any links that go outside of the provided base URL are noted but not followed.\n\/\/\n\/\/\n\/\/ Even though geomi was designed with the intended use being crawling ones own site,\n\/\/ or a client's site, it does come with some basic behavior configuration to make it\n\/\/ a friendly bot:\n\/\/   * respects ROBOTS.txt TODO\n\/\/   * configurable concurrent walkers TODO\n\/\/   * configurable wait interval range TODO\n\/\/   * configurable max requests per: TODO\n\/\/     * min\n\/\/     * hour\n\/\/     * day\n\/\/     * month\n\/\/\n\/\/ To start, go get the geomi package:\n\/\/    go get github.com\/mohae\/geomi\n\/\/\n\/\/ Import it into your code:\n\/\/    import github.com\/mohae\/geomi\n\/\/\n\/\/ Set up the site for the spider:\n\/\/   s := geomi.NewSite(\"http:\/\/example.com\")\n\/\/\n\/\/ The url that is passed to the NewSite() function is the base case, after which\n\/\/ a BFS traversal is done.\n\/\/\npackage geomi\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/mohae\/utilitybelt\/queue\"\n\t\"github.com\/temoto\/robotstxt.go\"\n\t\"golang.org\/x\/net\/html\"\n)\n\n\/\/ Fetcher is an interface that makes it easier to test. In the future, it may be\n\/\/ useful for other purposes, but that would require exporting the method that uses\n\/\/ it first.\ntype Fetcher interface {\n\t\/\/ Fetch returns the body of URL and\n\t\/\/ a slice of URLs found on that page\n\tFetch(url string) (body string, urls []string, err error)\n}\n\n\/\/}\n\/\/ fetched tracks URLs that have been (or are being) fetched.\n\/\/ The lock must be held while reading from or writing to the map.\nvar fetched = struct {\n\tm map[string]error\n\tsync.Mutex\n}{m: make(map[string]error)}\n\nvar loading = errors.New(\"url load in progress\") \/\/ sentinel value\n\n\/\/ a page is a url. This is usually some content wiht a number of elements, but it\n\/\/ could be something as simple as the url for cat.jpg on your site and represent that\n\/\/ image.\ntype Page struct {\n\t*url.URL\n\tdistance int\n\tbody     string\n\tlinks    []string \/\/ immediate children\n}\n\n\/\/ responseInfo contains the status and error information from a get\ntype responseInfo struct {\n\tStatus     string\n\tStatusCode int\n\tErr        error\n}\n\n\/\/ Site is a type that implements fetcher\ntype Site struct {\n\t*url.URL\n}\n\n\/\/ Implements fetcher.\n\/\/ TODO: make the design cleaner\nfunc (s Site) Fetch(url string) (body string, urls []string, err error) {\n\t\/\/ see if the passed url is outside of the baseURL\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuff := &bytes.Buffer{}\n\ttee := io.TeeReader(resp.Body, buff)\n\ttokens := getTokens(tee)\n\tif len(tokens) == 0 {\n\t\treturn \"\", nil, fmt.Errorf(\"%s: nothing in body\", url)\n\t}\n\turls, err = s.linksFromTokens(tokens)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treturn buff.String(), urls, nil\n}\n\n\/\/ linksFromTokens returns a list of links (href a) found in the token slice\n\/\/ TODO should internal links be tracked separatly? i.e. record them in a\n\/\/ separate var (so they don't get fetched)\nfunc (s *Site) linksFromTokens(tokens []html.Token) ([]string, error) {\n\tvar links []string\n\tfor _, token := range tokens {\n\t\tif token.Type == html.StartTagToken && token.DataAtom.String() == \"a\" {\n\t\t\tfor _, attr := range token.Attr {\n\t\t\t\t\/\/ We only care about links that aren't #\n\t\t\t\tif attr.Key == \"href\" && !strings.HasPrefix(attr.Val, \"#\") {\n\t\t\t\t\t\/\/ parse the url\n\t\t\t\t\turl, err := url.Parse(attr.Val)\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\tlink := s.URL.ResolveReference(url)\n\t\t\t\t\tlinks = append(links, link.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn links, nil\n}\n\n\/\/ Spider crawls the target. It contains all information needed to manage the crawl\n\/\/ including keeping track of work to do, work done, and the results.\ntype Spider struct {\n\t*queue.Queue\n\tsync.Mutex\n\twg                 sync.WaitGroup\n\t*url.URL                  \/\/ the start url\n\tbot                string \/\/ the name of the bot for robots\n\tconcurrency        int    \/\/ concurrency level of crawling\n\tfetchInterval      int64  \/\/ if > 0, interval, in milliseconds to wait between gets\n\tintervalJitter     int64  \/\/ the max jitter to be added, per fetch. Jitter is a rand with this as max.\n\tRestrictToScheme   bool   \/\/ if true, only crawls urls with the same scheme as baseURL\n\tRespectRobots      bool   \/\/ whether or not to respect the robots.txt\n\tCheckExternalLinks bool   \/\/ Check the status of any links that go to other domains\n\trobots             *robotstxt.Group\n\tmaxDepth           int\n\tPages              map[string]Page\n\tfoundURLs          map[string]struct{}     \/\/ keeps track of urls found to prevent recrawling\n\tfetchedURLs        map[string]error        \/\/ urls that have been fetched with their status\n\tskippedURLs        map[string]struct{}     \/\/ urls within the same domain that are not retrieved\n\texternalHosts      map[string]struct{}     \/\/ list of external hosts TODO: elide?\n\texternalLinks      map[string]responseInfo \/\/ list of external links; if fetched,\n}\n\n\/\/ returns a Spider with the its site's baseUrl set. The baseUrl is the start point for\n\/\/ the crawl. It is also the restriction on the crawl:\nfunc NewSpider(start string) (*Spider, error) {\n\tif start == \"\" {\n\t\treturn nil, errors.New(\"newSpider: the start url cannot be empty\")\n\t}\n\tvar err error\n\tspider := &Spider{Queue: queue.New(128, 0),\n\t\tbot:           \"geomi\",\n\t\tRespectRobots: true,\n\t\tPages:         make(map[string]Page),\n\t\tfoundURLs:     make(map[string]struct{}),\n\t\tfetchedURLs:   make(map[string]error),\n\t\tskippedURLs:   make(map[string]struct{}),\n\t\texternalHosts: make(map[string]struct{}),\n\t\texternalLinks: make(map[string]responseInfo),\n\t}\n\tspider.URL, err = url.Parse(start)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn spider, nil\n}\n\n\/\/ SetFetchInterval set's the spiders wait interval, and calculates the intervalJitter\n\/\/ value for the random jitter added to the wait. This value is in milliseconds, 1000\n\/\/ means 1 second.\n\/\/\n\/\/ When fetchInterval > 0:\n\/\/ time between fetches = fetchInterval + rand(intervalJitter)\n\/\/ max time between fetches = fetchInterval + intervalJitter\nfunc (s *Spider) SetFetchInterval(i int64) {\n\ts.fetchInterval = i\n\tjitter := i \/ 5 \/\/ jitter is, at most 20% of the fetchInterval, Min interval is 10ms\n\t\/\/ 10ms is used as the floor because arbitrary. A larger floor might be reasonable\n\tif jitter >= 10 {\n\t\ts.intervalJitter = jitter\n\t}\n}\n\n\/\/ Crawl is the exposed method for starting a crawl at baseURL. The crawl private method\n\/\/ does the actual work. The depth is the maximum depth, or distance, to crawl from the\n\/\/ baseURL. If depth == -1, no limits are set and it is expected that the entire site\n\/\/ will be crawled.\nfunc (s *Spider) Crawl(depth int) (message string, err error) {\n\ts.maxDepth = depth\n\tS := Site{URL: s.URL}\n\t\/\/ if we are to respect the robots.txt, set up the info\n\tif s.RespectRobots {\n\t\ts.getRobotsTxt()\n\t}\n\ts.Queue.Enqueue(Page{URL: s.URL})\n\terr = s.crawl(S)\n\treturn fmt.Sprintf(\"%d nodes were processed; %d external links linking to %d external hosts were not processed\", len(s.Pages), len(s.externalLinks), len(s.externalHosts)), err\n}\n\n\/\/ This crawl does all the work.\nfunc (s *Spider) crawl(fetcher Fetcher) error {\n\tvar err error\n\tfor !s.Queue.IsEmpty() {\n\t\t\/\/ get next item from queue\n\t\tpage := s.Queue.Dequeue().(Page)\n\t\t\/\/ if a depth value was passed and the distance is > depth, we are done\n\t\t\/\/ depth of 0 means no limit\n\t\tif s.maxDepth != -1 && page.distance > s.maxDepth {\n\t\t\treturn nil\n\t\t}\n\t\t\/\/ see if this is an external url\n\t\tif s.externalURL(page.URL) {\n\t\t\tif s.CheckExternalLinks {\n\t\t\t\ts.fetchExternalLink(page.URL)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ check to see if this url should be skipped for other reasons\n\t\tif s.skip(page.URL) {\n\t\t\t\/\/ see if the skipped is external and process accordingly\n\t\t\tcontinue\n\t\t}\n\t\ts.foundURLs[page.URL.String()] = struct{}{}\n\t\t\/\/ get the url\n\t\tpage.body, page.links, err = fetcher.Fetch(page.URL.String())\n\t\t\/\/ add the page and status to the map. map isn't checked for membership becuase we don't\n\t\t\/\/ fetch found urls.\n\t\ts.Lock()\n\t\ts.Pages[page.URL.String()] = page\n\t\ts.fetchedURLs[page.URL.String()] = err\n\t\ts.Unlock()\n\t\t\/\/ add the urls that the node contains to the queue\n\t\tfor _, l := range page.links {\n\t\t\tu, _ := url.Parse(l)\n\t\t\ts.Queue.Enqueue(Page{URL: u, distance: page.distance + 1})\n\t\t}\n\t\t\/\/ if their is a wait between fetches, sleep for that + random jitter\n\t\tif s.fetchInterval > 0 {\n\t\t\twait := s.fetchInterval\n\t\t\t\/\/ if there is a value for jitter, add a random jitter\n\t\t\tif s.intervalJitter > 0 {\n\t\t\t\twait += rand.Int63n(s.intervalJitter)\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(wait) * time.Millisecond)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ skip determines whether the url should be skipped.\n\/\/   * skip urls that have already been fetched\n\/\/   * skip urls that are outside of the basePath\n\/\/   * conditionally skip urls that are outside of the current scheme, even if\n\/\/     they are within the current pasePath\n\/\/   * skip if not allowed by robots\nfunc (s *Spider) skip(u *url.URL) bool {\n\ts.Lock()\n\t_, ok := s.foundURLs[u.String()]\n\ts.Unlock()\n\tif ok { \/\/ if it was found, skip it\n\t\ts.addSkippedURL(u)\n\t\treturn true\n\t}\n\n\t\/\/ skip if we are restricted to current scheme\n\tif s.RestrictToScheme {\n\t\tif u.Scheme != s.URL.Scheme {\n\t\t\ts.addSkippedURL(u)\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.RespectRobots {\n\t\tok := s.robotsAllowed(u)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ skip if the url is outside of base\n\t\/\/ remove the scheme + schemePrefix so just the rest of the url is being compared\n\tif !strings.HasPrefix(u.Path, s.URL.Path) {\n\t\ts.addSkippedURL(u)\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ addSkippedURL add's the url info too the skipped info\nfunc (s *Spider) addSkippedURL(u *url.URL) {\n\ts.Lock()\n\ts.skippedURLs[u.Path] = struct{}{}\n\ts.Unlock()\n}\n\n\/\/ externalURL check's to see if the url is external to the site, host isn't the same.\n\/\/ and add's that info to the ext structs.\nfunc (s *Spider) externalURL(u *url.URL) bool {\n\tif u.Host != s.URL.Host {\n\t\ts.Lock()\n\t\t\/\/ see if the host is already in the map\n\t\t_, ok := s.externalHosts[u.Host]\n\t\tif !ok {\n\t\t\ts.externalHosts[u.Host] = struct{}{}\n\t\t}\n\t\t\/\/ same with url\n\t\t_, ok = s.externalLinks[u.String()]\n\t\tif !ok {\n\t\t\ts.externalLinks[u.String()] = responseInfo{}\n\t\t}\n\t\ts.Unlock()\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ fetchExternalLink: fetches an external link and check's it status. Note, this\n\/\/ does not implement fetcher\nfunc (s *Spider) fetchExternalLink(u *url.URL) error {\n\t\/\/ if this has already benn fetched, don't\n\tvar ri responseInfo\n\ts.Lock()\n\tr, _ := s.externalLinks[u.String()]\n\tif r != ri { \/\/ if !0 value, it's been retrieved\n\t\ts.Unlock()\n\t\treturn nil\n\t}\n\ts.Unlock()\n\tresp, err := http.Get(u.String())\n\tresp.Body.Close()\n\tif err != nil {\n\t\tr.Err = err\n\t\ts.Lock()\n\t\ts.externalLinks[u.String()] = r\n\t\ts.Unlock()\n\t\treturn err\n\t}\n\tr.Status = resp.Status\n\tr.StatusCode = resp.StatusCode\n\ts.Lock()\n\ts.externalLinks[u.String()] = r\n\ts.Unlock()\n\treturn nil\n}\n\n\/\/ getRobotsTxt retrieves and processes the site's robot.txt. If the robots.txt doesn't\n\/\/ exist, it is assumed that everything is allowed.\nfunc (s *Spider) getRobotsTxt() error {\n\tresp, err := http.Get(\"http:\/\/\" + s.URL.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\trobots, err := robotstxt.FromResponse(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.robots = robots.FindGroup(s.bot)\n\treturn nil\n}\n\n\/\/ robotsAllowed checks to see if the passed path is allowed by Robots.txt. If the\n\/\/ robots isn't set, it's always true\nfunc (s *Spider) robotsAllowed(u *url.URL) bool {\n\tif s.robots != nil {\n\t\treturn s.robots.Test(u.Path)\n\t}\n\treturn true\n}\n\n\/\/ getTokens returns all tokens in the body\nfunc getTokens(body io.Reader) []html.Token {\n\ttokens := make([]html.Token, 0)\n\tpage := html.NewTokenizer(body)\n\tfor {\n\t\ttyp := page.Next()\n\t\tif typ == html.ErrorToken {\n\t\t\treturn tokens\n\t\t}\n\t\ttokens = append(tokens, page.Token())\n\t}\n}\n\nfunc init() {\n\t\/\/ We just use math\/rand because it's good enough for our purpose.\n\trand.Seed(time.Now().UTC().UnixNano())\n}\n<commit_msg>simplify first unlock() handling in fetchExternalLink<commit_after>\/\/ geomi, 거미, is a basic spider for crawling specific webs. It was designed to crawl\n\/\/ either a site, or a subset of a site, indexing the pages and where they link to.\n\/\/ Any links that go outside of the provided base URL are noted but not followed.\n\/\/\n\/\/\n\/\/ Even though geomi was designed with the intended use being crawling ones own site,\n\/\/ or a client's site, it does come with some basic behavior configuration to make it\n\/\/ a friendly bot:\n\/\/   * respects ROBOTS.txt TODO\n\/\/   * configurable concurrent walkers TODO\n\/\/   * configurable wait interval range TODO\n\/\/   * configurable max requests per: TODO\n\/\/     * min\n\/\/     * hour\n\/\/     * day\n\/\/     * month\n\/\/\n\/\/ To start, go get the geomi package:\n\/\/    go get github.com\/mohae\/geomi\n\/\/\n\/\/ Import it into your code:\n\/\/    import github.com\/mohae\/geomi\n\/\/\n\/\/ Set up the site for the spider:\n\/\/   s := geomi.NewSite(\"http:\/\/example.com\")\n\/\/\n\/\/ The url that is passed to the NewSite() function is the base case, after which\n\/\/ a BFS traversal is done.\n\/\/\npackage geomi\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/mohae\/utilitybelt\/queue\"\n\t\"github.com\/temoto\/robotstxt.go\"\n\t\"golang.org\/x\/net\/html\"\n)\n\n\/\/ Fetcher is an interface that makes it easier to test. In the future, it may be\n\/\/ useful for other purposes, but that would require exporting the method that uses\n\/\/ it first.\ntype Fetcher interface {\n\t\/\/ Fetch returns the body of URL and\n\t\/\/ a slice of URLs found on that page\n\tFetch(url string) (body string, urls []string, err error)\n}\n\n\/\/}\n\/\/ fetched tracks URLs that have been (or are being) fetched.\n\/\/ The lock must be held while reading from or writing to the map.\nvar fetched = struct {\n\tm map[string]error\n\tsync.Mutex\n}{m: make(map[string]error)}\n\nvar loading = errors.New(\"url load in progress\") \/\/ sentinel value\n\n\/\/ a page is a url. This is usually some content wiht a number of elements, but it\n\/\/ could be something as simple as the url for cat.jpg on your site and represent that\n\/\/ image.\ntype Page struct {\n\t*url.URL\n\tdistance int\n\tbody     string\n\tlinks    []string \/\/ immediate children\n}\n\n\/\/ responseInfo contains the status and error information from a get\ntype responseInfo struct {\n\tStatus     string\n\tStatusCode int\n\tErr        error\n}\n\n\/\/ Site is a type that implements fetcher\ntype Site struct {\n\t*url.URL\n}\n\n\/\/ Implements fetcher.\n\/\/ TODO: make the design cleaner\nfunc (s Site) Fetch(url string) (body string, urls []string, err error) {\n\t\/\/ see if the passed url is outside of the baseURL\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbuff := &bytes.Buffer{}\n\ttee := io.TeeReader(resp.Body, buff)\n\ttokens := getTokens(tee)\n\tif len(tokens) == 0 {\n\t\treturn \"\", nil, fmt.Errorf(\"%s: nothing in body\", url)\n\t}\n\turls, err = s.linksFromTokens(tokens)\n\tif err != nil {\n\t\treturn \"\", nil, err\n\t}\n\treturn buff.String(), urls, nil\n}\n\n\/\/ linksFromTokens returns a list of links (href a) found in the token slice\n\/\/ TODO should internal links be tracked separatly? i.e. record them in a\n\/\/ separate var (so they don't get fetched)\nfunc (s *Site) linksFromTokens(tokens []html.Token) ([]string, error) {\n\tvar links []string\n\tfor _, token := range tokens {\n\t\tif token.Type == html.StartTagToken && token.DataAtom.String() == \"a\" {\n\t\t\tfor _, attr := range token.Attr {\n\t\t\t\t\/\/ We only care about links that aren't #\n\t\t\t\tif attr.Key == \"href\" && !strings.HasPrefix(attr.Val, \"#\") {\n\t\t\t\t\t\/\/ parse the url\n\t\t\t\t\turl, err := url.Parse(attr.Val)\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\tlink := s.URL.ResolveReference(url)\n\t\t\t\t\tlinks = append(links, link.String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn links, nil\n}\n\n\/\/ Spider crawls the target. It contains all information needed to manage the crawl\n\/\/ including keeping track of work to do, work done, and the results.\ntype Spider struct {\n\t*queue.Queue\n\tsync.Mutex\n\twg                 sync.WaitGroup\n\t*url.URL                  \/\/ the start url\n\tbot                string \/\/ the name of the bot for robots\n\tconcurrency        int    \/\/ concurrency level of crawling\n\tfetchInterval      int64  \/\/ if > 0, interval, in milliseconds to wait between gets\n\tintervalJitter     int64  \/\/ the max jitter to be added, per fetch. Jitter is a rand with this as max.\n\tRestrictToScheme   bool   \/\/ if true, only crawls urls with the same scheme as baseURL\n\tRespectRobots      bool   \/\/ whether or not to respect the robots.txt\n\tCheckExternalLinks bool   \/\/ Check the status of any links that go to other domains\n\trobots             *robotstxt.Group\n\tmaxDepth           int\n\tPages              map[string]Page\n\tfoundURLs          map[string]struct{}     \/\/ keeps track of urls found to prevent recrawling\n\tfetchedURLs        map[string]error        \/\/ urls that have been fetched with their status\n\tskippedURLs        map[string]struct{}     \/\/ urls within the same domain that are not retrieved\n\texternalHosts      map[string]struct{}     \/\/ list of external hosts TODO: elide?\n\texternalLinks      map[string]responseInfo \/\/ list of external links; if fetched,\n}\n\n\/\/ returns a Spider with the its site's baseUrl set. The baseUrl is the start point for\n\/\/ the crawl. It is also the restriction on the crawl:\nfunc NewSpider(start string) (*Spider, error) {\n\tif start == \"\" {\n\t\treturn nil, errors.New(\"newSpider: the start url cannot be empty\")\n\t}\n\tvar err error\n\tspider := &Spider{Queue: queue.New(128, 0),\n\t\tbot:           \"geomi\",\n\t\tRespectRobots: true,\n\t\tPages:         make(map[string]Page),\n\t\tfoundURLs:     make(map[string]struct{}),\n\t\tfetchedURLs:   make(map[string]error),\n\t\tskippedURLs:   make(map[string]struct{}),\n\t\texternalHosts: make(map[string]struct{}),\n\t\texternalLinks: make(map[string]responseInfo),\n\t}\n\tspider.URL, err = url.Parse(start)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn spider, nil\n}\n\n\/\/ SetFetchInterval set's the spiders wait interval, and calculates the intervalJitter\n\/\/ value for the random jitter added to the wait. This value is in milliseconds, 1000\n\/\/ means 1 second.\n\/\/\n\/\/ When fetchInterval > 0:\n\/\/ time between fetches = fetchInterval + rand(intervalJitter)\n\/\/ max time between fetches = fetchInterval + intervalJitter\nfunc (s *Spider) SetFetchInterval(i int64) {\n\ts.fetchInterval = i\n\tjitter := i \/ 5 \/\/ jitter is, at most 20% of the fetchInterval, Min interval is 10ms\n\t\/\/ 10ms is used as the floor because arbitrary. A larger floor might be reasonable\n\tif jitter >= 10 {\n\t\ts.intervalJitter = jitter\n\t}\n}\n\n\/\/ Crawl is the exposed method for starting a crawl at baseURL. The crawl private method\n\/\/ does the actual work. The depth is the maximum depth, or distance, to crawl from the\n\/\/ baseURL. If depth == -1, no limits are set and it is expected that the entire site\n\/\/ will be crawled.\nfunc (s *Spider) Crawl(depth int) (message string, err error) {\n\ts.maxDepth = depth\n\tS := Site{URL: s.URL}\n\t\/\/ if we are to respect the robots.txt, set up the info\n\tif s.RespectRobots {\n\t\ts.getRobotsTxt()\n\t}\n\ts.Queue.Enqueue(Page{URL: s.URL})\n\terr = s.crawl(S)\n\treturn fmt.Sprintf(\"%d nodes were processed; %d external links linking to %d external hosts were not processed\", len(s.Pages), len(s.externalLinks), len(s.externalHosts)), err\n}\n\n\/\/ This crawl does all the work.\nfunc (s *Spider) crawl(fetcher Fetcher) error {\n\tvar err error\n\tfor !s.Queue.IsEmpty() {\n\t\t\/\/ get next item from queue\n\t\tpage := s.Queue.Dequeue().(Page)\n\t\t\/\/ if a depth value was passed and the distance is > depth, we are done\n\t\t\/\/ depth of 0 means no limit\n\t\tif s.maxDepth != -1 && page.distance > s.maxDepth {\n\t\t\treturn nil\n\t\t}\n\t\t\/\/ see if this is an external url\n\t\tif s.externalURL(page.URL) {\n\t\t\tif s.CheckExternalLinks {\n\t\t\t\ts.fetchExternalLink(page.URL)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ check to see if this url should be skipped for other reasons\n\t\tif s.skip(page.URL) {\n\t\t\t\/\/ see if the skipped is external and process accordingly\n\t\t\tcontinue\n\t\t}\n\t\ts.foundURLs[page.URL.String()] = struct{}{}\n\t\t\/\/ get the url\n\t\tpage.body, page.links, err = fetcher.Fetch(page.URL.String())\n\t\t\/\/ add the page and status to the map. map isn't checked for membership becuase we don't\n\t\t\/\/ fetch found urls.\n\t\ts.Lock()\n\t\ts.Pages[page.URL.String()] = page\n\t\ts.fetchedURLs[page.URL.String()] = err\n\t\ts.Unlock()\n\t\t\/\/ add the urls that the node contains to the queue\n\t\tfor _, l := range page.links {\n\t\t\tu, _ := url.Parse(l)\n\t\t\ts.Queue.Enqueue(Page{URL: u, distance: page.distance + 1})\n\t\t}\n\t\t\/\/ if their is a wait between fetches, sleep for that + random jitter\n\t\tif s.fetchInterval > 0 {\n\t\t\twait := s.fetchInterval\n\t\t\t\/\/ if there is a value for jitter, add a random jitter\n\t\t\tif s.intervalJitter > 0 {\n\t\t\t\twait += rand.Int63n(s.intervalJitter)\n\t\t\t}\n\t\t\ttime.Sleep(time.Duration(wait) * time.Millisecond)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ skip determines whether the url should be skipped.\n\/\/   * skip urls that have already been fetched\n\/\/   * skip urls that are outside of the basePath\n\/\/   * conditionally skip urls that are outside of the current scheme, even if\n\/\/     they are within the current pasePath\n\/\/   * skip if not allowed by robots\nfunc (s *Spider) skip(u *url.URL) bool {\n\ts.Lock()\n\t_, ok := s.foundURLs[u.String()]\n\ts.Unlock()\n\tif ok { \/\/ if it was found, skip it\n\t\ts.addSkippedURL(u)\n\t\treturn true\n\t}\n\n\t\/\/ skip if we are restricted to current scheme\n\tif s.RestrictToScheme {\n\t\tif u.Scheme != s.URL.Scheme {\n\t\t\ts.addSkippedURL(u)\n\t\t\treturn true\n\t\t}\n\t}\n\tif s.RespectRobots {\n\t\tok := s.robotsAllowed(u)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ skip if the url is outside of base\n\t\/\/ remove the scheme + schemePrefix so just the rest of the url is being compared\n\tif !strings.HasPrefix(u.Path, s.URL.Path) {\n\t\ts.addSkippedURL(u)\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ addSkippedURL add's the url info too the skipped info\nfunc (s *Spider) addSkippedURL(u *url.URL) {\n\ts.Lock()\n\ts.skippedURLs[u.Path] = struct{}{}\n\ts.Unlock()\n}\n\n\/\/ externalURL check's to see if the url is external to the site, host isn't the same.\n\/\/ and add's that info to the ext structs.\nfunc (s *Spider) externalURL(u *url.URL) bool {\n\tif u.Host != s.URL.Host {\n\t\ts.Lock()\n\t\t\/\/ see if the host is already in the map\n\t\t_, ok := s.externalHosts[u.Host]\n\t\tif !ok {\n\t\t\ts.externalHosts[u.Host] = struct{}{}\n\t\t}\n\t\t\/\/ same with url\n\t\t_, ok = s.externalLinks[u.String()]\n\t\tif !ok {\n\t\t\ts.externalLinks[u.String()] = responseInfo{}\n\t\t}\n\t\ts.Unlock()\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ fetchExternalLink: fetches an external link and check's it status. Note, this\n\/\/ does not implement fetcher\nfunc (s *Spider) fetchExternalLink(u *url.URL) error {\n\t\/\/ if this has already benn fetched, don't\n\tvar ri responseInfo\n\ts.Lock()\n\tr, _ := s.externalLinks[u.String()]\n\ts.Unlock()\n\tif r != ri { \/\/ if !0 value, it's been retrieved\n\n\t\treturn nil\n\t}\n\ts.Unlock()\n\tresp, err := http.Get(u.String())\n\tresp.Body.Close()\n\tif err != nil {\n\t\tr.Err = err\n\t\ts.Lock()\n\t\ts.externalLinks[u.String()] = r\n\t\ts.Unlock()\n\t\treturn err\n\t}\n\tr.Status = resp.Status\n\tr.StatusCode = resp.StatusCode\n\ts.Lock()\n\ts.externalLinks[u.String()] = r\n\ts.Unlock()\n\treturn nil\n}\n\n\/\/ getRobotsTxt retrieves and processes the site's robot.txt. If the robots.txt doesn't\n\/\/ exist, it is assumed that everything is allowed.\nfunc (s *Spider) getRobotsTxt() error {\n\tresp, err := http.Get(\"http:\/\/\" + s.URL.Host)\n\tif err != nil {\n\t\treturn err\n\t}\n\trobots, err := robotstxt.FromResponse(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.robots = robots.FindGroup(s.bot)\n\treturn nil\n}\n\n\/\/ robotsAllowed checks to see if the passed path is allowed by Robots.txt. If the\n\/\/ robots isn't set, it's always true\nfunc (s *Spider) robotsAllowed(u *url.URL) bool {\n\tif s.robots != nil {\n\t\treturn s.robots.Test(u.Path)\n\t}\n\treturn true\n}\n\n\/\/ getTokens returns all tokens in the body\nfunc getTokens(body io.Reader) []html.Token {\n\ttokens := make([]html.Token, 0)\n\tpage := html.NewTokenizer(body)\n\tfor {\n\t\ttyp := page.Next()\n\t\tif typ == html.ErrorToken {\n\t\t\treturn tokens\n\t\t}\n\t\ttokens = append(tokens, page.Token())\n\t}\n}\n\nfunc init() {\n\t\/\/ We just use math\/rand because it's good enough for our purpose.\n\trand.Seed(time.Now().UTC().UnixNano())\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"fmt\"\n  \"strings\"\n  \"flag\"\n  \"os\"\n  \/\/ \"io\/ioutil\"\n  \/\/ \"net\/http\"\n\n)\n\n\/\/ this curler is currently purpose-built to hit neo4j hosts and figure out\n\/\/ if the host is master\/slave, or up at all.\n\/\/ I'll expand it's utility just a bit later.\n\/\/ Also, this is ONLY functional with HA neo4j, not causal clustering or\n\/\/ singletons at the moment. I'll fix that later. Right now I'm all POC all the time\n\/\/ like, you know, POC to prod without any changes ftw\n\nfunc main() {\n  rawHostAddress := flag.String(\"host\", \"\", \"enter a host address or IP\") \/\/ using fqdn relies on faithful DNS resolution\n  rawNeo4jRole := flag.String(\"role\", \"master\", \"enter master or slave\") \/\/ Neo4j HA cluster has 3 roles: master, slave, arbiter. We won't test for the latter\n  rawFlagAuthContent := flag.String(\"auth\", \"\", \"enter JUST the base64-encoded auth content. We will add the rest for you. Example: aaAaaaAAaaaAbbbBb678bV==\")\n\n  flag.Parse() \/\/ parse those flags!\n\n  hostAddress := strings.ToLower(*rawHostAddress)\n  neo4jRole := strings.ToLower(*rawNeo4jRole)\n  flagAuthContent := *rawFlagAuthContent\n  fmt.Println(\"debug: printing hostAddress\", hostAddress)\n  fmt.Println(\"debug: printing neo4jRole\", neo4jRole)\n  fmt.Println(\"debug: printing flagAuthContent\", flagAuthContent)\n  \/\/ make sure neo4jRole is master or slave\n  if neo4jRole != \"master\" && neo4jRole != \"slave\" {\n    fmt.Println(\"Please ONLY use master or slave with the -role flag\")\n    os.Exit(1)\n  }\n  \/\/ rawHostAddress\/hostAddress cannot be empty\n  if hostAddress == \"\" {\n    fmt.Println(\"Enter an address for your curl target\")\n    os.Exit(1)\n  }\n  \/\/ auth content cannot be empty in this specific case\n  if flagAuthContent == \"\" {\n    fmt.Println(\"You must enter a base64-encoded auth string\")\n    os.Exit(1)\n  }\n\n  curlTarget := fmt.Sprintf(\"http:\/\/%v:7474\/db\/manage\/server\/ha\/%v\", hostAddress, neo4jRole)\n\n  fmt.Println(curlTarget)\n\n  \/\/ create the curl\n  req, err := http.NewRequest(\"GET\", curlTarget, nil)\n  if err != nil {\n    os.Exit(1)\n  }\n  \/\/ add in authorization\n  req.Header.Set(\"Authorization\", flagAuthContent)\n  \/\/ give it a method to ingest the response\n  res, _ := http.DefaultClient.Do(req)\n  \/\/ don't forget to eventually close the session\n  defer res.Body.Close()\n  \/\/ read the body into 'body'\n  rawBody, _ := ioutil.ReadAll(res.Body)\n  body := strings.ToLower(*rawBody)\n\n  fmt.Println(\"debug: printing contents of 'body' variable\", body)\n\n  if body != neo4jRole {\n    fmt.Println(\"Warning: Neo4j Server currently set to wrong role. Role should be\", neo4jRole)\n    os.Exit(1)\n  }\n}\n<commit_msg>fixed dumb mistakes, uncommented imports I'm using now<commit_after>package main\n\nimport (\n  \"fmt\"\n  \"strings\"\n  \"flag\"\n  \"os\"\n  \"io\/ioutil\"\n  \"net\/http\"\n\n)\n\n\/\/ this curler is currently purpose-built to hit neo4j hosts and figure out\n\/\/ if the host is master\/slave, or up at all.\n\/\/ I'll expand it's utility just a bit later.\n\/\/ Also, this is ONLY functional with HA neo4j, not causal clustering or\n\/\/ singletons at the moment. I'll fix that later. Right now I'm all POC all the time\n\/\/ like, you know, POC to prod without any changes ftw\n\nfunc main() {\n  rawHostAddress := flag.String(\"host\", \"\", \"enter a host address or IP\") \/\/ using fqdn relies on faithful DNS resolution\n  rawNeo4jRole := flag.String(\"role\", \"master\", \"enter master or slave\") \/\/ Neo4j HA cluster has 3 roles: master, slave, arbiter. We won't test for the latter\n  rawFlagAuthContent := flag.String(\"auth\", \"\", \"enter JUST the base64-encoded auth content. We will add the rest for you. Example: aaAaaaAAaaaAbbbBb678bV==\")\n\n  flag.Parse() \/\/ parse those flags!\n\n  hostAddress := strings.ToLower(*rawHostAddress)\n  neo4jRole := strings.ToLower(*rawNeo4jRole)\n  flagAuthContent := *rawFlagAuthContent\n  fmt.Println(\"debug: printing hostAddress\", hostAddress)\n  fmt.Println(\"debug: printing neo4jRole\", neo4jRole)\n  fmt.Println(\"debug: printing flagAuthContent\", flagAuthContent)\n  \/\/ make sure neo4jRole is master or slave\n  if neo4jRole != \"master\" && neo4jRole != \"slave\" {\n    fmt.Println(\"Please ONLY use master or slave with the -role flag\")\n    os.Exit(1)\n  }\n  \/\/ rawHostAddress\/hostAddress cannot be empty\n  if hostAddress == \"\" {\n    fmt.Println(\"Enter an address for your curl target\")\n    os.Exit(1)\n  }\n  \/\/ auth content cannot be empty in this specific case\n  if flagAuthContent == \"\" {\n    fmt.Println(\"You must enter a base64-encoded auth string\")\n    os.Exit(1)\n  }\n\n  curlTarget := fmt.Sprintf(\"http:\/\/%v:7474\/db\/manage\/server\/ha\/%v\", hostAddress, neo4jRole)\n\n  fmt.Println(curlTarget)\n\n  \/\/ create the curl\n  req, err := http.NewRequest(\"GET\", curlTarget, nil)\n  if err != nil {\n    os.Exit(1)\n  }\n  \/\/ add in authorization\n  req.Header.Set(\"Authorization\", flagAuthContent)\n  \/\/ give it a method to ingest the response\n  res, _ := http.DefaultClient.Do(req)\n  \/\/ don't forget to eventually close the session\n  defer res.Body.Close()\n  \/\/ read the body into 'body'\n  rawBody, _ := ioutil.ReadAll(res.Body)\n  body := strings.ToLower(string(rawBody))\n\n  fmt.Println(\"debug: printing contents of 'body' variable\", body)\n\n  if body != neo4jRole {\n    fmt.Println(\"Warning: Neo4j Server currently set to wrong role. Role should be\", neo4jRole)\n    os.Exit(1)\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ type Annotation struct is defined in annotation.go\n\nfunc addAnnotationHandler(rw http.ResponseWriter, req *http.Request) {\n\tlog.Printf(\"\\n\\naddAnnotation-request: %v\\n\", req)\n\n\t\/\/ get session\n\tcs, err := getClientSession(req.Header.Get(headerKeySessionKey))\n\tif err != nil {\n\t\thttp.Error(rw, \"error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer cs.done()\n\n\t\/\/ get account\n\tacc := cs.account\n\tif acc == nil {\n\t\thttp.Error(rw, \"forbidden\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase \"POST\":\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tlog.Printf(\"\\n\\nbody is %s\\n\", string(body))\n\t\tannot := &Annotation{}\n\t\terr := json.Unmarshal(body, annot)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"\\n\\nJSON unmarshal error %#v\\n\", err)\n\t\t\thttp.Error(rw, \"JSON unmarshal error\", http.StatusBadRequest) \/\/ 400\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Set every other field to things we control.\n\t\tannot.ID = bson.NewObjectId()\n\t\tannot.Annotator = acc.Username\n\t\tannot.CreateDate = time.Now()\n\t\tannot.Comments = []Comment{}\n\n\t\tlog.Printf(\"\\n\\nAnnotation to insert is: %#v\\n\", *annot)\n\n\t\terr = insertAnnotation(annot)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error inserting annotation: error %#v\\n\", err)\n\t\t\thttp.Error(rw, \"error inserting annotation\", http.StatusInternalServerError) \/\/ 500\n\t\t\treturn\n\t\t}\n\n\t\trw.WriteHeader(200)\n\t\trw.Write([]byte(`OK, inserted`))\n\t\treturn\n\tdefault:\n\t\thttp.Error(rw, \"error\", http.StatusMethodNotAllowed) \/\/ 405\n\t}\n}\n\n<commit_msg>gofmt...<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ type Annotation struct is defined in annotation.go\n\nfunc addAnnotationHandler(rw http.ResponseWriter, req *http.Request) {\n\tlog.Printf(\"\\n\\naddAnnotation-request: %v\\n\", req)\n\n\t\/\/ get session\n\tcs, err := getClientSession(req.Header.Get(headerKeySessionKey))\n\tif err != nil {\n\t\thttp.Error(rw, \"error\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdefer cs.done()\n\n\t\/\/ get account\n\tacc := cs.account\n\tif acc == nil {\n\t\thttp.Error(rw, \"forbidden\", http.StatusForbidden)\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase \"POST\":\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tlog.Printf(\"\\n\\nbody is %s\\n\", string(body))\n\t\tannot := &Annotation{}\n\t\terr := json.Unmarshal(body, annot)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"\\n\\nJSON unmarshal error %#v\\n\", err)\n\t\t\thttp.Error(rw, \"JSON unmarshal error\", http.StatusBadRequest) \/\/ 400\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Set every other field to things we control.\n\t\tannot.ID = bson.NewObjectId()\n\t\tannot.Annotator = acc.Username\n\t\tannot.CreateDate = time.Now()\n\t\tannot.Comments = []Comment{}\n\n\t\tlog.Printf(\"\\n\\nAnnotation to insert is: %#v\\n\", *annot)\n\n\t\terr = insertAnnotation(annot)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error inserting annotation: error %#v\\n\", err)\n\t\t\thttp.Error(rw, \"error inserting annotation\", http.StatusInternalServerError) \/\/ 500\n\t\t\treturn\n\t\t}\n\n\t\trw.WriteHeader(200)\n\t\trw.Write([]byte(`OK, inserted`))\n\t\treturn\n\tdefault:\n\t\thttp.Error(rw, \"error\", http.StatusMethodNotAllowed) \/\/ 405\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix orientation default value<commit_after><|endoftext|>"}
{"text":"<commit_before>package followingfeed\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/tools\/logger\"\n\t\"socialapi\/models\"\n\n\tverbalexpressions \"github.com\/VerbalExpressions\/GoVerbalExpressions\"\n\t\"github.com\/jinzhu\/gorm\"\n)\n\n\/\/ s := \"naber #foo hede #bar dede gel # baz #123 #-`3sdf\"\n\/\/ will find [foo, bar, 123]\n\/\/ will not find [' baz', '-`3sdf']\n\/\/ here is the regex -> (?m)(?:#)(\\w+)(?: )\nvar topicRegex = verbalexpressions.New().\n\tFind(\"#\").\n\tBeginCapture().\n\tWord().\n\tEndCapture().\n\tFind(\" \").\n\tRegex()\n\ntype Action func(*TopicFeedController, *models.ChannelMessage) error\n\ntype TopicFeedController struct {\n\troutes map[string]Action\n\tlog    logger.Log\n}\n\nvar HandlerNotFoundErr = errors.New(\"Handler Not Found\")\n\nfunc NewTopicFeedController(log logger.Log) *TopicFeedController {\n\t\/\/ s := \"naber #foo hede #bar dede gel # baz #123 #-`3sdf\"\n\t\/\/ res := topicRegex.FindAllStringSubmatch(s, -1)\n\t\/\/ fmt.Println(\"res\", res)\n\t\/\/ fmt.Println(\"res\", res[0][1])\n\t\/\/ fmt.Println(\"res\", res[1][1])\n\t\/\/ fmt.Println(topicRegex.String())\n\n\tffc := &TopicFeedController{\n\t\tlog: log,\n\t}\n\n\troutes := map[string]Action{\n\t\t\"channel_message_created\": (*TopicFeedController).MessageSaved,\n\t\t\"channel_message_update\":  (*TopicFeedController).MessageUpdated,\n\t\t\"channel_message_deleted\": (*TopicFeedController).MessageDeleted,\n\t}\n\n\tffc.routes = routes\n\n\treturn ffc\n}\n\nfunc (f *TopicFeedController) HandleEvent(event string, data []byte) error {\n\tf.log.Debug(\"New Event Recieved %s\", event)\n\thandler, ok := f.routes[event]\n\tif !ok {\n\t\treturn HandlerNotFoundErr\n\t}\n\n\tcm, err := mapMessage(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := isEligible(cm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !res {\n\t\treturn nil\n\t}\n\n\treturn handler(f, cm)\n}\n\nfunc (f *TopicFeedController) MessageSaved(data *models.ChannelMessage) error {\n\n\tres := topicRegex.FindAllStringSubmatch(data.Body, -1)\n\tif len(res) == 0 {\n\t\tf.log.Debug(\"Message doesnt have any topic Body: %s\", data.Body)\n\t\treturn nil\n\t}\n\n\tc, err := fetchChannel(data.InitialChannelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttopics := map[string]struct{}{}\n\n\tfor _, ele := range res {\n\t\ttopics[ele[1]] = struct{}{}\n\t}\n\n\tfor topic := range topics {\n\t\tchannelName := topic\n\t\ttc, err := fetchTopicChannel(c.Group, channelName)\n\t\tif err != nil && err != gorm.RecordNotFound {\n\t\t\treturn err\n\t\t}\n\n\t\tif err == gorm.RecordNotFound {\n\t\t\ttc, err = createTopicChannel(data.AccountId, c.Group, channelName, c.Privacy)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t_, err = tc.AddMessage(data.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc extractTopics(body string) []string {\n\tflattened := make([]string, 0)\n\n\tres := topicRegex.FindAllStringSubmatch(body, -1)\n\tif len(res) == 0 {\n\t\treturn flattened\n\t}\n\n\ttopics := map[string]struct{}{}\n\t\/\/ remove duplicate tag usages\n\tfor _, ele := range res {\n\t\ttopics[ele[1]] = struct{}{}\n\t}\n\n\tfor topic := range topics {\n\t\tflattened = append(flattened, topic)\n\t}\n\n\treturn flattened\n}\n\nfunc (f *TopicFeedController) MessageUpdated(data *models.ChannelMessage) error {\n\tf.log.Debug(\"udpate message %s\", data.Id)\n\t\/\/ fetch message's current topics from the db\n\tchannels, err := fetchMessageChannels(data.Id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ get current topics from\n\ttopics := extractTopics(data.Body)\n\tif topics == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ if message and the topics dont have any item, we can safely return\n\tif len(channels) == 0 && len(topics) == 0 {\n\t\treturn nil\n\t}\n\n\tres := getTopicDiff(channels, topics)\n\n\t\/\/ add messages\n\tif len(res[\"added\"]) > 0 {\n\t\tinitialChannel, err := fetchChannel(data.InitialChannelId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := ensureChannelMessages(initialChannel, data, res[\"added\"]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ delete messages\n\tif len(res[\"deleted\"]) > 0 {\n\t\tif err := deleteChannelMessages(channels, data, res[\"deleted\"]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc deleteChannelMessages(channels []models.Channel, data *models.ChannelMessage, toBeDeletedTopics []string) error {\n\tfor _, channel := range channels {\n\t\tfor _, topic := range toBeDeletedTopics {\n\t\t\tif channel.Name != topic {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcml := models.NewChannelMessageList()\n\t\t\tselector := map[string]interface{}{\n\t\t\t\t\"mesage_id\":  data.Id,\n\t\t\t\t\"channel_id\": channel.Id,\n\t\t\t}\n\n\t\t\tif err := cml.DeleteMessagesBySelector(selector); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\nfunc getTopicDiff(channels []models.Channel, topics []string) map[string][]string {\n\tres := make(map[string][]string)\n\n\t\/\/ aggregate all channel names into map\n\tchannelNames := map[string]struct{}{}\n\tfor _, channel := range channels {\n\t\tchannelNames[channel.Name] = struct{}{}\n\t}\n\n\t\/\/ range over new topics, bacause we are gonna remove\n\t\/\/ unused channels\n\tfor _, topic := range topics {\n\t\tfound := false\n\t\tfor channelName := range channelNames {\n\t\t\tif channelName == topic {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tres[\"added\"] = append(res[\"added\"], topic)\n\t\t} else {\n\t\t\t\/\/ if we have topic in channels\n\t\t\t\/\/ do remove it because at the end we are gonna mark\n\t\t\t\/\/ channels as deleted which are still in channelNames\n\t\t\tdelete(channelNames, topic)\n\t\t}\n\t}\n\t\/\/ flatten the deleted channel names\n\tfor channelName := range channelNames {\n\t\tres[\"deleted\"] = append(res[\"deleted\"], channelName)\n\t}\n\n\treturn res\n}\n\nfunc (f *TopicFeedController) MessageDeleted(data *models.ChannelMessage) error {\n\tcml := models.NewChannelMessageList()\n\tselector := map[string]interface{}{\n\t\t\"mesage_id\": data.Id,\n\t}\n\n\tif err := cml.DeleteMessagesBySelector(selector); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc mapMessage(data []byte) (*models.ChannelMessage, error) {\n\tcm := models.NewChannelMessage()\n\tif err := json.Unmarshal(data, cm); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cm, nil\n}\n\nfunc isEligible(cm *models.ChannelMessage) (bool, error) {\n\tif cm.InitialChannelId == 0 {\n\t\treturn false, nil\n\t}\n\n\tif cm.Type != models.ChannelMessage_TYPE_POST {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\n\/\/ todo add caching here\nfunc fetchChannel(channelId int64) (*models.Channel, error) {\n\tc := models.NewChannel()\n\tc.Id = channelId\n\t\/\/ todo - fetch only name here\n\tif err := c.Fetch(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\n\/\/ todo add caching here\nfunc fetchTopicChannel(groupName, channelName string) (*models.Channel, error) {\n\tc := models.NewChannel()\n\n\tselector := map[string]interface{}{\n\t\t\"group\": groupName,\n\t\t\"name\":  channelName,\n\t\t\"type\":  models.Channel_TYPE_TOPIC,\n\t}\n\n\terr := c.One(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc createTopicChannel(creatorId int64, groupName, channelName, privacy string) (*models.Channel, error) {\n\tc := models.NewChannel()\n\tc.Name = channelName\n\tc.CreatorId = creatorId\n\tc.Group = groupName\n\tc.Purpose = fmt.Sprintf(\"Channel for %s topic\", channelName)\n\tc.Type = models.Channel_TYPE_TOPIC\n\tc.Privacy = privacy\n\tif err := c.Create(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n<commit_msg>social: add a function for fetching channels of messages<commit_after>package followingfeed\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/tools\/logger\"\n\t\"socialapi\/models\"\n\n\tverbalexpressions \"github.com\/VerbalExpressions\/GoVerbalExpressions\"\n\t\"github.com\/jinzhu\/gorm\"\n)\n\n\/\/ s := \"naber #foo hede #bar dede gel # baz #123 #-`3sdf\"\n\/\/ will find [foo, bar, 123]\n\/\/ will not find [' baz', '-`3sdf']\n\/\/ here is the regex -> (?m)(?:#)(\\w+)(?: )\nvar topicRegex = verbalexpressions.New().\n\tFind(\"#\").\n\tBeginCapture().\n\tWord().\n\tEndCapture().\n\tFind(\" \").\n\tRegex()\n\ntype Action func(*TopicFeedController, *models.ChannelMessage) error\n\ntype TopicFeedController struct {\n\troutes map[string]Action\n\tlog    logger.Log\n}\n\nvar HandlerNotFoundErr = errors.New(\"Handler Not Found\")\n\nfunc NewTopicFeedController(log logger.Log) *TopicFeedController {\n\t\/\/ s := \"naber #foo hede #bar dede gel # baz #123 #-`3sdf\"\n\t\/\/ res := topicRegex.FindAllStringSubmatch(s, -1)\n\t\/\/ fmt.Println(\"res\", res)\n\t\/\/ fmt.Println(\"res\", res[0][1])\n\t\/\/ fmt.Println(\"res\", res[1][1])\n\t\/\/ fmt.Println(topicRegex.String())\n\n\tffc := &TopicFeedController{\n\t\tlog: log,\n\t}\n\n\troutes := map[string]Action{\n\t\t\"channel_message_created\": (*TopicFeedController).MessageSaved,\n\t\t\"channel_message_update\":  (*TopicFeedController).MessageUpdated,\n\t\t\"channel_message_deleted\": (*TopicFeedController).MessageDeleted,\n\t}\n\n\tffc.routes = routes\n\n\treturn ffc\n}\n\nfunc (f *TopicFeedController) HandleEvent(event string, data []byte) error {\n\tf.log.Debug(\"New Event Recieved %s\", event)\n\thandler, ok := f.routes[event]\n\tif !ok {\n\t\treturn HandlerNotFoundErr\n\t}\n\n\tcm, err := mapMessage(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := isEligible(cm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !res {\n\t\treturn nil\n\t}\n\n\treturn handler(f, cm)\n}\n\nfunc (f *TopicFeedController) MessageSaved(data *models.ChannelMessage) error {\n\n\tres := topicRegex.FindAllStringSubmatch(data.Body, -1)\n\tif len(res) == 0 {\n\t\tf.log.Debug(\"Message doesnt have any topic Body: %s\", data.Body)\n\t\treturn nil\n\t}\n\n\tc, err := fetchChannel(data.InitialChannelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttopics := map[string]struct{}{}\n\n\tfor _, ele := range res {\n\t\ttopics[ele[1]] = struct{}{}\n\t}\n\n\tfor topic := range topics {\n\t\tchannelName := topic\n\t\ttc, err := fetchTopicChannel(c.Group, channelName)\n\t\tif err != nil && err != gorm.RecordNotFound {\n\t\t\treturn err\n\t\t}\n\n\t\tif err == gorm.RecordNotFound {\n\t\t\ttc, err = createTopicChannel(data.AccountId, c.Group, channelName, c.Privacy)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t_, err = tc.AddMessage(data.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc extractTopics(body string) []string {\n\tflattened := make([]string, 0)\n\n\tres := topicRegex.FindAllStringSubmatch(body, -1)\n\tif len(res) == 0 {\n\t\treturn flattened\n\t}\n\n\ttopics := map[string]struct{}{}\n\t\/\/ remove duplicate tag usages\n\tfor _, ele := range res {\n\t\ttopics[ele[1]] = struct{}{}\n\t}\n\n\tfor topic := range topics {\n\t\tflattened = append(flattened, topic)\n\t}\n\n\treturn flattened\n}\n\nfunc (f *TopicFeedController) MessageUpdated(data *models.ChannelMessage) error {\n\tf.log.Debug(\"udpate message %s\", data.Id)\n\t\/\/ fetch message's current topics from the db\n\tchannels, err := fetchMessageChannels(data.Id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ get current topics from\n\ttopics := extractTopics(data.Body)\n\tif topics == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ if message and the topics dont have any item, we can safely return\n\tif len(channels) == 0 && len(topics) == 0 {\n\t\treturn nil\n\t}\n\n\tres := getTopicDiff(channels, topics)\n\n\t\/\/ add messages\n\tif len(res[\"added\"]) > 0 {\n\t\tinitialChannel, err := fetchChannel(data.InitialChannelId)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := ensureChannelMessages(initialChannel, data, res[\"added\"]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ delete messages\n\tif len(res[\"deleted\"]) > 0 {\n\t\tif err := deleteChannelMessages(channels, data, res[\"deleted\"]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc deleteChannelMessages(channels []models.Channel, data *models.ChannelMessage, toBeDeletedTopics []string) error {\n\tfor _, channel := range channels {\n\t\tfor _, topic := range toBeDeletedTopics {\n\t\t\tif channel.Name != topic {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcml := models.NewChannelMessageList()\n\t\t\tselector := map[string]interface{}{\n\t\t\t\t\"mesage_id\":  data.Id,\n\t\t\t\t\"channel_id\": channel.Id,\n\t\t\t}\n\n\t\t\tif err := cml.DeleteMessagesBySelector(selector); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc fetchMessageChannels(messageId int64) ([]models.Channel, error) {\n\tcml := models.NewChannelMessageList()\n\treturn cml.FetchMessageChannels(messageId)\n}\n\nfunc getTopicDiff(channels []models.Channel, topics []string) map[string][]string {\n\tres := make(map[string][]string)\n\n\t\/\/ aggregate all channel names into map\n\tchannelNames := map[string]struct{}{}\n\tfor _, channel := range channels {\n\t\tchannelNames[channel.Name] = struct{}{}\n\t}\n\n\t\/\/ range over new topics, bacause we are gonna remove\n\t\/\/ unused channels\n\tfor _, topic := range topics {\n\t\tfound := false\n\t\tfor channelName := range channelNames {\n\t\t\tif channelName == topic {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tres[\"added\"] = append(res[\"added\"], topic)\n\t\t} else {\n\t\t\t\/\/ if we have topic in channels\n\t\t\t\/\/ do remove it because at the end we are gonna mark\n\t\t\t\/\/ channels as deleted which are still in channelNames\n\t\t\tdelete(channelNames, topic)\n\t\t}\n\t}\n\t\/\/ flatten the deleted channel names\n\tfor channelName := range channelNames {\n\t\tres[\"deleted\"] = append(res[\"deleted\"], channelName)\n\t}\n\n\treturn res\n}\n\nfunc (f *TopicFeedController) MessageDeleted(data *models.ChannelMessage) error {\n\tcml := models.NewChannelMessageList()\n\tselector := map[string]interface{}{\n\t\t\"mesage_id\": data.Id,\n\t}\n\n\tif err := cml.DeleteMessagesBySelector(selector); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc mapMessage(data []byte) (*models.ChannelMessage, error) {\n\tcm := models.NewChannelMessage()\n\tif err := json.Unmarshal(data, cm); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cm, nil\n}\n\nfunc isEligible(cm *models.ChannelMessage) (bool, error) {\n\tif cm.InitialChannelId == 0 {\n\t\treturn false, nil\n\t}\n\n\tif cm.Type != models.ChannelMessage_TYPE_POST {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\n\/\/ todo add caching here\nfunc fetchChannel(channelId int64) (*models.Channel, error) {\n\tc := models.NewChannel()\n\tc.Id = channelId\n\t\/\/ todo - fetch only name here\n\tif err := c.Fetch(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\n\/\/ todo add caching here\nfunc fetchTopicChannel(groupName, channelName string) (*models.Channel, error) {\n\tc := models.NewChannel()\n\n\tselector := map[string]interface{}{\n\t\t\"group\": groupName,\n\t\t\"name\":  channelName,\n\t\t\"type\":  models.Channel_TYPE_TOPIC,\n\t}\n\n\terr := c.One(selector)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc createTopicChannel(creatorId int64, groupName, channelName, privacy string) (*models.Channel, error) {\n\tc := models.NewChannel()\n\tc.Name = channelName\n\tc.CreatorId = creatorId\n\tc.Group = groupName\n\tc.Purpose = fmt.Sprintf(\"Channel for %s topic\", channelName)\n\tc.Type = models.Channel_TYPE_TOPIC\n\tc.Privacy = privacy\n\tif err := c.Create(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package toolbox_test\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/viant\/toolbox\"\n\t\"testing\"\n)\n\nfunc TestNewFileSetInfoInfo(t *testing.T) {\n\n\tfileSetInfo, err := toolbox.NewFileSetInfo(\".\/fileset_info_test\/\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tassert.Equal(t, 2, len(fileSetInfo.FilesInfo()))\n\n\tfileInfo := fileSetInfo.FileInfo(\"user_test.go\")\n\tassert.NotNil(t, fileInfo)\n\n\taddresses := fileSetInfo.Type(\"Addresses\")\n\tassert.NotNil(t, addresses)\n\n\tassert.False(t, fileInfo.HasType(\"F\"))\n\tassert.True(t, fileInfo.HasType(\"User\"))\n\n\tassert.Equal(t, 7, len(fileInfo.Types()))\n\n\taddress := fileSetInfo.Type(\"Address\")\n\tassert.NotNil(t, address)\n\n\tassert.Equal(t, 2, len(address.Fields()))\n\tcountry := address.Field(\"Country\")\n\tassert.NotNil(t, country)\n\tassert.True(t, country.IsAnonymous)\n\n\tz := fileSetInfo.Type(\"Z\")\n\tassert.NotNil(t, z)\n\n\taddress2 := fileSetInfo.Type(\"Address2\")\n\tassert.Nil(t, address2)\n\n\tuserInfo := fileInfo.Type(\"User\")\n\tassert.NotNil(t, userInfo)\n\n\tassert.True(t, userInfo.HasField(\"ID\"))\n\tassert.True(t, userInfo.HasField(\"Name\"))\n\tassert.False(t, userInfo.HasField(\"FF\"))\n\n\tassert.Equal(t, 11, len(userInfo.Fields()))\n\n\tidInfo := userInfo.Field(\"ID\")\n\tassert.True(t, idInfo.IsPointer)\n\tassert.Equal(t, \"int\", idInfo.TypeName)\n\tassert.Equal(t, true, idInfo.IsPointer)\n\n\tdobInfo := userInfo.Field(\"DateOfBirth\")\n\n\tassert.Equal(t, \"time.Time\", dobInfo.TypeName)\n\tassert.Equal(t, \"time\", dobInfo.TypePackage)\n\n\tassert.Equal(t, \"`foo=\\\"bar\\\"`\", dobInfo.Tag)\n\n\taddressPointer := userInfo.Field(\"AddressPointer\")\n\tassert.NotNil(t, addressPointer)\n\tassert.Equal(t, \"Address\", addressPointer.TypeName)\n\n\tcInfo := userInfo.Field(\"C\")\n\tassert.True(t, cInfo.IsChannel)\n\n\tmInfo := userInfo.Field(\"M\")\n\tassert.True(t, mInfo.IsMap)\n\tassert.Equal(t, \"string\", mInfo.KeyTypeName)\n\tassert.Equal(t, \"[]string\", mInfo.ValueTypeName)\n\n\tintsInfo := userInfo.Field(\"Ints\")\n\tassert.True(t, intsInfo.IsSlice)\n\tassert.Equal(t, \"my comments\", userInfo.Comment)\n\n\tassert.False(t, userInfo.HasReceiver(\"Abc\"))\n\n\tassert.Equal(t, 3, len(userInfo.Receivers()))\n\tassert.True(t, userInfo.HasReceiver(\"Test\"))\n\tassert.True(t, userInfo.HasReceiver(\"Test2\"))\n\n\treceiver := userInfo.Receiver(\"Test\")\n\tassert.NotNil(t, receiver)\n\n\tappointments := userInfo.Field(\"Appointments\")\n\tassert.NotNil(t, appointments)\n\tassert.Equal(t, \"time.Time\", appointments.ComponentType)\n\n}\n<commit_msg>updated test<commit_after>package toolbox_test\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/viant\/toolbox\"\n\t\"testing\"\n)\n\nfunc TestNewFileSetInfoInfo(t *testing.T) {\n\n\tfileSetInfo, err := toolbox.NewFileSetInfo(\".\/fileset_info_test\/\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tassert.True(t, len(fileSetInfo.FilesInfo()) > 0)\n\n\tfileInfo := fileSetInfo.FileInfo(\"user_test.go\")\n\tassert.NotNil(t, fileInfo)\n\n\taddresses := fileSetInfo.Type(\"Addresses\")\n\tassert.NotNil(t, addresses)\n\n\tassert.False(t, fileInfo.HasType(\"F\"))\n\tassert.True(t, fileInfo.HasType(\"User\"))\n\n\tassert.Equal(t, 7, len(fileInfo.Types()))\n\n\taddress := fileSetInfo.Type(\"Address\")\n\tassert.NotNil(t, address)\n\n\tassert.Equal(t, 2, len(address.Fields()))\n\tcountry := address.Field(\"Country\")\n\tassert.NotNil(t, country)\n\tassert.True(t, country.IsAnonymous)\n\n\tz := fileSetInfo.Type(\"Z\")\n\tassert.NotNil(t, z)\n\n\taddress2 := fileSetInfo.Type(\"Address2\")\n\tassert.Nil(t, address2)\n\n\tuserInfo := fileInfo.Type(\"User\")\n\tassert.NotNil(t, userInfo)\n\n\tassert.True(t, userInfo.HasField(\"ID\"))\n\tassert.True(t, userInfo.HasField(\"Name\"))\n\tassert.False(t, userInfo.HasField(\"FF\"))\n\n\tassert.Equal(t, 11, len(userInfo.Fields()))\n\n\tidInfo := userInfo.Field(\"ID\")\n\tassert.True(t, idInfo.IsPointer)\n\tassert.Equal(t, \"int\", idInfo.TypeName)\n\tassert.Equal(t, true, idInfo.IsPointer)\n\n\tdobInfo := userInfo.Field(\"DateOfBirth\")\n\n\tassert.Equal(t, \"time.Time\", dobInfo.TypeName)\n\tassert.Equal(t, \"time\", dobInfo.TypePackage)\n\n\tassert.Equal(t, \"`foo=\\\"bar\\\"`\", dobInfo.Tag)\n\n\taddressPointer := userInfo.Field(\"AddressPointer\")\n\tassert.NotNil(t, addressPointer)\n\tassert.Equal(t, \"Address\", addressPointer.TypeName)\n\n\tcInfo := userInfo.Field(\"C\")\n\tassert.True(t, cInfo.IsChannel)\n\n\tmInfo := userInfo.Field(\"M\")\n\tassert.True(t, mInfo.IsMap)\n\tassert.Equal(t, \"string\", mInfo.KeyTypeName)\n\tassert.Equal(t, \"[]string\", mInfo.ValueTypeName)\n\n\tintsInfo := userInfo.Field(\"Ints\")\n\tassert.True(t, intsInfo.IsSlice)\n\tassert.Equal(t, \"my comments\", userInfo.Comment)\n\n\tassert.False(t, userInfo.HasReceiver(\"Abc\"))\n\n\tassert.True(t, len(userInfo.Receivers()) > 1)\n\tassert.True(t, userInfo.HasReceiver(\"Test\"))\n\tassert.True(t, userInfo.HasReceiver(\"Test2\"))\n\n\treceiver := userInfo.Receiver(\"Test\")\n\tassert.NotNil(t, receiver)\n\n\tappointments := userInfo.Field(\"Appointments\")\n\tassert.NotNil(t, appointments)\n\tassert.Equal(t, \"time.Time\", appointments.ComponentType)\n\n}\n<|endoftext|>"}
