{"text":"\/\/ 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}\ngoinstall: report all newly-installed public packages\/\/ 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":"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}\nFix typo: s\/validiate\/validate\/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":"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() {}\nfixed typopackage 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":"\/\/ 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}\nMove TODO to README, remove concurrency pieces.\/\/ 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":"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}\nAdd balance transaction to reversalspackage 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":"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}\nFixed type errorpackage 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)<"} {"text":"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}\nCreate moderator add and remove notificationspackage 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":"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}\ncleaning up schema declarationspackage 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":"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}\nthrow away type assertion failurespackage 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":"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}\ntreat multipart\/related as multipart\/mixedpackage 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":"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}\nCommented out diagnostic output.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":"\/\/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}\nGot line wrapping working in quotePrintEncode - just need to implement special char encoding.\/\/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":"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}\nfix(mockdb): fix type issuepackage 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":"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}\ncontainerd: backfill testspackage 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":"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}\nadded writing to json file all services opened via OPEN_ALL for automated validationpackage 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":"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}\nClose with timeout for write bufferpackage 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":"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}\nRemove 24h time range validation from maislerver request (#1792)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":"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}\nImplement inmemory contact storepackage 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":"\/\/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}\nUpdate email.go\/\/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":"\/\/ 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}\nImplemented the first tries to the ClientStarter.\/\/ 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":"\/\/ 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}\nTest fix\/\/ 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":"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}\nset arn from parameter group responsepackage 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":"\/*\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}\nBug fix on router subdomain\/*\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":"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}\nfunc for naming thingspackage 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":"\/\/ 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}\nAdd AddBoolField and ensure MetricData.Fields is initialized.\/\/ 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":"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}\nOmit replies for notification requestspackage 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":"\/\/ 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}\nPermit sub-4-byte padding in ID3 v2.4 tags\/\/ 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":"\/\/ 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}\nchore: group fix(deps) with chore(deps) in notes (#578)\/\/ 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":"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}\nFix: typopackage 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":"\/\/ 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}\nSome doc for MemSize exported functions in memory_size.go.\/\/ 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":"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}\nminor changespackage 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":"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 = `\n\n\n\t\n\t\titems<\/key>\n\t\t\n\t\t\t\n\t\t\t\tassets<\/key>\n\t\t\t\t\n\t\t\t\t\t{{if .IpaUrl}}\n\t\t\t\t\t\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tsoftware-package<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tdisplay-image<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tfull-size-image<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\tmetadata<\/key>\n\t\t\t\t\n\t\t\t\t\t{{if .BundleIdentifer}}\n\t\t\t\t\tbundle-identifier<\/key>\n\t\t\t\t\t{{.BundleIdentifer}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .BundleVersion}}\n\t\t\t\t\tbundle-version<\/key>\n\t\t\t\t\t{{.BundleVersion}}<\/string>\n\t\t\t\t\tkind<\/key>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .Title}}\n\t\t\t\t\tsoftware<\/string>\n\t\t\t\t\ttitle<\/key>\n\t\t\t\t\t{{.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}\ndynamic plist : snapshotpackage 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 = `\n\n\n\t\n\t\titems<\/key>\n\t\t\n\t\t\t\n\t\t\t\tassets<\/key>\n\t\t\t\t\n\t\t\t\t\t{{if .IpaUrl}}\n\t\t\t\t\t\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tsoftware-package<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tdisplay-image<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\n\t\t\t\t\t\tkind<\/key>\n\t\t\t\t\t\tfull-size-image<\/string>\n\t\t\t\t\t\turl<\/key>\n\t\t\t\t\t\t{{.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\tmetadata<\/key>\n\t\t\t\t\n\t\t\t\t\t{{if .BundleIdentifer}}\n\t\t\t\t\tbundle-identifier<\/key>\n\t\t\t\t\t{{.BundleIdentifer}}<\/string>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .BundleVersion}}\n\t\t\t\t\tbundle-version<\/key>\n\t\t\t\t\t{{.BundleVersion}}<\/string>\n\t\t\t\t\tkind<\/key>\n\t\t\t\t\t{{end}}\n\t\t\t\t\t{{if .Title}}\n\t\t\t\t\tsoftware<\/string>\n\t\t\t\t\ttitle<\/key>\n\t\t\t\t\t{{.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":"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}\nstring printf issuepackage 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":"\/\/ Copyright (c) - Damien Fontaine \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 \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}\nListCollections to test connection in Mongo\/\/ Copyright (c) - Damien Fontaine \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 \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":"\/\/ 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}\nClean up logging\/\/ 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":"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}\nerror package code coveragepackage 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":"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}\nUpdate NewContext commentpackage 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":"\/\/ 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}\nFix tests\/\/ 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":"\/*\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}\nverify gid in runasuser tests\/*\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":"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}\ngpio: increase test coverage for buzzer driverpackage 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":"\/\/ 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 = `
{{html .}}<\/pre>`\n\nvar frontPageText = `\n\n\n