{"text":"\/\/ Package githubhook implements handling and verification of github webhooks\npackage githubhook\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ Hook is an inbound github webhook\ntype Hook struct {\n\n\t\/\/ Id specifies the Id of a github webhook request.\n\t\/\/\n\t\/\/ Id is extracted from the inbound request's `X-Github-Delivery` header.\n\tId string\n\n\t\/\/ Event specifies the event name of a github webhook request.\n\t\/\/\n\t\/\/ Event is extracted from the inbound request's `X-GitHub-Event` header.\n\t\/\/ See: https:\/\/developer.github.com\/webhooks\/#events\n\tEvent string\n\n\t\/\/ Signature specifies the signature of a github webhook request.\n\t\/\/\n\t\/\/ Signature is extracted from the inbound request's `X-Hub-Signature` header.\n\tSignature string\n\n\t\/\/ Payload contains the raw contents of the webhook request.\n\t\/\/\n\t\/\/ Payload is extracted from the JSON-formatted body of the inbound request.\n\tPayload []byte\n}\n\nconst signaturePrefix = \"sha1=\"\nconst signatureLength = 45 \/\/ len(SignaturePrefix) + len(hex(sha1))\n\nfunc signBody(secret, body []byte) []byte {\n\tcomputed := hmac.New(sha1.New, secret)\n\tcomputed.Write(body)\n\treturn []byte(computed.Sum(nil))\n}\n\n\/\/ SignedBy checks that the provided secret matches the hook Signature\n\/\/\n\/\/ Implements validation described in github's documentation:\n\/\/ https:\/\/developer.github.com\/webhooks\/securing\/\nfunc (h *Hook) SignedBy(secret []byte) bool {\n\tif len(h.Signature) != signatureLength || !strings.HasPrefix(h.Signature, signaturePrefix) {\n\t\treturn false\n\t}\n\n\tactual := make([]byte, 20)\n\thex.Decode(actual, []byte(h.Signature[5:]))\n\n\treturn hmac.Equal(signBody(secret, h.Payload), actual)\n}\n\n\/\/ New reads a Hook from an incoming HTTP Request.\nfunc New(req *http.Request) (hook *Hook, err error) {\n\thook = new(Hook)\n\tif !strings.EqualFold(req.Method, \"POST\") {\n\t\treturn nil, errors.New(\"Unknown method!\")\n\t}\n\n\tif hook.Signature = req.Header.Get(\"x-hub-signature\"); len(hook.Signature) == 0 {\n\t\treturn nil, errors.New(\"No signature!\")\n\t}\n\n\tif hook.Event = req.Header.Get(\"x-github-event\"); len(hook.Event) == 0 {\n\t\treturn nil, errors.New(\"No event!\")\n\t}\n\n\tif hook.Id = req.Header.Get(\"x-github-delivery\"); len(hook.Id) == 0 {\n\t\treturn nil, errors.New(\"No event Id!\")\n\t}\n\n\thook.Payload, err = ioutil.ReadAll(req.Body)\n\treturn\n}\n\n\/\/ Parse reads and verifies the hook in an inbound request.\nfunc Parse(secret []byte, req *http.Request) (hook *Hook, err error) {\n\thook, err = New(req)\n\tif err == nil && !hook.SignedBy(secret) {\n\t\terr = errors.New(\"Invalid signature\")\n\t}\n\treturn\n}\nAdds `Extract` method to `Hook`\/\/ Package githubhook implements handling and verification of github webhooks\npackage githubhook\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ Hook is an inbound github webhook\ntype Hook struct {\n\n\t\/\/ Id specifies the Id of a github webhook request.\n\t\/\/\n\t\/\/ Id is extracted from the inbound request's `X-Github-Delivery` header.\n\tId string\n\n\t\/\/ Event specifies the event name of a github webhook request.\n\t\/\/\n\t\/\/ Event is extracted from the inbound request's `X-GitHub-Event` header.\n\t\/\/ See: https:\/\/developer.github.com\/webhooks\/#events\n\tEvent string\n\n\t\/\/ Signature specifies the signature of a github webhook request.\n\t\/\/\n\t\/\/ Signature is extracted from the inbound request's `X-Hub-Signature` header.\n\tSignature string\n\n\t\/\/ Payload contains the raw contents of the webhook request.\n\t\/\/\n\t\/\/ Payload is extracted from the JSON-formatted body of the inbound request.\n\tPayload []byte\n}\n\nconst signaturePrefix = \"sha1=\"\nconst signatureLength = 45 \/\/ len(SignaturePrefix) + len(hex(sha1))\n\nfunc signBody(secret, body []byte) []byte {\n\tcomputed := hmac.New(sha1.New, secret)\n\tcomputed.Write(body)\n\treturn []byte(computed.Sum(nil))\n}\n\n\/\/ SignedBy checks that the provided secret matches the hook Signature\n\/\/\n\/\/ Implements validation described in github's documentation:\n\/\/ https:\/\/developer.github.com\/webhooks\/securing\/\nfunc (h *Hook) SignedBy(secret []byte) bool {\n\tif len(h.Signature) != signatureLength || !strings.HasPrefix(h.Signature, signaturePrefix) {\n\t\treturn false\n\t}\n\n\tactual := make([]byte, 20)\n\thex.Decode(actual, []byte(h.Signature[5:]))\n\n\treturn hmac.Equal(signBody(secret, h.Payload), actual)\n}\n\n\/\/ Extract unmarshals Payload into a destination interface.\nfunc (h *Hook) Extract(dst interface{}) error {\n\treturn json.Unmarshal(h.Payload, dst)\n}\n\n\/\/ New reads a Hook from an incoming HTTP Request.\nfunc New(req *http.Request) (hook *Hook, err error) {\n\thook = new(Hook)\n\tif !strings.EqualFold(req.Method, \"POST\") {\n\t\treturn nil, errors.New(\"Unknown method!\")\n\t}\n\n\tif hook.Signature = req.Header.Get(\"x-hub-signature\"); len(hook.Signature) == 0 {\n\t\treturn nil, errors.New(\"No signature!\")\n\t}\n\n\tif hook.Event = req.Header.Get(\"x-github-event\"); len(hook.Event) == 0 {\n\t\treturn nil, errors.New(\"No event!\")\n\t}\n\n\tif hook.Id = req.Header.Get(\"x-github-delivery\"); len(hook.Id) == 0 {\n\t\treturn nil, errors.New(\"No event Id!\")\n\t}\n\n\thook.Payload, err = ioutil.ReadAll(req.Body)\n\treturn\n}\n\n\/\/ Parse reads and verifies the hook in an inbound request.\nfunc Parse(secret []byte, req *http.Request) (hook *Hook, err error) {\n\thook, err = New(req)\n\tif err == nil && !hook.SignedBy(secret) {\n\t\terr = errors.New(\"Invalid signature\")\n\t}\n\treturn\n}\n<|endoftext|>"} {"text":"package charm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ InfoResponse is sent by the charm store in response to charm-info requests.\ntype InfoResponse struct {\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tSha256 string `json:\"sha256,omitempty\"`\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n}\n\n\/\/ Repository respresents a collection of charms.\ntype Repository interface {\n\tGet(curl *URL) (Charm, error)\n\tLatest(curl *URL) (int, error)\n}\n\n\/\/ store is a Repository that talks to the juju charm server (in ..\/store).\ntype store struct {\n\tbaseURL string\n\tcachePath string\n}\n\nconst (\n\tstoreURL = \"https:\/\/store.juju.ubuntu.com\"\n\tcachePath = \"$HOME\/.juju\/cache\"\n)\n\n\/\/ Store returns a Repository that provides access to the juju charm store.\nfunc Store() Repository {\n\treturn &store{storeURL, os.ExpandEnv(cachePath)}\n}\n\n\/\/ info returns the revision and SHA256 digest of the charm referenced by curl.\nfunc (s *store) info(curl *URL) (rev int, digest string, err error) {\n\tkey := curl.String()\n\tresp, err := http.Get(s.baseURL + \"\/charm-info?charms=\" + url.QueryEscape(key))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\tinfos := make(map[string]*InfoResponse)\n\tif err = json.Unmarshal(body, &infos); err != nil {\n\t\treturn\n\t}\n\tinfo, found := infos[key]\n\tif !found {\n\t\terr = fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t\treturn\n\t}\n\tfor _, w := range info.Warnings {\n\t\tlog.Printf(\"charm: WARNING: charm store reports for %q: %s\", key, w)\n\t}\n\tif info.Errors != nil {\n\t\terr = fmt.Errorf(\n\t\t\t\"charm info errors for %q: %s\", key, strings.Join(info.Errors, \"; \"),\n\t\t)\n\t\treturn\n\t}\n\treturn info.Revision, info.Sha256, nil\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (s *store) Latest(curl *URL) (int, error) {\n\trev, _, err := s.info(curl.WithRevision(-1))\n\treturn rev, err\n}\n\n\/\/ verify returns an error unless a file exists at path with a hex-encoded\n\/\/ SHA256 matching digest.\nfunc verify(path, digest string) error {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\th := sha256.New()\n\th.Write(b)\n\tif hex.EncodeToString(h.Sum(nil)) != digest {\n\t\treturn fmt.Errorf(\"bad SHA256 of %q\", path)\n\t}\n\treturn nil\n}\n\n\/\/ Get returns the charm referenced by curl.\nfunc (s *store) Get(curl *URL) (Charm, error) {\n\tif err := os.MkdirAll(s.cachePath, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\trev, digest, err := s.info(curl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif curl.Revision == -1 {\n\t\tcurl = curl.WithRevision(rev)\n\t} else if curl.Revision != rev {\n\t\treturn nil, fmt.Errorf(\"charm: store returned charm with wrong revision for %q\", curl.String())\n\t}\n\tpath := filepath.Join(s.cachePath, Quote(curl.String())+\".charm\")\n\tif verify(path, digest) != nil {\n\t\tresp, err := http.Get(s.baseURL + \"\/charm\/\" + url.QueryEscape(curl.Path()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tf, err := ioutil.TempFile(s.cachePath, \"charm-download\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdlPath := f.Name()\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif cerr := f.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\tif err != nil {\n\t\t\tos.Remove(dlPath)\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.Rename(dlPath, path); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := verify(path, digest); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ReadBundle(path)\n}\n\n\/\/ LocalRepository represents a local directory containing subdirectories\n\/\/ named after an Ubuntu series, each of which contains charms targeted for\n\/\/ that series. For example:\n\/\/\n\/\/ \/path\/to\/repository\/oneiric\/mongodb\/\n\/\/ \/path\/to\/repository\/precise\/mongodb.charm\n\/\/ \/path\/to\/repository\/precise\/wordpress\/\ntype LocalRepository struct {\n\tPath string\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (r *LocalRepository) Latest(curl *URL) (int, error) {\n\tch, err := r.Get(curl.WithRevision(-1))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn ch.Revision(), nil\n}\n\nfunc repoNotFound(path string) error {\n\treturn fmt.Errorf(\"no repository found at %q\", path)\n}\n\nfunc charmNotFound(curl *URL) error {\n\treturn fmt.Errorf(\"no charms found matching %q\", curl)\n}\n\nfunc mightBeCharm(info os.FileInfo) bool {\n\tif info.IsDir() {\n\t\treturn !strings.HasPrefix(info.Name(), \".\")\n\t}\n\treturn strings.HasSuffix(info.Name(), \".charm\")\n}\n\n\/\/ Get returns a charm matching curl, if one exists. If curl has a revision of\n\/\/ -1, it returns the latest charm that matches curl. If multiple candidates\n\/\/ satisfy the foregoing, the first one encountered will be returned.\nfunc (r *LocalRepository) Get(curl *URL) (Charm, error) {\n\tif curl.Schema != \"local\" {\n\t\treturn nil, fmt.Errorf(\"local repository got URL with non-local schema: %q\", curl)\n\t}\n\tinfo, err := os.Stat(r.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = repoNotFound(r.Path)\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !info.IsDir() {\n\t\treturn nil, repoNotFound(r.Path)\n\t}\n\tpath := filepath.Join(r.Path, curl.Series)\n\tinfos, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, charmNotFound(curl)\n\t}\n\tvar latest Charm\n\tfor _, info := range infos {\n\t\tif !mightBeCharm(info) {\n\t\t\tcontinue\n\t\t}\n\t\tchPath := filepath.Join(path, info.Name())\n\t\tif ch, err := Read(chPath); err != nil {\n\t\t\tlog.Printf(\"charm: WARNING: failed to load charm at %q: %s\", chPath, err)\n\t\t} else if ch.Meta().Name == curl.Name {\n\t\t\tif ch.Revision() == curl.Revision {\n\t\t\t\treturn ch, nil\n\t\t\t}\n\t\t\tif latest == nil || ch.Revision() > latest.Revision() {\n\t\t\t\tlatest = ch\n\t\t\t}\n\t\t}\n\t}\n\tif curl.Revision == -1 && latest != nil {\n\t\treturn latest, nil\n\t}\n\treturn nil, charmNotFound(curl)\n}\ncharm: stream SHA256 of charmpackage charm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ InfoResponse is sent by the charm store in response to charm-info requests.\ntype InfoResponse struct {\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tSha256 string `json:\"sha256,omitempty\"`\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n}\n\n\/\/ Repository respresents a collection of charms.\ntype Repository interface {\n\tGet(curl *URL) (Charm, error)\n\tLatest(curl *URL) (int, error)\n}\n\n\/\/ store is a Repository that talks to the juju charm server (in ..\/store).\ntype store struct {\n\tbaseURL string\n\tcachePath string\n}\n\nconst (\n\tstoreURL = \"https:\/\/store.juju.ubuntu.com\"\n\tcachePath = \"$HOME\/.juju\/cache\"\n)\n\n\/\/ Store returns a Repository that provides access to the juju charm store.\nfunc Store() Repository {\n\treturn &store{storeURL, os.ExpandEnv(cachePath)}\n}\n\n\/\/ info returns the revision and SHA256 digest of the charm referenced by curl.\nfunc (s *store) info(curl *URL) (rev int, digest string, err error) {\n\tkey := curl.String()\n\tresp, err := http.Get(s.baseURL + \"\/charm-info?charms=\" + url.QueryEscape(key))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\tinfos := make(map[string]*InfoResponse)\n\tif err = json.Unmarshal(body, &infos); err != nil {\n\t\treturn\n\t}\n\tinfo, found := infos[key]\n\tif !found {\n\t\terr = fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t\treturn\n\t}\n\tfor _, w := range info.Warnings {\n\t\tlog.Printf(\"charm: WARNING: charm store reports for %q: %s\", key, w)\n\t}\n\tif info.Errors != nil {\n\t\terr = fmt.Errorf(\n\t\t\t\"charm info errors for %q: %s\", key, strings.Join(info.Errors, \"; \"),\n\t\t)\n\t\treturn\n\t}\n\treturn info.Revision, info.Sha256, nil\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (s *store) Latest(curl *URL) (int, error) {\n\trev, _, err := s.info(curl.WithRevision(-1))\n\treturn rev, err\n}\n\n\/\/ verify returns an error unless a file exists at path with a hex-encoded\n\/\/ SHA256 matching digest.\nfunc verify(path, digest string) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn err\n\t}\n\tif hex.EncodeToString(h.Sum(nil)) != digest {\n\t\treturn fmt.Errorf(\"bad SHA256 of %q\", path)\n\t}\n\treturn nil\n}\n\n\/\/ Get returns the charm referenced by curl.\nfunc (s *store) Get(curl *URL) (Charm, error) {\n\tif err := os.MkdirAll(s.cachePath, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\trev, digest, err := s.info(curl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif curl.Revision == -1 {\n\t\tcurl = curl.WithRevision(rev)\n\t} else if curl.Revision != rev {\n\t\treturn nil, fmt.Errorf(\"charm: store returned charm with wrong revision for %q\", curl.String())\n\t}\n\tpath := filepath.Join(s.cachePath, Quote(curl.String())+\".charm\")\n\tif verify(path, digest) != nil {\n\t\tresp, err := http.Get(s.baseURL + \"\/charm\/\" + url.QueryEscape(curl.Path()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tf, err := ioutil.TempFile(s.cachePath, \"charm-download\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdlPath := f.Name()\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif cerr := f.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\tif err != nil {\n\t\t\tos.Remove(dlPath)\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.Rename(dlPath, path); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := verify(path, digest); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ReadBundle(path)\n}\n\n\/\/ LocalRepository represents a local directory containing subdirectories\n\/\/ named after an Ubuntu series, each of which contains charms targeted for\n\/\/ that series. For example:\n\/\/\n\/\/ \/path\/to\/repository\/oneiric\/mongodb\/\n\/\/ \/path\/to\/repository\/precise\/mongodb.charm\n\/\/ \/path\/to\/repository\/precise\/wordpress\/\ntype LocalRepository struct {\n\tPath string\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (r *LocalRepository) Latest(curl *URL) (int, error) {\n\tch, err := r.Get(curl.WithRevision(-1))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn ch.Revision(), nil\n}\n\nfunc repoNotFound(path string) error {\n\treturn fmt.Errorf(\"no repository found at %q\", path)\n}\n\nfunc charmNotFound(curl *URL) error {\n\treturn fmt.Errorf(\"no charms found matching %q\", curl)\n}\n\nfunc mightBeCharm(info os.FileInfo) bool {\n\tif info.IsDir() {\n\t\treturn !strings.HasPrefix(info.Name(), \".\")\n\t}\n\treturn strings.HasSuffix(info.Name(), \".charm\")\n}\n\n\/\/ Get returns a charm matching curl, if one exists. If curl has a revision of\n\/\/ -1, it returns the latest charm that matches curl. If multiple candidates\n\/\/ satisfy the foregoing, the first one encountered will be returned.\nfunc (r *LocalRepository) Get(curl *URL) (Charm, error) {\n\tif curl.Schema != \"local\" {\n\t\treturn nil, fmt.Errorf(\"local repository got URL with non-local schema: %q\", curl)\n\t}\n\tinfo, err := os.Stat(r.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = repoNotFound(r.Path)\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !info.IsDir() {\n\t\treturn nil, repoNotFound(r.Path)\n\t}\n\tpath := filepath.Join(r.Path, curl.Series)\n\tinfos, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, charmNotFound(curl)\n\t}\n\tvar latest Charm\n\tfor _, info := range infos {\n\t\tif !mightBeCharm(info) {\n\t\t\tcontinue\n\t\t}\n\t\tchPath := filepath.Join(path, info.Name())\n\t\tif ch, err := Read(chPath); err != nil {\n\t\t\tlog.Printf(\"charm: WARNING: failed to load charm at %q: %s\", chPath, err)\n\t\t} else if ch.Meta().Name == curl.Name {\n\t\t\tif ch.Revision() == curl.Revision {\n\t\t\t\treturn ch, nil\n\t\t\t}\n\t\t\tif latest == nil || ch.Revision() > latest.Revision() {\n\t\t\t\tlatest = ch\n\t\t\t}\n\t\t}\n\t}\n\tif curl.Revision == -1 && latest != nil {\n\t\treturn latest, nil\n\t}\n\treturn nil, charmNotFound(curl)\n}\n<|endoftext|>"} {"text":"package main\n\nvar WorkerVersion = \"0.0.0-dev\"\nset worker version default to emptypackage main\n\nvar WorkerVersion = \"\"\n<|endoftext|>"} {"text":"package paxos\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"goshawkdb.io\/common\"\n\t\"goshawkdb.io\/server\"\n\tmsgs \"goshawkdb.io\/server\/capnp\"\n\t\"goshawkdb.io\/server\/configuration\"\n)\n\n\/\/ OutcomeAccumulator groups together all the different outcomes we've\n\/\/ received for a given txn. Once we have at least fInc outcomes from\n\/\/ distinct acceptors which all have equal Clocks, we know we have a\n\/\/ consensus on the result.\ntype OutcomeAccumulator struct {\n\tacceptorIdToTxnOutcome map[common.RMId]*txnOutcome\n\toutcomes []*txnOutcome\n\tdecidingOutcome *txnOutcome\n\tpendingTGC map[common.RMId]server.EmptyStruct\n\tfInc int\n\tacceptorCount int\n}\n\nfunc NewOutcomeAccumulator(fInc int, acceptors common.RMIds) *OutcomeAccumulator {\n\tpendingTGC := make(map[common.RMId]server.EmptyStruct, len(acceptors))\n\tfor _, rmId := range acceptors {\n\t\tpendingTGC[rmId] = server.EmptyStructVal\n\t}\n\treturn &OutcomeAccumulator{\n\t\tacceptorIdToTxnOutcome: make(map[common.RMId]*txnOutcome),\n\t\toutcomes: []*txnOutcome{},\n\t\tpendingTGC: pendingTGC,\n\t\tfInc: fInc,\n\t\tacceptorCount: len(acceptors),\n\t}\n}\n\nfunc (oa *OutcomeAccumulator) TopologyChange(topology *configuration.Topology) bool {\n\tresult := false\n\tfor rmId := range topology.RMsRemoved() {\n\t\tif _, found := oa.pendingTGC[rmId]; found {\n\t\t\tdelete(oa.pendingTGC, rmId)\n\t\t\tif outcome, found := oa.acceptorIdToTxnOutcome[rmId]; found {\n\t\t\t\tdelete(oa.acceptorIdToTxnOutcome, rmId)\n\t\t\t\toutcome.outcomeReceivedCount--\n\t\t\t}\n\t\t\toa.acceptorCount--\n\t\t\tif oa.acceptorCount > oa.fInc {\n\t\t\t\toa.fInc = oa.acceptorCount\n\t\t\t}\n\t\t\tif oa.decidingOutcome != nil {\n\t\t\t\tresult = result || oa.decidingOutcome.outcomeReceivedCount == oa.acceptorCount\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (oa *OutcomeAccumulator) BallotOutcomeReceived(acceptorId common.RMId, outcome *msgs.Outcome) (*msgs.Outcome, bool) {\n\toutcomeEq := (*outcomeEqualId)(outcome)\n\tif tOut, found := oa.acceptorIdToTxnOutcome[acceptorId]; found {\n\t\tif tOut.outcome.Equal(outcomeEq) {\n\t\t\t\/\/ It's completely a duplicate msg. No change to our state so just return\n\t\t\treturn nil, false\n\t\t} else {\n\t\t\t\/\/ The acceptor has changed its mind.\n\t\t\ttOut.outcomeReceivedCount--\n\t\t\t\/\/ Paxos guarantees that in this case, tOut != oa.decidingOutcome\n\t\t}\n\t}\n\n\ttOut := oa.getOutcome(outcomeEq)\n\tif tOut == nil {\n\t\ttOut = &txnOutcome{\n\t\t\toutcome: outcomeEq,\n\t\t\toutcomeReceivedCount: 1,\n\t\t}\n\t\toa.addToOutcomes(tOut)\n\n\t} else {\n\t\t\/\/ We've checked for duplicate msgs above, so we don't need to\n\t\t\/\/ worry about that here.\n\t\ttOut.outcomeReceivedCount++\n\t}\n\toa.acceptorIdToTxnOutcome[acceptorId] = tOut\n\n\tallAgreed := tOut.outcomeReceivedCount == oa.acceptorCount\n\tif oa.decidingOutcome == nil && oa.fInc == tOut.outcomeReceivedCount {\n\t\toa.decidingOutcome = tOut\n\t\treturn (*msgs.Outcome)(oa.decidingOutcome.outcome), allAgreed\n\t}\n\treturn nil, allAgreed\n}\n\nfunc (oa *OutcomeAccumulator) TxnGloballyCompleteReceived(acceptorId common.RMId) bool {\n\tserver.Log(\"TGC received from\", acceptorId, \"; pending:\", oa.pendingTGC)\n\tdelete(oa.pendingTGC, acceptorId)\n\treturn len(oa.pendingTGC) == 0\n}\n\nfunc (oa *OutcomeAccumulator) addToOutcomes(tOut *txnOutcome) {\n\toa.outcomes = append(oa.outcomes, tOut)\n}\n\nfunc (oa *OutcomeAccumulator) getOutcome(outcome *outcomeEqualId) *txnOutcome {\n\tfor _, tOut := range oa.outcomes {\n\t\tif tOut.outcome.Equal(outcome) {\n\t\t\treturn tOut\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (oa *OutcomeAccumulator) IsAllAborts() []common.RMId {\n\tcount := len(oa.acceptorIdToTxnOutcome)\n\tfor _, outcome := range oa.outcomes {\n\t\tif outcome.outcomeReceivedCount == count && (*msgs.Outcome)(outcome.outcome).Which() == msgs.OUTCOME_ABORT {\n\t\t\tacceptors := make([]common.RMId, 0, count)\n\t\t\tfor rmId := range oa.acceptorIdToTxnOutcome {\n\t\t\t\tacceptors = append(acceptors, rmId)\n\t\t\t}\n\t\t\treturn acceptors\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (oa *OutcomeAccumulator) Status(sc *server.StatusConsumer) {\n\toutcomeToAcceptors := make(map[*txnOutcome][]common.RMId)\n\tacceptors := make([]common.RMId, 0, len(oa.acceptorIdToTxnOutcome))\n\tfor rmId, outcome := range oa.acceptorIdToTxnOutcome {\n\t\tacceptors = append(acceptors, rmId)\n\t\tif list, found := outcomeToAcceptors[outcome]; found {\n\t\t\toutcomeToAcceptors[outcome] = append(list, rmId)\n\t\t} else {\n\t\t\toutcomeToAcceptors[outcome] = []common.RMId{rmId}\n\t\t}\n\t}\n\tsc.Emit(fmt.Sprintf(\"- known outcomes from acceptors: %v\", acceptors))\n\tsc.Emit(fmt.Sprintf(\"- unique outcomes: %v\", outcomeToAcceptors))\n\tsc.Emit(fmt.Sprintf(\"- outcome decided? %v\", oa.decidingOutcome != nil))\n\tsc.Emit(fmt.Sprintf(\"- pending TGCs from: %v\", oa.pendingTGC))\n\tsc.Join()\n}\n\ntype txnOutcome struct {\n\toutcome *outcomeEqualId\n\toutcomeReceivedCount int\n}\n\nfunc (to *txnOutcome) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", to.outcome, to.outcomeReceivedCount)\n}\n\ntype outcomeEqualId msgs.Outcome\n\nfunc (id *outcomeEqualId) String() string {\n\tidList := (*msgs.Outcome)(id).Id()\n\tbuf := \"OutcomeId[\"\n\tfor idx, l := 0, idList.Len(); idx < l; idx++ {\n\t\toutId := idList.At(idx)\n\t\tbuf += fmt.Sprintf(\"%v{\", common.MakeVarUUId(outId.VarId()))\n\t\tinstList := outId.AcceptedInstances()\n\t\tfor idy, m := 0, instList.Len(); idy < m; idy++ {\n\t\t\tinst := instList.At(idy)\n\t\t\tbuf += fmt.Sprintf(\"(instance %v: vote %v)\", common.RMId(inst.RmId()), inst.Vote())\n\t\t}\n\t\tbuf += \"} \"\n\t}\n\tbuf += \"]\"\n\treturn buf\n}\n\nfunc (a *outcomeEqualId) Equal(b *outcomeEqualId) bool {\n\tswitch {\n\tcase a == b:\n\t\treturn true\n\tcase a == nil || b == nil:\n\t\treturn false\n\tdefault:\n\t\taIdList, bIdList := (*msgs.Outcome)(a).Id(), (*msgs.Outcome)(b).Id()\n\t\tif aIdList.Len() != bIdList.Len() {\n\t\t\treturn false\n\t\t}\n\t\tfor idx, l := 0, aIdList.Len(); idx < l; idx++ {\n\t\t\taOutId, bOutId := aIdList.At(idx), bIdList.At(idx)\n\t\t\tif !bytes.Equal(aOutId.VarId(), bOutId.VarId()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\taAccInstList, bAccInstList := aOutId.AcceptedInstances(), bOutId.AcceptedInstances()\n\t\t\tif aAccInstList.Len() != bAccInstList.Len() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor idy, m := 0, aAccInstList.Len(); idy < m; idy++ {\n\t\t\t\taAccInstId, bAccInstId := aAccInstList.At(idy), bAccInstList.At(idy)\n\t\t\t\tif !(aAccInstId.RmId() == bAccInstId.RmId() && aAccInstId.Vote() == bAccInstId.Vote()) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\nReworked outcome accumulator. This is probably now slightly out of date given most recent thinking, but it's still better than what was. Does not compile yet though as much more needs to be changed. Yay. However, I do see a path forwards which isn't as terrifying as I was thinking it might become, so that's good. Ref T6.package paxos\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"goshawkdb.io\/common\"\n\t\"goshawkdb.io\/server\"\n\tmsgs \"goshawkdb.io\/server\/capnp\"\n\t\"goshawkdb.io\/server\/configuration\"\n)\n\n\/\/ OutcomeAccumulator groups together all the different outcomes we've\n\/\/ received for a given txn. Once we have at least fInc outcomes from\n\/\/ distinct acceptors which all have equal Ids, we know we have a\n\/\/ consensus on the result.\ntype OutcomeAccumulator struct {\n\tacceptors common.RMIds\n\tacceptorIdToTxnOutcome map[common.RMId]*acceptorIdxWithTxnOutcome\n\twinningOutcome *txnOutcome\n\tallKnownOutcomes []*txnOutcome\n\tfInc int\n\tpendingTGC int\n}\n\ntype acceptorIdxWithTxnOutcome struct {\n\tidx int\n\ttgcReceived bool\n\ttOut *txnOutcome\n}\n\ntype txnOutcome struct {\n\toutcome *outcomeEqualId\n\tacceptors common.RMIds\n\toutcomeReceivedCount int\n}\n\nfunc NewOutcomeAccumulator(fInc int, acceptors common.RMIds) *OutcomeAccumulator {\n\tacceptorIdToTxnOutcome := make(map[common.RMId]*acceptorIdxWithTxnOutcome, len(acceptors))\n\tids := make([]acceptorIdxWithTxnOutcome, len(acceptors))\n\tfor idx, rmId := range acceptors {\n\t\tptr := &ids[idx]\n\t\tptr.idx = idx\n\t\tacceptorIdToTxnOutcome[rmId] = ptr\n\t}\n\treturn &OutcomeAccumulator{\n\t\tacceptors: acceptors,\n\t\tacceptorIdToTxnOutcome: acceptorIdToTxnOutcome,\n\t\twinningOutcome: nil,\n\t\tallKnownOutcomes: make([]*txnOutcome, 0, 1),\n\t\tfInc: fInc,\n\t\tpendingTGC: len(acceptors),\n\t}\n}\n\nfunc (oa *OutcomeAccumulator) TopologyChange(topology *configuration.Topology) bool {\n\tfor rmId := range topology.RMsRemoved() {\n\t\tif accIdxTOut, found := oa.acceptorIdToTxnOutcome[rmId]; found {\n\t\t\tdelete(oa.acceptorIdToTxnOutcome, rmId)\n\t\t\toa.acceptors[accIdxTOut.idx] = common.RMIdEmpty\n\t\t\tif l := len(oa.acceptors); l > oa.fInc {\n\t\t\t\toa.fInc = l\n\t\t\t}\n\n\t\t\taccIdxTOut.tgcReceived = true\n\t\t\tif tOut := accIdxTOut.tOut; tOut != nil {\n\t\t\t\taccIdxTOut.tOut = nil\n\t\t\t\ttOut.outcomeReceivedCount--\n\t\t\t\ttOut.acceptors[accIdxTOut.idx] = common.RMIdEmpty\n\t\t\t}\n\t\t}\n\t}\n\treturn oa.winningOutcome != nil && oa.winningOutcome.outcomeReceivedCount == oa.acceptors.NonEmptyLen()\n}\n\nfunc (oa *OutcomeAccumulator) BallotOutcomeReceived(acceptorId common.RMId, outcome *msgs.Outcome) (*msgs.Outcome, common.RMIds, bool) {\n\tif accIdxTOut, found := oa.acceptorIdToTxnOutcome[acceptorId]; found {\n\t\toutcomeEq := (*outcomeEqualId)(outcome)\n\t\ttOut := accIdxTOut.tOut\n\n\t\tif tOut != nil {\n\t\t\tif tOut.outcome.Equal(outcomeEq) {\n\t\t\t\t\/\/ It's completely a duplicate msg. No change to our state so just return\n\t\t\t\treturn nil, nil, false\n\t\t\t} else {\n\t\t\t\t\/\/ The acceptor has changed its mind.\n\t\t\t\ttOut.outcomeReceivedCount--\n\t\t\t\ttOut.acceptors[accIdxTOut.idx] = common.RMIdEmpty\n\t\t\t\t\/\/ Paxos guarantees that in this case, tOut != oa.winningOutcome\n\t\t\t}\n\t\t}\n\n\t\ttOut = oa.getOutcome(outcomeEq)\n\t\tif tOut == nil {\n\t\t\ttOut = &txnOutcome{\n\t\t\t\toutcome: outcomeEq,\n\t\t\t\tacceptors: make([]common.RMId, len(oa.acceptors)),\n\t\t\t\toutcomeReceivedCount: 1,\n\t\t\t}\n\t\t\ttOut.acceptors[accIdxTOut.idx] = acceptorId\n\t\t\toa.addToOutcomes(tOut)\n\n\t\t} else {\n\t\t\t\/\/ We've checked for duplicate msgs above, so we don't need to\n\t\t\t\/\/ worry about that here.\n\t\t\ttOut.outcomeReceivedCount++\n\t\t\ttOut.acceptors[accIdxTOut.idx] = acceptorId\n\t\t}\n\t\taccIdxTOut.tOut = tOut\n\n\t\tif oa.winningOutcome == nil && oa.fInc == tOut.outcomeReceivedCount {\n\t\t\toa.winningOutcome = tOut\n\t\t\treturn (*msgs.Outcome)(oa.winningOutcome.outcome),\n\t\t\t\ttOut.acceptors.NonEmpty(),\n\t\t\t\ttOut.outcomeReceivedCount == oa.acceptors.NonEmptyLen()\n\t\t} else if oa.winningOutcome == tOut {\n\t\t\treturn nil, []common.RMId{acceptorId}, tOut.outcomeReceivedCount == oa.acceptors.NonEmptyLen()\n\t\t}\n\t}\n\treturn nil, nil, false\n}\n\nfunc (oa *OutcomeAccumulator) TxnGloballyCompleteReceived(acceptorId common.RMId) bool {\n\tserver.Log(\"TGC received from\", acceptorId)\n\tif accIdxTOut, found := oa.acceptorIdToTxnOutcome[acceptorId]; found && !accIdxTOut.tgcReceived {\n\t\taccIdxTOut.tgcReceived = true\n\t\toa.pendingTGC--\n\t\treturn oa.pendingTGC == 0\n\t}\n\treturn false\n}\n\nfunc (oa *OutcomeAccumulator) addToOutcomes(tOut *txnOutcome) {\n\toa.allKnownOutcomes = append(oa.allKnownOutcomes, tOut)\n}\n\nfunc (oa *OutcomeAccumulator) getOutcome(outcome *outcomeEqualId) *txnOutcome {\n\tfor _, tOut := range oa.allKnownOutcomes {\n\t\tif outcome.Equal(tOut.outcome) {\n\t\t\treturn tOut\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (oa *OutcomeAccumulator) IsAllAborts() []common.RMId {\n\tvar nonEmpty *txnOutcome\n\tfor _, tOut := range oa.allKnownOutcomes {\n\t\tif tOut.outcomeReceivedCount != 0 {\n\t\t\tif nonEmpty == nil && (*msgs.Outcome)(tOut.outcome).Which() == msgs.OUTCOME_ABORT {\n\t\t\t\tnonEmpty = tOut\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif nonEmpty != nil {\n\t\treturn nonEmpty.acceptors.NonEmpty()\n\t}\n\treturn nil\n}\n\nfunc (oa *OutcomeAccumulator) Status(sc *server.StatusConsumer) {\n\tsc.Emit(fmt.Sprintf(\"- unique outcomes: %v\", oa.allKnownOutcomes))\n\tsc.Emit(fmt.Sprintf(\"- outcome decided? %v\", oa.winningOutcome != nil))\n\tsc.Emit(fmt.Sprintf(\"- pending TGC count: %v\", oa.pendingTGC))\n\tsc.Join()\n}\n\nfunc (to *txnOutcome) String() string {\n\treturn fmt.Sprintf(\"%v:%v\", to.outcome, to.acceptors.NonEmpty())\n}\n\ntype outcomeEqualId msgs.Outcome\n\nfunc (id *outcomeEqualId) String() string {\n\tidList := (*msgs.Outcome)(id).Id()\n\tbuf := \"OutcomeId[\"\n\tfor idx, l := 0, idList.Len(); idx < l; idx++ {\n\t\toutId := idList.At(idx)\n\t\tbuf += fmt.Sprintf(\"%v{\", common.MakeVarUUId(outId.VarId()))\n\t\tinstList := outId.AcceptedInstances()\n\t\tfor idy, m := 0, instList.Len(); idy < m; idy++ {\n\t\t\tinst := instList.At(idy)\n\t\t\tbuf += fmt.Sprintf(\"(instance %v: vote %v)\", common.RMId(inst.RmId()), inst.Vote())\n\t\t}\n\t\tbuf += \"} \"\n\t}\n\tbuf += \"]\"\n\treturn buf\n}\n\nfunc (a *outcomeEqualId) Equal(b *outcomeEqualId) bool {\n\tswitch {\n\tcase a == b:\n\t\treturn true\n\tcase a == nil || b == nil:\n\t\treturn false\n\tdefault:\n\t\taIdList, bIdList := (*msgs.Outcome)(a).Id(), (*msgs.Outcome)(b).Id()\n\t\tif aIdList.Len() != bIdList.Len() {\n\t\t\treturn false\n\t\t}\n\t\tfor idx, l := 0, aIdList.Len(); idx < l; idx++ {\n\t\t\taOutId, bOutId := aIdList.At(idx), bIdList.At(idx)\n\t\t\tif !bytes.Equal(aOutId.VarId(), bOutId.VarId()) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\taAccInstList, bAccInstList := aOutId.AcceptedInstances(), bOutId.AcceptedInstances()\n\t\t\tif aAccInstList.Len() != bAccInstList.Len() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor idy, m := 0, aAccInstList.Len(); idy < m; idy++ {\n\t\t\t\taAccInstId, bAccInstId := aAccInstList.At(idy), bAccInstList.At(idy)\n\t\t\t\tif !(aAccInstId.RmId() == bAccInstId.RmId() && aAccInstId.Vote() == bAccInstId.Vote()) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ CacheDir stores the charm cache directory path.\nvar CacheDir string\n\n\/\/ InfoResponse is sent by the charm store in response to charm-info requests.\ntype InfoResponse struct {\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tSha256 string `json:\"sha256,omitempty\"`\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n}\n\n\/\/ EventResponse is sent by the charm store in response to charm-event requests.\ntype EventResponse struct {\n\tKind string `json:\"kind\"`\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n\tTime string `json:\"time,omitempty\"`\n}\n\n\/\/ Repository respresents a collection of charms.\ntype Repository interface {\n\tGet(curl *URL) (Charm, error)\n\tLatest(curl *URL) (int, error)\n}\n\n\/\/ NotFoundError represents an error indicating that the requested data wasn't found.\ntype NotFoundError struct {\n\tmsg string\n}\n\nfunc (e *NotFoundError) Error() string {\n\treturn e.msg\n}\n\n\/\/ CharmStore is a Repository that provides access to the public juju charm store.\ntype CharmStore struct {\n\tBaseURL string\n}\n\nvar Store = &CharmStore{\"https:\/\/store.juju.ubuntu.com\"}\n\n\/\/ Info returns details for a charm in the charm store.\nfunc (s *CharmStore) Info(curl *URL) (*InfoResponse, error) {\n\tkey := curl.String()\n\tresp, err := http.Get(s.BaseURL + \"\/charm-info?charms=\" + url.QueryEscape(key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinfos := make(map[string]*InfoResponse)\n\tif err = json.Unmarshal(body, &infos); err != nil {\n\t\treturn nil, err\n\t}\n\tinfo, found := infos[key]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t}\n\tif len(info.Errors) == 1 && info.Errors[0] == \"entry not found\" {\n\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm not found: %s\", curl)}\n\t}\n\treturn info, nil\n}\n\n\/\/ Event returns details for a charm event in the charm store.\n\/\/\n\/\/ If digest is empty, the latest event is returned.\nfunc (s *CharmStore) Event(curl *URL, digest string) (*EventResponse, error) {\n\tkey := curl.String()\n\tquery := key\n\tif digest != \"\" {\n\t\tquery += \"@\" + digest\n\t}\n\tresp, err := http.Get(s.BaseURL + \"\/charm-event?charms=\" + url.QueryEscape(query))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tevents := make(map[string]*EventResponse)\n\tif err = json.Unmarshal(body, &events); err != nil {\n\t\treturn nil, err\n\t}\n\tevent, found := events[key]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t}\n\tif len(event.Errors) == 1 && event.Errors[0] == \"entry not found\" {\n\t\tif digest == \"\" {\n\t\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm event not found for %q\", curl)}\n\t\t} else {\n\t\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm event not found for %q with digest %q\", curl, digest)}\n\t\t}\n\t}\n\treturn event, nil\n}\n\n\/\/ revision returns the revision and SHA256 digest of the charm referenced by curl.\nfunc (s *CharmStore) revision(curl *URL) (revision int, digest string, err error) {\n\tinfo, err := s.Info(curl)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\tfor _, w := range info.Warnings {\n\t\tlog.Warningf(\"charm: charm store reports for %q: %s\", curl, w)\n\t}\n\tif info.Errors != nil {\n\t\treturn 0, \"\", fmt.Errorf(\"charm info errors for %q: %s\", curl, strings.Join(info.Errors, \"; \"))\n\t}\n\treturn info.Revision, info.Sha256, nil\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (s *CharmStore) Latest(curl *URL) (int, error) {\n\trev, _, err := s.revision(curl.WithRevision(-1))\n\treturn rev, err\n}\n\n\/\/ BranchLocation returns the location for the branch holding the charm at curl.\nfunc (s *CharmStore) BranchLocation(curl *URL) string {\n\tif curl.User != \"\" {\n\t\treturn fmt.Sprintf(\"lp:~%s\/charms\/%s\/%s\/trunk\", curl.User, curl.Series, curl.Name)\n\t}\n\treturn fmt.Sprintf(\"lp:charms\/%s\/%s\", curl.Series, curl.Name)\n}\n\nvar branchPrefixes = []string{\n\t\"lp:\",\n\t\"bzr+ssh:\/\/bazaar.launchpad.net\/+branch\/\",\n\t\"bzr+ssh:\/\/bazaar.launchpad.net\/\",\n\t\"http:\/\/launchpad.net\/+branch\/\",\n\t\"http:\/\/launchpad.net\/\",\n\t\"https:\/\/launchpad.net\/+branch\/\",\n\t\"https:\/\/launchpad.net\/\",\n\t\"http:\/\/code.launchpad.net\/+branch\/\",\n\t\"http:\/\/code.launchpad.net\/\",\n\t\"https:\/\/code.launchpad.net\/+branch\/\",\n\t\"https:\/\/code.launchpad.net\/\",\n}\n\n\/\/ CharmURL returns the charm URL for the branch at location.\nfunc (s *CharmStore) CharmURL(location string) (*URL, error) {\n\tvar l string\n\tif len(location) > 0 && location[0] == '~' {\n\t\tl = location\n\t} else {\n\t\tfor _, prefix := range branchPrefixes {\n\t\t\tif strings.HasPrefix(location, prefix) {\n\t\t\t\tl = location[len(prefix):]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif l != \"\" {\n\t\tfor len(l) > 0 && l[len(l)-1] == '\/' {\n\t\t\tl = l[:len(l)-1]\n\t\t}\n\t\tu := strings.Split(l, \"\/\")\n\t\tif len(u) == 3 && u[0] == \"charms\" {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\", u[1], u[2]))\n\t\t}\n\t\tif len(u) == 4 && u[0] == \"charms\" && u[3] == \"trunk\" {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\", u[1], u[2]))\n\t\t}\n\t\tif len(u) == 5 && u[1] == \"charms\" && u[4] == \"trunk\" && len(u[0]) > 0 && u[0][0] == '~' {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\/%s\", u[0], u[2], u[3]))\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"unknown branch location: %q\", location)\n}\n\n\/\/ verify returns an error unless a file exists at path with a hex-encoded\n\/\/ SHA256 matching digest.\nfunc verify(path, digest string) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn err\n\t}\n\tif hex.EncodeToString(h.Sum(nil)) != digest {\n\t\treturn fmt.Errorf(\"bad SHA256 of %q\", path)\n\t}\n\treturn nil\n}\n\n\/\/ Get returns the charm referenced by curl.\n\/\/ CacheDir must have been set, otherwise Get will panic.\nfunc (s *CharmStore) Get(curl *URL) (Charm, error) {\n\t\/\/ The cache location must have been previously set.\n\tif CacheDir == \"\" {\n\t\tpanic(\"charm cache directory path is empty\")\n\t}\n\tif err := os.MkdirAll(CacheDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\trev, digest, err := s.revision(curl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif curl.Revision == -1 {\n\t\tcurl = curl.WithRevision(rev)\n\t} else if curl.Revision != rev {\n\t\treturn nil, fmt.Errorf(\"charm: store returned charm with wrong revision for %q\", curl.String())\n\t}\n\tpath := filepath.Join(CacheDir, Quote(curl.String())+\".charm\")\n\tif verify(path, digest) != nil {\n\t\tresp, err := http.Get(s.BaseURL + \"\/charm\/\" + url.QueryEscape(curl.Path()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tf, err := ioutil.TempFile(CacheDir, \"charm-download\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdlPath := f.Name()\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif cerr := f.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\tif err != nil {\n\t\t\tos.Remove(dlPath)\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.Rename(dlPath, path); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := verify(path, digest); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ReadBundle(path)\n}\n\n\/\/ LocalRepository represents a local directory containing subdirectories\n\/\/ named after an Ubuntu series, each of which contains charms targeted for\n\/\/ that series. For example:\n\/\/\n\/\/ \/path\/to\/repository\/oneiric\/mongodb\/\n\/\/ \/path\/to\/repository\/precise\/mongodb.charm\n\/\/ \/path\/to\/repository\/precise\/wordpress\/\ntype LocalRepository struct {\n\tPath string\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (r *LocalRepository) Latest(curl *URL) (int, error) {\n\tch, err := r.Get(curl.WithRevision(-1))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn ch.Revision(), nil\n}\n\nfunc repoNotFound(path string) error {\n\treturn &NotFoundError{fmt.Sprintf(\"no repository found at %q\", path)}\n}\n\nfunc charmNotFound(curl *URL, repoPath string) error {\n\treturn &NotFoundError{fmt.Sprintf(\"charm not found in %q: %s\", repoPath, curl)}\n}\n\nfunc mightBeCharm(chPath string, info os.FileInfo) (bool, error) {\n\trepoName := info.Name()\n\tif info.Mode()&os.ModeSymlink != 0 {\n\t\tvar err error\n\t\tif chPath, err = os.Readlink(chPath); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif info, err = os.Stat(chPath); err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\tif info.IsDir() {\n\t\treturn !strings.HasPrefix(repoName, \".\"), nil\n\t}\n\treturn strings.HasSuffix(repoName, \".charm\"), nil\n}\n\n\/\/ Get returns a charm matching curl, if one exists. If curl has a revision of\n\/\/ -1, it returns the latest charm that matches curl. If multiple candidates\n\/\/ satisfy the foregoing, the first one encountered will be returned.\nfunc (r *LocalRepository) Get(curl *URL) (Charm, error) {\n\tif curl.Schema != \"local\" {\n\t\treturn nil, fmt.Errorf(\"local repository got URL with non-local schema: %q\", curl)\n\t}\n\tinfo, err := os.Stat(r.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = repoNotFound(r.Path)\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !info.IsDir() {\n\t\treturn nil, repoNotFound(r.Path)\n\t}\n\tpath := filepath.Join(r.Path, curl.Series)\n\tinfos, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, charmNotFound(curl, r.Path)\n\t}\n\tvar latest Charm\n\tfor _, info := range infos {\n\t\tchPath := filepath.Join(path, info.Name())\n\t\tif ok, err := mightBeCharm(chPath, info); err != nil {\n\t\t\treturn nil, err\n\t\t} else if !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif ch, err := Read(chPath); err != nil {\n\t\t\tlog.Warningf(\"charm: failed to load charm at %q: %s\", chPath, err)\n\t\t} else if ch.Meta().Name == curl.Name {\n\t\t\tif ch.Revision() == curl.Revision {\n\t\t\t\treturn ch, nil\n\t\t\t}\n\t\t\tif latest == nil || ch.Revision() > latest.Revision() {\n\t\t\t\tlatest = ch\n\t\t\t}\n\t\t}\n\t}\n\tif curl.Revision == -1 && latest != nil {\n\t\treturn latest, nil\n\t}\n\treturn nil, charmNotFound(curl, r.Path)\n}\nrework for simplicity\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ CacheDir stores the charm cache directory path.\nvar CacheDir string\n\n\/\/ InfoResponse is sent by the charm store in response to charm-info requests.\ntype InfoResponse struct {\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tSha256 string `json:\"sha256,omitempty\"`\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n}\n\n\/\/ EventResponse is sent by the charm store in response to charm-event requests.\ntype EventResponse struct {\n\tKind string `json:\"kind\"`\n\tRevision int `json:\"revision\"` \/\/ Zero is valid. Can't omitempty.\n\tDigest string `json:\"digest,omitempty\"`\n\tErrors []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n\tTime string `json:\"time,omitempty\"`\n}\n\n\/\/ Repository respresents a collection of charms.\ntype Repository interface {\n\tGet(curl *URL) (Charm, error)\n\tLatest(curl *URL) (int, error)\n}\n\n\/\/ NotFoundError represents an error indicating that the requested data wasn't found.\ntype NotFoundError struct {\n\tmsg string\n}\n\nfunc (e *NotFoundError) Error() string {\n\treturn e.msg\n}\n\n\/\/ CharmStore is a Repository that provides access to the public juju charm store.\ntype CharmStore struct {\n\tBaseURL string\n}\n\nvar Store = &CharmStore{\"https:\/\/store.juju.ubuntu.com\"}\n\n\/\/ Info returns details for a charm in the charm store.\nfunc (s *CharmStore) Info(curl *URL) (*InfoResponse, error) {\n\tkey := curl.String()\n\tresp, err := http.Get(s.BaseURL + \"\/charm-info?charms=\" + url.QueryEscape(key))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinfos := make(map[string]*InfoResponse)\n\tif err = json.Unmarshal(body, &infos); err != nil {\n\t\treturn nil, err\n\t}\n\tinfo, found := infos[key]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t}\n\tif len(info.Errors) == 1 && info.Errors[0] == \"entry not found\" {\n\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm not found: %s\", curl)}\n\t}\n\treturn info, nil\n}\n\n\/\/ Event returns details for a charm event in the charm store.\n\/\/\n\/\/ If digest is empty, the latest event is returned.\nfunc (s *CharmStore) Event(curl *URL, digest string) (*EventResponse, error) {\n\tkey := curl.String()\n\tquery := key\n\tif digest != \"\" {\n\t\tquery += \"@\" + digest\n\t}\n\tresp, err := http.Get(s.BaseURL + \"\/charm-event?charms=\" + url.QueryEscape(query))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tevents := make(map[string]*EventResponse)\n\tif err = json.Unmarshal(body, &events); err != nil {\n\t\treturn nil, err\n\t}\n\tevent, found := events[key]\n\tif !found {\n\t\treturn nil, fmt.Errorf(\"charm: charm store returned response without charm %q\", key)\n\t}\n\tif len(event.Errors) == 1 && event.Errors[0] == \"entry not found\" {\n\t\tif digest == \"\" {\n\t\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm event not found for %q\", curl)}\n\t\t} else {\n\t\t\treturn nil, &NotFoundError{fmt.Sprintf(\"charm event not found for %q with digest %q\", curl, digest)}\n\t\t}\n\t}\n\treturn event, nil\n}\n\n\/\/ revision returns the revision and SHA256 digest of the charm referenced by curl.\nfunc (s *CharmStore) revision(curl *URL) (revision int, digest string, err error) {\n\tinfo, err := s.Info(curl)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\tfor _, w := range info.Warnings {\n\t\tlog.Warningf(\"charm: charm store reports for %q: %s\", curl, w)\n\t}\n\tif info.Errors != nil {\n\t\treturn 0, \"\", fmt.Errorf(\"charm info errors for %q: %s\", curl, strings.Join(info.Errors, \"; \"))\n\t}\n\treturn info.Revision, info.Sha256, nil\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (s *CharmStore) Latest(curl *URL) (int, error) {\n\trev, _, err := s.revision(curl.WithRevision(-1))\n\treturn rev, err\n}\n\n\/\/ BranchLocation returns the location for the branch holding the charm at curl.\nfunc (s *CharmStore) BranchLocation(curl *URL) string {\n\tif curl.User != \"\" {\n\t\treturn fmt.Sprintf(\"lp:~%s\/charms\/%s\/%s\/trunk\", curl.User, curl.Series, curl.Name)\n\t}\n\treturn fmt.Sprintf(\"lp:charms\/%s\/%s\", curl.Series, curl.Name)\n}\n\nvar branchPrefixes = []string{\n\t\"lp:\",\n\t\"bzr+ssh:\/\/bazaar.launchpad.net\/+branch\/\",\n\t\"bzr+ssh:\/\/bazaar.launchpad.net\/\",\n\t\"http:\/\/launchpad.net\/+branch\/\",\n\t\"http:\/\/launchpad.net\/\",\n\t\"https:\/\/launchpad.net\/+branch\/\",\n\t\"https:\/\/launchpad.net\/\",\n\t\"http:\/\/code.launchpad.net\/+branch\/\",\n\t\"http:\/\/code.launchpad.net\/\",\n\t\"https:\/\/code.launchpad.net\/+branch\/\",\n\t\"https:\/\/code.launchpad.net\/\",\n}\n\n\/\/ CharmURL returns the charm URL for the branch at location.\nfunc (s *CharmStore) CharmURL(location string) (*URL, error) {\n\tvar l string\n\tif len(location) > 0 && location[0] == '~' {\n\t\tl = location\n\t} else {\n\t\tfor _, prefix := range branchPrefixes {\n\t\t\tif strings.HasPrefix(location, prefix) {\n\t\t\t\tl = location[len(prefix):]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif l != \"\" {\n\t\tfor len(l) > 0 && l[len(l)-1] == '\/' {\n\t\t\tl = l[:len(l)-1]\n\t\t}\n\t\tu := strings.Split(l, \"\/\")\n\t\tif len(u) == 3 && u[0] == \"charms\" {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\", u[1], u[2]))\n\t\t}\n\t\tif len(u) == 4 && u[0] == \"charms\" && u[3] == \"trunk\" {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\", u[1], u[2]))\n\t\t}\n\t\tif len(u) == 5 && u[1] == \"charms\" && u[4] == \"trunk\" && len(u[0]) > 0 && u[0][0] == '~' {\n\t\t\treturn ParseURL(fmt.Sprintf(\"cs:%s\/%s\/%s\", u[0], u[2], u[3]))\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"unknown branch location: %q\", location)\n}\n\n\/\/ verify returns an error unless a file exists at path with a hex-encoded\n\/\/ SHA256 matching digest.\nfunc verify(path, digest string) error {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\th := sha256.New()\n\tif _, err := io.Copy(h, f); err != nil {\n\t\treturn err\n\t}\n\tif hex.EncodeToString(h.Sum(nil)) != digest {\n\t\treturn fmt.Errorf(\"bad SHA256 of %q\", path)\n\t}\n\treturn nil\n}\n\n\/\/ Get returns the charm referenced by curl.\n\/\/ CacheDir must have been set, otherwise Get will panic.\nfunc (s *CharmStore) Get(curl *URL) (Charm, error) {\n\t\/\/ The cache location must have been previously set.\n\tif CacheDir == \"\" {\n\t\tpanic(\"charm cache directory path is empty\")\n\t}\n\tif err := os.MkdirAll(CacheDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\trev, digest, err := s.revision(curl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif curl.Revision == -1 {\n\t\tcurl = curl.WithRevision(rev)\n\t} else if curl.Revision != rev {\n\t\treturn nil, fmt.Errorf(\"charm: store returned charm with wrong revision for %q\", curl.String())\n\t}\n\tpath := filepath.Join(CacheDir, Quote(curl.String())+\".charm\")\n\tif verify(path, digest) != nil {\n\t\tresp, err := http.Get(s.BaseURL + \"\/charm\/\" + url.QueryEscape(curl.Path()))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tf, err := ioutil.TempFile(CacheDir, \"charm-download\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdlPath := f.Name()\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif cerr := f.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\tif err != nil {\n\t\t\tos.Remove(dlPath)\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := os.Rename(dlPath, path); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err := verify(path, digest); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ReadBundle(path)\n}\n\n\/\/ LocalRepository represents a local directory containing subdirectories\n\/\/ named after an Ubuntu series, each of which contains charms targeted for\n\/\/ that series. For example:\n\/\/\n\/\/ \/path\/to\/repository\/oneiric\/mongodb\/\n\/\/ \/path\/to\/repository\/precise\/mongodb.charm\n\/\/ \/path\/to\/repository\/precise\/wordpress\/\ntype LocalRepository struct {\n\tPath string\n}\n\n\/\/ Latest returns the latest revision of the charm referenced by curl, regardless\n\/\/ of the revision set on curl itself.\nfunc (r *LocalRepository) Latest(curl *URL) (int, error) {\n\tch, err := r.Get(curl.WithRevision(-1))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn ch.Revision(), nil\n}\n\nfunc repoNotFound(path string) error {\n\treturn &NotFoundError{fmt.Sprintf(\"no repository found at %q\", path)}\n}\n\nfunc charmNotFound(curl *URL, repoPath string) error {\n\treturn &NotFoundError{fmt.Sprintf(\"charm not found in %q: %s\", repoPath, curl)}\n}\n\nfunc mightBeCharm(info os.FileInfo) bool {\n\tif info.IsDir() {\n\t\treturn !strings.HasPrefix(info.Name(), \".\")\n\t}\n\treturn strings.HasSuffix(info.Name(), \".charm\")\n}\n\n\/\/ Get returns a charm matching curl, if one exists. If curl has a revision of\n\/\/ -1, it returns the latest charm that matches curl. If multiple candidates\n\/\/ satisfy the foregoing, the first one encountered will be returned.\nfunc (r *LocalRepository) Get(curl *URL) (Charm, error) {\n\tif curl.Schema != \"local\" {\n\t\treturn nil, fmt.Errorf(\"local repository got URL with non-local schema: %q\", curl)\n\t}\n\tinfo, err := os.Stat(r.Path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\terr = repoNotFound(r.Path)\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !info.IsDir() {\n\t\treturn nil, repoNotFound(r.Path)\n\t}\n\tpath := filepath.Join(r.Path, curl.Series)\n\tinfos, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, charmNotFound(curl, r.Path)\n\t}\n\tvar latest Charm\n\tfor _, info := range infos {\n\t\tchPath := filepath.Join(path, info.Name())\n\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\tvar err error\n\t\t\tif info, err = os.Stat(chPath); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\tif !mightBeCharm(info) {\n\t\t\tcontinue\n\t\t}\n\t\tif ch, err := Read(chPath); err != nil {\n\t\t\tlog.Warningf(\"charm: failed to load charm at %q: %s\", chPath, err)\n\t\t} else if ch.Meta().Name == curl.Name {\n\t\t\tif ch.Revision() == curl.Revision {\n\t\t\t\treturn ch, nil\n\t\t\t}\n\t\t\tif latest == nil || ch.Revision() > latest.Revision() {\n\t\t\t\tlatest = ch\n\t\t\t}\n\t\t}\n\t}\n\tif curl.Revision == -1 && latest != nil {\n\t\treturn latest, nil\n\t}\n\treturn nil, charmNotFound(curl, r.Path)\n}\n<|endoftext|>"} {"text":"\/\/ PromHouse\n\/\/ Copyright (C) 2017 Percona LLC\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published\n\/\/ by the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nconst (\n\tupstream = `# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n# TYPE go_gc_duration_seconds summary\ngo_gc_duration_seconds{quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum 0.0285907\ngo_gc_duration_seconds_count 28\n# HELP go_goroutines Number of goroutines that currently exist.\n# TYPE go_goroutines gauge\ngo_goroutines 38\n# HELP go_info Information about the Go environment.\n# TYPE go_info gauge\ngo_info{version=\"go1.9.2\"} 1\n# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.\n# TYPE go_memstats_alloc_bytes_total counter\ngo_memstats_alloc_bytes_total 1.293258864e+09\n# HELP node_netstat_TcpExt_TCPSackMerged Statistic TcpExtTCPSackMerged.\n# TYPE node_netstat_TcpExt_TCPSackMerged untyped\nnode_netstat_TcpExt_TCPSackMerged 0\n`\n\n\tresult = `# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n# TYPE go_gc_duration_seconds summary\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum{instance=\"instance1\"} 0.0285907\ngo_gc_duration_seconds_count{instance=\"instance1\"} 28\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum{instance=\"instance2\"} 0.0285907\ngo_gc_duration_seconds_count{instance=\"instance2\"} 28\n# HELP go_goroutines Number of goroutines that currently exist.\n# TYPE go_goroutines gauge\ngo_goroutines{instance=\"instance1\"} 38\ngo_goroutines{instance=\"instance2\"} 41\n# HELP go_info Information about the Go environment.\n# TYPE go_info gauge\ngo_info{instance=\"\",version=\"instance1\"} 1\ngo_info{instance=\"\",version=\"instance2\"} 1\n# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.\n# TYPE go_memstats_alloc_bytes_total counter\ngo_memstats_alloc_bytes_total{instance=\"instance1\"} 1.335822613e+09\ngo_memstats_alloc_bytes_total{instance=\"instance2\"} 1.277148528e+09\n# HELP node_netstat_TcpExt_TCPSackMerged Statistic TcpExtTCPSackMerged.\n# TYPE node_netstat_TcpExt_TCPSackMerged untyped\nnode_netstat_TcpExt_TCPSackMerged{instance=\"instance1\"} 0\nnode_netstat_TcpExt_TCPSackMerged{instance=\"instance2\"} 0\n`\n)\n\nfunc TestFaker(t *testing.T) {\n\tfaker := newFaker(\"instance%d\", 2)\n\tfaker.sort = true\n\tfaker.rnd.Seed(1)\n\n\tsrc := strings.NewReader(upstream)\n\tvar dst bytes.Buffer\n\trequire.NoError(t, faker.multi(&dst, src))\n\texpected := strings.Split(result, \"\\n\")\n\tactual := strings.Split(dst.String(), \"\\n\")\n\tassert.Equal(t, expected, actual, \"=== expected:\\n%s\\n\\n=== actual:\\n%s\\n\", result, dst.String())\n}\nFix test.\/\/ PromHouse\n\/\/ Copyright (C) 2017 Percona LLC\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published\n\/\/ by the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nconst (\n\tupstream = `# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n# TYPE go_gc_duration_seconds summary\ngo_gc_duration_seconds{quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum 0.0285907\ngo_gc_duration_seconds_count 28\n# HELP go_goroutines Number of goroutines that currently exist.\n# TYPE go_goroutines gauge\ngo_goroutines 38\n# HELP go_info Information about the Go environment.\n# TYPE go_info gauge\ngo_info{version=\"go1.9.2\"} 1\n# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.\n# TYPE go_memstats_alloc_bytes_total counter\ngo_memstats_alloc_bytes_total 1.293258864e+09\n# HELP node_netstat_TcpExt_TCPSackMerged Statistic TcpExtTCPSackMerged.\n# TYPE node_netstat_TcpExt_TCPSackMerged untyped\nnode_netstat_TcpExt_TCPSackMerged 0\n`\n\n\tresult = `# HELP go_gc_duration_seconds A summary of the GC invocation durations.\n# TYPE go_gc_duration_seconds summary\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{instance=\"instance1\",quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum{instance=\"instance1\"} 0.0285907\ngo_gc_duration_seconds_count{instance=\"instance1\"} 28\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0\"} 6.91e-05\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.25\"} 0.0001714\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.5\"} 0.0002509\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"0.75\"} 0.0010951\ngo_gc_duration_seconds{instance=\"instance2\",quantile=\"1\"} 0.0053027\ngo_gc_duration_seconds_sum{instance=\"instance2\"} 0.0285907\ngo_gc_duration_seconds_count{instance=\"instance2\"} 28\n# HELP go_goroutines Number of goroutines that currently exist.\n# TYPE go_goroutines gauge\ngo_goroutines{instance=\"instance1\"} 38\ngo_goroutines{instance=\"instance2\"} 41\n# HELP go_info Information about the Go environment.\n# TYPE go_info gauge\ngo_info{instance=\"\",version=\"instance1\"} 1\ngo_info{instance=\"\",version=\"instance2\"} 1\n# HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.\n# TYPE go_memstats_alloc_bytes_total counter\ngo_memstats_alloc_bytes_total{instance=\"instance1\"} 1.335822613e+09\ngo_memstats_alloc_bytes_total{instance=\"instance2\"} 1.277148528e+09\n# HELP node_netstat_TcpExt_TCPSackMerged Statistic TcpExtTCPSackMerged.\n# TYPE node_netstat_TcpExt_TCPSackMerged untyped\nnode_netstat_TcpExt_TCPSackMerged{instance=\"instance1\"} 0\nnode_netstat_TcpExt_TCPSackMerged{instance=\"instance2\"} 0\n`\n)\n\nfunc TestFaker(t *testing.T) {\n\tfaker := newFaker(\"instance%d\", 2)\n\tfaker.sort = true\n\tfaker.rnd.Seed(1)\n\n\tsrc := strings.NewReader(upstream)\n\tvar dst bytes.Buffer\n\trequire.NoError(t, faker.generate(&dst, src))\n\texpected := strings.Split(result, \"\\n\")\n\tactual := strings.Split(dst.String(), \"\\n\")\n\tassert.Equal(t, expected, actual, \"=== expected:\\n%s\\n\\n=== actual:\\n%s\\n\", result, dst.String())\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"github.com\/nfnt\/resize\"\n\t_ \"golang.org\/x\/image\/tiff\"\n\t\"image\"\n\t\"image\/draw\"\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\t\"os\"\n)\n\n\/\/ SimpleImage implements IIIFImage for reading non-JP2 image types. These can\n\/\/ only handle a basic \"read it all, then crop\/resize\" flow, and thus should\n\/\/ have very careful load testing.\ntype SimpleImage struct {\n\tfile *os.File\n\tconf image.Config\n\tdecodeWidth int\n\tdecodeHeight int\n\tscaleFactor float64\n\tdecodeArea image.Rectangle\n}\n\nfunc NewSimpleImage(filename string) (*SimpleImage, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti := &SimpleImage{file: file}\n\ti.conf, _, err = image.DecodeConfig(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ti.file.Seek(0, 0)\n\n\t\/\/ Default to full size, no crop\n\ti.decodeWidth = i.conf.Width\n\ti.decodeHeight = i.conf.Height\n\ti.decodeArea = image.Rect(0, 0, i.decodeWidth, i.decodeHeight)\n\n\treturn i, nil\n}\n\n\/\/ SetResizeWH sets the image to scale to the given width and height. If one\n\/\/ dimension is 0, the decoded image will preserve the aspect ratio while\n\/\/ scaling to the non-zero dimension.\nfunc (i *SimpleImage) SetResizeWH(width, height int) {\n\ti.decodeWidth = width\n\ti.decodeHeight = height\n}\n\nfunc (i *SimpleImage) SetCrop(r image.Rectangle) {\n\ti.decodeArea = r\n}\n\n\/\/ DecodeImage returns an image.Image that holds the decoded image data,\n\/\/ resized and cropped if resizing or cropping was requested. Both cropping\n\/\/ and resizing happen here due to the nature of openjpeg, so SetScale,\n\/\/ SetResizeWH, and SetCrop must be called before this function.\nfunc (i *SimpleImage) DecodeImage() (image.Image, error) {\n\timg, _, err := image.Decode(i.file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif i.decodeArea != img.Bounds() {\n\t\tsrcB := img.Bounds()\n\t\tdstB := i.decodeArea\n\t\tdst := image.NewRGBA(image.Rect(0, 0, dstB.Dx(), dstB.Dy()))\n\t\tdraw.Draw(dst, srcB, img, dstB.Min, draw.Src)\n\t\timg = dst\n\t}\n\n\tif i.decodeWidth != i.decodeArea.Dx() || i.decodeHeight != i.decodeArea.Dy() {\n\t\timg = resize.Resize(uint(i.decodeWidth), uint(i.decodeHeight), img, resize.Bilinear)\n\t}\n\n\treturn img, nil\n}\n\n\/\/ GetWidth returns the image width\nfunc (i *SimpleImage) GetWidth() int {\n\treturn i.conf.Width\n}\n\n\/\/ GetHeight returns the image height\nfunc (i *SimpleImage) GetHeight() int {\n\treturn i.conf.Height\n}\nAdd comment about image croppingpackage main\n\nimport (\n\t\"github.com\/nfnt\/resize\"\n\t_ \"golang.org\/x\/image\/tiff\"\n\t\"image\"\n\t\"image\/draw\"\n\t_ \"image\/gif\"\n\t_ \"image\/jpeg\"\n\t_ \"image\/png\"\n\t\"os\"\n)\n\n\/\/ SimpleImage implements IIIFImage for reading non-JP2 image types. These can\n\/\/ only handle a basic \"read it all, then crop\/resize\" flow, and thus should\n\/\/ have very careful load testing.\ntype SimpleImage struct {\n\tfile *os.File\n\tconf image.Config\n\tdecodeWidth int\n\tdecodeHeight int\n\tscaleFactor float64\n\tdecodeArea image.Rectangle\n}\n\nfunc NewSimpleImage(filename string) (*SimpleImage, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ti := &SimpleImage{file: file}\n\ti.conf, _, err = image.DecodeConfig(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ti.file.Seek(0, 0)\n\n\t\/\/ Default to full size, no crop\n\ti.decodeWidth = i.conf.Width\n\ti.decodeHeight = i.conf.Height\n\ti.decodeArea = image.Rect(0, 0, i.decodeWidth, i.decodeHeight)\n\n\treturn i, nil\n}\n\n\/\/ SetResizeWH sets the image to scale to the given width and height. If one\n\/\/ dimension is 0, the decoded image will preserve the aspect ratio while\n\/\/ scaling to the non-zero dimension.\nfunc (i *SimpleImage) SetResizeWH(width, height int) {\n\ti.decodeWidth = width\n\ti.decodeHeight = height\n}\n\nfunc (i *SimpleImage) SetCrop(r image.Rectangle) {\n\ti.decodeArea = r\n}\n\n\/\/ DecodeImage returns an image.Image that holds the decoded image data,\n\/\/ resized and cropped if resizing or cropping was requested. Both cropping\n\/\/ and resizing happen here due to the nature of openjpeg, so SetScale,\n\/\/ SetResizeWH, and SetCrop must be called before this function.\nfunc (i *SimpleImage) DecodeImage() (image.Image, error) {\n\timg, _, err := image.Decode(i.file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Draw a new image of the requested size if the decode area isn't the same\n\t\/\/ rectangle as the source image\n\tif i.decodeArea != img.Bounds() {\n\t\tsrcB := img.Bounds()\n\t\tdstB := i.decodeArea\n\t\tdst := image.NewRGBA(image.Rect(0, 0, dstB.Dx(), dstB.Dy()))\n\t\tdraw.Draw(dst, srcB, img, dstB.Min, draw.Src)\n\t\timg = dst\n\t}\n\n\tif i.decodeWidth != i.decodeArea.Dx() || i.decodeHeight != i.decodeArea.Dy() {\n\t\timg = resize.Resize(uint(i.decodeWidth), uint(i.decodeHeight), img, resize.Bilinear)\n\t}\n\n\treturn img, nil\n}\n\n\/\/ GetWidth returns the image width\nfunc (i *SimpleImage) GetWidth() int {\n\treturn i.conf.Width\n}\n\n\/\/ GetHeight returns the image height\nfunc (i *SimpleImage) GetHeight() int {\n\treturn i.conf.Height\n}\n<|endoftext|>"} {"text":"package forms\n\nimport (\n\t\"github.com\/bep\/gr\"\n\t\"github.com\/bep\/gr\/attr\"\n\t\"github.com\/bep\/gr\/el\"\n\t\"github.com\/bep\/gr\/evt\"\n)\n\nvar (\n\treactSelect = gr.FromGlobal(\"Select\")\n\treactCreatableSelect = gr.FromGlobal(\"Select\", \"Creatable\")\n)\n\nfunc TextField(name, id string, v interface{}, storeFunc func(*gr.Event)) *gr.Element {\n\n\tvar value string\n\n\tvalueStr, ok := v.(string)\n\tif ok {\n\t\tvalue = valueStr\n\t}\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Input(\n\t\t\tattr.Type(\"text\"),\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tattr.Value(value),\n\t\t\tevt.Change(storeFunc),\n\t\t),\n\t)\n}\n\nfunc NumberField(name, id string, value interface{}, storeFunc func(*gr.Event)) *gr.Element {\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Input(\n\t\t\tattr.Type(\"number\"),\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tattr.Value(value),\n\t\t\tevt.Change(storeFunc),\n\t\t),\n\t)\n}\n\nfunc TextArea(name, id string, value string, storeFunc func(*gr.Event)) *gr.Element {\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.TextArea(\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tevt.Change(storeFunc),\n\t\t\tattr.Value(value),\n\t\t\tattr.Rows(8),\n\t\t),\n\t)\n}\n\nfunc Checkbox(name, id string, value bool, storeFunc func(*gr.Event)) *gr.Element {\n\n\tlabel := \"disabled\"\n\tvar checked gr.Modifier\n\tif value {\n\t\tlabel = \"enabled\"\n\t\tchecked = attr.Checked(true)\n\t}\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Div(\n\t\t\tgr.CSS(\"checkbox\"),\n\t\t\tel.Label(\n\t\t\t\tel.Input(\n\t\t\t\t\tattr.Value(\"\"), \/\/ to stop the warning about a uncontrolled components\n\t\t\t\t\tattr.Type(\"checkbox\"),\n\t\t\t\t\tattr.ID(id),\n\t\t\t\t\tchecked,\n\t\t\t\t\tevt.Change(storeFunc).StopPropagation(),\n\t\t\t\t),\n\t\t\t\tgr.Text(label),\n\t\t\t),\n\t\t),\n\t)\n}\n\nfunc SelectOne(name, id string, options []string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelect := gr.FromGlobal(\"Select\")\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"clearable\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc SelectOneMeta(name, id string, options []string, optionsMeta map[string]string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option + \" - \" + optionsMeta[option],\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\t\/\/reactSelect := gr.FromGlobal(\"Select\")\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"clearable\": false,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc CreateableSelectMeta(name, id string, options []string, optionsMeta map[string]string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\n\tselStr := value.(string)\n\texisting := false\n\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option + \" - \" + optionsMeta[option],\n\t\t}\n\t\tif option == selStr {\n\t\t\texisting = true\n\t\t}\n\t}\n\n\t\/\/ Creatable API seems to be a bit in limbo currently, so doing this to account for the experienced wonkiness\n\tif !existing {\n\t\tnewVal := make(map[string]string)\n\t\tnewVal[\"value\"] = selStr\n\t\tnewVal[\"label\"] = selStr\n\t\topts = append(opts, newVal)\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactCreatableSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": false,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc SelectMultiple(name, id string, options []string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc CreateableSelectMultiple(name, id string, options []string, s interface{}, storeSelect func(string, interface{})) *gr.Element {\n\n\tvar selected []interface{}\n\tselectedSlice, ok := s.([]interface{})\n\tif ok {\n\t\tselected = selectedSlice\n\t}\n\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\t\/\/ Creatable API seems to be a bit in limbo currently, so doing this to account for the experienced wonkiness\n\tvar value []interface{}\n\tfor _, sel := range selected {\n\t\tselStr, ok := sel.(string)\n\t\tif ok {\n\t\t\tnewVal := make(map[string]string)\n\t\t\tnewVal[\"value\"] = selStr\n\t\t\tnewVal[\"label\"] = selStr\n\t\t\tvalue = append(value, newVal)\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactCreatableSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\nmake clearablepackage forms\n\nimport (\n\t\"github.com\/bep\/gr\"\n\t\"github.com\/bep\/gr\/attr\"\n\t\"github.com\/bep\/gr\/el\"\n\t\"github.com\/bep\/gr\/evt\"\n)\n\nvar (\n\treactSelect = gr.FromGlobal(\"Select\")\n\treactCreatableSelect = gr.FromGlobal(\"Select\", \"Creatable\")\n)\n\nfunc TextField(name, id string, v interface{}, storeFunc func(*gr.Event)) *gr.Element {\n\n\tvar value string\n\n\tvalueStr, ok := v.(string)\n\tif ok {\n\t\tvalue = valueStr\n\t}\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Input(\n\t\t\tattr.Type(\"text\"),\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tattr.Value(value),\n\t\t\tevt.Change(storeFunc),\n\t\t),\n\t)\n}\n\nfunc NumberField(name, id string, value interface{}, storeFunc func(*gr.Event)) *gr.Element {\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Input(\n\t\t\tattr.Type(\"number\"),\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tattr.Value(value),\n\t\t\tevt.Change(storeFunc),\n\t\t),\n\t)\n}\n\nfunc TextArea(name, id string, value string, storeFunc func(*gr.Event)) *gr.Element {\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.TextArea(\n\t\t\tattr.ClassName(\"form-control\"),\n\t\t\tattr.ID(id),\n\t\t\tattr.Placeholder(name),\n\t\t\tevt.Change(storeFunc),\n\t\t\tattr.Value(value),\n\t\t\tattr.Rows(8),\n\t\t),\n\t)\n}\n\nfunc Checkbox(name, id string, value bool, storeFunc func(*gr.Event)) *gr.Element {\n\n\tlabel := \"disabled\"\n\tvar checked gr.Modifier\n\tif value {\n\t\tlabel = \"enabled\"\n\t\tchecked = attr.Checked(true)\n\t}\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\tel.Div(\n\t\t\tgr.CSS(\"checkbox\"),\n\t\t\tel.Label(\n\t\t\t\tel.Input(\n\t\t\t\t\tattr.Value(\"\"), \/\/ to stop the warning about a uncontrolled components\n\t\t\t\t\tattr.Type(\"checkbox\"),\n\t\t\t\t\tattr.ID(id),\n\t\t\t\t\tchecked,\n\t\t\t\t\tevt.Change(storeFunc).StopPropagation(),\n\t\t\t\t),\n\t\t\t\tgr.Text(label),\n\t\t\t),\n\t\t),\n\t)\n}\n\nfunc SelectOne(name, id string, options []string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelect := gr.FromGlobal(\"Select\")\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"clearable\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc SelectOneMeta(name, id string, options []string, optionsMeta map[string]string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option + \" - \" + optionsMeta[option],\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\t\/\/reactSelect := gr.FromGlobal(\"Select\")\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"clearable\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc CreateableSelectMeta(name, id string, options []string, optionsMeta map[string]string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\n\tselStr := value.(string)\n\texisting := false\n\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option + \" - \" + optionsMeta[option],\n\t\t}\n\t\tif option == selStr {\n\t\t\texisting = true\n\t\t}\n\t}\n\n\t\/\/ Creatable API seems to be a bit in limbo currently, so doing this to account for the experienced wonkiness\n\tif !existing {\n\t\tnewVal := make(map[string]string)\n\t\tnewVal[\"value\"] = selStr\n\t\tnewVal[\"label\"] = selStr\n\t\topts = append(opts, newVal)\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactCreatableSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": false,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc SelectMultiple(name, id string, options []string, value interface{}, storeSelect func(string, interface{})) *gr.Element {\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n\nfunc CreateableSelectMultiple(name, id string, options []string, s interface{}, storeSelect func(string, interface{})) *gr.Element {\n\n\tvar selected []interface{}\n\tselectedSlice, ok := s.([]interface{})\n\tif ok {\n\t\tselected = selectedSlice\n\t}\n\n\topts := make([]interface{}, len(options))\n\tfor i, option := range options {\n\t\topts[i] = map[string]string{\n\t\t\t\"value\": option,\n\t\t\t\"label\": option,\n\t\t}\n\t}\n\n\t\/\/ Creatable API seems to be a bit in limbo currently, so doing this to account for the experienced wonkiness\n\tvar value []interface{}\n\tfor _, sel := range selected {\n\t\tselStr, ok := sel.(string)\n\t\tif ok {\n\t\t\tnewVal := make(map[string]string)\n\t\t\tnewVal[\"value\"] = selStr\n\t\t\tnewVal[\"label\"] = selStr\n\t\t\tvalue = append(value, newVal)\n\t\t}\n\t}\n\n\tonChange := func(vals interface{}) {\n\t\tstoreSelect(id, vals)\n\t}\n\n\treactSelectElem := reactCreatableSelect.CreateElement(gr.Props{\n\t\t\"name\": name,\n\t\t\"value\": value,\n\t\t\"options\": opts,\n\t\t\"onChange\": onChange,\n\t\t\"multi\": true,\n\t\t\"scrollMenuIntoView\": false,\n\t})\n\n\treturn el.Div(\n\t\tgr.CSS(\"form-group\"),\n\t\tel.Label(\n\t\t\tgr.Text(name),\n\t\t),\n\t\treactSelectElem,\n\t)\n}\n<|endoftext|>"} {"text":"package main\n\nimport \"github.com\/go-martini\/martini\"\n\nfunc main() {\n m := martini.Classic()\n m.Get(\"\/\", func () string {\n return(\" Server Working !!\")\n }}\n m.Run()\n}\nUpdate server.go\/\/Copyright 2015 Bestupefy Inc\n\n \/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n \/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n \/\/Unless required by applicable law or agreed to in writing, software\n \/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n \/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n \/\/See the License for the specific language governing permissions and\n \/\/limitations under the License.\n \npackage main\n\nimport (\n \"os\"\n \n \"github.com\/Sirupsen\/logrus\"\n\t \"github.com\/codegangsta\/cli\"\n\t \"github.com\/go-martini\/martini\"\n)\n\nfunc main() {\n m := martini.Classic()\n m.Get(\"\/\", func () string {\n return(\" Server Working !!\")\n }}\n m.Run()\n}\n<|endoftext|>"} {"text":"package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/go-utils\/cmdex\"\n\t\"github.com\/bitrise-io\/go-utils\/pathutil\"\n\t\"github.com\/bitrise-io\/stepman\/models\"\n\t\"github.com\/bitrise-io\/stepman\/stepman\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc updateCollection(steplibSource string) (models.StepCollectionModel, error) {\n\troute, found := stepman.ReadRoute(steplibSource)\n\tif !found {\n\t\treturn models.StepCollectionModel{},\n\t\t\tfmt.Errorf(\"No collection found for lib, call 'stepman delete -c %s' for cleanup\", steplibSource)\n\t}\n\n\tpth := stepman.GetCollectionBaseDirPath(route)\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t} else if !exists {\n\t\treturn models.StepCollectionModel{}, errors.New(\"Not initialized\")\n\t}\n\n\tif err := cmdex.GitPull(pth); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t}\n\n\tif err := stepman.ReGenerateStepSpec(route); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t}\n\n\treturn stepman.ReadStepSpec(steplibSource)\n}\n\nfunc update(c *cli.Context) error {\n\tcollectionURIs := []string{}\n\n\t\/\/ StepSpec collection path\n\tcollectionURI := c.String(CollectionKey)\n\tif collectionURI == \"\" {\n\t\tlog.Info(\"[STEPMAN] - No step collection specified, update all\")\n\t\tcollectionURIs = stepman.GetAllStepCollectionPath()\n\t} else {\n\t\tcollectionURIs = []string{collectionURI}\n\t}\n\n\tfor _, URI := range collectionURIs {\n\t\tif _, err := updateCollection(URI); err != nil {\n\t\t\tlog.Fatalf(\"Failed to update collection (%s), err: %s\", collectionURI, err)\n\t\t}\n\t}\n\n\treturn nil\n}\nsteplib update logging fixpackage cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/go-utils\/cmdex\"\n\t\"github.com\/bitrise-io\/go-utils\/pathutil\"\n\t\"github.com\/bitrise-io\/stepman\/models\"\n\t\"github.com\/bitrise-io\/stepman\/stepman\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc updateCollection(steplibSource string) (models.StepCollectionModel, error) {\n\troute, found := stepman.ReadRoute(steplibSource)\n\tif !found {\n\t\treturn models.StepCollectionModel{},\n\t\t\tfmt.Errorf(\"No collection found for lib, call 'stepman delete -c %s' for cleanup\", steplibSource)\n\t}\n\n\tpth := stepman.GetCollectionBaseDirPath(route)\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t} else if !exists {\n\t\treturn models.StepCollectionModel{}, errors.New(\"Not initialized\")\n\t}\n\n\tif err := cmdex.GitPull(pth); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t}\n\n\tif err := stepman.ReGenerateStepSpec(route); err != nil {\n\t\treturn models.StepCollectionModel{}, err\n\t}\n\n\treturn stepman.ReadStepSpec(steplibSource)\n}\n\nfunc update(c *cli.Context) error {\n\tcollectionURIs := []string{}\n\n\t\/\/ StepSpec collection path\n\tcollectionURI := c.String(CollectionKey)\n\tif collectionURI == \"\" {\n\t\tlog.Info(\"No StepLib specified, update all...\")\n\t\tcollectionURIs = stepman.GetAllStepCollectionPath()\n\t} else {\n\t\tcollectionURIs = []string{collectionURI}\n\t}\n\n\tif len(collectionURIs) == 0 {\n\t\tlog.Info(\"No local StepLib found, nothing to update...\")\n\t}\n\n\tfor _, URI := range collectionURIs {\n\t\tlog.Infof(\"Update StepLib (%s)...\", URI)\n\t\tif _, err := updateCollection(URI); err != nil {\n\t\t\tlog.Fatalf(err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ run\n\n\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Test that selects do not consume undue memory.\n\npackage main\n\nimport \"runtime\"\n\nfunc sender(c chan int, n int) {\n\tfor i := 0; i < n; i++ {\n\t\tc <- 1\n\t}\n}\n\nfunc receiver(c, dummy chan int, n int) {\n\tfor i := 0; i < n; i++ {\n\t\tselect {\n\t\tcase <-c:\n\t\t\t\/\/ nothing\n\t\tcase <-dummy:\n\t\t\tpanic(\"dummy\")\n\t\t}\n\t}\n}\n\nfunc main() {\n\truntime.MemProfileRate = 0\n\n\tc := make(chan int)\n\tdummy := make(chan int)\n\n\t\/\/ warm up\n\tgo sender(c, 100000)\n\treceiver(c, dummy, 100000)\n\truntime.GC()\n\tmemstats := new(runtime.MemStats)\n\truntime.ReadMemStats(memstats)\n\talloc := memstats.Alloc\n\n\t\/\/ second time shouldn't increase footprint by much\n\tgo sender(c, 100000)\n\treceiver(c, dummy, 100000)\n\truntime.GC()\n\truntime.ReadMemStats(memstats)\n\n\tif memstats.Alloc-alloc > 1e5 {\n\t\tprintln(\"BUG: too much memory for 100,000 selects:\", memstats.Alloc-alloc)\n\t}\n}\ntest: raise the allocation threshold for chan\/select2.go failure\/\/ run\n\n\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Test that selects do not consume undue memory.\n\npackage main\n\nimport \"runtime\"\n\nfunc sender(c chan int, n int) {\n\tfor i := 0; i < n; i++ {\n\t\tc <- 1\n\t}\n}\n\nfunc receiver(c, dummy chan int, n int) {\n\tfor i := 0; i < n; i++ {\n\t\tselect {\n\t\tcase <-c:\n\t\t\t\/\/ nothing\n\t\tcase <-dummy:\n\t\t\tpanic(\"dummy\")\n\t\t}\n\t}\n}\n\nfunc main() {\n\truntime.MemProfileRate = 0\n\n\tc := make(chan int)\n\tdummy := make(chan int)\n\n\t\/\/ warm up\n\tgo sender(c, 100000)\n\treceiver(c, dummy, 100000)\n\truntime.GC()\n\tmemstats := new(runtime.MemStats)\n\truntime.ReadMemStats(memstats)\n\talloc := memstats.Alloc\n\n\t\/\/ second time shouldn't increase footprint by much\n\tgo sender(c, 100000)\n\treceiver(c, dummy, 100000)\n\truntime.GC()\n\truntime.ReadMemStats(memstats)\n\n\tif memstats.Alloc-alloc > 1.1e5 {\n\t\tprintln(\"BUG: too much memory for 100,000 selects:\", memstats.Alloc-alloc)\n\t}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2015 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/fields\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nconst (\n\tpodListTimeout = time.Minute\n\tserverStartTimeout = podStartTimeout + 3*time.Minute\n)\n\nvar _ = Describe(\"Examples e2e\", func() {\n\tvar c *client.Client\n\tvar ns string\n\tvar testingNs *api.Namespace\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tc, err = loadClient()\n\t\texpectNoError(err)\n\t\ttestingNs, err = createTestingNS(\"examples\", c)\n\t\tns = testingNs.Name\n\t\tExpect(err).NotTo(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tBy(fmt.Sprintf(\"Destroying namespace for this suite %v\", ns))\n\t\tif err := c.Namespaces().Delete(ns); err != nil {\n\t\t\tFailf(\"Couldn't delete ns %s\", err)\n\t\t}\n\t})\n\n\tDescribe(\"[Skipped][Example]Redis\", func() {\n\t\tIt(\"should create and stop redis servers\", func() {\n\t\t\tmkpath := func(file string) string {\n\t\t\t\treturn filepath.Join(testContext.RepoRoot, \"examples\/redis\", file)\n\t\t\t}\n\t\t\tbootstrapYaml := mkpath(\"redis-master.yaml\")\n\t\t\tsentinelServiceYaml := mkpath(\"redis-sentinel-service.yaml\")\n\t\t\tsentinelControllerYaml := mkpath(\"redis-sentinel-controller.yaml\")\n\t\t\tcontrollerYaml := mkpath(\"redis-controller.yaml\")\n\n\t\t\tbootstrapPodName := \"redis-master\"\n\t\t\tredisRC := \"redis\"\n\t\t\tsentinelRC := \"redis-sentinel\"\n\t\t\tnsFlag := fmt.Sprintf(\"--namespace=%v\", ns)\n\t\t\texpectedOnServer := \"The server is now ready to accept connections\"\n\t\t\texpectedOnSentinel := \"+monitor master\"\n\n\t\t\tBy(\"starting redis bootstrap\")\n\t\t\trunKubectl(\"create\", \"-f\", bootstrapYaml, nsFlag)\n\t\t\tcleanupBootstrap := true\n\t\t\tdefer func() {\n\t\t\t\tif cleanupBootstrap {\n\t\t\t\t\tcleanup(bootstrapYaml, ns, \"name=redis\", \"name=redis-sentinel\")\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\terr := waitForPodRunningInNamespace(c, bootstrapPodName, ns)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t_, err = lookForStringInLog(ns, bootstrapPodName, \"master\", expectedOnServer, serverStartTimeout)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t_, err = lookForStringInLog(ns, bootstrapPodName, \"sentinel\", expectedOnSentinel, serverStartTimeout)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"setting up services and controllers\")\n\t\t\trunKubectl(\"create\", \"-f\", sentinelServiceYaml, nsFlag)\n\t\t\tdefer cleanup(sentinelServiceYaml, ns, \"name=redis-sentinel\")\n\t\t\trunKubectl(\"create\", \"-f\", sentinelControllerYaml, nsFlag)\n\t\t\tdefer cleanup(sentinelControllerYaml, ns, \"name=redis-sentinel\")\n\t\t\trunKubectl(\"create\", \"-f\", controllerYaml, nsFlag)\n\t\t\tdefer cleanup(controllerYaml, ns, \"name=redis\")\n\n\t\t\tBy(\"scaling up the deployment\")\n\t\t\trunKubectl(\"scale\", \"rc\", redisRC, \"--replicas=3\", nsFlag)\n\t\t\trunKubectl(\"scale\", \"rc\", sentinelRC, \"--replicas=3\", nsFlag)\n\n\t\t\tBy(\"checking up the services\")\n\t\t\tcheckAllLogs := func() {\n\t\t\t\tforEachPod(c, ns, \"name\", \"redis\", func(pod api.Pod) {\n\t\t\t\t\tif pod.Name != bootstrapPodName {\n\t\t\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"redis\", expectedOnServer, serverStartTimeout)\n\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tforEachPod(c, ns, \"name\", \"redis-sentinel\", func(pod api.Pod) {\n\t\t\t\t\tif pod.Name != bootstrapPodName {\n\t\t\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"sentinel\", expectedOnSentinel, serverStartTimeout)\n\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tcheckAllLogs()\n\n\t\t\tBy(\"turning down bootstrap\")\n\t\t\trunKubectl(\"delete\", \"-f\", bootstrapYaml, nsFlag)\n\t\t\tcleanupBootstrap = false\n\t\t\terr = waitForRCPodToDisappear(c, ns, redisRC, bootstrapPodName)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"waiting for the new master election\")\n\t\t\tcheckAllLogs()\n\t\t})\n\t})\n\n\tDescribe(\"[Skipped][Example]Celery-RabbitMQ\", func() {\n\t\tIt(\"should create and stop celery+rabbitmq servers\", func() {\n\t\t\tmkpath := func(file string) string {\n\t\t\t\treturn filepath.Join(testContext.RepoRoot, \"examples\", \"celery-rabbitmq\", file)\n\t\t\t}\n\t\t\trabbitmqServiceYaml := mkpath(\"rabbitmq-service.yaml\")\n\t\t\trabbitmqControllerYaml := mkpath(\"rabbitmq-controller.yaml\")\n\t\t\tceleryControllerYaml := mkpath(\"celery-controller.yaml\")\n\t\t\tflowerControllerYaml := mkpath(\"flower-controller.yaml\")\n\t\t\tnsFlag := fmt.Sprintf(\"--namespace=%v\", ns)\n\n\t\t\tBy(\"starting rabbitmq\")\n\t\t\trunKubectl(\"create\", \"-f\", rabbitmqServiceYaml, nsFlag)\n\t\t\tdefer cleanup(rabbitmqServiceYaml, ns, \"component=rabbitmq\")\n\t\t\trunKubectl(\"create\", \"-f\", rabbitmqControllerYaml, nsFlag)\n\t\t\tdefer cleanup(rabbitmqControllerYaml, ns, \"component=rabbitmq\")\n\t\t\tforEachPod(c, ns, \"component\", \"rabbitmq\", func(pod api.Pod) {\n\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"rabbitmq\", \"Server startup complete\", serverStartTimeout)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tBy(\"starting celery\")\n\t\t\trunKubectl(\"create\", \"-f\", celeryControllerYaml, nsFlag)\n\t\t\tdefer cleanup(celeryControllerYaml, ns, \"component=celery\")\n\t\t\tforEachPod(c, ns, \"component\", \"celery\", func(pod api.Pod) {\n\t\t\t\t_, err := lookForStringInFile(ns, pod.Name, \"celery\", \"\/data\/celery.log\", \" ready.\", serverStartTimeout)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tBy(\"starting flower\")\n\t\t\trunKubectl(\"create\", \"-f\", flowerControllerYaml, nsFlag)\n\t\t\tdefer cleanup(flowerControllerYaml, ns, \"component=flower\")\n\t\t\tforEachPod(c, ns, \"component\", \"flower\", func(pod api.Pod) {\n\t\t\t\t\/\/TODO: Do a http request after a flower service is added to the example.\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc forEachPod(c *client.Client, ns, selectorKey, selectorValue string, fn func(api.Pod)) {\n\tvar pods *api.PodList\n\tvar err error\n\tfor t := time.Now(); time.Since(t) < podListTimeout; time.Sleep(poll) {\n\t\tpods, err = c.Pods(ns).List(labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue})), fields.Everything())\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tif len(pods.Items) > 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif pods == nil || len(pods.Items) == 0 {\n\t\tFailf(\"No pods found\")\n\t}\n\tfor _, pod := range pods.Items {\n\t\terr = waitForPodRunningInNamespace(c, pod.Name, ns)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tfn(pod)\n\t}\n}\n\nfunc lookForStringInLog(ns, podName, container, expectedString string, timeout time.Duration) (result string, err error) {\n\treturn lookForString(expectedString, timeout, func() string {\n\t\treturn runKubectl(\"log\", podName, container, fmt.Sprintf(\"--namespace=%v\", ns))\n\t})\n}\n\nfunc lookForStringInFile(ns, podName, container, file, expectedString string, timeout time.Duration) (result string, err error) {\n\treturn lookForString(expectedString, timeout, func() string {\n\t\treturn runKubectl(\"exec\", podName, \"-c\", container, fmt.Sprintf(\"--namespace=%v\", ns), \"--\", \"cat\", file)\n\t})\n}\n\n\/\/ Looks for the given string in the output of fn, repeatedly calling fn until\n\/\/ the timeout is reached or the string is found. Returns last log and possibly\n\/\/ error if the string was not found.\nfunc lookForString(expectedString string, timeout time.Duration, fn func() string) (result string, err error) {\n\tfor t := time.Now(); time.Since(t) < timeout; time.Sleep(poll) {\n\t\tresult = fn()\n\t\tif strings.Contains(result, expectedString) {\n\t\t\treturn\n\t\t}\n\t}\n\terr = fmt.Errorf(\"Failed to find \\\"%s\\\"\", expectedString)\n\treturn\n}\nRemove deferred cleanups from tests\/e2e\/examples.go\/*\nCopyright 2015 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/fields\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nconst (\n\tpodListTimeout = time.Minute\n\tserverStartTimeout = podStartTimeout + 3*time.Minute\n)\n\nvar _ = Describe(\"Examples e2e\", func() {\n\tvar c *client.Client\n\tvar ns string\n\tvar testingNs *api.Namespace\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tc, err = loadClient()\n\t\texpectNoError(err)\n\t\ttestingNs, err = createTestingNS(\"examples\", c)\n\t\tns = testingNs.Name\n\t\tExpect(err).NotTo(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tBy(fmt.Sprintf(\"Destroying namespace for this suite %v\", ns))\n\t\tif err := c.Namespaces().Delete(ns); err != nil {\n\t\t\tFailf(\"Couldn't delete ns %s\", err)\n\t\t}\n\t})\n\n\tDescribe(\"[Skipped][Example]Redis\", func() {\n\t\tIt(\"should create and stop redis servers\", func() {\n\t\t\tmkpath := func(file string) string {\n\t\t\t\treturn filepath.Join(testContext.RepoRoot, \"examples\/redis\", file)\n\t\t\t}\n\t\t\tbootstrapYaml := mkpath(\"redis-master.yaml\")\n\t\t\tsentinelServiceYaml := mkpath(\"redis-sentinel-service.yaml\")\n\t\t\tsentinelControllerYaml := mkpath(\"redis-sentinel-controller.yaml\")\n\t\t\tcontrollerYaml := mkpath(\"redis-controller.yaml\")\n\n\t\t\tbootstrapPodName := \"redis-master\"\n\t\t\tredisRC := \"redis\"\n\t\t\tsentinelRC := \"redis-sentinel\"\n\t\t\tnsFlag := fmt.Sprintf(\"--namespace=%v\", ns)\n\t\t\texpectedOnServer := \"The server is now ready to accept connections\"\n\t\t\texpectedOnSentinel := \"+monitor master\"\n\n\t\t\tBy(\"starting redis bootstrap\")\n\t\t\trunKubectl(\"create\", \"-f\", bootstrapYaml, nsFlag)\n\t\t\terr := waitForPodRunningInNamespace(c, bootstrapPodName, ns)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t_, err = lookForStringInLog(ns, bootstrapPodName, \"master\", expectedOnServer, serverStartTimeout)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t_, err = lookForStringInLog(ns, bootstrapPodName, \"sentinel\", expectedOnSentinel, serverStartTimeout)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"setting up services and controllers\")\n\t\t\trunKubectl(\"create\", \"-f\", sentinelServiceYaml, nsFlag)\n\t\t\trunKubectl(\"create\", \"-f\", sentinelControllerYaml, nsFlag)\n\t\t\trunKubectl(\"create\", \"-f\", controllerYaml, nsFlag)\n\n\t\t\tBy(\"scaling up the deployment\")\n\t\t\trunKubectl(\"scale\", \"rc\", redisRC, \"--replicas=3\", nsFlag)\n\t\t\trunKubectl(\"scale\", \"rc\", sentinelRC, \"--replicas=3\", nsFlag)\n\n\t\t\tBy(\"checking up the services\")\n\t\t\tcheckAllLogs := func() {\n\t\t\t\tforEachPod(c, ns, \"name\", \"redis\", func(pod api.Pod) {\n\t\t\t\t\tif pod.Name != bootstrapPodName {\n\t\t\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"redis\", expectedOnServer, serverStartTimeout)\n\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tforEachPod(c, ns, \"name\", \"redis-sentinel\", func(pod api.Pod) {\n\t\t\t\t\tif pod.Name != bootstrapPodName {\n\t\t\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"sentinel\", expectedOnSentinel, serverStartTimeout)\n\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tcheckAllLogs()\n\n\t\t\tBy(\"turning down bootstrap\")\n\t\t\trunKubectl(\"delete\", \"-f\", bootstrapYaml, nsFlag)\n\t\t\terr = waitForRCPodToDisappear(c, ns, redisRC, bootstrapPodName)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tBy(\"waiting for the new master election\")\n\t\t\tcheckAllLogs()\n\t\t})\n\t})\n\n\tDescribe(\"[Skipped][Example]Celery-RabbitMQ\", func() {\n\t\tIt(\"should create and stop celery+rabbitmq servers\", func() {\n\t\t\tmkpath := func(file string) string {\n\t\t\t\treturn filepath.Join(testContext.RepoRoot, \"examples\", \"celery-rabbitmq\", file)\n\t\t\t}\n\t\t\trabbitmqServiceYaml := mkpath(\"rabbitmq-service.yaml\")\n\t\t\trabbitmqControllerYaml := mkpath(\"rabbitmq-controller.yaml\")\n\t\t\tceleryControllerYaml := mkpath(\"celery-controller.yaml\")\n\t\t\tflowerControllerYaml := mkpath(\"flower-controller.yaml\")\n\t\t\tnsFlag := fmt.Sprintf(\"--namespace=%v\", ns)\n\n\t\t\tBy(\"starting rabbitmq\")\n\t\t\trunKubectl(\"create\", \"-f\", rabbitmqServiceYaml, nsFlag)\n\t\t\trunKubectl(\"create\", \"-f\", rabbitmqControllerYaml, nsFlag)\n\t\t\tforEachPod(c, ns, \"component\", \"rabbitmq\", func(pod api.Pod) {\n\t\t\t\t_, err := lookForStringInLog(ns, pod.Name, \"rabbitmq\", \"Server startup complete\", serverStartTimeout)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\t\t\tBy(\"starting celery\")\n\t\t\trunKubectl(\"create\", \"-f\", celeryControllerYaml, nsFlag)\n\t\t\tforEachPod(c, ns, \"component\", \"celery\", func(pod api.Pod) {\n\t\t\t\t_, err := lookForStringInFile(ns, pod.Name, \"celery\", \"\/data\/celery.log\", \" ready.\", serverStartTimeout)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tBy(\"starting flower\")\n\t\t\trunKubectl(\"create\", \"-f\", flowerControllerYaml, nsFlag)\n\t\t\tforEachPod(c, ns, \"component\", \"flower\", func(pod api.Pod) {\n\t\t\t\t\/\/TODO: Do a http request after a flower service is added to the example.\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc forEachPod(c *client.Client, ns, selectorKey, selectorValue string, fn func(api.Pod)) {\n\tvar pods *api.PodList\n\tvar err error\n\tfor t := time.Now(); time.Since(t) < podListTimeout; time.Sleep(poll) {\n\t\tpods, err = c.Pods(ns).List(labels.SelectorFromSet(labels.Set(map[string]string{selectorKey: selectorValue})), fields.Everything())\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tif len(pods.Items) > 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif pods == nil || len(pods.Items) == 0 {\n\t\tFailf(\"No pods found\")\n\t}\n\tfor _, pod := range pods.Items {\n\t\terr = waitForPodRunningInNamespace(c, pod.Name, ns)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tfn(pod)\n\t}\n}\n\nfunc lookForStringInLog(ns, podName, container, expectedString string, timeout time.Duration) (result string, err error) {\n\treturn lookForString(expectedString, timeout, func() string {\n\t\treturn runKubectl(\"log\", podName, container, fmt.Sprintf(\"--namespace=%v\", ns))\n\t})\n}\n\nfunc lookForStringInFile(ns, podName, container, file, expectedString string, timeout time.Duration) (result string, err error) {\n\treturn lookForString(expectedString, timeout, func() string {\n\t\treturn runKubectl(\"exec\", podName, \"-c\", container, fmt.Sprintf(\"--namespace=%v\", ns), \"--\", \"cat\", file)\n\t})\n}\n\n\/\/ Looks for the given string in the output of fn, repeatedly calling fn until\n\/\/ the timeout is reached or the string is found. Returns last log and possibly\n\/\/ error if the string was not found.\nfunc lookForString(expectedString string, timeout time.Duration, fn func() string) (result string, err error) {\n\tfor t := time.Now(); time.Since(t) < timeout; time.Sleep(poll) {\n\t\tresult = fn()\n\t\tif strings.Contains(result, expectedString) {\n\t\t\treturn\n\t\t}\n\t}\n\terr = fmt.Errorf(\"Failed to find \\\"%s\\\"\", expectedString)\n\treturn\n}\n<|endoftext|>"} {"text":"\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype Event struct {\n\tName string\n\tLink string\n\tDesc string\n}\n\nfunc main() {\n\tnameMap := map[string]string{\n\t\t\"afterprint\": \"AfterPrint\",\n\t\t\"animationend\": \"AnimationEnd\",\n\t\t\"animationiteration\": \"AnimationIteration\",\n\t\t\"animationstart\": \"AnimationStart\",\n\t\t\"audioprocess\": \"AudioProcess\",\n\t\t\"audioend\": \"AudioEnd\",\n\t\t\"audiostart\": \"AudioStart\",\n\t\t\"beforeprint\": \"BeforePrint\",\n\t\t\"beforeunload\": \"BeforeUnload\",\n\t\t\"canplay\": \"CanPlay\",\n\t\t\"canplaythrough\": \"CanPlayThrough\",\n\t\t\"chargingchange\": \"ChargingChange\",\n\t\t\"chargingtimechange\": \"ChargingTimeChange\",\n\t\t\"compassneedscalibration\": \"CompassNeedsCalibration\",\n\t\t\"compositionend\": \"CompositionEnd\",\n\t\t\"compositionstart\": \"CompositionStart\",\n\t\t\"compositionupdate\": \"CompositionUpdate\",\n\t\t\"contextmenu\": \"ContextMenu\",\n\t\t\"dblclick\": \"DoubleClick\",\n\t\t\"devicelight\": \"DeviceLight\",\n\t\t\"devicemotion\": \"DeviceMotion\",\n\t\t\"deviceorientation\": \"DeviceOrientation\",\n\t\t\"deviceproximity\": \"DeviceProximity\",\n\t\t\"dischargingtimechange\": \"DischargingTimeChange\",\n\t\t\"dragend\": \"DragEnd\",\n\t\t\"dragenter\": \"DragEnter\",\n\t\t\"dragleave\": \"DragLeave\",\n\t\t\"dragover\": \"DragOver\",\n\t\t\"dragstart\": \"DragStart\",\n\t\t\"durationchange\": \"DurationChange\",\n\t\t\"focusin\": \"FocusIn\",\n\t\t\"focusout\": \"FocusOut\",\n\t\t\"fullscreenchange\": \"FullScreenChange\",\n\t\t\"fullscreenerror\": \"FullScreenError\",\n\t\t\"gamepadconnected\": \"GamepadConnected\",\n\t\t\"gamepaddisconnected\": \"GamepadDisconnected\",\n\t\t\"gotpointercapture\": \"GotPointerCapture\",\n\t\t\"hashchange\": \"HashChange\",\n\t\t\"keydown\": \"KeyDown\",\n\t\t\"keypress\": \"KeyPress\",\n\t\t\"keyup\": \"KeyUp\",\n\t\t\"languagechange\": \"LanguageChange\",\n\t\t\"levelchange\": \"LevelChange\",\n\t\t\"loadeddata\": \"LoadedData\",\n\t\t\"loadedmetadata\": \"LoadedMetadata\",\n\t\t\"loadend\": \"LoadEnd\",\n\t\t\"loadstart\": \"LoadStart\",\n\t\t\"lostpointercapture\": \"LostPointerCapture\",\n\t\t\"mousedown\": \"MouseDown\",\n\t\t\"mouseenter\": \"MouseEnter\",\n\t\t\"mouseleave\": \"MouseLeave\",\n\t\t\"mousemove\": \"MouseMove\",\n\t\t\"mouseout\": \"MouseOut\",\n\t\t\"mouseover\": \"MouseOver\",\n\t\t\"mouseup\": \"MouseUp\",\n\t\t\"noupdate\": \"NoUpdate\",\n\t\t\"nomatch\": \"NoMatch\",\n\t\t\"notificationclick\": \"NotificationClick\",\n\t\t\"orientationchange\": \"OrientationChange\",\n\t\t\"pagehide\": \"PageHide\",\n\t\t\"pageshow\": \"PageShow\",\n\t\t\"pointercancel\": \"PointerCancel\",\n\t\t\"pointerdown\": \"PointerDown\",\n\t\t\"pointerenter\": \"PointerEnter\",\n\t\t\"pointerleave\": \"PointerLeave\",\n\t\t\"pointerlockchange\": \"PointerLockChange\",\n\t\t\"pointerlockerror\": \"PointerLockError\",\n\t\t\"pointermove\": \"PointerMove\",\n\t\t\"pointerout\": \"PointerOut\",\n\t\t\"pointerover\": \"PointerOver\",\n\t\t\"pointerup\": \"PointerUp\",\n\t\t\"popstate\": \"PopState\",\n\t\t\"pushsubscriptionchange\": \"PushSubscriptionChange\",\n\t\t\"ratechange\": \"RateChange\",\n\t\t\"readystatechange\": \"ReadyStateChange\",\n\t\t\"resourcetimingbufferfull\": \"ResourceTimingBufferFull\",\n\t\t\"selectstart\": \"SelectStart\",\n\t\t\"selectionchange\": \"SelectionChange\",\n\t\t\"soundend\": \"SoundEnd\",\n\t\t\"soundstart\": \"SoundStart\",\n\t\t\"speechend\": \"SpeechEnd\",\n\t\t\"speechstart\": \"SpeechStart\",\n\t\t\"timeupdate\": \"TimeUpdate\",\n\t\t\"touchcancel\": \"TouchCancel\",\n\t\t\"touchend\": \"TouchEnd\",\n\t\t\"touchenter\": \"TouchEnter\",\n\t\t\"touchleave\": \"TouchLeave\",\n\t\t\"touchmove\": \"TouchMove\",\n\t\t\"touchstart\": \"TouchStart\",\n\t\t\"transitionend\": \"TransitionEnd\",\n\t\t\"updateready\": \"UpdateReady\",\n\t\t\"upgradeneeded\": \"UpgradeNeeded\",\n\t\t\"userproximity\": \"UserProximity\",\n\t\t\"versionchange\": \"VersionChange\",\n\t\t\"visibilitychange\": \"VisibilityChange\",\n\t\t\"voiceschanged\": \"VoicesChanged\",\n\t\t\"volumechange\": \"VolumeChange\",\n\t}\n\n\tdoc, err := goquery.NewDocument(\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tevents := make(map[string]*Event)\n\n\tdoc.Find(\".standard-table\").Eq(0).Find(\"tr\").Each(func(i int, s *goquery.Selection) {\n\t\tcols := s.Find(\"td\")\n\t\tif cols.Length() == 0 || cols.Find(\".icon-thumbs-down-alt\").Length() != 0 {\n\t\t\treturn\n\t\t}\n\t\tlink := cols.Eq(0).Find(\"a\").Eq(0)\n\t\tvar e Event\n\t\te.Name = link.Text()\n\t\te.Link, _ = link.Attr(\"href\")\n\t\te.Desc = strings.TrimSpace(cols.Eq(3).Text())\n\t\tif e.Desc == \"\" {\n\t\t\te.Desc = \"(no documentation)\"\n\t\t}\n\n\t\tfunName := nameMap[e.Name]\n\t\tif funName == \"\" {\n\t\t\tfunName = capitalize(e.Name)\n\t\t}\n\n\t\tevents[funName] = &e\n\t})\n\n\tvar names []string\n\tfor name := range events {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\n\tfile, err := os.Create(\"event.gen.go\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tfmt.Fprint(file, `\/\/go:generate go run generate.go\n\n\/\/ Package event defines markup to bind DOM events.\n\/\/\n\/\/ Generated from \"Event reference\" by Mozilla Contributors, https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events, licensed under CC-BY-SA 2.5.\npackage event\n\nimport \"github.com\/gopherjs\/vecty\"\n`)\n\n\tfor _, name := range names {\n\t\te := events[name]\n\t\tfmt.Fprintf(file, `\n\/\/ %s\n\/\/\n\/\/ https:\/\/developer.mozilla.org%s\nfunc %s(listener func(*vecty.Event)) *vecty.EventListener {\n\treturn &vecty.EventListener{Name: \"%s\", Listener: listener}\n}\n`, e.Desc, e.Link[6:], name, e.Name)\n\t}\n}\n\nfunc capitalize(s string) string {\n\treturn strings.ToUpper(s[:1]) + s[1:]\n}\nevent: add name translations for vrdisplay*** event types\/\/ +build ignore\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype Event struct {\n\tName string\n\tLink string\n\tDesc string\n}\n\nfunc main() {\n\tnameMap := map[string]string{\n\t\t\"afterprint\": \"AfterPrint\",\n\t\t\"animationend\": \"AnimationEnd\",\n\t\t\"animationiteration\": \"AnimationIteration\",\n\t\t\"animationstart\": \"AnimationStart\",\n\t\t\"audioprocess\": \"AudioProcess\",\n\t\t\"audioend\": \"AudioEnd\",\n\t\t\"audiostart\": \"AudioStart\",\n\t\t\"beforeprint\": \"BeforePrint\",\n\t\t\"beforeunload\": \"BeforeUnload\",\n\t\t\"canplay\": \"CanPlay\",\n\t\t\"canplaythrough\": \"CanPlayThrough\",\n\t\t\"chargingchange\": \"ChargingChange\",\n\t\t\"chargingtimechange\": \"ChargingTimeChange\",\n\t\t\"compassneedscalibration\": \"CompassNeedsCalibration\",\n\t\t\"compositionend\": \"CompositionEnd\",\n\t\t\"compositionstart\": \"CompositionStart\",\n\t\t\"compositionupdate\": \"CompositionUpdate\",\n\t\t\"contextmenu\": \"ContextMenu\",\n\t\t\"dblclick\": \"DoubleClick\",\n\t\t\"devicelight\": \"DeviceLight\",\n\t\t\"devicemotion\": \"DeviceMotion\",\n\t\t\"deviceorientation\": \"DeviceOrientation\",\n\t\t\"deviceproximity\": \"DeviceProximity\",\n\t\t\"dischargingtimechange\": \"DischargingTimeChange\",\n\t\t\"dragend\": \"DragEnd\",\n\t\t\"dragenter\": \"DragEnter\",\n\t\t\"dragleave\": \"DragLeave\",\n\t\t\"dragover\": \"DragOver\",\n\t\t\"dragstart\": \"DragStart\",\n\t\t\"durationchange\": \"DurationChange\",\n\t\t\"focusin\": \"FocusIn\",\n\t\t\"focusout\": \"FocusOut\",\n\t\t\"fullscreenchange\": \"FullScreenChange\",\n\t\t\"fullscreenerror\": \"FullScreenError\",\n\t\t\"gamepadconnected\": \"GamepadConnected\",\n\t\t\"gamepaddisconnected\": \"GamepadDisconnected\",\n\t\t\"gotpointercapture\": \"GotPointerCapture\",\n\t\t\"hashchange\": \"HashChange\",\n\t\t\"keydown\": \"KeyDown\",\n\t\t\"keypress\": \"KeyPress\",\n\t\t\"keyup\": \"KeyUp\",\n\t\t\"languagechange\": \"LanguageChange\",\n\t\t\"levelchange\": \"LevelChange\",\n\t\t\"loadeddata\": \"LoadedData\",\n\t\t\"loadedmetadata\": \"LoadedMetadata\",\n\t\t\"loadend\": \"LoadEnd\",\n\t\t\"loadstart\": \"LoadStart\",\n\t\t\"lostpointercapture\": \"LostPointerCapture\",\n\t\t\"mousedown\": \"MouseDown\",\n\t\t\"mouseenter\": \"MouseEnter\",\n\t\t\"mouseleave\": \"MouseLeave\",\n\t\t\"mousemove\": \"MouseMove\",\n\t\t\"mouseout\": \"MouseOut\",\n\t\t\"mouseover\": \"MouseOver\",\n\t\t\"mouseup\": \"MouseUp\",\n\t\t\"noupdate\": \"NoUpdate\",\n\t\t\"nomatch\": \"NoMatch\",\n\t\t\"notificationclick\": \"NotificationClick\",\n\t\t\"orientationchange\": \"OrientationChange\",\n\t\t\"pagehide\": \"PageHide\",\n\t\t\"pageshow\": \"PageShow\",\n\t\t\"pointercancel\": \"PointerCancel\",\n\t\t\"pointerdown\": \"PointerDown\",\n\t\t\"pointerenter\": \"PointerEnter\",\n\t\t\"pointerleave\": \"PointerLeave\",\n\t\t\"pointerlockchange\": \"PointerLockChange\",\n\t\t\"pointerlockerror\": \"PointerLockError\",\n\t\t\"pointermove\": \"PointerMove\",\n\t\t\"pointerout\": \"PointerOut\",\n\t\t\"pointerover\": \"PointerOver\",\n\t\t\"pointerup\": \"PointerUp\",\n\t\t\"popstate\": \"PopState\",\n\t\t\"pushsubscriptionchange\": \"PushSubscriptionChange\",\n\t\t\"ratechange\": \"RateChange\",\n\t\t\"readystatechange\": \"ReadyStateChange\",\n\t\t\"resourcetimingbufferfull\": \"ResourceTimingBufferFull\",\n\t\t\"selectstart\": \"SelectStart\",\n\t\t\"selectionchange\": \"SelectionChange\",\n\t\t\"soundend\": \"SoundEnd\",\n\t\t\"soundstart\": \"SoundStart\",\n\t\t\"speechend\": \"SpeechEnd\",\n\t\t\"speechstart\": \"SpeechStart\",\n\t\t\"timeupdate\": \"TimeUpdate\",\n\t\t\"touchcancel\": \"TouchCancel\",\n\t\t\"touchend\": \"TouchEnd\",\n\t\t\"touchenter\": \"TouchEnter\",\n\t\t\"touchleave\": \"TouchLeave\",\n\t\t\"touchmove\": \"TouchMove\",\n\t\t\"touchstart\": \"TouchStart\",\n\t\t\"transitionend\": \"TransitionEnd\",\n\t\t\"updateready\": \"UpdateReady\",\n\t\t\"upgradeneeded\": \"UpgradeNeeded\",\n\t\t\"userproximity\": \"UserProximity\",\n\t\t\"versionchange\": \"VersionChange\",\n\t\t\"visibilitychange\": \"VisibilityChange\",\n\t\t\"voiceschanged\": \"VoicesChanged\",\n\t\t\"volumechange\": \"VolumeChange\",\n\t\t\"vrdisplayconnected\": \"VRDisplayConnected\",\n\t\t\"vrdisplaydisconnected\": \"VRDisplayDisconnected\",\n\t\t\"vrdisplaypresentchange\": \"VRDisplayPresentChange\",\n\t}\n\n\tdoc, err := goquery.NewDocument(\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tevents := make(map[string]*Event)\n\n\tdoc.Find(\".standard-table\").Eq(0).Find(\"tr\").Each(func(i int, s *goquery.Selection) {\n\t\tcols := s.Find(\"td\")\n\t\tif cols.Length() == 0 || cols.Find(\".icon-thumbs-down-alt\").Length() != 0 {\n\t\t\treturn\n\t\t}\n\t\tlink := cols.Eq(0).Find(\"a\").Eq(0)\n\t\tvar e Event\n\t\te.Name = link.Text()\n\t\te.Link, _ = link.Attr(\"href\")\n\t\te.Desc = strings.TrimSpace(cols.Eq(3).Text())\n\t\tif e.Desc == \"\" {\n\t\t\te.Desc = \"(no documentation)\"\n\t\t}\n\n\t\tfunName := nameMap[e.Name]\n\t\tif funName == \"\" {\n\t\t\tfunName = capitalize(e.Name)\n\t\t}\n\n\t\tevents[funName] = &e\n\t})\n\n\tvar names []string\n\tfor name := range events {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\n\tfile, err := os.Create(\"event.gen.go\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer file.Close()\n\n\tfmt.Fprint(file, `\/\/go:generate go run generate.go\n\n\/\/ Package event defines markup to bind DOM events.\n\/\/\n\/\/ Generated from \"Event reference\" by Mozilla Contributors, https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Events, licensed under CC-BY-SA 2.5.\npackage event\n\nimport \"github.com\/gopherjs\/vecty\"\n`)\n\n\tfor _, name := range names {\n\t\te := events[name]\n\t\tfmt.Fprintf(file, `\n\/\/ %s\n\/\/\n\/\/ https:\/\/developer.mozilla.org%s\nfunc %s(listener func(*vecty.Event)) *vecty.EventListener {\n\treturn &vecty.EventListener{Name: \"%s\", Listener: listener}\n}\n`, e.Desc, e.Link[6:], name, e.Name)\n\t}\n}\n\nfunc capitalize(s string) string {\n\treturn strings.ToUpper(s[:1]) + s[1:]\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 OpenConfigd Project.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n\n\t\"github.com\/coreswitch\/component\"\n\t\"github.com\/coreswitch\/openconfigd\/config\"\n\t\"github.com\/jessevdk\/go-flags\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nfunc EsiHook() {\n\tif _, err := os.Stat(\"\/etc\/esi\/env\"); err == nil {\n\t\tconfig.RibdAsyncUpdate = true\n\t}\n}\n\nfunc main() {\n\tfmt.Println(\"Starting openconfigd.\")\n\n\tEsiHook()\n\n\tvar opts struct {\n\t\tConfigActiveFile string `short:\"c\" long:\"config-file\" description:\"active config file name\" default:\"openconfigd.conf\"`\n\t\tConfigFileDir string `short:\"p\" long:\"config-dir\" description:\"config file directory\" default:\"\/usr\/local\/etc\"`\n\t\tYangPaths string `short:\"y\" long:\"yang-paths\" description:\"comma separated YANG load path directories\"`\n\t\tTwoPhaseCommit bool `short:\"2\" long:\"two-phase\" description:\"two phase commit\"`\n\t\tZeroConfig bool `short:\"z\" long:\"zero-config\" description:\"Do not save or load config other than openconfigd.conf\"`\n\t}\n\n\targs, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Arguments are YANG module names. When no modules is specified \"coreswitch\"\n\t\/\/ is set as default YANG module name.\n\tif len(args) == 0 {\n\t\targs = []string{\"coreswitch\"}\n\t}\n\n\t\/\/ Set log output.\n\tlog.SetOutput(os.Stdout)\n\tlog.SetFormatter(&log.JSONFormatter{})\n\n\t\/\/ Set maxprocs\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ YANG Component\n\tyangComponent := &config.YangComponent{\n\t\tYangPaths: opts.YangPaths,\n\t\tYangModules: args,\n\t}\n\n\t\/\/ Config component\n\tconfigComponent := &config.ConfigComponent{\n\t\tConfigFileDir: opts.ConfigFileDir,\n\t\tConfigActiveFile: opts.ConfigActiveFile,\n\t\tTwoPhaseCommit: opts.TwoPhaseCommit,\n\t\tZeroConfig: opts.ZeroConfig,\n\t}\n\n\t\/\/ CLI component\n\tcliComponent := &config.CliComponent{}\n\n\t\/\/ Rpc Component\n\trpcComponent := &config.RpcComponent{}\n\n\tsystemMap := component.SystemMap{\n\t\t\"yang\": yangComponent,\n\t\t\"cli\": component.ComponentWith(cliComponent, \"yang\"),\n\t\t\"config\": component.ComponentWith(configComponent, \"yang\", \"cli\"),\n\t\t\"rpc\": component.ComponentWith(rpcComponent, \"config\"),\n\t}\n\n\t\/\/ Register clearn up function.\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\t<-c\n\t\tsystemMap.Stop()\n\t\tos.Exit(1)\n\t}()\n\n\t\/\/ Start components.\n\tsystemMap.Start()\n}\nSet default RpcEndPoint.\/\/ Copyright 2016 OpenConfigd Project.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n\n\t\"github.com\/coreswitch\/component\"\n\t\"github.com\/coreswitch\/openconfigd\/config\"\n\t\"github.com\/jessevdk\/go-flags\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nfunc EsiHook() {\n\tif _, err := os.Stat(\"\/etc\/esi\/env\"); err == nil {\n\t\tconfig.RibdAsyncUpdate = true\n\t}\n}\n\nfunc main() {\n\tfmt.Println(\"Starting openconfigd.\")\n\n\tEsiHook()\n\n\tvar opts struct {\n\t\tConfigActiveFile string `short:\"c\" long:\"config-file\" description:\"active config file name\" default:\"openconfigd.conf\"`\n\t\tConfigFileDir string `short:\"p\" long:\"config-dir\" description:\"config file directory\" default:\"\/usr\/local\/etc\"`\n\t\tRpcEndPoint string `short:\"g\" long:\"grpc-endpoint\" description:\"Grpc End Point\" default:\"127.0.0.1:2650\"`\n\t\tYangPaths string `short:\"y\" long:\"yang-paths\" description:\"comma separated YANG load path directories\"`\n\t\tTwoPhaseCommit bool `short:\"2\" long:\"two-phase\" description:\"two phase commit\"`\n\t\tZeroConfig bool `short:\"z\" long:\"zero-config\" description:\"Do not save or load config other than openconfigd.conf\"`\n\t}\n\n\targs, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Arguments are YANG module names. When no modules is specified \"coreswitch\"\n\t\/\/ is set as default YANG module name.\n\tif len(args) == 0 {\n\t\targs = []string{\"coreswitch\"}\n\t}\n\n\t\/\/ Set log output.\n\tlog.SetOutput(os.Stdout)\n\tlog.SetFormatter(&log.JSONFormatter{})\n\n\t\/\/ Set maxprocs\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ YANG Component\n\tyangComponent := &config.YangComponent{\n\t\tYangPaths: opts.YangPaths,\n\t\tYangModules: args,\n\t}\n\n\t\/\/ Config component\n\tconfigComponent := &config.ConfigComponent{\n\t\tConfigFileDir: opts.ConfigFileDir,\n\t\tConfigActiveFile: opts.ConfigActiveFile,\n\t\tTwoPhaseCommit: opts.TwoPhaseCommit,\n\t\tZeroConfig: opts.ZeroConfig,\n\t}\n\n\t\/\/ CLI component\n\tcliComponent := &config.CliComponent{}\n\n\t\/\/ Rpc Component\n\trpcComponent := &config.RpcComponent{\n\t\tGrpcEndpoint: opts.RpcEndPoint,\n\t}\n\n\tsystemMap := component.SystemMap{\n\t\t\"yang\": yangComponent,\n\t\t\"cli\": component.ComponentWith(cliComponent, \"yang\"),\n\t\t\"config\": component.ComponentWith(configComponent, \"yang\", \"cli\"),\n\t\t\"rpc\": component.ComponentWith(rpcComponent, \"config\"),\n\t}\n\n\t\/\/ Register clearn up function.\n\tc := make(chan os.Signal, 2)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\t<-c\n\t\tsystemMap.Stop()\n\t\tos.Exit(1)\n\t}()\n\n\t\/\/ Start components.\n\tsystemMap.Start()\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Gocov Authors.\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/axw\/gocov\"\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/printer\"\n\t\"go\/token\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst gocovPackagePath = \"github.com\/axw\/gocov\"\nconst instrumentedPathPrefix = gocovPackagePath + \"\/instrumented\"\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage:\\n\\n\\tgocov command [arguments]\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"The commands are:\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tannotate\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\ttest\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\treport\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nvar (\n\ttestFlags = flag.NewFlagSet(\"test\", flag.ExitOnError)\n\ttestExcludeFlag = testFlags.String(\n\t\t\"exclude\", \"\",\n\t\t\"print the name of the temporary work directory \"+\n\t\t\t\"and do not delete it when exiting.\")\n\ttestExcludeGorootFlag = testFlags.Bool(\n\t\t\"exclude-goroot\", true,\n\t\t\"exclude packages in GOROOT from instrumentation\")\n\ttestWorkFlag = testFlags.Bool(\n\t\t\"work\", false,\n\t\t\"packages to exclude, separated by comma\")\n\tverbose bool\n)\n\nfunc init() {\n\ttestFlags.BoolVar(&verbose, \"v\", false, \"verbose\")\n}\n\ntype instrumenter struct {\n\tgopath string \/\/ temporary gopath\n\texcluded []string\n\tinstrumented map[string]*gocov.Package\n\tprocessed map[string]struct{}\n}\n\nfunc putenv(env []string, key, value string) []string {\n\tfor i, s := range env {\n\t\tif strings.HasPrefix(s, key+\"=\") {\n\t\t\tenv[i] = key + \"=\" + value\n\t\t\treturn env\n\t\t}\n\t}\n\treturn append(env, key+\"=\"+value)\n}\n\nfunc parsePackage(path string, fset *token.FileSet) (*build.Package, *ast.Package, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tp, err := build.Import(path, cwd, 0)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tgoFiles := append(p.GoFiles[:], p.CgoFiles...)\n\tsort.Strings(goFiles)\n\tfilter := func(f os.FileInfo) bool {\n\t\tname := f.Name()\n\t\ti := sort.SearchStrings(goFiles, name)\n\t\treturn i < len(goFiles) && goFiles[i] == name\n\t}\n\tmode := parser.DeclarationErrors | parser.ParseComments\n\tpkgs, err := parser.ParseDir(fset, p.Dir, filter, mode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn p, pkgs[p.Name], err\n}\n\nfunc symlinkHierarchy(src, dst string) error {\n\tfn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trel, err := filepath.Rel(src, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttarget := filepath.Join(dst, rel)\n\t\tif _, err = os.Stat(target); err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\treturn os.MkdirAll(target, 0700)\n\t\t} else {\n\t\t\terr = os.Symlink(path, target)\n\t\t\tif err != nil {\n\t\t\t\tsrcfile, err := os.Open(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer srcfile.Close()\n\t\t\t\tdstfile, err := os.OpenFile(\n\t\t\t\t\ttarget, os.O_RDWR|os.O_CREATE, 0600)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer dstfile.Close()\n\t\t\t\t_, err = io.Copy(dstfile, srcfile)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn filepath.Walk(src, fn)\n}\n\n\/\/ FIXME(axw)\n\/\/\n\/\/ As we change the name of the package to avoid being obscured by GOROOT, we\n\/\/ can't instrument packages that have Go functions implemented in C, such as\n\/\/ those below.\n\/\/\n\/\/ It may be preferable to have a faked GOROOT, but we'll need to come up with\n\/\/ a way to avoid the import loop introduced by importing gocov into the\n\/\/ instrumented pakcage.\n\/\/\nfunc instrumentable(path string) bool {\n\tswitch path {\n\tcase \"C\": fallthrough\n\tcase \"reflect\": fallthrough\n\tcase \"runtime\": fallthrough\n\tcase \"os\": fallthrough\n\tcase \"sync\": fallthrough\n\tcase \"syscall\": fallthrough\n\tcase \"time\": fallthrough\n\tcase \"testing\": fallthrough\n\tcase \"unsafe\": return false\n\t}\n\treturn true\n}\n\nfunc (in *instrumenter) instrumentPackage(pkgpath string) error {\n\tif _, already := in.processed[pkgpath]; already {\n\t\treturn nil\n\t}\n\tdefer func(){\n\t\tif _, already := in.instrumented[pkgpath]; !already {\n\t\t\tin.processed[pkgpath] = struct{}{}\n\t\t}\n\t}()\n\n\t\/\/ Certain packages should always be skipped.\n\tif !instrumentable(pkgpath) {\n\t\tif verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"skipping uninstrumentable package %q\\n\", pkgpath)\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Ignore explicitly excluded packages.\n\tif i := sort.SearchStrings(in.excluded, pkgpath); i < len(in.excluded) {\n\t\tif in.excluded[i] == pkgpath {\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"skipping excluded package %q\\n\", pkgpath)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfset := token.NewFileSet()\n\tbuildpkg, pkg, err := parsePackage(pkgpath, fset)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif buildpkg.Goroot && *testExcludeGorootFlag {\n\t\tif verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"skipping GOROOT package %q\\n\", pkgpath)\n\t\t}\n\t\treturn nil\n\t}\n\n\tin.instrumented[pkgpath] = nil \/\/ created in first instrumented file\n\tif verbose {\n\t\tfmt.Fprintf(os.Stderr, \"instrumenting package %q\\n\", pkgpath)\n\t}\n\n\timports := buildpkg.Imports[:]\n\timports = append(imports, buildpkg.TestImports...)\n\timports = append(imports, buildpkg.XTestImports...)\n\tfor _, subpkgpath := range imports {\n\t\tif _, done := in.instrumented[subpkgpath]; !done {\n\t\t\terr = in.instrumentPackage(subpkgpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Fix imports in test files, but don't instrument them.\n\trewriteFiles := make(map[string]*ast.File)\n\ttestGoFiles := buildpkg.TestGoFiles[:]\n\ttestGoFiles = append(testGoFiles, buildpkg.XTestGoFiles...)\n\tfor _, filename := range testGoFiles {\n\t\tpath := filepath.Join(buildpkg.Dir, filename)\n\t\tmode := parser.DeclarationErrors | parser.ParseComments\n\t\tfile, err := parser.ParseFile(fset, path, nil, mode)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tin.redirectImports(file)\n\t\trewriteFiles[filename] = file\n\t}\n\n\t\/\/ Clone the directory structure, symlinking files (if possible),\n\t\/\/ otherwise copying the files. Instrumented files will replace\n\t\/\/ the symlinks with new files.\n\tcloneDir := filepath.Join(in.gopath, \"src\", instrumentedPathPrefix, pkgpath)\n\terr = symlinkHierarchy(buildpkg.Dir, cloneDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor filename, f := range pkg.Files {\n\t\terr := in.instrumentFile(f, fset, pkgpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trewriteFiles[filename] = f\n\t}\n\tfor filename, f := range rewriteFiles {\n\t\tfilepath := filepath.Join(cloneDir, filepath.Base(filename))\n\t\terr = os.Remove(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfile, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprinter.Fprint(file, fset, f) \/\/ TODO check err?\n\t\terr = file.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc marshalJson(packages []*gocov.Package) ([]byte, error) {\n\treturn json.Marshal(struct{ Packages []*gocov.Package }{packages})\n}\n\nfunc unmarshalJson(data []byte) (packages []*gocov.Package, err error) {\n\tresult := &struct{ Packages []*gocov.Package }{}\n\terr = json.Unmarshal(data, result)\n\tif err == nil {\n\t\tpackages = result.Packages\n\t}\n\treturn\n}\n\nfunc instrumentAndTest() (rc int) {\n\ttestFlags.Parse(os.Args[2:])\n\tpackageName := \".\"\n\tif testFlags.NArg() > 0 {\n\t\tpackageName = testFlags.Arg(0)\n\t}\n\n\ttempDir, err := ioutil.TempDir(\"\", \"gocov\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to create temporary GOPATH: %s\", err)\n\t\treturn 1\n\t}\n\tif *testWorkFlag {\n\t\tfmt.Fprintf(os.Stderr, \"WORK=%s\\n\", tempDir)\n\t} else {\n\t\tdefer func() {\n\t\t\terr := os.RemoveAll(tempDir)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\t\"warning: failed to delete temporary GOPATH (%s)\", tempDir)\n\t\t\t}\n\t\t}()\n\t}\n\n\terr = os.Mkdir(filepath.Join(tempDir, \"src\"), 0700)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\"failed to create temporary src directory: %s\", err)\n\t\treturn 1\n\t}\n\n\t\/\/ Copy gocov into the temporary GOPATH, since otherwise it'll\n\t\/\/ be eclipsed by the instrumented packages root.\n\tif p, err := build.Import(gocovPackagePath, \"\", build.FindOnly); err == nil {\n\t\terr = symlinkHierarchy(p.Dir, filepath.Join(tempDir, \"src\", gocovPackagePath))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to symlink gocov: %s\", err)\n\t\t\treturn 1\n\t\t}\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"failed to locate gocov: %s\", err)\n\t\treturn 1\n\t}\n\n\tvar excluded []string\n\tif len(*testExcludeFlag) > 0 {\n\t\texcluded = strings.Split(*testExcludeFlag, \",\")\n\t\tsort.Strings(excluded)\n\t}\n\n\tin := &instrumenter{\n\t\tgopath: tempDir,\n\t\tinstrumented: make(map[string]*gocov.Package),\n\t\texcluded: excluded,\n\t\tprocessed: make(map[string]struct{})}\n\terr = in.instrumentPackage(packageName)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to instrument package(%s): %s\\n\",\n\t\t\tpackageName, err)\n\t\treturn 1\n\t}\n\n\t\/\/ Run \"go test\".\n\t\/\/ TODO pass through test flags.\n\toutfilePath := filepath.Join(tempDir, \"gocov.out\")\n\tenv := os.Environ()\n\tenv = putenv(env, \"GOCOVOUT\", outfilePath)\n\tif gopath := os.Getenv(\"GOPATH\"); gopath != \"\" {\n\t\tgopath = fmt.Sprintf(\"%s%c%s\", tempDir, os.PathListSeparator, gopath)\n\t\tenv = putenv(env, \"GOPATH\", gopath)\n\t} else {\n\t\tenv = putenv(env, \"GOPATH\", tempDir)\n\t}\n\targs := []string{\"test\"}\n\tif verbose {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args, instrumentedPathPrefix + \"\/\" + packageName)\n\tcmd := exec.Command(\"go\", args...)\n\tcmd.Env = env\n\tcmd.Stdout = os.Stderr\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"go test failed: %s\\n\", err)\n\t\trc = 1\n\t}\n\n\tpackages, err := gocov.ParseTrace(outfilePath)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to parse gocov output: %s\\n\", err)\n\t} else {\n\t\tdata, err := marshalJson(packages)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to format as JSON: %s\\n\", err)\n\t\t} else {\n\t\t\tfmt.Println(string(data))\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\tflag.Usage = usage\n\tflag.Parse()\n\tcommand := \"\"\n\tif flag.NArg() > 0 {\n\t\tcommand = flag.Arg(0)\n\t\tswitch command {\n\t\tcase \"annotate\":\n\t\t\tos.Exit(annotateSource())\n\t\tcase \"report\":\n\t\t\tos.Exit(reportCoverage())\n\t\tcase \"test\":\n\t\t\tos.Exit(instrumentAndTest())\n\t\t\/\/case \"run\"\n\t\tdefault:\n\t\t\tfmt.Fprintf(os.Stderr, \"Unknown command: %#q\\n\\n\", command)\n\t\t\tusage()\n\t\t}\n\t} else {\n\t\tusage()\n\t}\n}\nFix gocov test help usage, run go fmt.\/\/ Copyright (c) 2012 The Gocov Authors.\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/axw\/gocov\"\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/printer\"\n\t\"go\/token\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst gocovPackagePath = \"github.com\/axw\/gocov\"\nconst instrumentedPathPrefix = gocovPackagePath + \"\/instrumented\"\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage:\\n\\n\\tgocov command [arguments]\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"The commands are:\\n\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\tannotate\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\ttest\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\treport\\n\")\n\tfmt.Fprintf(os.Stderr, \"\\n\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nvar (\n\ttestFlags = flag.NewFlagSet(\"test\", flag.ExitOnError)\n\ttestExcludeFlag = testFlags.String(\n\t\t\"exclude\", \"\",\n\t\t\"packages to exclude, separated by comma\")\n\ttestExcludeGorootFlag = testFlags.Bool(\n\t\t\"exclude-goroot\", true,\n\t\t\"exclude packages in GOROOT from instrumentation\")\n\ttestWorkFlag = testFlags.Bool(\n\t\t\"work\", false,\n\t\t\"print the name of the temporary work directory \"+\n\t\t\t\"and do not delete it when exiting\")\n\tverbose bool\n)\n\nfunc init() {\n\ttestFlags.BoolVar(&verbose, \"v\", false, \"verbose\")\n}\n\ntype instrumenter struct {\n\tgopath string \/\/ temporary gopath\n\texcluded []string\n\tinstrumented map[string]*gocov.Package\n\tprocessed map[string]struct{}\n}\n\nfunc putenv(env []string, key, value string) []string {\n\tfor i, s := range env {\n\t\tif strings.HasPrefix(s, key+\"=\") {\n\t\t\tenv[i] = key + \"=\" + value\n\t\t\treturn env\n\t\t}\n\t}\n\treturn append(env, key+\"=\"+value)\n}\n\nfunc parsePackage(path string, fset *token.FileSet) (*build.Package, *ast.Package, error) {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tp, err := build.Import(path, cwd, 0)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tgoFiles := append(p.GoFiles[:], p.CgoFiles...)\n\tsort.Strings(goFiles)\n\tfilter := func(f os.FileInfo) bool {\n\t\tname := f.Name()\n\t\ti := sort.SearchStrings(goFiles, name)\n\t\treturn i < len(goFiles) && goFiles[i] == name\n\t}\n\tmode := parser.DeclarationErrors | parser.ParseComments\n\tpkgs, err := parser.ParseDir(fset, p.Dir, filter, mode)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn p, pkgs[p.Name], err\n}\n\nfunc symlinkHierarchy(src, dst string) error {\n\tfn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trel, err := filepath.Rel(src, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttarget := filepath.Join(dst, rel)\n\t\tif _, err = os.Stat(target); err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\treturn os.MkdirAll(target, 0700)\n\t\t} else {\n\t\t\terr = os.Symlink(path, target)\n\t\t\tif err != nil {\n\t\t\t\tsrcfile, err := os.Open(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer srcfile.Close()\n\t\t\t\tdstfile, err := os.OpenFile(\n\t\t\t\t\ttarget, os.O_RDWR|os.O_CREATE, 0600)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer dstfile.Close()\n\t\t\t\t_, err = io.Copy(dstfile, srcfile)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\treturn filepath.Walk(src, fn)\n}\n\n\/\/ FIXME(axw)\n\/\/\n\/\/ As we change the name of the package to avoid being obscured by GOROOT, we\n\/\/ can't instrument packages that have Go functions implemented in C, such as\n\/\/ those below.\n\/\/\n\/\/ It may be preferable to have a faked GOROOT, but we'll need to come up with\n\/\/ a way to avoid the import loop introduced by importing gocov into the\n\/\/ instrumented pakcage.\n\/\/\nfunc instrumentable(path string) bool {\n\tswitch path {\n\tcase \"C\":\n\t\tfallthrough\n\tcase \"reflect\":\n\t\tfallthrough\n\tcase \"runtime\":\n\t\tfallthrough\n\tcase \"os\":\n\t\tfallthrough\n\tcase \"sync\":\n\t\tfallthrough\n\tcase \"syscall\":\n\t\tfallthrough\n\tcase \"time\":\n\t\tfallthrough\n\tcase \"testing\":\n\t\tfallthrough\n\tcase \"unsafe\":\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (in *instrumenter) instrumentPackage(pkgpath string) error {\n\tif _, already := in.processed[pkgpath]; already {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\tif _, already := in.instrumented[pkgpath]; !already {\n\t\t\tin.processed[pkgpath] = struct{}{}\n\t\t}\n\t}()\n\n\t\/\/ Certain packages should always be skipped.\n\tif !instrumentable(pkgpath) {\n\t\tif verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"skipping uninstrumentable package %q\\n\", pkgpath)\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ Ignore explicitly excluded packages.\n\tif i := sort.SearchStrings(in.excluded, pkgpath); i < len(in.excluded) {\n\t\tif in.excluded[i] == pkgpath {\n\t\t\tif verbose {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"skipping excluded package %q\\n\", pkgpath)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfset := token.NewFileSet()\n\tbuildpkg, pkg, err := parsePackage(pkgpath, fset)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif buildpkg.Goroot && *testExcludeGorootFlag {\n\t\tif verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"skipping GOROOT package %q\\n\", pkgpath)\n\t\t}\n\t\treturn nil\n\t}\n\n\tin.instrumented[pkgpath] = nil \/\/ created in first instrumented file\n\tif verbose {\n\t\tfmt.Fprintf(os.Stderr, \"instrumenting package %q\\n\", pkgpath)\n\t}\n\n\timports := buildpkg.Imports[:]\n\timports = append(imports, buildpkg.TestImports...)\n\timports = append(imports, buildpkg.XTestImports...)\n\tfor _, subpkgpath := range imports {\n\t\tif _, done := in.instrumented[subpkgpath]; !done {\n\t\t\terr = in.instrumentPackage(subpkgpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Fix imports in test files, but don't instrument them.\n\trewriteFiles := make(map[string]*ast.File)\n\ttestGoFiles := buildpkg.TestGoFiles[:]\n\ttestGoFiles = append(testGoFiles, buildpkg.XTestGoFiles...)\n\tfor _, filename := range testGoFiles {\n\t\tpath := filepath.Join(buildpkg.Dir, filename)\n\t\tmode := parser.DeclarationErrors | parser.ParseComments\n\t\tfile, err := parser.ParseFile(fset, path, nil, mode)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tin.redirectImports(file)\n\t\trewriteFiles[filename] = file\n\t}\n\n\t\/\/ Clone the directory structure, symlinking files (if possible),\n\t\/\/ otherwise copying the files. Instrumented files will replace\n\t\/\/ the symlinks with new files.\n\tcloneDir := filepath.Join(in.gopath, \"src\", instrumentedPathPrefix, pkgpath)\n\terr = symlinkHierarchy(buildpkg.Dir, cloneDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor filename, f := range pkg.Files {\n\t\terr := in.instrumentFile(f, fset, pkgpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trewriteFiles[filename] = f\n\t}\n\tfor filename, f := range rewriteFiles {\n\t\tfilepath := filepath.Join(cloneDir, filepath.Base(filename))\n\t\terr = os.Remove(filepath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfile, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprinter.Fprint(file, fset, f) \/\/ TODO check err?\n\t\terr = file.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc marshalJson(packages []*gocov.Package) ([]byte, error) {\n\treturn json.Marshal(struct{ Packages []*gocov.Package }{packages})\n}\n\nfunc unmarshalJson(data []byte) (packages []*gocov.Package, err error) {\n\tresult := &struct{ Packages []*gocov.Package }{}\n\terr = json.Unmarshal(data, result)\n\tif err == nil {\n\t\tpackages = result.Packages\n\t}\n\treturn\n}\n\nfunc instrumentAndTest() (rc int) {\n\ttestFlags.Parse(os.Args[2:])\n\tpackageName := \".\"\n\tif testFlags.NArg() > 0 {\n\t\tpackageName = testFlags.Arg(0)\n\t}\n\n\ttempDir, err := ioutil.TempDir(\"\", \"gocov\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to create temporary GOPATH: %s\", err)\n\t\treturn 1\n\t}\n\tif *testWorkFlag {\n\t\tfmt.Fprintf(os.Stderr, \"WORK=%s\\n\", tempDir)\n\t} else {\n\t\tdefer func() {\n\t\t\terr := os.RemoveAll(tempDir)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\t\t\"warning: failed to delete temporary GOPATH (%s)\", tempDir)\n\t\t\t}\n\t\t}()\n\t}\n\n\terr = os.Mkdir(filepath.Join(tempDir, \"src\"), 0700)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\"failed to create temporary src directory: %s\", err)\n\t\treturn 1\n\t}\n\n\t\/\/ Copy gocov into the temporary GOPATH, since otherwise it'll\n\t\/\/ be eclipsed by the instrumented packages root.\n\tif p, err := build.Import(gocovPackagePath, \"\", build.FindOnly); err == nil {\n\t\terr = symlinkHierarchy(p.Dir, filepath.Join(tempDir, \"src\", gocovPackagePath))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to symlink gocov: %s\", err)\n\t\t\treturn 1\n\t\t}\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"failed to locate gocov: %s\", err)\n\t\treturn 1\n\t}\n\n\tvar excluded []string\n\tif len(*testExcludeFlag) > 0 {\n\t\texcluded = strings.Split(*testExcludeFlag, \",\")\n\t\tsort.Strings(excluded)\n\t}\n\n\tin := &instrumenter{\n\t\tgopath: tempDir,\n\t\tinstrumented: make(map[string]*gocov.Package),\n\t\texcluded: excluded,\n\t\tprocessed: make(map[string]struct{})}\n\terr = in.instrumentPackage(packageName)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to instrument package(%s): %s\\n\",\n\t\t\tpackageName, err)\n\t\treturn 1\n\t}\n\n\t\/\/ Run \"go test\".\n\t\/\/ TODO pass through test flags.\n\toutfilePath := filepath.Join(tempDir, \"gocov.out\")\n\tenv := os.Environ()\n\tenv = putenv(env, \"GOCOVOUT\", outfilePath)\n\tif gopath := os.Getenv(\"GOPATH\"); gopath != \"\" {\n\t\tgopath = fmt.Sprintf(\"%s%c%s\", tempDir, os.PathListSeparator, gopath)\n\t\tenv = putenv(env, \"GOPATH\", gopath)\n\t} else {\n\t\tenv = putenv(env, \"GOPATH\", tempDir)\n\t}\n\targs := []string{\"test\"}\n\tif verbose {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args, instrumentedPathPrefix+\"\/\"+packageName)\n\tcmd := exec.Command(\"go\", args...)\n\tcmd.Env = env\n\tcmd.Stdout = os.Stderr\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"go test failed: %s\\n\", err)\n\t\trc = 1\n\t}\n\n\tpackages, err := gocov.ParseTrace(outfilePath)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to parse gocov output: %s\\n\", err)\n\t} else {\n\t\tdata, err := marshalJson(packages)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to format as JSON: %s\\n\", err)\n\t\t} else {\n\t\t\tfmt.Println(string(data))\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\tflag.Usage = usage\n\tflag.Parse()\n\tcommand := \"\"\n\tif flag.NArg() > 0 {\n\t\tcommand = flag.Arg(0)\n\t\tswitch command {\n\t\tcase \"annotate\":\n\t\t\tos.Exit(annotateSource())\n\t\tcase \"report\":\n\t\t\tos.Exit(reportCoverage())\n\t\tcase \"test\":\n\t\t\tos.Exit(instrumentAndTest())\n\t\t\/\/case \"run\"\n\t\tdefault:\n\t\t\tfmt.Fprintf(os.Stderr, \"Unknown command: %#q\\n\\n\", command)\n\t\t\tusage()\n\t\t}\n\t} else {\n\t\tusage()\n\t}\n}\n<|endoftext|>"} {"text":"package gosideways\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Node struct {\n\tAddr string\n\tPort int\n\tData map[string]Data\n\tSiblings map[string]*Node\n\n\tsave chan Data\n\trepl chan Data\n}\n\ntype Data struct {\n\tKey string\n\tText string\n\tDate time.Time\n\tExpires time.Time\n}\n\nfunc (n *Node) AddSibling(addr string, port int) error {\n\tkey := addr + \":\" + fmt.Sprint(port)\n\tif _, exists := n.Siblings[key]; exists {\n\t\treturn errors.New(\"Sibling \" + key + \" already registered\")\n\t}\n\n\tn.Siblings[key] = newNode(addr, port)\n\n\treturn nil\n}\n\nfunc Listen(port int) *Node {\n\tnode := newNode(\"127.0.0.1\", port)\n\tgo node.clean()\n\tgo node.Run()\n\treturn node\n}\n\nfunc (n *Node) Run() {\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", n.Port))\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tgo n.handleConnection(conn)\n\t}\n}\n\nfunc (n *Node) Get(key string) *Data {\n\treturn n.get(key)\n}\n\nfunc (n *Node) Set(key string, data string, valid time.Duration) {\n\td := n.newData(key, data, valid)\n\n\tn.save <- d\n\tn.repl <- d\n}\n\nfunc (n *Node) newData(key string, data string, valid time.Duration) Data {\n\treturn Data{\n\t\tKey: key,\n\t\tText: data,\n\t\tDate: time.Now(),\n\t\tExpires: time.Now().Add(valid),\n\t}\n}\n\nfunc (n *Node) replicate(d Data) {\n\tfor _, s := range n.Siblings {\n\t\tif s.Addr == n.Addr && s.Port == n.Port {\n\t\t\tcontinue\n\t\t}\n\n\t\taddr := fmt.Sprintf(\"%s:%d\", s.Addr, s.Port)\n\t\tconn, err := net.Dial(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\texp := int(d.Expires.Sub(time.Now()).Seconds() + .5)\n\n\t\tfmt.Fprintf(conn, \"REPLICATE %s %d %s\", d.Key, exp, d.Text)\n\t\tconn.Close()\n\t}\n}\n\nfunc (n *Node) get(key string) *Data {\n\tvar data *Data\n\n\tif aux, ok := n.Data[key]; ok {\n\t\tif aux.Expires.Before(time.Now()) {\n\t\t\tn.del(key)\n\t\t} else {\n\t\t\tdata = &aux\n\t\t}\n\t}\n\n\treturn data\n}\n\nfunc (n *Node) del(key string) {\n\tif _, ok := n.Data[key]; ok {\n\t\tdelete(n.Data, key)\n\t}\n}\n\nfunc (n *Node) clean() {\n\tfor {\n\t\tnow := time.Now()\n\t\tfor key, data := range n.Data {\n\t\t\tif data.Expires.Before(now) {\n\t\t\t\tn.del(key)\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc newNode(addr string, port int) *Node {\n\tnode := &Node{\n\t\tAddr: addr,\n\t\tPort: port,\n\t\tData: make(map[string]Data),\n\t\tSiblings: make(map[string]*Node),\n\n\t\tsave: make(chan Data, 1024),\n\t\trepl: make(chan Data, 1024),\n\t}\n\n\tgo func() {\n\t\tfor d := range node.save {\n\t\t\tnode.Data[d.Key] = d\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor d := range node.repl {\n\t\t\tnode.replicate(d)\n\t\t}\n\t}()\n\n\treturn node\n}\n\nfunc (n *Node) handleConnection(c net.Conn) {\n\tdefer c.Close()\n\n\tscanner := bufio.NewScanner(c)\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tcommand := strings.SplitN(line, \" \", 3)\n\t\tif len(command) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcommand[0] = strings.ToUpper(command[0])\n\t\tfor i := 1; i < len(command); i++ {\n\t\t\tcommand[i] = strings.TrimSpace(command[i])\n\t\t}\n\n\t\tswitch command[0] {\n\t\tcase \"GET\":\n\t\t\tdata := n.get(command[1])\n\t\t\tif data != nil {\n\t\t\t\tfmt.Fprintln(c, data.Text)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"SET\", \"REPLICATE\":\n\t\t\tif len(command) < 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\taux := strings.SplitN(command[2], \" \", 2)\n\t\t\tif len(aux) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tseconds, _ := strconv.Atoi(aux[0])\n\t\t\tif seconds <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\td := n.newData(command[1], aux[1], time.Duration(seconds)*time.Second)\n\n\t\t\tn.save <- d\n\n\t\t\tif command[0] == \"SET\" {\n\t\t\t\tn.repl <- d\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"DELETE\":\n\t\t\tn.del(command[1])\n\t\t\tbreak\n\t\t}\n\t}\n}\nProviding length on SET and REPLICATE commands for multiline datapackage gosideways\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Node struct {\n\tAddr string\n\tPort int\n\tData map[string]Data\n\tSiblings map[string]*Node\n\n\tsave chan Data\n\trepl chan Data\n}\n\ntype Data struct {\n\tKey string\n\tText string\n\tDate time.Time\n\tExpires time.Time\n}\n\nfunc (n *Node) AddSibling(addr string, port int) error {\n\tkey := addr + \":\" + fmt.Sprint(port)\n\tif _, exists := n.Siblings[key]; exists {\n\t\treturn errors.New(\"Sibling \" + key + \" already registered\")\n\t}\n\n\tn.Siblings[key] = newNode(addr, port)\n\n\treturn nil\n}\n\nfunc Listen(port int) *Node {\n\tnode := newNode(\"127.0.0.1\", port)\n\tgo node.clean()\n\tgo node.Run()\n\treturn node\n}\n\nfunc (n *Node) Run() {\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", n.Port))\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn\n\t}\n\tdefer listener.Close()\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\tgo n.handleConnection(conn)\n\t}\n}\n\nfunc (n *Node) Get(key string) *Data {\n\treturn n.get(key)\n}\n\nfunc (n *Node) Set(key string, data string, valid time.Duration) {\n\td := n.newData(key, data, valid)\n\n\tn.save <- d\n\tn.repl <- d\n}\n\nfunc (n *Node) newData(key string, data string, valid time.Duration) Data {\n\treturn Data{\n\t\tKey: key,\n\t\tText: data,\n\t\tDate: time.Now(),\n\t\tExpires: time.Now().Add(valid),\n\t}\n}\n\nfunc (n *Node) replicate(d Data) {\n\tfor _, s := range n.Siblings {\n\t\tif s.Addr == n.Addr && s.Port == n.Port {\n\t\t\tcontinue\n\t\t}\n\n\t\taddr := fmt.Sprintf(\"%s:%d\", s.Addr, s.Port)\n\t\tconn, err := net.Dial(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tcontinue\n\t\t}\n\n\t\texp := int(d.Expires.Sub(time.Now()).Seconds() + .5)\n\n\t\tfmt.Fprintf(conn, \"REPLICATE %s %d %d %s\", d.Key, exp, len(d.Text), d.Text)\n\t\tconn.Close()\n\t}\n}\n\nfunc (n *Node) get(key string) *Data {\n\tvar data *Data\n\n\tif aux, ok := n.Data[key]; ok {\n\t\tif aux.Expires.Before(time.Now()) {\n\t\t\tn.del(key)\n\t\t} else {\n\t\t\tdata = &aux\n\t\t}\n\t}\n\n\treturn data\n}\n\nfunc (n *Node) del(key string) {\n\tif _, ok := n.Data[key]; ok {\n\t\tdelete(n.Data, key)\n\t}\n}\n\nfunc (n *Node) clean() {\n\tfor {\n\t\tnow := time.Now()\n\t\tfor key, data := range n.Data {\n\t\t\tif data.Expires.Before(now) {\n\t\t\t\tn.del(key)\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc newNode(addr string, port int) *Node {\n\tnode := &Node{\n\t\tAddr: addr,\n\t\tPort: port,\n\t\tData: make(map[string]Data),\n\t\tSiblings: make(map[string]*Node),\n\n\t\tsave: make(chan Data, 1024),\n\t\trepl: make(chan Data, 1024),\n\t}\n\n\tgo func() {\n\t\tfor d := range node.save {\n\t\t\tnode.Data[d.Key] = d\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor d := range node.repl {\n\t\t\tnode.replicate(d)\n\t\t}\n\t}()\n\n\treturn node\n}\n\nfunc (n *Node) handleConnection(c net.Conn) {\n\tdefer c.Close()\n\n\tscanner := bufio.NewScanner(c)\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tcommand := strings.SplitN(line, \" \", 3)\n\t\tif len(command) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcommand[0] = strings.ToUpper(command[0])\n\t\tfor i := 1; i < len(command); i++ {\n\t\t\tcommand[i] = strings.TrimSpace(command[i])\n\t\t}\n\n\t\tswitch command[0] {\n\t\tcase \"GET\":\n\t\t\tdata := n.get(command[1])\n\t\t\tif data != nil {\n\t\t\t\tfmt.Fprintln(c, data.Text)\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"SET\", \"REPLICATE\":\n\t\t\tif len(command) < 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\taux := strings.SplitN(command[2], \" \", 3)\n\t\t\tif len(aux) < 3 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tseconds, _ := strconv.Atoi(aux[0])\n\t\t\tif seconds <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlength, _ := strconv.Atoi(aux[1])\n\t\t\tif length <= 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\td := n.newData(command[1], aux[2], time.Duration(seconds)*time.Second)\n\n\t\t\tfor len(d.Text) < length {\n\t\t\t\tscanner.Scan()\n\t\t\t\td.Text += \"\\n\" + scanner.Text()\n\t\t\t}\n\n\t\t\tn.save <- d\n\n\t\t\tif command[0] == \"SET\" {\n\t\t\t\tn.repl <- d\n\t\t\t}\n\t\t\tbreak\n\t\tcase \"DELETE\":\n\t\t\tn.del(command[1])\n\t\t\tbreak\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017 AlexRuzin (stan.ruzin@gmail.com)\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n \npackage govfs\n\nimport (\n \"testing\"\n \"time\"\n \"os\"\n \"io\"\n _\"bytes\"\n \"bytes\"\n \"runtime\"\n)\n\nconst FS_DATABASE_FILE string = \"test_db\"\n\nfunc TestFSWriter(t *testing.T) {\n \/*\n * This test will generate the raw fs stream file, along with some contents\n * that will be later loaded by the TestFSReader() method\n *\/\n out(\"[+] Running Standard I\/O Sanity Test...\")\n\n \/* Remove the test database if it exists *\/\n var filename = gen_raw_filename(FS_DATABASE_FILE)\n if _, err := os.Stat(filename); os.IsExist(err) {\n os.Remove(filename)\n }\n\n var header = CreateDatabase(filename, 0)\n if header == nil {\n drive_fail(\"TEST1: Failed to obtain header\", t)\n }\n out(\"[+] Test 1 PASS\")\n \n \/\/ The root file \"\/\" must at least exist\n if file, err := header.Create(\"\/\"); file != nil && err == nil {\n drive_fail(\"TEST2: Failed to return root handle\", t)\n }\n out(\"[+] Test 2 PASS\")\n \n \/*\n * Try to delete the root file \"\/\"\n *\/\n if header.Delete(\"\/\") == nil {\n drive_fail(\"TEST3: Cannot delete root -- critical\", t)\n }\n out(\"[+] Test 3 PASS\")\n\n \/*\n * Attempt to write to a nonexistant file\n *\/\n var data = []byte{ 1, 2 }\n if header.Write(\"\/folder5\/folder5\/file5\", data) == nil {\n drive_fail(\"TEST4: Cannot write to a nonexistant file\", t)\n }\n out(\"[+] Test 4 PASS\")\n\n \/*\n * Create empty file file9\n *\/\n if file, err := header.Create(\"\/folder5\/folder4\/folder2\/file9\"); file == nil || err != nil {\n drive_fail(\"TEST4.1: file9 cannot be created\", t)\n }\n out(\"[+] Test 4.1 PASS\")\n\n \/*\n * Attempt to create a new file0\n *\/\n if file, err := header.Create(\"\/folder0\/folder0\/file0\"); file == nil || err != nil {\n drive_fail(\"TEST5.0: file0 cannot be created\", t)\n }\n out(\"[+] Test 5.0 PASS\")\n\n \/*\n * Attempt to create a new file0, this will fail since it should already exist\n *\/\n if file, err := header.Create(\"\/folder0\/folder0\/file0\"); file != nil && err == nil {\n drive_fail(\"TEST5.1: file0 cannot be created twice\", t)\n }\n out(\"[+] Test 5.1 PASS\")\n\n \n \/*\n * Write some data into file0\n *\/\n data = []byte{ 1, 2, 3, 4 }\n if header.Write(\"\/folder0\/folder0\/file0\", data) != nil {\n drive_fail(\"TEST6: Failed to write data in file0\", t)\n }\n out(\"[+] Test 6 PASS\")\n\n \/*\n * Check that the size of file0 is 4\n *\/\n if k, _ := header.get_file_size(\"\/folder0\/folder0\/file0\"); k != uint(len(data)) {\n drive_fail(\"TEST6.1: The size of data does not match\", t)\n }\n out(\"[+] Test 6.1 PASS\")\n \n \/*\n * Attempt to create a new file3\n *\/\n if file, err := header.Create(\"\/folder1\/folder0\/file3\"); file == nil || err != nil {\n drive_fail(\"TEST7: file3 cannot be created\", t)\n }\n out(\"[+] Test 7 PASS\")\n \n \/*\n * Write some data into file3\n *\/\n var data2 = []byte{ 1, 2, 3, 4, 5, 6, 7 }\n if header.Write(\"\/folder1\/folder0\/file3\", data2) != nil {\n drive_fail(\"TEST8: Failed to write data in file3\", t)\n }\n out(\"[+] Test 8 PASS\")\n\n \/*\n * Write some data into file3\n *\/\n if header.Write(\"\/folder1\/folder0\/file3\", data2) != nil {\n drive_fail(\"TEST8.1: Failed to write data in file3\", t)\n }\n out(\"[+] Test 8.1 PASS\")\n \n \/*\n * Read the written data from file0 and compare\n *\/\n output_data, _ := header.Read(\"\/folder0\/folder0\/file0\")\n if output_data == nil || len(output_data) != len(data) || header.t_size - 7 \/* len(file3) *\/ != uint(len(data)) {\n drive_fail(\"TEST9: Failed to read data from file0\", t)\n }\n out(\"[+] Test 9 PASS\")\n \n \/*\n * Read the written data from file3 and compare\n *\/\n output_data, _ = header.Read(\"\/folder1\/folder0\/file3\")\n if output_data == nil || len(output_data) != len(data2) || header.t_size - 4 \/* len(file0) *\/ != uint(len(data2)) {\n drive_fail(\"TEST10: Failed to read data from file3\", t)\n }\n out(\"[+] Test 10 PASS\")\n \n \/*\n * Write other data to file0\n *\/\n data = []byte{ 1, 2, 3 }\n if header.Write(\"\/folder0\/folder0\/file0\", data) != nil {\n drive_fail(\"TEST11: Failed to write data in file1\", t)\n } \n out(\"[+] Test 11 PASS\")\n \n \/*\n * Read the new data from file0\n *\/\n output_data, _ = header.Read(\"\/folder0\/folder0\/file0\")\n if output_data == nil || len(output_data) != len(data) {\n drive_fail(\"TEST12: Failed to read data from file1\", t)\n }\n out(\"[+] Test 12 PASS\")\n\n \/*\n * Attempt to create a new file5. This will be a blank file\n *\/\n if file, err := header.Create(\"\/folder2\/file7\"); file == nil || err != nil {\n drive_fail(\"TEST13: file3 cannot be created\", t)\n }\n out(\"[+] Test 13 PASS\")\n \n \/*\n * Delete file0 -- complete this\n *\/\n \/\/ FIXME\/ADDME\n\n \/*\n * Create just a folder\n *\/\n if file, err := header.Create(\"\/folder2\/file5\/\"); file == nil || err != nil {\n drive_fail(\"TEST15: folder file5 cannot be created\", t)\n }\n out(\"[+] Test 15 PASS\")\n\n \/*\n * Tests the Reader interface\n *\/\n reader, err := header.NewReader(\"\/folder0\/folder0\/file0\")\n if err != nil {\n drive_fail(\"TEST15.1: Failed to create Reader\", t)\n }\n\n file0data := make([]byte, 3)\n data_read, err := reader.Read(file0data)\n if data_read != len(data) || err != io.EOF || bytes.Compare(file0data, data) != 0 {\n drive_fail(\"TEST15.2: Failed to read from NewReader\", t)\n }\n\n \/* Test the reader interface again *\/\n file0data = make([]byte, 1)\n data_read, err = reader.Read(file0data)\n if data_read != 1 || err != nil || file0data[0] != 1 {\n drive_fail(\"TEST15.3: Invalid Reader interface behaviour\", t)\n }\n out(\"[+] Test 15.1, 15.2, 15.3 PASS -- Reader interface\")\n\n \/*\n * Tests the Writer interface\n *\/\n file0data = []byte{1, 2, 3, 4, 5, 6, 7, 8}\n writer, err := header.NewWriter(\"\/folder0\/folder0\/file0\")\n if writer == nil || err != nil {\n drive_fail(\"TEST15.4: Invalid Writer object\", t)\n }\n\n written, err := writer.Write(file0data)\n if written != len(file0data) || err != io.EOF {\n drive_fail(\"TEST15.4: Invalid Writer response\", t)\n }\n\n file0data = make([]byte, 8)\n data_read, err = reader.Read(file0data)\n if data_read != 8 || err != io.EOF || file0data[0] != 1 || file0data[1] != 2 {\n drive_fail(\"TEST15.5: Invalid Reader data\",t )\n }\n out(\"[+] Test 15.4, 15.5 PASS -- Writer interface\")\n\n\n \/*\n * Print out files\n *\/\n file_list := header.get_file_list()\n for _, e := range file_list {\n out(e)\n }\n\n \/*\n * Unmount\/commit database to file\n *\/\n if err := header.unmount_db(); err != nil {\n drive_fail(\"TEST16: Failed to commit database\", t)\n }\n out(\"[+] Test 16 PASS. Raw FS stream written to: \" + header.filename)\n\n time.Sleep(10000)\n}\n\nfunc TestFSReader(t *testing.T) {\n \/*\n * Read in FS_DATABASE_FILE and do basic tests\n *\/\n var filename = gen_raw_filename(FS_DATABASE_FILE)\n out(\"[+] Loading Raw FS stream file: \" + filename)\n\n \/* Remove the test database if it exists *\/\n if _, err := os.Stat(filename); os.IsNotExist(err) {\n drive_fail(\"error: Standard raw fs stream \" + filename + \" does not exist\", t)\n }\n\n var header = CreateDatabase(filename, 0)\n if header == nil {\n drive_fail(\"TEST1: Failed to obtain header\", t)\n }\n out(\"[+] Test 1 PASS (Loaded FS stream)\")\n}\n\nfunc gen_raw_filename(suffix string) string {\n if runtime.GOOS == \"windows\" {\n return os.Getenv(\"TEMP\") + \"\\\\\" + suffix + \".db\"\n }\n\n if runtime.GOOS == \"linux\" {\n return suffix + \".db\"\n }\n\n return suffix + \".db\"\n}\n\nfunc drive_fail(output string, t *testing.T) {\n t.Errorf(output)\n t.FailNow()\n}\nImplemented the StartIOController() method\/*\n * Copyright (c) 2017 AlexRuzin (stan.ruzin@gmail.com)\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n \npackage govfs\n\nimport (\n \"testing\"\n \"time\"\n \"os\"\n \"io\"\n _\"bytes\"\n \"bytes\"\n \"runtime\"\n)\n\nconst FS_DATABASE_FILE string = \"test_db\"\n\nfunc TestFSWriter(t *testing.T) {\n \/*\n * This test will generate the raw fs stream file, along with some contents\n * that will be later loaded by the TestFSReader() method\n *\/\n out(\"[+] Running Standard I\/O Sanity Test...\")\n\n \/* Remove the test database if it exists *\/\n var filename = gen_raw_filename(FS_DATABASE_FILE)\n if _, err := os.Stat(filename); os.IsExist(err) {\n os.Remove(filename)\n }\n\n var header = CreateDatabase(filename, 0)\n if header == nil {\n drive_fail(\"TEST1: Failed to obtain header\", t)\n }\n if err := header.StartIOController(); err != nil {\n drive_fail(\"TEST1.1: Failed to start IOController\", t)\n }\n out(\"[+] Test 1 PASS\")\n \n \/\/ The root file \"\/\" must at least exist\n if file, err := header.Create(\"\/\"); file != nil && err == nil {\n drive_fail(\"TEST2: Failed to return root handle\", t)\n }\n out(\"[+] Test 2 PASS\")\n \n \/*\n * Try to delete the root file \"\/\"\n *\/\n if header.Delete(\"\/\") == nil {\n drive_fail(\"TEST3: Cannot delete root -- critical\", t)\n }\n out(\"[+] Test 3 PASS\")\n\n \/*\n * Attempt to write to a nonexistant file\n *\/\n var data = []byte{ 1, 2 }\n if header.Write(\"\/folder5\/folder5\/file5\", data) == nil {\n drive_fail(\"TEST4: Cannot write to a nonexistant file\", t)\n }\n out(\"[+] Test 4 PASS\")\n\n \/*\n * Create empty file file9\n *\/\n if file, err := header.Create(\"\/folder5\/folder4\/folder2\/file9\"); file == nil || err != nil {\n drive_fail(\"TEST4.1: file9 cannot be created\", t)\n }\n out(\"[+] Test 4.1 PASS\")\n\n \/*\n * Attempt to create a new file0\n *\/\n if file, err := header.Create(\"\/folder0\/folder0\/file0\"); file == nil || err != nil {\n drive_fail(\"TEST5.0: file0 cannot be created\", t)\n }\n out(\"[+] Test 5.0 PASS\")\n\n \/*\n * Attempt to create a new file0, this will fail since it should already exist\n *\/\n if file, err := header.Create(\"\/folder0\/folder0\/file0\"); file != nil && err == nil {\n drive_fail(\"TEST5.1: file0 cannot be created twice\", t)\n }\n out(\"[+] Test 5.1 PASS\")\n\n \n \/*\n * Write some data into file0\n *\/\n data = []byte{ 1, 2, 3, 4 }\n if header.Write(\"\/folder0\/folder0\/file0\", data) != nil {\n drive_fail(\"TEST6: Failed to write data in file0\", t)\n }\n out(\"[+] Test 6 PASS\")\n\n \/*\n * Check that the size of file0 is 4\n *\/\n if k, _ := header.get_file_size(\"\/folder0\/folder0\/file0\"); k != uint(len(data)) {\n drive_fail(\"TEST6.1: The size of data does not match\", t)\n }\n out(\"[+] Test 6.1 PASS\")\n \n \/*\n * Attempt to create a new file3\n *\/\n if file, err := header.Create(\"\/folder1\/folder0\/file3\"); file == nil || err != nil {\n drive_fail(\"TEST7: file3 cannot be created\", t)\n }\n out(\"[+] Test 7 PASS\")\n \n \/*\n * Write some data into file3\n *\/\n var data2 = []byte{ 1, 2, 3, 4, 5, 6, 7 }\n if header.Write(\"\/folder1\/folder0\/file3\", data2) != nil {\n drive_fail(\"TEST8: Failed to write data in file3\", t)\n }\n out(\"[+] Test 8 PASS\")\n\n \/*\n * Write some data into file3\n *\/\n if header.Write(\"\/folder1\/folder0\/file3\", data2) != nil {\n drive_fail(\"TEST8.1: Failed to write data in file3\", t)\n }\n out(\"[+] Test 8.1 PASS\")\n \n \/*\n * Read the written data from file0 and compare\n *\/\n output_data, _ := header.Read(\"\/folder0\/folder0\/file0\")\n if output_data == nil || len(output_data) != len(data) || header.t_size - 7 \/* len(file3) *\/ != uint(len(data)) {\n drive_fail(\"TEST9: Failed to read data from file0\", t)\n }\n out(\"[+] Test 9 PASS\")\n \n \/*\n * Read the written data from file3 and compare\n *\/\n output_data, _ = header.Read(\"\/folder1\/folder0\/file3\")\n if output_data == nil || len(output_data) != len(data2) || header.t_size - 4 \/* len(file0) *\/ != uint(len(data2)) {\n drive_fail(\"TEST10: Failed to read data from file3\", t)\n }\n out(\"[+] Test 10 PASS\")\n \n \/*\n * Write other data to file0\n *\/\n data = []byte{ 1, 2, 3 }\n if header.Write(\"\/folder0\/folder0\/file0\", data) != nil {\n drive_fail(\"TEST11: Failed to write data in file1\", t)\n } \n out(\"[+] Test 11 PASS\")\n \n \/*\n * Read the new data from file0\n *\/\n output_data, _ = header.Read(\"\/folder0\/folder0\/file0\")\n if output_data == nil || len(output_data) != len(data) {\n drive_fail(\"TEST12: Failed to read data from file1\", t)\n }\n out(\"[+] Test 12 PASS\")\n\n \/*\n * Attempt to create a new file5. This will be a blank file\n *\/\n if file, err := header.Create(\"\/folder2\/file7\"); file == nil || err != nil {\n drive_fail(\"TEST13: file3 cannot be created\", t)\n }\n out(\"[+] Test 13 PASS\")\n \n \/*\n * Delete file0 -- complete this\n *\/\n \/\/ FIXME\/ADDME\n\n \/*\n * Create just a folder\n *\/\n if file, err := header.Create(\"\/folder2\/file5\/\"); file == nil || err != nil {\n drive_fail(\"TEST15: folder file5 cannot be created\", t)\n }\n out(\"[+] Test 15 PASS\")\n\n \/*\n * Tests the Reader interface\n *\/\n reader, err := header.NewReader(\"\/folder0\/folder0\/file0\")\n if err != nil {\n drive_fail(\"TEST15.1: Failed to create Reader\", t)\n }\n\n file0data := make([]byte, 3)\n data_read, err := reader.Read(file0data)\n if data_read != len(data) || err != io.EOF || bytes.Compare(file0data, data) != 0 {\n drive_fail(\"TEST15.2: Failed to read from NewReader\", t)\n }\n\n \/* Test the reader interface again *\/\n file0data = make([]byte, 1)\n data_read, err = reader.Read(file0data)\n if data_read != 1 || err != nil || file0data[0] != 1 {\n drive_fail(\"TEST15.3: Invalid Reader interface behaviour\", t)\n }\n out(\"[+] Test 15.1, 15.2, 15.3 PASS -- Reader interface\")\n\n \/*\n * Tests the Writer interface\n *\/\n file0data = []byte{1, 2, 3, 4, 5, 6, 7, 8}\n writer, err := header.NewWriter(\"\/folder0\/folder0\/file0\")\n if writer == nil || err != nil {\n drive_fail(\"TEST15.4: Invalid Writer object\", t)\n }\n\n written, err := writer.Write(file0data)\n if written != len(file0data) || err != io.EOF {\n drive_fail(\"TEST15.4: Invalid Writer response\", t)\n }\n\n file0data = make([]byte, 8)\n data_read, err = reader.Read(file0data)\n if data_read != 8 || err != io.EOF || file0data[0] != 1 || file0data[1] != 2 {\n drive_fail(\"TEST15.5: Invalid Reader data\",t )\n }\n out(\"[+] Test 15.4, 15.5 PASS -- Writer interface\")\n\n\n \/*\n * Print out files\n *\/\n file_list := header.get_file_list()\n for _, e := range file_list {\n out(e)\n }\n\n \/*\n * Unmount\/commit database to file\n *\/\n if err := header.unmount_db(); err != nil {\n drive_fail(\"TEST16: Failed to commit database\", t)\n }\n out(\"[+] Test 16 PASS. Raw FS stream written to: \" + header.filename)\n\n time.Sleep(10000)\n}\n\nfunc TestFSReader(t *testing.T) {\n \/*\n * Read in FS_DATABASE_FILE and do basic tests\n *\/\n var filename = gen_raw_filename(FS_DATABASE_FILE)\n out(\"[+] Loading Raw FS stream file: \" + filename)\n\n \/* Remove the test database if it exists *\/\n if _, err := os.Stat(filename); os.IsNotExist(err) {\n drive_fail(\"error: Standard raw fs stream \" + filename + \" does not exist\", t)\n }\n\n var header = CreateDatabase(filename, 0)\n if header == nil {\n drive_fail(\"TEST1: Failed to obtain header\", t)\n }\n\n if err := header.StartIOController(); err != nil {\n drive_fail(\"TEST1.1: Failed to start IOController\", t)\n }\n out(\"[+] Test 1 PASS (Loaded FS stream)\")\n}\n\nfunc gen_raw_filename(suffix string) string {\n if runtime.GOOS == \"windows\" {\n return os.Getenv(\"TEMP\") + \"\\\\\" + suffix + \".db\"\n }\n\n if runtime.GOOS == \"linux\" {\n return suffix + \".db\"\n }\n\n return suffix + \".db\"\n}\n\nfunc drive_fail(output string, t *testing.T) {\n t.Errorf(output)\n t.FailNow()\n}\n<|endoftext|>"} {"text":"\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage constants\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetHRP(t *testing.T) {\n\ttests := []struct {\n\t\tid uint32\n\t\thrp string\n\t}{\n\t\t{\n\t\t\tid: MainnetID,\n\t\t\thrp: MainnetHRP,\n\t\t},\n\t\t{\n\t\t\tid: TestnetID,\n\t\t\thrp: FujiHRP,\n\t\t},\n\t\t{\n\t\t\tid: FujiID,\n\t\t\thrp: FujiHRP,\n\t\t},\n\t\t{\n\t\t\tid: LocalID,\n\t\t\thrp: LocalHRP,\n\t\t},\n\t\t{\n\t\t\tid: 4294967295,\n\t\t\thrp: FallbackHRP,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.hrp, func(t *testing.T) {\n\t\t\tif hrp := GetHRP(test.id); hrp != test.hrp {\n\t\t\t\tt.Fatalf(\"GetHRP(%d) returned %q but expected %q\",\n\t\t\t\t\ttest.id, hrp, test.hrp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNetworkName(t *testing.T) {\n\ttests := []struct {\n\t\tid uint32\n\t\tname string\n\t}{\n\t\t{\n\t\t\tid: MainnetID,\n\t\t\tname: MainnetName,\n\t\t},\n\t\t{\n\t\t\tid: TestnetID,\n\t\t\tname: FujiName,\n\t\t},\n\t\t{\n\t\t\tid: FujiID,\n\t\t\tname: FujiName,\n\t\t},\n\t\t{\n\t\t\tid: LocalID,\n\t\t\tname: LocalName,\n\t\t},\n\t\t{\n\t\t\tid: 4294967295,\n\t\t\tname: \"network-4294967295\",\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif name := NetworkName(test.id); name != test.name {\n\t\t\t\tt.Fatalf(\"NetworkName(%d) returned %q but expected %q\",\n\t\t\t\t\ttest.id, name, test.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNetworkID(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tid uint32\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tname: MainnetName,\n\t\t\tid: MainnetID,\n\t\t},\n\t\t{\n\t\t\tname: \"MaInNeT\",\n\t\t\tid: MainnetID,\n\t\t},\n\t\t{\n\t\t\tname: TestnetName,\n\t\t\tid: TestnetID,\n\t\t},\n\t\t{\n\t\t\tname: FujiName,\n\t\t\tid: FujiID,\n\t\t},\n\t\t{\n\t\t\tname: LocalName,\n\t\t\tid: LocalID,\n\t\t},\n\t\t{\n\t\t\tname: \"network-4294967295\",\n\t\t\tid: 4294967295,\n\t\t},\n\t\t{\n\t\t\tname: \"4294967295\",\n\t\t\tid: 4294967295,\n\t\t},\n\t\t{\n\t\t\tname: \"networ-4294967295\",\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"network-4294967295123123\",\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"4294967295123123\",\n\t\t\tshouldErr: true,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tid, err := NetworkID(test.name)\n\t\t\tif err == nil && test.shouldErr {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) returned %d but should have errored\", test.name, test.id)\n\t\t\t}\n\t\t\tif err != nil && !test.shouldErr {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) unexpectedly errored with: %s\", test.name, err)\n\t\t\t}\n\t\t\tif id != test.id {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) returned %d but expected %d\", test.name, id, test.id)\n\t\t\t}\n\t\t})\n\t}\n}\nfixed manhattan test\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage constants\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetHRP(t *testing.T) {\n\ttests := []struct {\n\t\tid uint32\n\t\thrp string\n\t}{\n\t\t{\n\t\t\tid: MainnetID,\n\t\t\thrp: MainnetHRP,\n\t\t},\n\t\t{\n\t\t\tid: TestnetID,\n\t\t\thrp: FallbackHRP,\n\t\t},\n\t\t{\n\t\t\tid: FujiID,\n\t\t\thrp: FujiHRP,\n\t\t},\n\t\t{\n\t\t\tid: LocalID,\n\t\t\thrp: LocalHRP,\n\t\t},\n\t\t{\n\t\t\tid: 4294967295,\n\t\t\thrp: FallbackHRP,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.hrp, func(t *testing.T) {\n\t\t\tif hrp := GetHRP(test.id); hrp != test.hrp {\n\t\t\t\tt.Fatalf(\"GetHRP(%d) returned %q but expected %q\",\n\t\t\t\t\ttest.id, hrp, test.hrp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNetworkName(t *testing.T) {\n\ttests := []struct {\n\t\tid uint32\n\t\tname string\n\t}{\n\t\t{\n\t\t\tid: MainnetID,\n\t\t\tname: MainnetName,\n\t\t},\n\t\t{\n\t\t\tid: TestnetID,\n\t\t\tname: ManhattanName,\n\t\t},\n\t\t{\n\t\t\tid: FujiID,\n\t\t\tname: FujiName,\n\t\t},\n\t\t{\n\t\t\tid: LocalID,\n\t\t\tname: LocalName,\n\t\t},\n\t\t{\n\t\t\tid: 4294967295,\n\t\t\tname: \"network-4294967295\",\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tif name := NetworkName(test.id); name != test.name {\n\t\t\t\tt.Fatalf(\"NetworkName(%d) returned %q but expected %q\",\n\t\t\t\t\ttest.id, name, test.name)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNetworkID(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tid uint32\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tname: MainnetName,\n\t\t\tid: MainnetID,\n\t\t},\n\t\t{\n\t\t\tname: \"MaInNeT\",\n\t\t\tid: MainnetID,\n\t\t},\n\t\t{\n\t\t\tname: TestnetName,\n\t\t\tid: TestnetID,\n\t\t},\n\t\t{\n\t\t\tname: FujiName,\n\t\t\tid: FujiID,\n\t\t},\n\t\t{\n\t\t\tname: LocalName,\n\t\t\tid: LocalID,\n\t\t},\n\t\t{\n\t\t\tname: \"network-4294967295\",\n\t\t\tid: 4294967295,\n\t\t},\n\t\t{\n\t\t\tname: \"4294967295\",\n\t\t\tid: 4294967295,\n\t\t},\n\t\t{\n\t\t\tname: \"networ-4294967295\",\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"network-4294967295123123\",\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"4294967295123123\",\n\t\t\tshouldErr: true,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tid, err := NetworkID(test.name)\n\t\t\tif err == nil && test.shouldErr {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) returned %d but should have errored\", test.name, test.id)\n\t\t\t}\n\t\t\tif err != nil && !test.shouldErr {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) unexpectedly errored with: %s\", test.name, err)\n\t\t\t}\n\t\t\tif id != test.id {\n\t\t\t\tt.Fatalf(\"NetworkID(%q) returned %d but expected %d\", test.name, id, test.id)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017, Janoš Guljaš \n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httpServer\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"resenje.org\/web\/servers\"\n)\n\nvar (\n\t_ servers.Server = new(Server)\n\t_ servers.TCPServer = new(Server)\n)\n\n\/\/ Options struct holds parameters that can be configure using\n\/\/ functions with prefix With.\ntype Options struct {\n\ttlsConfig *tls.Config\n}\n\n\/\/ Option is a function that sets optional parameters for\n\/\/ the Server.\ntype Option func(*Options)\n\n\/\/ WithTLSConfig sets a TLS configuration for the HTTP server\n\/\/ and creates a TLS listener.\nfunc WithTLSConfig(tlsConfig *tls.Config) Option { return func(o *Options) { o.tlsConfig = tlsConfig } }\n\n\/\/ Server wraps http.Server to provide methods for\n\/\/ resenje.org\/web\/servers.Server interface.\ntype Server struct {\n\thttp.Server\n}\n\n\/\/ New creates a new instance of Server.\nfunc New(handler http.Handler, opts ...Option) (s *Server) {\n\to := &Options{}\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\ts = &Server{\n\t\tServer: http.Server{\n\t\t\tHandler: handler,\n\t\t\tTLSConfig: o.tlsConfig,\n\t\t},\n\t}\n\treturn\n}\n\n\/\/ ServeTCP executes http.Server.Serve method.\n\/\/ If the provided listener is net.TCPListener, keep alive\n\/\/ will be enabled. If server is configured with TLS,\n\/\/ a tls.Listener will be created with provided listener.\nfunc (s *Server) ServeTCP(ln net.Listener) (err error) {\n\tif l, ok := ln.(*net.TCPListener); ok {\n\t\tln = tcpKeepAliveListener{TCPListener: l}\n\t}\n\tif s.TLSConfig != nil {\n\t\tln = tls.NewListener(ln, s.TLSConfig)\n\t}\n\n\terr = s.Server.Serve(ln)\n\tif err == http.ErrServerClosed {\n\t\treturn nil\n\t}\n\treturn\n}\n\n\/\/ TCPKeepAliveListener sets TCP keep alive period.\ntype tcpKeepAliveListener struct {\n\t*net.TCPListener\n}\n\n\/\/ Accept accepts TCP connection and sets TCP keep alive period\nfunc (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {\n\ttc, err := ln.AcceptTCP()\n\tif err != nil {\n\t\treturn\n\t}\n\ttc.SetKeepAlive(true)\n\ttc.SetKeepAlivePeriod(3 * time.Minute)\n\treturn tc, nil\n}\nCheck for errors from SetKeepAlive and SetKeepAlivePeriod in HTTP server Accept\/\/ Copyright (c) 2017, Janoš Guljaš \n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httpServer\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"resenje.org\/web\/servers\"\n)\n\nvar (\n\t_ servers.Server = new(Server)\n\t_ servers.TCPServer = new(Server)\n)\n\n\/\/ Options struct holds parameters that can be configure using\n\/\/ functions with prefix With.\ntype Options struct {\n\ttlsConfig *tls.Config\n}\n\n\/\/ Option is a function that sets optional parameters for\n\/\/ the Server.\ntype Option func(*Options)\n\n\/\/ WithTLSConfig sets a TLS configuration for the HTTP server\n\/\/ and creates a TLS listener.\nfunc WithTLSConfig(tlsConfig *tls.Config) Option { return func(o *Options) { o.tlsConfig = tlsConfig } }\n\n\/\/ Server wraps http.Server to provide methods for\n\/\/ resenje.org\/web\/servers.Server interface.\ntype Server struct {\n\thttp.Server\n}\n\n\/\/ New creates a new instance of Server.\nfunc New(handler http.Handler, opts ...Option) (s *Server) {\n\to := &Options{}\n\tfor _, opt := range opts {\n\t\topt(o)\n\t}\n\ts = &Server{\n\t\tServer: http.Server{\n\t\t\tHandler: handler,\n\t\t\tTLSConfig: o.tlsConfig,\n\t\t},\n\t}\n\treturn\n}\n\n\/\/ ServeTCP executes http.Server.Serve method.\n\/\/ If the provided listener is net.TCPListener, keep alive\n\/\/ will be enabled. If server is configured with TLS,\n\/\/ a tls.Listener will be created with provided listener.\nfunc (s *Server) ServeTCP(ln net.Listener) (err error) {\n\tif l, ok := ln.(*net.TCPListener); ok {\n\t\tln = tcpKeepAliveListener{TCPListener: l}\n\t}\n\tif s.TLSConfig != nil {\n\t\tln = tls.NewListener(ln, s.TLSConfig)\n\t}\n\n\terr = s.Server.Serve(ln)\n\tif err == http.ErrServerClosed {\n\t\treturn nil\n\t}\n\treturn\n}\n\n\/\/ TCPKeepAliveListener sets TCP keep alive period.\ntype tcpKeepAliveListener struct {\n\t*net.TCPListener\n}\n\n\/\/ Accept accepts TCP connection and sets TCP keep alive period\nfunc (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {\n\ttc, err := ln.AcceptTCP()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err := tc.SetKeepAlive(true); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := tc.SetKeepAlivePeriod(3 * time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tc, nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/robfig\/cron\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\n\/\/go:generate go run .\/scripts\/package-templates.go\n\ntype defaultLogger struct{}\n\nfunc (defaultLogger) Printf(format string, a ...interface{}) {\n\tlog.Printf(format, a...)\n}\n\nvar (\n\ttemplateFile string\n\tnginxRoot string\n\tzookeeperNodes string\n\tserviceRoot string\n\tt *template.Template\n\trenderedTemplate bytes.Buffer\n\tsitesAvailable string\n\tsitesEnabled string\n\thashes = make(map[string]string)\n\tlogger defaultLogger\n)\n\n\/\/ check is a simple wrapper to avoid the verbosity of\n\/\/ `if err != nil` checks.\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Config is a simple mapping of service name and upstream endpoints\n\/\/ so that we can generate nginx service configuration\ntype Config struct {\n\tService string\n\tUpstreamEndpoints []string\n}\n\n\/\/ updateService will iterate through the services available in zookeeper\n\/\/ and generate a new template for them.\nfunc updateService(zookeeper *zk.Conn, serviceRoot string) {\n\tchildren, _, _, err := zookeeper.ChildrenW(serviceRoot)\n\tcheck(err)\n\treload := false\n\n\tfor _, child := range children {\n\t\tserviceInstance := strings.Join([]string{serviceRoot, child, \"instances\"}, \"\/\")\n\t\tinfo, _, _, err := zookeeper.ChildrenW(serviceInstance)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tvar upstreamEndpoints []string\n\n\t\tfor _, instanceInfo := range info {\n\t\t\ti := strings.Join(strings.Split(instanceInfo, \"_\"), \":\")\n\t\t\tupstreamEndpoints = append(upstreamEndpoints, i)\n\t\t}\n\n\t\tdata := Config{\n\t\t\tService: child,\n\t\t\tUpstreamEndpoints: upstreamEndpoints,\n\t\t}\n\n\t\tt.Execute(&renderedTemplate, data)\n\t\tr := rewriteConfig(child)\n\t\tif r == true {\n\t\t\twriteOutput(child)\n\t\t\t\/\/ reload = true\n\t\t}\n\n\t\trenderedTemplate.Reset()\n\t}\n\tif reload == true {\n\t\treloadNginx()\n\t}\n}\n\n\/\/ writeOutput will check if the service exists, remove and recreate it\nfunc writeOutput(service string) {\n\tfname := fmt.Sprintf(\"%s\/%s.service\", sitesAvailable, service)\n\terr := os.Remove(fname)\n\tcheck(err)\n\tf, err := os.OpenFile(fname, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0444)\n\tcheck(err)\n\t_, err = f.WriteString(renderedTemplate.String())\n\tcheck(err)\n\tf.Close()\n}\n\n\/\/ rewriteConfig will check if the configuration file needs to be overwritten\n\/\/ and if it's overwritten it needs to signal that nginx must be reloaded\nfunc rewriteConfig(service string) bool {\n\thasher := md5.New()\n\thasher.Write([]byte(renderedTemplate.String()))\n\trenderedHash := hex.EncodeToString(hasher.Sum(nil))\n\tif val, ok := hashes[service]; ok {\n\t\tif val != renderedHash {\n\t\t\thashes[service] = renderedHash\n\t\t} else {\n\t\t\tlogger.Printf(\"%+v :: %+v unchanged. Not updating.\", service, renderedHash)\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\thashes[service] = renderedHash\n\t}\n\tlogger.Printf(\"%+v :: %+v changed. Updating.\", service, renderedHash)\n\treturn true\n}\n\n\/\/ symlink is a wrapper on os.Symlink\nfunc symlink(service string) {\n\terr := os.Symlink(fmt.Sprintf(\"%s\/%s.service\", sitesAvailable, service),\n\t\tfmt.Sprintf(\"%s\/%s.service\", sitesEnabled, service))\n\tcheck(err)\n}\n\n\/\/ reloadNginx is a wrapper to shell out to reload the configuration\nfunc reloadNginx() {\n\treloadCommand := exec.Command(\"service\", \"nginx reload\")\n\terr := reloadCommand.Run()\n\tcheck(err)\n}\n\nfunc main() {\n\tflag.StringVar(&templateFile, \"template\", \"\", \"nginx template to use\")\n\tflag.StringVar(&nginxRoot, \"nginx-root\", \"\/etc\/nginx\/\", \"The root of the nginx installation\")\n\tflag.StringVar(&zookeeperNodes, \"zookeeper-nodes\", \"127.0.0.1:2181\", \"The zookeeper instance to connect to\")\n\tflag.StringVar(&serviceRoot, \"service-root\", \"\/\", \"The root path with your service metadata\")\n\tflag.Parse()\n\n\tsitesAvailable = fmt.Sprintf(\"%s\/sites-available\/\", nginxRoot)\n\tsitesEnabled = fmt.Sprintf(\"%s\/sites-enabled\/\", nginxRoot)\n\n\tvar err error\n\tif len(templateFile) == 0 {\n\t\tt, err = template.New(\"service-template\").Parse(defaultService)\n\t\tcheck(err)\n\t} else {\n\t\tt, err = template.New(\"service-template\").ParseFiles(templateFile)\n\t\tcheck(err)\n\t}\n\n\tsigc := make(chan os.Signal, 1)\n\tsignal.Notify(sigc, os.Interrupt, os.Kill)\n\n\tzookeeper, _, err := zk.Connect([]string{zookeeperNodes}, time.Second)\n\tcheck(err)\n\n\tc := cron.New()\n\tc.AddFunc(\"*\/10 * * * *\", func() {\n\t\tupdateService(zookeeper, serviceRoot)\n\t})\n\tc.Start()\n\n\tdefer c.Stop()\n\t<-sigc\n}\nAdded back reloading.package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/robfig\/cron\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\n\/\/go:generate go run .\/scripts\/package-templates.go\n\ntype defaultLogger struct{}\n\nfunc (defaultLogger) Printf(format string, a ...interface{}) {\n\tlog.Printf(format, a...)\n}\n\nvar (\n\ttemplateFile string\n\tnginxRoot string\n\tzookeeperNodes string\n\tserviceRoot string\n\tt *template.Template\n\trenderedTemplate bytes.Buffer\n\tsitesAvailable string\n\tsitesEnabled string\n\thashes = make(map[string]string)\n\tlogger defaultLogger\n)\n\n\/\/ check is a simple wrapper to avoid the verbosity of\n\/\/ `if err != nil` checks.\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Config is a simple mapping of service name and upstream endpoints\n\/\/ so that we can generate nginx service configuration\ntype Config struct {\n\tService string\n\tUpstreamEndpoints []string\n}\n\n\/\/ updateService will iterate through the services available in zookeeper\n\/\/ and generate a new template for them.\nfunc updateService(zookeeper *zk.Conn, serviceRoot string) {\n\tchildren, _, _, err := zookeeper.ChildrenW(serviceRoot)\n\tcheck(err)\n\treload := false\n\n\tfor _, child := range children {\n\t\tserviceInstance := strings.Join([]string{serviceRoot, child, \"instances\"}, \"\/\")\n\t\tinfo, _, _, err := zookeeper.ChildrenW(serviceInstance)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tvar upstreamEndpoints []string\n\n\t\tfor _, instanceInfo := range info {\n\t\t\ti := strings.Join(strings.Split(instanceInfo, \"_\"), \":\")\n\t\t\tupstreamEndpoints = append(upstreamEndpoints, i)\n\t\t}\n\n\t\tdata := Config{\n\t\t\tService: child,\n\t\t\tUpstreamEndpoints: upstreamEndpoints,\n\t\t}\n\n\t\tt.Execute(&renderedTemplate, data)\n\t\tr := rewriteConfig(child)\n\t\tif r == true {\n\t\t\twriteOutput(child)\n\t\t\treload = true\n\t\t}\n\n\t\trenderedTemplate.Reset()\n\t}\n\tif reload == true {\n\t\treloadNginx()\n\t}\n}\n\n\/\/ writeOutput will check if the service exists, remove and recreate it\nfunc writeOutput(service string) {\n\tfname := fmt.Sprintf(\"%s\/%s.service\", sitesAvailable, service)\n\terr := os.Remove(fname)\n\tcheck(err)\n\tf, err := os.OpenFile(fname, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0444)\n\tcheck(err)\n\t_, err = f.WriteString(renderedTemplate.String())\n\tcheck(err)\n\tf.Close()\n}\n\n\/\/ rewriteConfig will check if the configuration file needs to be overwritten\n\/\/ and if it's overwritten it needs to signal that nginx must be reloaded\nfunc rewriteConfig(service string) bool {\n\thasher := md5.New()\n\thasher.Write([]byte(renderedTemplate.String()))\n\trenderedHash := hex.EncodeToString(hasher.Sum(nil))\n\tif val, ok := hashes[service]; ok {\n\t\tif val != renderedHash {\n\t\t\thashes[service] = renderedHash\n\t\t} else {\n\t\t\tlogger.Printf(\"%+v :: %+v unchanged. Not updating.\", service, renderedHash)\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\thashes[service] = renderedHash\n\t}\n\tlogger.Printf(\"%+v :: %+v changed. Updating.\", service, renderedHash)\n\treturn true\n}\n\n\/\/ symlink is a wrapper on os.Symlink\nfunc symlink(service string) {\n\terr := os.Symlink(fmt.Sprintf(\"%s\/%s.service\", sitesAvailable, service),\n\t\tfmt.Sprintf(\"%s\/%s.service\", sitesEnabled, service))\n\tcheck(err)\n}\n\n\/\/ reloadNginx is a wrapper to shell out to reload the configuration\nfunc reloadNginx() {\n\treloadCommand := exec.Command(\"service\", \"nginx reload\")\n\terr := reloadCommand.Run()\n\tcheck(err)\n}\n\nfunc main() {\n\tflag.StringVar(&templateFile, \"template\", \"\", \"nginx template to use\")\n\tflag.StringVar(&nginxRoot, \"nginx-root\", \"\/etc\/nginx\/\", \"The root of the nginx installation\")\n\tflag.StringVar(&zookeeperNodes, \"zookeeper-nodes\", \"127.0.0.1:2181\", \"The zookeeper instance to connect to\")\n\tflag.StringVar(&serviceRoot, \"service-root\", \"\/\", \"The root path with your service metadata\")\n\tflag.Parse()\n\n\tsitesAvailable = fmt.Sprintf(\"%s\/sites-available\/\", nginxRoot)\n\tsitesEnabled = fmt.Sprintf(\"%s\/sites-enabled\/\", nginxRoot)\n\n\tvar err error\n\tif len(templateFile) == 0 {\n\t\tt, err = template.New(\"service-template\").Parse(defaultService)\n\t\tcheck(err)\n\t} else {\n\t\tt, err = template.New(\"service-template\").ParseFiles(templateFile)\n\t\tcheck(err)\n\t}\n\n\tsigc := make(chan os.Signal, 1)\n\tsignal.Notify(sigc, os.Interrupt, os.Kill)\n\n\tzookeeper, _, err := zk.Connect([]string{zookeeperNodes}, time.Second)\n\tcheck(err)\n\n\tc := cron.New()\n\tc.AddFunc(\"*\/10 * * * *\", func() {\n\t\tupdateService(zookeeper, serviceRoot)\n\t})\n\tc.Start()\n\n\tdefer c.Stop()\n\t<-sigc\n}\n<|endoftext|>"} {"text":"package buildah_test\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/werf\/werf\/pkg\/util\"\n\n\t\"github.com\/werf\/werf\/pkg\/docker\"\n\n\t\"github.com\/werf\/werf\/pkg\/werf\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/werf\/werf\/pkg\/buildah\"\n)\n\nfunc TestBuildah(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Buildah suite\")\n}\n\nvar _ = BeforeSuite(func() {\n\tExpect(werf.Init(\"\", \"\")).To(Succeed())\n\tExpect(docker.Init(context.Background(), \"\", false, false, \"\")).To(Succeed())\n})\n\nvar _ = Describe(\"Buildah client\", func() {\n\tSkip(\"not working inside go test yet\")\n\n\tvar b buildah.Buildah\n\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tb, err = buildah.NewBuildah(buildah.ModeDockerWithFuse, buildah.BuildahOpts{})\n\t\tExpect(err).To(Succeed())\n\t})\n\n\tIt(\"Builds projects using Dockerfile\", func() {\n\t\tfor _, desc := range []struct {\n\t\t\tDockerfilePath string\n\t\t\tContextPath string\n\t\t}{\n\t\t\t{\".\/buildah_test\/Dockerfile.ghost\", \"\"},\n\t\t\t{\".\/buildah_test\/Dockerfile.neovim\", \"\"},\n\t\t\t{\".\/buildah_test\/app1\/Dockerfile\", \".\/buildah_test\/app1\"},\n\t\t\t{\".\/buildah_test\/app2\/Dockerfile\", \".\/buildah_test\/app2\"},\n\t\t\t{\".\/buildah_test\/app3\/Dockerfile\", \".\/buildah_test\/app3\"},\n\t\t} {\n\t\t\td, c := loadDockerfileAndContext(desc.DockerfilePath, desc.ContextPath)\n\n\t\t\t_, err := b.BuildFromDockerfile(context.Background(), d, buildah.BuildFromDockerfileOpts{\n\t\t\t\tCommonOpts: buildah.CommonOpts{LogWriter: os.Stdout},\n\t\t\t\tContextTar: c,\n\t\t\t})\n\n\t\t\tExpect(err).To(Succeed())\n\t\t}\n\t})\n})\n\nfunc loadDockerfileAndContext(dockerfilePath string, contextPath string) ([]byte, io.Reader) {\n\tdata, err := ioutil.ReadFile(dockerfilePath)\n\tExpect(err).To(Succeed())\n\n\tif contextPath == \"\" {\n\t\treturn data, nil\n\t}\n\n\treader := util.ReadDirAsTar(contextPath)\n\n\treturn data, reader\n}\ntests: fix test skippingpackage buildah_test\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/werf\/werf\/pkg\/util\"\n\n\t\"github.com\/werf\/werf\/pkg\/docker\"\n\n\t\"github.com\/werf\/werf\/pkg\/werf\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/werf\/werf\/pkg\/buildah\"\n)\n\nfunc TestBuildah(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Buildah suite\")\n}\n\nvar _ = BeforeSuite(func() {\n\tExpect(werf.Init(\"\", \"\")).To(Succeed())\n\tExpect(docker.Init(context.Background(), \"\", false, false, \"\")).To(Succeed())\n})\n\nvar _ = Describe(\"Buildah client\", func() {\n\tvar b buildah.Buildah\n\n\tBeforeEach(func() {\n\t\tSkip(\"not working inside go test yet\")\n\n\t\tvar err error\n\t\tb, err = buildah.NewBuildah(buildah.ModeDockerWithFuse, buildah.BuildahOpts{})\n\t\tExpect(err).To(Succeed())\n\t})\n\n\tIt(\"Builds projects using Dockerfile\", func() {\n\t\tfor _, desc := range []struct {\n\t\t\tDockerfilePath string\n\t\t\tContextPath string\n\t\t}{\n\t\t\t{\".\/buildah_test\/Dockerfile.ghost\", \"\"},\n\t\t\t{\".\/buildah_test\/Dockerfile.neovim\", \"\"},\n\t\t\t{\".\/buildah_test\/app1\/Dockerfile\", \".\/buildah_test\/app1\"},\n\t\t\t{\".\/buildah_test\/app2\/Dockerfile\", \".\/buildah_test\/app2\"},\n\t\t\t{\".\/buildah_test\/app3\/Dockerfile\", \".\/buildah_test\/app3\"},\n\t\t} {\n\t\t\td, c := loadDockerfileAndContext(desc.DockerfilePath, desc.ContextPath)\n\n\t\t\t_, err := b.BuildFromDockerfile(context.Background(), d, buildah.BuildFromDockerfileOpts{\n\t\t\t\tCommonOpts: buildah.CommonOpts{LogWriter: os.Stdout},\n\t\t\t\tContextTar: c,\n\t\t\t})\n\n\t\t\tExpect(err).To(Succeed())\n\t\t}\n\t})\n})\n\nfunc loadDockerfileAndContext(dockerfilePath string, contextPath string) ([]byte, io.Reader) {\n\tdata, err := ioutil.ReadFile(dockerfilePath)\n\tExpect(err).To(Succeed())\n\n\tif contextPath == \"\" {\n\t\treturn data, nil\n\t}\n\n\treader := util.ReadDirAsTar(contextPath)\n\n\treturn data, reader\n}\n<|endoftext|>"} {"text":"package writer\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-kit\/log\"\n\t\"github.com\/go-kit\/log\/level\"\n)\n\nconst (\n\tLogEntry = \"%s %s\\n\"\n)\n\ntype Writer struct {\n\tw io.Writer\n\tsent chan time.Time\n\tinterval time.Duration\n\toutOfOrderPercentage int\n\toutOfOrderMin time.Duration\n\toutOfOrderMax time.Duration\n\tsize int\n\tprevTsLen int\n\tpad string\n\tquit chan struct{}\n\tdone chan struct{}\n\n\tlogger log.Logger\n}\n\nfunc NewWriter(\n\twriter io.Writer,\n\tsentChan chan time.Time,\n\tentryInterval, outOfOrderMin, outOfOrderMax time.Duration,\n\toutOfOrderPercentage, entrySize int,\n\tlogger log.Logger,\n) *Writer {\n\n\tw := &Writer{\n\t\tw: writer,\n\t\tsent: sentChan,\n\t\tinterval: entryInterval,\n\t\toutOfOrderPercentage: outOfOrderPercentage,\n\t\toutOfOrderMin: outOfOrderMin,\n\t\toutOfOrderMax: outOfOrderMax,\n\t\tsize: entrySize,\n\t\tprevTsLen: 0,\n\t\tquit: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t\tlogger: logger,\n\t}\n\n\tgo w.run()\n\n\treturn w\n}\n\nfunc (w *Writer) Stop() {\n\tif w.quit != nil {\n\t\tclose(w.quit)\n\t\t<-w.done\n\t\tw.quit = nil\n\t}\n}\n\nfunc (w *Writer) run() {\n\tt := time.NewTicker(w.interval)\n\tdefer func() {\n\t\tt.Stop()\n\t\tclose(w.done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tt := time.Now()\n\t\t\tif i := rand.Intn(100); i < w.outOfOrderPercentage {\n\t\t\t\tn := rand.Intn(int(w.outOfOrderMax.Seconds()-w.outOfOrderMin.Seconds())) + int(w.outOfOrderMin.Seconds())\n\t\t\t\tt = t.Add(-time.Duration(n) * time.Second)\n\t\t\t}\n\t\t\tts := strconv.FormatInt(t.UnixNano(), 10)\n\t\t\ttsLen := len(ts)\n\n\t\t\t\/\/ I guess some day this could happen????\n\t\t\tif w.prevTsLen != tsLen {\n\t\t\t\tvar str strings.Builder\n\t\t\t\t\/\/ Total line length includes timestamp, white space separator, new line char. Subtract those out\n\t\t\t\tfor str.Len() < w.size-tsLen-2 {\n\t\t\t\t\tstr.WriteString(\"p\")\n\t\t\t\t}\n\t\t\t\tw.pad = str.String()\n\t\t\t\tw.prevTsLen = tsLen\n\t\t\t}\n\n\t\t\t_, err := fmt.Fprintf(w.w, LogEntry, ts, w.pad)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Error(w.logger).Log(\"msg\", \"failed to write log entry\", \"error\", err)\n\t\t\t}\n\t\t\tw.sent <- t\n\t\tcase <-w.quit:\n\t\t\treturn\n\t\t}\n\t}\n\n}\nfix(loki-canary): Send to Loki after updating `totalEntries`. (#7211)package writer\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/go-kit\/log\"\n\t\"github.com\/go-kit\/log\/level\"\n)\n\nconst (\n\tLogEntry = \"%s %s\\n\"\n)\n\ntype Writer struct {\n\tw io.Writer\n\tsent chan time.Time\n\tinterval time.Duration\n\toutOfOrderPercentage int\n\toutOfOrderMin time.Duration\n\toutOfOrderMax time.Duration\n\tsize int\n\tprevTsLen int\n\tpad string\n\tquit chan struct{}\n\tdone chan struct{}\n\n\tlogger log.Logger\n}\n\nfunc NewWriter(\n\twriter io.Writer,\n\tsentChan chan time.Time,\n\tentryInterval, outOfOrderMin, outOfOrderMax time.Duration,\n\toutOfOrderPercentage, entrySize int,\n\tlogger log.Logger,\n) *Writer {\n\n\tw := &Writer{\n\t\tw: writer,\n\t\tsent: sentChan,\n\t\tinterval: entryInterval,\n\t\toutOfOrderPercentage: outOfOrderPercentage,\n\t\toutOfOrderMin: outOfOrderMin,\n\t\toutOfOrderMax: outOfOrderMax,\n\t\tsize: entrySize,\n\t\tprevTsLen: 0,\n\t\tquit: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t\tlogger: logger,\n\t}\n\n\tgo w.run()\n\n\treturn w\n}\n\nfunc (w *Writer) Stop() {\n\tif w.quit != nil {\n\t\tclose(w.quit)\n\t\t<-w.done\n\t\tw.quit = nil\n\t}\n}\n\nfunc (w *Writer) run() {\n\tt := time.NewTicker(w.interval)\n\tdefer func() {\n\t\tt.Stop()\n\t\tclose(w.done)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase <-t.C:\n\t\t\tt := time.Now()\n\t\t\tif i := rand.Intn(100); i < w.outOfOrderPercentage {\n\t\t\t\tn := rand.Intn(int(w.outOfOrderMax.Seconds()-w.outOfOrderMin.Seconds())) + int(w.outOfOrderMin.Seconds())\n\t\t\t\tt = t.Add(-time.Duration(n) * time.Second)\n\t\t\t}\n\t\t\tts := strconv.FormatInt(t.UnixNano(), 10)\n\t\t\ttsLen := len(ts)\n\n\t\t\t\/\/ I guess some day this could happen????\n\t\t\tif w.prevTsLen != tsLen {\n\t\t\t\tvar str strings.Builder\n\t\t\t\t\/\/ Total line length includes timestamp, white space separator, new line char. Subtract those out\n\t\t\t\tfor str.Len() < w.size-tsLen-2 {\n\t\t\t\t\tstr.WriteString(\"p\")\n\t\t\t\t}\n\t\t\t\tw.pad = str.String()\n\t\t\t\tw.prevTsLen = tsLen\n\t\t\t}\n\t\t\tw.sent <- t\n\t\t\t_, err := fmt.Fprintf(w.w, LogEntry, ts, w.pad)\n\t\t\tif err != nil {\n\t\t\t\tlevel.Error(w.logger).Log(\"msg\", \"failed to write log entry\", \"error\", err)\n\t\t\t}\n\t\tcase <-w.quit:\n\t\t\treturn\n\t\t}\n\t}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Cisco Systems, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Index to aid in synchronizing AIM resources with the underlying\n\/\/ objects that generate them. We keep an index of the expected state\n\/\/ of the AIM resources that are associated with a given key, then\n\/\/ ensure that the corresponding ThirdPartyResource objects in the\n\/\/ kubernetes API are kept in sync\n\npackage controller\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\ntype aimKey struct {\n\tktype string\n\tkey string\n}\n\nfunc newAimKey(ktype string, key string) aimKey {\n\treturn aimKey{ktype, key}\n}\n\nfunc (cont *AciController) clearAimObjects(ktype string, key string) {\n\tcont.writeAimObjects(ktype, key, nil)\n}\n\nfunc addAimLabels(ktype string, key string, aci *Aci) {\n\taci.ObjectMeta.Labels[aimKeyTypeLabel] = ktype\n\taci.ObjectMeta.Labels[aimKeyLabel] = key\n}\n\nfunc (cont *AciController) aciObjLogger(aci *Aci) *logrus.Entry {\n\treturn cont.log.WithFields(logrus.Fields{\n\t\t\"KeyType\": aci.ObjectMeta.Labels[aimKeyTypeLabel],\n\t\t\"Key\": aci.ObjectMeta.Labels[aimKeyLabel],\n\t\t\"Type\": aci.Spec.Type,\n\t\t\"Name\": aci.ObjectMeta.Name,\n\t})\n}\n\nfunc (cont *AciController) reconcileAimObject(aci *Aci) {\n\tcont.indexMutex.Lock()\n\tif !cont.syncEnabled {\n\t\tcont.indexMutex.Unlock()\n\t\treturn\n\t}\n\tktype, ktok := aci.ObjectMeta.Labels[aimKeyTypeLabel]\n\tkey, kok := aci.ObjectMeta.Labels[aimKeyLabel]\n\n\tvar updates aciSlice\n\tvar deletes []string\n\n\tif ktok && kok {\n\t\takey := newAimKey(ktype, key)\n\n\t\tdelete := false\n\t\tif expected, ok := cont.aimDesiredState[akey]; ok {\n\t\t\tfound := false\n\t\t\tfor _, eobj := range expected {\n\t\t\t\tif eobj.ObjectMeta.Name == aci.ObjectMeta.Name {\n\t\t\t\t\tfound = true\n\n\t\t\t\t\tif !aciObjEq(eobj, aci) {\n\t\t\t\t\t\tcont.aciObjLogger(aci).\n\t\t\t\t\t\t\tWarning(\"Unexpected ACI object alteration\")\n\t\t\t\t\t\tupdates = aciSlice{eobj}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tdelete = true\n\t\t\t}\n\t\t} else {\n\t\t\tdelete = true\n\t\t}\n\t\tif delete {\n\t\t\tcont.aciObjLogger(aci).Warning(\"Deleting unexpected ACI object\")\n\t\t\tdeletes = []string{aci.ObjectMeta.Name}\n\t\t}\n\t}\n\n\tcont.indexMutex.Unlock()\n\n\tcont.executeAimDiff(nil, updates, deletes)\n}\n\nfunc (cont *AciController) reconcileAimDelete(aci *Aci) {\n\tcont.indexMutex.Lock()\n\tif !cont.syncEnabled {\n\t\tcont.indexMutex.Unlock()\n\t\treturn\n\t}\n\n\tktype, ktok := aci.ObjectMeta.Labels[aimKeyTypeLabel]\n\tkey, kok := aci.ObjectMeta.Labels[aimKeyLabel]\n\n\tvar adds aciSlice\n\n\tif ktok && kok {\n\t\takey := newAimKey(ktype, key)\n\n\t\tif expected, ok := cont.aimDesiredState[akey]; ok {\n\t\t\tfor _, eobj := range expected {\n\t\t\t\tif eobj.ObjectMeta.Name == aci.ObjectMeta.Name {\n\t\t\t\t\tcont.aciObjLogger(aci).\n\t\t\t\t\t\tWarning(\"Restoring unexpectedly deleted ACI object\")\n\t\t\t\t\tadds = aciSlice{eobj}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcont.indexMutex.Unlock()\n\n\tcont.executeAimDiff(adds, nil, nil)\n}\n\n\/\/ note that writing the same object with multiple keys will result in\n\/\/ undefined behavior.\nfunc (cont *AciController) writeAimObjects(ktype string,\n\tkey string, objects aciSlice) {\n\n\tsort.Sort(objects)\n\tfor _, o := range objects {\n\t\taddAimLabels(ktype, key, o)\n\t}\n\tk := newAimKey(ktype, key)\n\n\tcont.indexMutex.Lock()\n\tadds, updates, deletes :=\n\t\tcont.diffAimState(cont.aimDesiredState[k], objects)\n\tif objects == nil {\n\t\tdelete(cont.aimDesiredState, k)\n\t} else {\n\t\tcont.aimDesiredState[k] = objects\n\t}\n\tcont.indexMutex.Unlock()\n\n\tif cont.syncEnabled {\n\t\tcont.executeAimDiff(adds, updates, deletes)\n\t}\n}\n\nfunc (cont *AciController) aimFullSync() {\n\n\tcurrentState := make(map[aimKey]aciSlice)\n\tvar adds aciSlice\n\tvar updates aciSlice\n\tvar deletes []string\n\n\tcache.ListAllByNamespace(cont.aimInformer.GetIndexer(),\n\t\taimNamespace, labels.Everything(),\n\t\tfunc(aimobj interface{}) {\n\t\t\taim := aimobj.(*Aci)\n\t\t\tktype, ktok := aim.ObjectMeta.Labels[aimKeyTypeLabel]\n\t\t\tkey, kok := aim.ObjectMeta.Labels[aimKeyLabel]\n\t\t\tif ktok && kok {\n\t\t\t\takey := newAimKey(ktype, key)\n\t\t\t\tcurrentState[akey] = append(currentState[akey], aim)\n\t\t\t}\n\t\t})\n\n\tcont.indexMutex.Lock()\n\tfor akey, cstate := range currentState {\n\t\tsort.Sort(cstate)\n\t\ta, u, d := cont.diffAimState(cstate, cont.aimDesiredState[akey])\n\t\tadds = append(adds, a...)\n\t\tupdates = append(updates, u...)\n\t\tdeletes = append(deletes, d...)\n\t}\n\n\tfor akey, dstate := range cont.aimDesiredState {\n\t\tif _, ok := currentState[akey]; !ok {\n\t\t\t\/\/ entire key not present in current state\n\t\t\ta, _, _ := cont.diffAimState(nil, dstate)\n\t\t\tadds = append(adds, a...)\n\t\t}\n\t}\n\tcont.indexMutex.Unlock()\n\n\tif cont.syncEnabled {\n\t\tcont.executeAimDiff(adds, updates, deletes)\n\t}\n}\n\nfunc aciObjEq(a *Aci, b *Aci) bool {\n\treturn reflect.DeepEqual(a.Spec, b.Spec) &&\n\t\treflect.DeepEqual(a.Labels, b.Labels) &&\n\t\treflect.DeepEqual(a.Annotations, b.Annotations)\n}\n\nfunc (cont *AciController) diffAimState(currentState aciSlice,\n\tdesiredState aciSlice) (adds aciSlice, updates aciSlice, deletes []string) {\n\n\ti := 0\n\tj := 0\n\n\tfor i < len(currentState) && j < len(desiredState) {\n\t\tcmp := strings.Compare(currentState[i].Name, desiredState[j].Name)\n\t\tif cmp < 0 {\n\t\t\tdeletes = append(deletes, currentState[i].Name)\n\t\t\ti++\n\t\t} else if cmp > 0 {\n\t\t\tadds = append(adds, desiredState[j])\n\t\t\tj++\n\t\t} else {\n\t\t\tif !aciObjEq(currentState[i], desiredState[j]) {\n\t\t\t\tupdates = append(updates, desiredState[j])\n\t\t\t}\n\n\t\t\ti++\n\t\t\tj++\n\t\t}\n\t}\n\t\/\/ extra old objects\n\tfor i < len(currentState) {\n\t\tdeletes = append(deletes, currentState[i].Name)\n\t\ti++\n\t}\n\t\/\/ extra new objects\n\tfor j < len(desiredState) {\n\t\tadds = append(adds, desiredState[j])\n\t\tj++\n\t}\n\n\treturn\n}\n\nfunc (cont *AciController) executeAimDiff(adds aciSlice,\n\tupdates aciSlice, deletes []string) {\n\n\tfor _, delete := range deletes {\n\t\tcont.log.WithFields(logrus.Fields{\"Name\": delete}).\n\t\t\tDebug(\"Applying ACI object delete\")\n\t\terr := cont.deleteAim(delete, nil)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not delete AIM object: \", err)\n\t\t}\n\t}\n\tfor _, update := range updates {\n\t\tcont.aciObjLogger(update).Debug(\"Applying ACI object update\")\n\t\t_, err := cont.updateAim(update)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not update AIM object: \", err)\n\t\t}\n\t}\n\tfor _, add := range adds {\n\t\tcont.aciObjLogger(add).Debug(\"Applying ACI object add\")\n\t\t_, err := cont.addAim(add)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not add AIM object: \", err)\n\t\t}\n\t}\n}\nFix log message\/\/ Copyright 2017 Cisco Systems, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Index to aid in synchronizing AIM resources with the underlying\n\/\/ objects that generate them. We keep an index of the expected state\n\/\/ of the AIM resources that are associated with a given key, then\n\/\/ ensure that the corresponding ThirdPartyResource objects in the\n\/\/ kubernetes API are kept in sync\n\npackage controller\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\ntype aimKey struct {\n\tktype string\n\tkey string\n}\n\nfunc newAimKey(ktype string, key string) aimKey {\n\treturn aimKey{ktype, key}\n}\n\nfunc (cont *AciController) clearAimObjects(ktype string, key string) {\n\tcont.writeAimObjects(ktype, key, nil)\n}\n\nfunc addAimLabels(ktype string, key string, aci *Aci) {\n\taci.ObjectMeta.Labels[aimKeyTypeLabel] = ktype\n\taci.ObjectMeta.Labels[aimKeyLabel] = key\n}\n\nfunc (cont *AciController) aciObjLogger(aci *Aci) *logrus.Entry {\n\treturn cont.log.WithFields(logrus.Fields{\n\t\t\"KeyType\": aci.ObjectMeta.Labels[aimKeyTypeLabel],\n\t\t\"Key\": aci.ObjectMeta.Labels[aimKeyLabel],\n\t\t\"Type\": aci.Spec.Type,\n\t\t\"Name\": aci.ObjectMeta.Name,\n\t})\n}\n\nfunc (cont *AciController) reconcileAimObject(aci *Aci) {\n\tcont.indexMutex.Lock()\n\tif !cont.syncEnabled {\n\t\tcont.indexMutex.Unlock()\n\t\treturn\n\t}\n\tktype, ktok := aci.ObjectMeta.Labels[aimKeyTypeLabel]\n\tkey, kok := aci.ObjectMeta.Labels[aimKeyLabel]\n\n\tvar updates aciSlice\n\tvar deletes []string\n\n\tif ktok && kok {\n\t\takey := newAimKey(ktype, key)\n\n\t\tdelete := false\n\t\tif expected, ok := cont.aimDesiredState[akey]; ok {\n\t\t\tfound := false\n\t\t\tfor _, eobj := range expected {\n\t\t\t\tif eobj.ObjectMeta.Name == aci.ObjectMeta.Name {\n\t\t\t\t\tfound = true\n\n\t\t\t\t\tif !aciObjEq(eobj, aci) {\n\t\t\t\t\t\tcont.aciObjLogger(aci).\n\t\t\t\t\t\t\tWarning(\"Unexpected ACI object alteration\")\n\t\t\t\t\t\tupdates = aciSlice{eobj}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tdelete = true\n\t\t\t}\n\t\t} else {\n\t\t\tdelete = true\n\t\t}\n\t\tif delete {\n\t\t\tcont.aciObjLogger(aci).Warning(\"Deleting unexpected ACI object\")\n\t\t\tdeletes = []string{aci.ObjectMeta.Name}\n\t\t}\n\t}\n\n\tcont.indexMutex.Unlock()\n\n\tcont.executeAimDiff(nil, updates, deletes)\n}\n\nfunc (cont *AciController) reconcileAimDelete(aci *Aci) {\n\tcont.indexMutex.Lock()\n\tif !cont.syncEnabled {\n\t\tcont.indexMutex.Unlock()\n\t\treturn\n\t}\n\n\tktype, ktok := aci.ObjectMeta.Labels[aimKeyTypeLabel]\n\tkey, kok := aci.ObjectMeta.Labels[aimKeyLabel]\n\n\tvar adds aciSlice\n\n\tif ktok && kok {\n\t\takey := newAimKey(ktype, key)\n\n\t\tif expected, ok := cont.aimDesiredState[akey]; ok {\n\t\t\tfor _, eobj := range expected {\n\t\t\t\tif eobj.ObjectMeta.Name == aci.ObjectMeta.Name {\n\t\t\t\t\tcont.aciObjLogger(aci).\n\t\t\t\t\t\tWarning(\"Restoring unexpectedly deleted ACI object\")\n\t\t\t\t\tadds = aciSlice{eobj}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tcont.indexMutex.Unlock()\n\n\tcont.executeAimDiff(adds, nil, nil)\n}\n\n\/\/ note that writing the same object with multiple keys will result in\n\/\/ undefined behavior.\nfunc (cont *AciController) writeAimObjects(ktype string,\n\tkey string, objects aciSlice) {\n\n\tsort.Sort(objects)\n\tfor _, o := range objects {\n\t\taddAimLabels(ktype, key, o)\n\t}\n\tk := newAimKey(ktype, key)\n\n\tcont.indexMutex.Lock()\n\tadds, updates, deletes :=\n\t\tcont.diffAimState(cont.aimDesiredState[k], objects)\n\tif objects == nil {\n\t\tdelete(cont.aimDesiredState, k)\n\t} else {\n\t\tcont.aimDesiredState[k] = objects\n\t}\n\tcont.indexMutex.Unlock()\n\n\tif cont.syncEnabled {\n\t\tcont.executeAimDiff(adds, updates, deletes)\n\t}\n}\n\nfunc (cont *AciController) aimFullSync() {\n\n\tcurrentState := make(map[aimKey]aciSlice)\n\tvar adds aciSlice\n\tvar updates aciSlice\n\tvar deletes []string\n\n\tcache.ListAllByNamespace(cont.aimInformer.GetIndexer(),\n\t\taimNamespace, labels.Everything(),\n\t\tfunc(aimobj interface{}) {\n\t\t\taim := aimobj.(*Aci)\n\t\t\tktype, ktok := aim.ObjectMeta.Labels[aimKeyTypeLabel]\n\t\t\tkey, kok := aim.ObjectMeta.Labels[aimKeyLabel]\n\t\t\tif ktok && kok {\n\t\t\t\takey := newAimKey(ktype, key)\n\t\t\t\tcurrentState[akey] = append(currentState[akey], aim)\n\t\t\t}\n\t\t})\n\n\tcont.indexMutex.Lock()\n\tfor akey, cstate := range currentState {\n\t\tsort.Sort(cstate)\n\t\ta, u, d := cont.diffAimState(cstate, cont.aimDesiredState[akey])\n\t\tadds = append(adds, a...)\n\t\tupdates = append(updates, u...)\n\t\tdeletes = append(deletes, d...)\n\t}\n\n\tfor akey, dstate := range cont.aimDesiredState {\n\t\tif _, ok := currentState[akey]; !ok {\n\t\t\t\/\/ entire key not present in current state\n\t\t\ta, _, _ := cont.diffAimState(nil, dstate)\n\t\t\tadds = append(adds, a...)\n\t\t}\n\t}\n\tcont.indexMutex.Unlock()\n\n\tif cont.syncEnabled {\n\t\tcont.executeAimDiff(adds, updates, deletes)\n\t}\n}\n\nfunc aciObjEq(a *Aci, b *Aci) bool {\n\treturn reflect.DeepEqual(a.Spec, b.Spec) &&\n\t\treflect.DeepEqual(a.Labels, b.Labels) &&\n\t\treflect.DeepEqual(a.Annotations, b.Annotations)\n}\n\nfunc (cont *AciController) diffAimState(currentState aciSlice,\n\tdesiredState aciSlice) (adds aciSlice, updates aciSlice, deletes []string) {\n\n\ti := 0\n\tj := 0\n\n\tfor i < len(currentState) && j < len(desiredState) {\n\t\tcmp := strings.Compare(currentState[i].Name, desiredState[j].Name)\n\t\tif cmp < 0 {\n\t\t\tdeletes = append(deletes, currentState[i].Name)\n\t\t\ti++\n\t\t} else if cmp > 0 {\n\t\t\tadds = append(adds, desiredState[j])\n\t\t\tj++\n\t\t} else {\n\t\t\tif !aciObjEq(currentState[i], desiredState[j]) {\n\t\t\t\tupdates = append(updates, desiredState[j])\n\t\t\t}\n\n\t\t\ti++\n\t\t\tj++\n\t\t}\n\t}\n\t\/\/ extra old objects\n\tfor i < len(currentState) {\n\t\tdeletes = append(deletes, currentState[i].Name)\n\t\ti++\n\t}\n\t\/\/ extra new objects\n\tfor j < len(desiredState) {\n\t\tadds = append(adds, desiredState[j])\n\t\tj++\n\t}\n\n\treturn\n}\n\nfunc (cont *AciController) executeAimDiff(adds aciSlice,\n\tupdates aciSlice, deletes []string) {\n\n\tfor _, delete := range deletes {\n\t\tcont.log.WithFields(logrus.Fields{\"Name\": delete}).\n\t\t\tDebug(\"Applying ACI object delete\")\n\t\terr := cont.deleteAim(delete, nil)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not delete AIM object: \", err)\n\t\t}\n\t}\n\tfor _, update := range updates {\n\t\tcont.aciObjLogger(update).Debug(\"Applying ACI object update\")\n\t\t_, err := cont.updateAim(update)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not update AIM object: \", err)\n\t\t}\n\t}\n\tfor _, add := range adds {\n\t\tcont.aciObjLogger(add).Debug(\"Applying ACI object add\")\n\t\t_, err := cont.addAim(add)\n\t\tif err != nil {\n\t\t\tcont.log.Error(\"Could not add AIM object: \", err)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package instrument\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\tkitprom \"github.com\/go-kit\/kit\/metrics\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/lifesum\/configsum\/pkg\/errors\"\n)\n\n\/\/ Labels.\nconst (\n\tlabelErr = \"err\"\n\tlabelHost = \"host\"\n\tlabelMethod = \"method\"\n\tlabelOp = \"op\"\n\tlabelProto = \"proto\"\n\tlabelRepo = \"repo\"\n\tlabelRoute = \"route\"\n\tlabelStatusCode = \"statusCode\"\n\tlabelStore = \"store\"\n)\n\nvar (\n\trepoLatencies = map[string]*kitprom.Histogram{}\n\trequestLatencies = map[string]*kitprom.Histogram{}\n)\n\n\/\/ ObserveRepoFunc wraps a histogram to track repo op latencies.\ntype ObserveRepoFunc func(store, repo, op string, begin time.Time, err error)\n\n\/\/ ObserveRepo wraps a histogram to track repo op latencies.\nfunc ObserveRepo(namespace, subsystem string) ObserveRepoFunc {\n\tkey := fmt.Sprintf(\"%s-%s\", namespace, subsystem)\n\n\t_, ok := repoLatencies[key]\n\tif !ok {\n\t\trepoLatencies[key] = kitprom.NewHistogramFrom(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"op_latency_seconds\",\n\t\t\t\tHelp: \"Latency of repo operations.\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\tlabelErr,\n\t\t\t\tlabelOp,\n\t\t\t\tlabelRepo,\n\t\t\t\tlabelStore,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn func(store, repo, op string, begin time.Time, err error) {\n\t\terrVal := \"\"\n\n\t\tif e := errors.Cause(err); e != nil {\n\t\t\terrVal = e.Error()\n\t\t}\n\n\t\trepoLatencies[key].With(\n\t\t\tlabelErr, errVal,\n\t\t\tlabelOp, op,\n\t\t\tlabelRepo, repo,\n\t\t\tlabelStore, store,\n\t\t).Observe(time.Since(begin).Seconds())\n\t}\n}\n\n\/\/ ObserveRequestFunc wraps a histogram to track request latencies.\ntype ObserveRequestFunc func(\n\tcode int,\n\thost, method, proto, route string,\n\tbegin time.Time,\n)\n\n\/\/ ObserveRequest wraps a histogram to track request latencies.\nfunc ObserveRequest(namespace, subsystem string) ObserveRequestFunc {\n\tkey := fmt.Sprintf(\"%s-%s\", namespace, subsystem)\n\n\t_, ok := requestLatencies[key]\n\tif !ok {\n\t\trequestLatencies[key] = kitprom.NewHistogramFrom(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"transport_http_latency_seconds\",\n\t\t\t\tHelp: \"Total duration of requests in seconds\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\tlabelHost,\n\t\t\t\tlabelMethod,\n\t\t\t\tlabelProto,\n\t\t\t\tlabelStatusCode,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn func(code int, host, method, proto, route string, begin time.Time) {\n\t\trequestLatencies[key].With(\n\t\t\tlabelStatusCode, strconv.Itoa(code),\n\t\t\tlabelHost, host,\n\t\t\tlabelMethod, method,\n\t\t\tlabelProto, proto,\n\t\t\tlabelRoute, route,\n\t\t).Observe(time.Since(begin).Seconds())\n\t}\n}\nAdd missing route label to Histogrampackage instrument\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\tkitprom \"github.com\/go-kit\/kit\/metrics\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/lifesum\/configsum\/pkg\/errors\"\n)\n\n\/\/ Labels.\nconst (\n\tlabelErr = \"err\"\n\tlabelHost = \"host\"\n\tlabelMethod = \"method\"\n\tlabelOp = \"op\"\n\tlabelProto = \"proto\"\n\tlabelRepo = \"repo\"\n\tlabelRoute = \"route\"\n\tlabelStatusCode = \"statusCode\"\n\tlabelStore = \"store\"\n)\n\nvar (\n\trepoLatencies = map[string]*kitprom.Histogram{}\n\trequestLatencies = map[string]*kitprom.Histogram{}\n)\n\n\/\/ ObserveRepoFunc wraps a histogram to track repo op latencies.\ntype ObserveRepoFunc func(store, repo, op string, begin time.Time, err error)\n\n\/\/ ObserveRepo wraps a histogram to track repo op latencies.\nfunc ObserveRepo(namespace, subsystem string) ObserveRepoFunc {\n\tkey := fmt.Sprintf(\"%s-%s\", namespace, subsystem)\n\n\t_, ok := repoLatencies[key]\n\tif !ok {\n\t\trepoLatencies[key] = kitprom.NewHistogramFrom(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"op_latency_seconds\",\n\t\t\t\tHelp: \"Latency of repo operations.\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\tlabelErr,\n\t\t\t\tlabelOp,\n\t\t\t\tlabelRepo,\n\t\t\t\tlabelStore,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn func(store, repo, op string, begin time.Time, err error) {\n\t\terrVal := \"\"\n\n\t\tif e := errors.Cause(err); e != nil {\n\t\t\terrVal = e.Error()\n\t\t}\n\n\t\trepoLatencies[key].With(\n\t\t\tlabelErr, errVal,\n\t\t\tlabelOp, op,\n\t\t\tlabelRepo, repo,\n\t\t\tlabelStore, store,\n\t\t).Observe(time.Since(begin).Seconds())\n\t}\n}\n\n\/\/ ObserveRequestFunc wraps a histogram to track request latencies.\ntype ObserveRequestFunc func(\n\tcode int,\n\thost, method, proto, route string,\n\tbegin time.Time,\n)\n\n\/\/ ObserveRequest wraps a histogram to track request latencies.\nfunc ObserveRequest(namespace, subsystem string) ObserveRequestFunc {\n\tkey := fmt.Sprintf(\"%s-%s\", namespace, subsystem)\n\n\t_, ok := requestLatencies[key]\n\tif !ok {\n\t\trequestLatencies[key] = kitprom.NewHistogramFrom(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName: \"transport_http_latency_seconds\",\n\t\t\t\tHelp: \"Total duration of requests in seconds\",\n\t\t\t},\n\t\t\t[]string{\n\t\t\t\tlabelHost,\n\t\t\t\tlabelMethod,\n\t\t\t\tlabelProto,\n\t\t\t\tlabelStatusCode,\n\t\t\t\tlabelRoute,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn func(code int, host, method, proto, route string, begin time.Time) {\n\t\trequestLatencies[key].With(\n\t\t\tlabelStatusCode, strconv.Itoa(code),\n\t\t\tlabelHost, host,\n\t\t\tlabelMethod, method,\n\t\t\tlabelProto, proto,\n\t\t\tlabelRoute, route,\n\t\t).Observe(time.Since(begin).Seconds())\n\t}\n}\n<|endoftext|>"} {"text":"package jsonlog\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/docker\/docker\/pkg\/timeutils\"\n)\n\nfunc BenchmarkWriteLog(b *testing.B) {\n\tvar buf bytes.Buffer\n\te := json.NewEncoder(&buf)\n\ttestLine := \"Line that thinks that it is log line from docker\\n\"\n\tfor i := 0; i < 30; i++ {\n\t\te.Encode(JSONLog{Log: testLine, Stream: \"stdout\", Created: time.Now()})\n\t}\n\tr := bytes.NewReader(buf.Bytes())\n\tw := ioutil.Discard\n\tformat := timeutils.RFC3339NanoFixed\n\tb.SetBytes(int64(r.Len()))\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := WriteLog(r, w, format); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tb.StopTimer()\n\t\tr.Seek(0, 0)\n\t\tb.StartTimer()\n\t}\n}\nTest for jsonlog.WriteLogpackage jsonlog\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/docker\/docker\/pkg\/timeutils\"\n)\n\nfunc TestWriteLog(t *testing.T) {\n\tvar buf bytes.Buffer\n\te := json.NewEncoder(&buf)\n\ttestLine := \"Line that thinks that it is log line from docker\\n\"\n\tfor i := 0; i < 30; i++ {\n\t\te.Encode(JSONLog{Log: testLine, Stream: \"stdout\", Created: time.Now()})\n\t}\n\tw := bytes.NewBuffer(nil)\n\tformat := timeutils.RFC3339NanoFixed\n\tif err := WriteLog(&buf, w, format); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tres := w.String()\n\tt.Logf(\"Result of WriteLog: %q\", res)\n\tlines := strings.Split(strings.TrimSpace(res), \"\\n\")\n\tif len(lines) != 30 {\n\t\tt.Fatalf(\"Must be 30 lines but got %d\", len(lines))\n\t}\n\tlogRe := regexp.MustCompile(`\\[.*\\] Line that thinks that it is log line from docker`)\n\tfor _, l := range lines {\n\t\tif !logRe.MatchString(l) {\n\t\t\tt.Fatalf(\"Log line not in expected format: %q\", l)\n\t\t}\n\t}\n}\n\nfunc BenchmarkWriteLog(b *testing.B) {\n\tvar buf bytes.Buffer\n\te := json.NewEncoder(&buf)\n\ttestLine := \"Line that thinks that it is log line from docker\\n\"\n\tfor i := 0; i < 30; i++ {\n\t\te.Encode(JSONLog{Log: testLine, Stream: \"stdout\", Created: time.Now()})\n\t}\n\tr := bytes.NewReader(buf.Bytes())\n\tw := ioutil.Discard\n\tformat := timeutils.RFC3339NanoFixed\n\tb.SetBytes(int64(r.Len()))\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif err := WriteLog(r, w, format); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t\tb.StopTimer()\n\t\tr.Seek(0, 0)\n\t\tb.StartTimer()\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/io\"\n)\n\n\/\/ Usage:\n\/\/ go run kpub.go -z test -c test -t test -ack all -n 1024 -sz 25\n\/\/ gk peek -z test -c test -t test -body > test.txt\n\/\/ go run validator.go test.txt\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tpanic(\"Usage go run validator.go \")\n\t}\n\n\tf, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmin, max := 1<<10, 0\n\tlineN := 0\n\treader := bufio.NewReader(f)\n\tlast := -98734\n\tfor {\n\t\tl, err := io.ReadLine(reader)\n\t\tif err != nil {\n\t\t\t\/\/ EOF\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ {000000019} XXXXXXXXXXXXXXXXXXXXXXXXX\n\t\tn, err := strconv.Atoi(string(l[1:10]))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s for `%s`\\n\", err, string(l))\n\t\t\tbreak\n\t\t}\n\n\t\tif n > max {\n\t\t\tmax = n\n\t\t}\n\t\tif n < min {\n\t\t\tmin = n\n\t\t}\n\t\tlineN++\n\n\t\tif last >= 0 && n != last+1 {\n\t\t\tfmt.Println(color.Red(\"%d %d %d\", last, n, n-last))\n\t\t}\n\n\t\tlast = n\n\t}\n\n\tfmt.Printf(\"min=%d, max=%d, lines=%d\\n\", min, max, lineN)\n\tif lineN-max == 1 {\n\t\t\/\/ kpub always starts with 0\n\t\tfmt.Println(\"passed\")\n\t} else {\n\t\tfmt.Println(\"failed\")\n\t}\n}\ncolorpackage main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/io\"\n)\n\n\/\/ Usage:\n\/\/ go run kpub.go -z test -c test -t test -ack all -n 1024 -sz 25\n\/\/ gk peek -z test -c test -t test -body > test.txt\n\/\/ go run validator.go test.txt\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tpanic(\"Usage go run validator.go \")\n\t}\n\n\tf, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmin, max := 1<<10, 0\n\tlineN := 0\n\treader := bufio.NewReader(f)\n\tlast := -98734\n\tfor {\n\t\tl, err := io.ReadLine(reader)\n\t\tif err != nil {\n\t\t\t\/\/ EOF\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ {000000019} XXXXXXXXXXXXXXXXXXXXXXXXX\n\t\tn, err := strconv.Atoi(string(l[1:10]))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s for `%s`\\n\", err, string(l))\n\t\t\tbreak\n\t\t}\n\n\t\tif n > max {\n\t\t\tmax = n\n\t\t}\n\t\tif n < min {\n\t\t\tmin = n\n\t\t}\n\t\tlineN++\n\n\t\tif last >= 0 && n != last+1 {\n\t\t\tfmt.Println(color.Red(\"%d %d %d\", last, n, n-last))\n\t\t}\n\n\t\tlast = n\n\t}\n\n\tfmt.Printf(\"min=%d, max=%d, lines=%d\\n\", min, max, lineN)\n\tif lineN-max == 1 {\n\t\t\/\/ kpub always starts with 0\n\t\tfmt.Println(color.Green(\"passed\"))\n\t} else {\n\t\tfmt.Println(color.Red(\"failed\"))\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * nomad-syncer\n * Copyright (c) 2016 Yieldbot, Inc. (http:\/\/github.com\/yieldbot\/nomad-syncer)\n * For the full copyright and license information, please view the LICENSE.txt file.\n *\/\n\npackage client\n\nimport (\n\t\"time\"\n)\n\n\/\/ Jobs represents jobs structure\ntype Jobs struct {\n\tID string\n\tName string\n\tType string\n\tPriority int\n\tStatus string\n\tStatusDescription string\n\tCreateIndex uint64\n\tModifyIndex uint64\n}\n\n\/\/ Job represents job structure\ntype Job struct {\n\tRegion string\n\tID string\n\tName string\n\tType string\n\tPriority int\n\tAllAtOnce bool\n\tDatacenters []string\n\tConstraints []*Constraint\n\tTaskGroups []*TaskGroup\n\tUpdate *UpdateStrategy\n\tPeriodic *PeriodicConfig\n\tMeta map[string]string\n\tStatus string\n\tStatusDescription string\n\tCreateIndex uint64\n\tModifyIndex uint64\n}\n\n\/\/ Constraint represents constraint structure\ntype Constraint struct {\n\tLTarget string\n\tRTarget string\n\tOperand string\n}\n\n\/\/ TaskGroup represents the task group field\ntype TaskGroup struct {\n\tName string\n\tCount int\n\tConstraints []*Constraint\n\tRestartPolicy *RestartPolicy\n\tTasks []*Task\n\tMeta map[string]string\n}\n\n\/\/ RestartPolicy represents the restart policy field\ntype RestartPolicy struct {\n\tInterval time.Duration\n\tAttempts int\n\tDelay time.Duration\n\tRestartOnSuccess bool\n\tMode string\n}\n\n\/\/ Task represents the task field\ntype Task struct {\n\tName string\n\tDriver string\n\tConfig map[string]interface{}\n\tEnv map[string]string\n\tServices []Service\n\tConstraints []*Constraint\n\tResources *Resources\n\tMeta map[string]string\n\tKillTimeout time.Duration\n}\n\n\/\/ Service represents the service field\ntype Service struct {\n\tID string\n\tName string\n\tTags []string\n\tPortLabel string `mapstructure:\"port\"`\n\tChecks []ServiceCheck\n}\n\n\/\/ ServiceCheck represents the service check field\ntype ServiceCheck struct {\n\tID string\n\tName string\n\tType string\n\tScript string\n\tPath string\n\tProtocol string\n\tInterval time.Duration\n\tTimeout time.Duration\n}\n\n\/\/ Resources represents the resources field\ntype Resources struct {\n\tCPU int\n\tMemoryMB int\n\tDiskMB int\n\tIOPS int\n\tNetworks []*NetworkResource\n}\n\n\/\/ NetworkResource represents the network resource field\ntype NetworkResource struct {\n\tDevice string\n\tCIDR string\n\tIP string\n\tMBits int\n\tReservedPorts []Port\n\tDynamicPorts []Port\n\tPublic bool\n}\n\n\/\/ Port represents port structure\ntype Port struct {\n\tLabel string\n\tValue int\n}\n\n\/\/ UpdateStrategy represents the update strategy field\ntype UpdateStrategy struct {\n\tStagger time.Duration\n\tMaxParallel int\n}\n\n\/\/ PeriodicConfig represents the periodic config field\ntype PeriodicConfig struct {\n\tEnabled bool\n\tSpec string\n\tSpecType string\n\tProhibitOverlap bool\n}\nAdd SyncJob\/*\n * nomad-syncer\n * Copyright (c) 2016 Yieldbot, Inc. (http:\/\/github.com\/yieldbot\/nomad-syncer)\n * For the full copyright and license information, please view the LICENSE.txt file.\n *\/\n\npackage client\n\nimport (\n\t\"time\"\n)\n\n\/\/ Jobs represents jobs structure\ntype Jobs struct {\n\tID string\n\tName string\n\tType string\n\tPriority int\n\tStatus string\n\tStatusDescription string\n\tCreateIndex uint64\n\tModifyIndex uint64\n}\n\n\/\/ Job represents job structure\ntype Job struct {\n\tRegion string\n\tID string\n\tName string\n\tType string\n\tPriority int\n\tAllAtOnce bool\n\tDatacenters []string\n\tConstraints []*Constraint\n\tTaskGroups []*TaskGroup\n\tUpdate *UpdateStrategy\n\tPeriodic *PeriodicConfig\n\tMeta map[string]string\n\tStatus string\n\tStatusDescription string\n\tCreateIndex uint64\n\tModifyIndex uint64\n}\n\n\/\/ Constraint represents constraint structure\ntype Constraint struct {\n\tLTarget string\n\tRTarget string\n\tOperand string\n}\n\n\/\/ TaskGroup represents the task group field\ntype TaskGroup struct {\n\tName string\n\tCount int\n\tConstraints []*Constraint\n\tRestartPolicy *RestartPolicy\n\tTasks []*Task\n\tMeta map[string]string\n}\n\n\/\/ RestartPolicy represents the restart policy field\ntype RestartPolicy struct {\n\tInterval time.Duration\n\tAttempts int\n\tDelay time.Duration\n\tRestartOnSuccess bool\n\tMode string\n}\n\n\/\/ Task represents the task field\ntype Task struct {\n\tName string\n\tDriver string\n\tConfig map[string]interface{}\n\tEnv map[string]string\n\tServices []Service\n\tConstraints []*Constraint\n\tResources *Resources\n\tMeta map[string]string\n\tKillTimeout time.Duration\n}\n\n\/\/ Service represents the service field\ntype Service struct {\n\tID string\n\tName string\n\tTags []string\n\tPortLabel string `mapstructure:\"port\"`\n\tChecks []ServiceCheck\n}\n\n\/\/ ServiceCheck represents the service check field\ntype ServiceCheck struct {\n\tID string\n\tName string\n\tType string\n\tScript string\n\tPath string\n\tProtocol string\n\tInterval time.Duration\n\tTimeout time.Duration\n}\n\n\/\/ Resources represents the resources field\ntype Resources struct {\n\tCPU int\n\tMemoryMB int\n\tDiskMB int\n\tIOPS int\n\tNetworks []*NetworkResource\n}\n\n\/\/ NetworkResource represents the network resource field\ntype NetworkResource struct {\n\tDevice string\n\tCIDR string\n\tIP string\n\tMBits int\n\tReservedPorts []Port\n\tDynamicPorts []Port\n\tPublic bool\n}\n\n\/\/ Port represents port structure\ntype Port struct {\n\tLabel string\n\tValue int\n}\n\n\/\/ UpdateStrategy represents the update strategy field\ntype UpdateStrategy struct {\n\tStagger time.Duration\n\tMaxParallel int\n}\n\n\/\/ PeriodicConfig represents the periodic config field\ntype PeriodicConfig struct {\n\tEnabled bool\n\tSpec string\n\tSpecType string\n\tProhibitOverlap bool\n}\n\n\/\/ SyncJob represents sync job structure\ntype SyncJob struct {\n\tJob *Job\n}\n<|endoftext|>"} {"text":"package client\n\nimport (\n\t\"github.com\/coreos\/fleet\/schema\"\n\t\"github.com\/juju\/errgo\"\n\n\t\"fmt\"\n\texecPkg \"os\/exec\"\n)\n\nconst (\n\tFLEETCTL = \"fleetctl\"\n\tENDPOINT_OPTION = \"--endpoint\"\n\tENDPOINT_VALUE = \"http:\/\/172.17.42.1:4001\"\n)\n\ntype ClientCLI struct {\n\tetcdPeer string\n}\n\nfunc NewClientCLI() FleetClient {\n\treturn NewClientCLIWithPeer(ENDPOINT_VALUE)\n}\n\nfunc NewClientCLIWithPeer(etcdPeer string) FleetClient {\n\treturn &ClientCLI{\n\t\tetcdPeer: etcdPeer,\n\t}\n}\n\nfunc (this *ClientCLI) Submit(name, filePath string) error {\n\tcmd := execPkg.Command(FLEETCTL, \"--drive\", \"etcd\", ENDPOINT_OPTION, this.etcdPeer, \"submit\", filePath)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Unit(name string) (*schema.Unit, error) {\n\treturn nil, fmt.Errorf(\"Method not implemented: ClientCLI.Unit\")\n}\n\nfunc (this *ClientCLI) Start(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"start\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Stop(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"stop\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Load(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"load\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Destroy(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"destroy\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\nfixed typopackage client\n\nimport (\n\t\"github.com\/coreos\/fleet\/schema\"\n\t\"github.com\/juju\/errgo\"\n\n\t\"fmt\"\n\texecPkg \"os\/exec\"\n)\n\nconst (\n\tFLEETCTL = \"fleetctl\"\n\tENDPOINT_OPTION = \"--endpoint\"\n\tENDPOINT_VALUE = \"http:\/\/172.17.42.1:4001\"\n)\n\ntype ClientCLI struct {\n\tetcdPeer string\n}\n\nfunc NewClientCLI() FleetClient {\n\treturn NewClientCLIWithPeer(ENDPOINT_VALUE)\n}\n\nfunc NewClientCLIWithPeer(etcdPeer string) FleetClient {\n\treturn &ClientCLI{\n\t\tetcdPeer: etcdPeer,\n\t}\n}\n\nfunc (this *ClientCLI) Submit(name, filePath string) error {\n\tcmd := execPkg.Command(FLEETCTL, \"--driver\", \"etcd\", ENDPOINT_OPTION, this.etcdPeer, \"submit\", filePath)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Unit(name string) (*schema.Unit, error) {\n\treturn nil, fmt.Errorf(\"Method not implemented: ClientCLI.Unit\")\n}\n\nfunc (this *ClientCLI) Start(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"start\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Stop(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"stop\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Load(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"load\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Destroy(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"destroy\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Author: Tamir Duberstein (tamird@gmail.com)\n\npackage protoutil\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/cockroachdb\/cockroach\/pkg\/util\/syncutil\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n)\n\nvar verbotenKinds = [...]reflect.Kind{\n\treflect.Array,\n}\n\ntype typeKey struct {\n\ttyp reflect.Type\n\tverboten reflect.Kind\n}\n\nvar types struct {\n\tsyncutil.Mutex\n\tknown map[typeKey]bool\n}\n\nfunc init() {\n\ttypes.known = make(map[typeKey]bool)\n}\n\n\/\/ Clone uses proto.Clone to return a deep copy of pb. It panics if pb\n\/\/ recursively contains any instances of types which are known to be\n\/\/ unsupported by proto.Clone.\n\/\/\n\/\/ This function and its associated lint (see `make check`) exist to ensure we\n\/\/ do not attempt to proto.Clone types which are not supported by proto.Clone.\n\/\/ This hackery is necessary because proto.Clone gives no direct indication\n\/\/ that it has incompletely cloned a type; it merely logs to standard output\n\/\/ (see https:\/\/github.com\/golang\/protobuf\/blob\/89238a3\/proto\/clone.go#L204).\n\/\/\n\/\/ The concrete case against which this is currently guarding may be resolved\n\/\/ upstream, see https:\/\/github.com\/gogo\/protobuf\/issues\/147.\nfunc Clone(pb proto.Message) proto.Message {\n\tfor _, verbotenKind := range verbotenKinds {\n\t\tif typeIsOrContainsVerboten(reflect.TypeOf(pb), verbotenKind) {\n\t\t\t\/\/ Try to find an example of the problematic field.\n\t\t\tif v := findVerboten(reflect.ValueOf(pb), verbotenKind); v != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"attempt to clone %T, which contains uncloneable %T %+v\", pb, v, v))\n\t\t\t}\n\t\t\t\/\/ If we couldn't find one, panic anyway.\n\t\t\tpanic(fmt.Sprintf(\"attempt to clone %T, which contains uncloneable fields\", pb))\n\t\t}\n\t}\n\n\treturn proto.Clone(pb)\n}\n\nfunc findVerboten(v reflect.Value, verboten reflect.Kind) interface{} {\n\tif val := findVerbotenInner(v, verboten); val != nil {\n\t\treturn val.Interface()\n\t}\n\treturn nil\n}\n\nfunc findVerbotenInner(v reflect.Value, verboten reflect.Kind) *reflect.Value {\n\t\/\/ Check if v's type can ever contain anything verboten.\n\tif v.IsValid() && !typeIsOrContainsVerboten(v.Type(), verboten) {\n\t\treturn nil\n\t}\n\n\t\/\/ OK, v might contain something verboten based on its type, now check if it\n\t\/\/ actually does.\n\tswitch v.Kind() {\n\tcase verboten:\n\t\treturn &v\n\n\tcase reflect.Ptr:\n\t\treturn findVerbotenInner(v.Elem(), verboten)\n\n\tcase reflect.Map:\n\t\tfor _, key := range v.MapKeys() {\n\t\t\tif elem := findVerbotenInner(v.MapIndex(key), verboten); elem != nil {\n\t\t\t\treturn elem\n\t\t\t}\n\t\t}\n\n\tcase reflect.Array, reflect.Slice:\n\t\tfor i := 0; i < v.Len(); i++ {\n\t\t\tif elem := findVerbotenInner(v.Index(i), verboten); elem != nil {\n\t\t\t\treturn elem\n\t\t\t}\n\t\t}\n\n\tcase reflect.Struct:\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\tif elem := findVerbotenInner(v.Field(i), verboten); elem != nil {\n\t\t\t\treturn elem\n\t\t\t}\n\t\t}\n\n\tcase reflect.Chan, reflect.Func:\n\t\t\/\/ Not strictly correct, but cloning these kinds is not allowed.\n\t\treturn &v\n\t}\n\n\treturn nil\n}\n\nfunc typeIsOrContainsVerboten(t reflect.Type, verboten reflect.Kind) bool {\n\ttypes.Lock()\n\tdefer types.Unlock()\n\n\treturn typeIsOrContainsVerbotenLocked(t, verboten)\n}\n\nfunc typeIsOrContainsVerbotenLocked(t reflect.Type, verboten reflect.Kind) bool {\n\tkey := typeKey{t, verboten}\n\tknownTypeIsOrContainsVerboten, ok := types.known[key]\n\tif !ok {\n\t\tknownTypeIsOrContainsVerboten = typeIsOrContainsVerbotenImpl(t, verboten)\n\t\ttypes.known[key] = knownTypeIsOrContainsVerboten\n\t}\n\treturn knownTypeIsOrContainsVerboten\n}\n\nfunc typeIsOrContainsVerbotenImpl(t reflect.Type, verboten reflect.Kind) bool {\n\tswitch t.Kind() {\n\tcase verboten:\n\t\treturn true\n\n\tcase reflect.Map:\n\t\tif typeIsOrContainsVerbotenLocked(t.Key(), verboten) || typeIsOrContainsVerbotenLocked(t.Elem(), verboten) {\n\t\t\treturn true\n\t\t}\n\n\tcase reflect.Array, reflect.Ptr, reflect.Slice:\n\t\tif typeIsOrContainsVerbotenLocked(t.Elem(), verboten) {\n\t\t\treturn true\n\t\t}\n\n\tcase reflect.Struct:\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tif typeIsOrContainsVerbotenLocked(t.Field(i).Type, verboten) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\tcase reflect.Chan, reflect.Func:\n\t\t\/\/ Not strictly correct, but cloning these kinds is not allowed.\n\t\treturn true\n\n\t}\n\n\treturn false\n}\nprotoutil: remove unused traversal through values\/\/ Copyright 2016 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Author: Tamir Duberstein (tamird@gmail.com)\n\npackage protoutil\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/cockroachdb\/cockroach\/pkg\/util\/syncutil\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n)\n\nvar verbotenKinds = [...]reflect.Kind{\n\treflect.Array,\n}\n\ntype typeKey struct {\n\ttyp reflect.Type\n\tverboten reflect.Kind\n}\n\nvar types struct {\n\tsyncutil.Mutex\n\tknown map[typeKey]reflect.Type\n}\n\nfunc init() {\n\ttypes.known = make(map[typeKey]reflect.Type)\n}\n\n\/\/ Clone uses proto.Clone to return a deep copy of pb. It panics if pb\n\/\/ recursively contains any instances of types which are known to be\n\/\/ unsupported by proto.Clone.\n\/\/\n\/\/ This function and its associated lint (see `make check`) exist to ensure we\n\/\/ do not attempt to proto.Clone types which are not supported by proto.Clone.\n\/\/ This hackery is necessary because proto.Clone gives no direct indication\n\/\/ that it has incompletely cloned a type; it merely logs to standard output\n\/\/ (see https:\/\/github.com\/golang\/protobuf\/blob\/89238a3\/proto\/clone.go#L204).\n\/\/\n\/\/ The concrete case against which this is currently guarding may be resolved\n\/\/ upstream, see https:\/\/github.com\/gogo\/protobuf\/issues\/147.\nfunc Clone(pb proto.Message) proto.Message {\n\tfor _, verbotenKind := range verbotenKinds {\n\t\tif t := typeIsOrContainsVerboten(reflect.TypeOf(pb), verbotenKind); t != nil {\n\t\t\tpanic(fmt.Sprintf(\"attempt to clone %T, which contains uncloneable field of type %s\", pb, t))\n\t\t}\n\t}\n\n\treturn proto.Clone(pb)\n}\n\nfunc typeIsOrContainsVerboten(t reflect.Type, verboten reflect.Kind) reflect.Type {\n\ttypes.Lock()\n\tdefer types.Unlock()\n\n\treturn typeIsOrContainsVerbotenLocked(t, verboten)\n}\n\nfunc typeIsOrContainsVerbotenLocked(t reflect.Type, verboten reflect.Kind) reflect.Type {\n\tkey := typeKey{t, verboten}\n\tknownTypeIsOrContainsVerboten, ok := types.known[key]\n\tif !ok {\n\t\tknownTypeIsOrContainsVerboten = typeIsOrContainsVerbotenImpl(t, verboten)\n\t\ttypes.known[key] = knownTypeIsOrContainsVerboten\n\t}\n\treturn knownTypeIsOrContainsVerboten\n}\n\nfunc typeIsOrContainsVerbotenImpl(t reflect.Type, verboten reflect.Kind) reflect.Type {\n\tswitch t.Kind() {\n\tcase verboten:\n\t\treturn t\n\n\tcase reflect.Map:\n\t\tif key := typeIsOrContainsVerbotenLocked(t.Key(), verboten); key != nil {\n\t\t\treturn key\n\t\t}\n\t\tif value := typeIsOrContainsVerbotenLocked(t.Elem(), verboten); value != nil {\n\t\t\treturn value\n\t\t}\n\n\tcase reflect.Array, reflect.Ptr, reflect.Slice:\n\t\tif value := typeIsOrContainsVerbotenLocked(t.Elem(), verboten); value != nil {\n\t\t\treturn value\n\t\t}\n\n\tcase reflect.Struct:\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tif field := typeIsOrContainsVerbotenLocked(t.Field(i).Type, verboten); field != nil {\n\t\t\t\treturn field\n\t\t\t}\n\t\t}\n\n\tcase reflect.Chan, reflect.Func:\n\t\t\/\/ Not strictly correct, but cloning these kinds is not allowed.\n\t\treturn t\n\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/*\n *\n * k6 - a next-generation load testing tool\n * Copyright (C) 2019 Load Impact\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\n *\/\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"github.com\/loadimpact\/k6\/lib\"\n\t\"github.com\/loadimpact\/k6\/lib\/scheduler\"\n\t\"github.com\/loadimpact\/k6\/stats\/cloud\"\n\t\"github.com\/loadimpact\/k6\/stats\/datadog\"\n\t\"github.com\/loadimpact\/k6\/stats\/influxdb\"\n\t\"github.com\/loadimpact\/k6\/stats\/kafka\"\n\t\"github.com\/loadimpact\/k6\/stats\/statsd\/common\"\n\t\"github.com\/pkg\/errors\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/afero\"\n\t\"github.com\/spf13\/pflag\"\n\tnull \"gopkg.in\/guregu\/null.v3\"\n)\n\n\/\/ configFlagSet returns a FlagSet with the default run configuration flags.\nfunc configFlagSet() *pflag.FlagSet {\n\tflags := pflag.NewFlagSet(\"\", 0)\n\tflags.SortFlags = false\n\tflags.StringArrayP(\"out\", \"o\", []string{}, \"`uri` for an external metrics database\")\n\tflags.BoolP(\"linger\", \"l\", false, \"keep the API server alive past test end\")\n\tflags.Bool(\"no-usage-report\", false, \"don't send anonymous stats to the developers\")\n\tflags.Bool(\"no-thresholds\", false, \"don't run thresholds\")\n\tflags.Bool(\"no-summary\", false, \"don't show the summary at the end of the test\")\n\treturn flags\n}\n\ntype Config struct {\n\tlib.Options\n\n\tOut []string `json:\"out\" envconfig:\"out\"`\n\tLinger null.Bool `json:\"linger\" envconfig:\"linger\"`\n\tNoUsageReport null.Bool `json:\"noUsageReport\" envconfig:\"no_usage_report\"`\n\tNoThresholds null.Bool `json:\"noThresholds\" envconfig:\"no_thresholds\"`\n\tNoSummary null.Bool `json:\"noSummary\" envconfig:\"no_summary\"`\n\n\tCollectors struct {\n\t\tInfluxDB influxdb.Config `json:\"influxdb\"`\n\t\tKafka kafka.Config `json:\"kafka\"`\n\t\tCloud cloud.Config `json:\"cloud\"`\n\t\tStatsD common.Config `json:\"statsd\"`\n\t\tDatadog datadog.Config `json:\"datadog\"`\n\t} `json:\"collectors\"`\n}\n\nfunc (c Config) Apply(cfg Config) Config {\n\tc.Options = c.Options.Apply(cfg.Options)\n\tif len(cfg.Out) > 0 {\n\t\tc.Out = cfg.Out\n\t}\n\tif cfg.Linger.Valid {\n\t\tc.Linger = cfg.Linger\n\t}\n\tif cfg.NoUsageReport.Valid {\n\t\tc.NoUsageReport = cfg.NoUsageReport\n\t}\n\tif cfg.NoThresholds.Valid {\n\t\tc.NoThresholds = cfg.NoThresholds\n\t}\n\tif cfg.NoSummary.Valid {\n\t\tc.NoSummary = cfg.NoSummary\n\t}\n\tc.Collectors.InfluxDB = c.Collectors.InfluxDB.Apply(cfg.Collectors.InfluxDB)\n\tc.Collectors.Cloud = c.Collectors.Cloud.Apply(cfg.Collectors.Cloud)\n\tc.Collectors.Kafka = c.Collectors.Kafka.Apply(cfg.Collectors.Kafka)\n\tc.Collectors.StatsD = c.Collectors.StatsD.Apply(cfg.Collectors.StatsD)\n\tc.Collectors.Datadog = c.Collectors.Datadog.Apply(cfg.Collectors.Datadog)\n\treturn c\n}\n\n\/\/ Gets configuration from CLI flags.\nfunc getConfig(flags *pflag.FlagSet) (Config, error) {\n\topts, err := getOptions(flags)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\tout, err := flags.GetStringArray(\"out\")\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn Config{\n\t\tOptions: opts,\n\t\tOut: out,\n\t\tLinger: getNullBool(flags, \"linger\"),\n\t\tNoUsageReport: getNullBool(flags, \"no-usage-report\"),\n\t\tNoThresholds: getNullBool(flags, \"no-thresholds\"),\n\t\tNoSummary: getNullBool(flags, \"no-summary\"),\n\t}, nil\n}\n\n\/\/ Reads a configuration file from disk and returns it and its path.\nfunc readDiskConfig(fs afero.Fs) (Config, string, error) {\n\trealConfigFilePath := configFilePath\n\tif realConfigFilePath == \"\" {\n\t\t\/\/ The user didn't specify K6_CONFIG or --config, use the default path\n\t\trealConfigFilePath = defaultConfigFilePath\n\t}\n\n\t\/\/ Try to see if the file exists in the supplied filesystem\n\tif _, err := fs.Stat(realConfigFilePath); err != nil {\n\t\tif os.IsNotExist(err) && configFilePath == \"\" {\n\t\t\t\/\/ If the file doesn't exist, but it was the default config file (i.e. the user\n\t\t\t\/\/ didn't specify anything), silence the error\n\t\t\terr = nil\n\t\t}\n\t\treturn Config{}, realConfigFilePath, err\n\t}\n\n\tdata, err := afero.ReadFile(fs, realConfigFilePath)\n\tif err != nil {\n\t\treturn Config{}, realConfigFilePath, err\n\t}\n\tvar conf Config\n\terr = json.Unmarshal(data, &conf)\n\treturn conf, realConfigFilePath, err\n}\n\n\/\/ Writes configuration back to disk.\nfunc writeDiskConfig(fs afero.Fs, configPath string, conf Config) error {\n\tdata, err := json.MarshalIndent(conf, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := fs.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn afero.WriteFile(fs, configPath, data, 0644)\n}\n\n\/\/ Reads configuration variables from the environment.\nfunc readEnvConfig() (conf Config, err error) {\n\t\/\/ TODO: replace envconfig and refactor the whole configuration from the groun up :\/\n\tfor _, err := range []error{\n\t\tenvconfig.Process(\"k6\", &conf),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.Cloud),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.InfluxDB),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.Kafka),\n\t} {\n\t\treturn conf, err\n\t}\n\treturn conf, nil\n}\n\n\/\/ This checks for conflicting options and turns any shortcut options (i.e. duration, iterations,\n\/\/ stages) into the proper scheduler configuration\nfunc buildExecutionConfig(conf Config) (Config, error) {\n\tresult := conf\n\tif conf.Duration.Valid {\n\t\tif conf.Iterations.Valid {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both duration and iterations is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Stages != nil {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both duration and stages is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Execution != nil {\n\t\t\t\/\/TODO: use a custom error type\n\t\t\treturn result, errors.New(\"specifying both duration and execution is not supported\")\n\t\t}\n\n\t\tif conf.Duration.Duration <= 0 {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying infinite duration in this way is deprecated and won't be supported in the future k6 versions\")\n\t\t} else {\n\t\t\tds := scheduler.NewConstantLoopingVUsConfig(lib.DefaultSchedulerName)\n\t\t\tds.VUs = conf.VUs\n\t\t\tds.Duration = conf.Duration\n\t\t\tds.Interruptible = null.NewBool(true, false) \/\/ Preserve backwards compatibility\n\t\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t\t}\n\t} else if conf.Stages != nil {\n\t\tif conf.Iterations.Valid {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both iterations and stages is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Execution != nil {\n\t\t\treturn conf, errors.New(\"specifying both stages and execution is not supported\")\n\t\t}\n\n\t\tds := scheduler.NewVariableLoopingVUsConfig(lib.DefaultSchedulerName)\n\t\tds.StartVUs = conf.VUs\n\t\tfor _, s := range conf.Stages {\n\t\t\tif s.Duration.Valid {\n\t\t\t\tds.Stages = append(ds.Stages, scheduler.Stage{Duration: s.Duration, Target: s.Target})\n\t\t\t}\n\t\t}\n\t\tds.Interruptible = null.NewBool(true, false) \/\/ Preserve backwards compatibility\n\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t} else if conf.Iterations.Valid {\n\t\tif conf.Execution != nil {\n\t\t\treturn conf, errors.New(\"specifying both iterations and execution is not supported\")\n\t\t}\n\t\t\/\/ TODO: maybe add a new flag that will be used as a shortcut to per-VU iterations?\n\n\t\tds := scheduler.NewSharedIterationsConfig(lib.DefaultSchedulerName)\n\t\tds.VUs = conf.VUs\n\t\tds.Iterations = conf.Iterations\n\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t} else if conf.Execution != nil {\n\t\t\/\/TODO: remove this warning in the next version\n\t\tlog.Warnf(\"The execution settings are not functional in this k6 release, they will be ignored\")\n\t} else {\n\t\t\/\/ No execution parameters whatsoever were specified, so we'll create a per-VU iterations config\n\t\t\/\/ with 1 VU and 1 iteration. We're choosing the per-VU config, since that one could also\n\t\t\/\/ be executed both locally, and in the cloud.\n\t\tresult.Execution = scheduler.ConfigMap{\n\t\t\tlib.DefaultSchedulerName: scheduler.NewPerVUIterationsConfig(lib.DefaultSchedulerName),\n\t\t}\n\t}\n\n\t\/\/TODO: validate the config; questions:\n\t\/\/ - separately validate the duration, iterations and stages for better error messages?\n\t\/\/ - or reuse the execution validation somehow, at the end? or something mixed?\n\t\/\/ - here or in getConsolidatedConfig() or somewhere else?\n\n\treturn result, nil\n}\n\n\/\/ Assemble the final consolidated configuration from all of the different sources:\n\/\/ - start with the CLI-provided options to get shadowed (non-Valid) defaults in there\n\/\/ - add the global file config options\n\/\/ - if supplied, add the Runner-provided options\n\/\/ - add the environment variables\n\/\/ - merge the user-supplied CLI flags back in on top, to give them the greatest priority\n\/\/ - set some defaults if they weren't previously specified\n\/\/ TODO: add better validation, more explicit default values and improve consistency between formats\n\/\/ TODO: accumulate all errors and differentiate between the layers?\nfunc getConsolidatedConfig(fs afero.Fs, cliConf Config, runner lib.Runner) (conf Config, err error) {\n\tcliConf.Collectors.InfluxDB = influxdb.NewConfig().Apply(cliConf.Collectors.InfluxDB)\n\tcliConf.Collectors.Cloud = cloud.NewConfig().Apply(cliConf.Collectors.Cloud)\n\tcliConf.Collectors.Kafka = kafka.NewConfig().Apply(cliConf.Collectors.Kafka)\n\n\tfileConf, _, err := readDiskConfig(fs)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\tenvConf, err := readEnvConfig()\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tconf = cliConf.Apply(fileConf)\n\tif runner != nil {\n\t\tconf = conf.Apply(Config{Options: runner.GetOptions()})\n\t}\n\tconf = conf.Apply(envConf).Apply(cliConf)\n\n\treturn buildExecutionConfig(conf)\n}\nImprove the comments on the funcitons that deal with the file config\/*\n *\n * k6 - a next-generation load testing tool\n * Copyright (C) 2019 Load Impact\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\n *\/\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"github.com\/loadimpact\/k6\/lib\"\n\t\"github.com\/loadimpact\/k6\/lib\/scheduler\"\n\t\"github.com\/loadimpact\/k6\/stats\/cloud\"\n\t\"github.com\/loadimpact\/k6\/stats\/datadog\"\n\t\"github.com\/loadimpact\/k6\/stats\/influxdb\"\n\t\"github.com\/loadimpact\/k6\/stats\/kafka\"\n\t\"github.com\/loadimpact\/k6\/stats\/statsd\/common\"\n\t\"github.com\/pkg\/errors\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/afero\"\n\t\"github.com\/spf13\/pflag\"\n\tnull \"gopkg.in\/guregu\/null.v3\"\n)\n\n\/\/ configFlagSet returns a FlagSet with the default run configuration flags.\nfunc configFlagSet() *pflag.FlagSet {\n\tflags := pflag.NewFlagSet(\"\", 0)\n\tflags.SortFlags = false\n\tflags.StringArrayP(\"out\", \"o\", []string{}, \"`uri` for an external metrics database\")\n\tflags.BoolP(\"linger\", \"l\", false, \"keep the API server alive past test end\")\n\tflags.Bool(\"no-usage-report\", false, \"don't send anonymous stats to the developers\")\n\tflags.Bool(\"no-thresholds\", false, \"don't run thresholds\")\n\tflags.Bool(\"no-summary\", false, \"don't show the summary at the end of the test\")\n\treturn flags\n}\n\ntype Config struct {\n\tlib.Options\n\n\tOut []string `json:\"out\" envconfig:\"out\"`\n\tLinger null.Bool `json:\"linger\" envconfig:\"linger\"`\n\tNoUsageReport null.Bool `json:\"noUsageReport\" envconfig:\"no_usage_report\"`\n\tNoThresholds null.Bool `json:\"noThresholds\" envconfig:\"no_thresholds\"`\n\tNoSummary null.Bool `json:\"noSummary\" envconfig:\"no_summary\"`\n\n\tCollectors struct {\n\t\tInfluxDB influxdb.Config `json:\"influxdb\"`\n\t\tKafka kafka.Config `json:\"kafka\"`\n\t\tCloud cloud.Config `json:\"cloud\"`\n\t\tStatsD common.Config `json:\"statsd\"`\n\t\tDatadog datadog.Config `json:\"datadog\"`\n\t} `json:\"collectors\"`\n}\n\nfunc (c Config) Apply(cfg Config) Config {\n\tc.Options = c.Options.Apply(cfg.Options)\n\tif len(cfg.Out) > 0 {\n\t\tc.Out = cfg.Out\n\t}\n\tif cfg.Linger.Valid {\n\t\tc.Linger = cfg.Linger\n\t}\n\tif cfg.NoUsageReport.Valid {\n\t\tc.NoUsageReport = cfg.NoUsageReport\n\t}\n\tif cfg.NoThresholds.Valid {\n\t\tc.NoThresholds = cfg.NoThresholds\n\t}\n\tif cfg.NoSummary.Valid {\n\t\tc.NoSummary = cfg.NoSummary\n\t}\n\tc.Collectors.InfluxDB = c.Collectors.InfluxDB.Apply(cfg.Collectors.InfluxDB)\n\tc.Collectors.Cloud = c.Collectors.Cloud.Apply(cfg.Collectors.Cloud)\n\tc.Collectors.Kafka = c.Collectors.Kafka.Apply(cfg.Collectors.Kafka)\n\tc.Collectors.StatsD = c.Collectors.StatsD.Apply(cfg.Collectors.StatsD)\n\tc.Collectors.Datadog = c.Collectors.Datadog.Apply(cfg.Collectors.Datadog)\n\treturn c\n}\n\n\/\/ Gets configuration from CLI flags.\nfunc getConfig(flags *pflag.FlagSet) (Config, error) {\n\topts, err := getOptions(flags)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\tout, err := flags.GetStringArray(\"out\")\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn Config{\n\t\tOptions: opts,\n\t\tOut: out,\n\t\tLinger: getNullBool(flags, \"linger\"),\n\t\tNoUsageReport: getNullBool(flags, \"no-usage-report\"),\n\t\tNoThresholds: getNullBool(flags, \"no-thresholds\"),\n\t\tNoSummary: getNullBool(flags, \"no-summary\"),\n\t}, nil\n}\n\n\/\/ Reads the configuration file from the supplied filesystem and returns it and its path.\n\/\/ It will first try to see if the user eplicitly specified a custom config file and will\n\/\/ try to read that. If there's a custom config specified and it couldn't be read or parsed,\n\/\/ an error will be returned.\n\/\/ If there's no custom config specified and no file exists in the default config path, it will\n\/\/ return an empty config struct, the default config location and *no* error.\nfunc readDiskConfig(fs afero.Fs) (Config, string, error) {\n\trealConfigFilePath := configFilePath\n\tif realConfigFilePath == \"\" {\n\t\t\/\/ The user didn't specify K6_CONFIG or --config, use the default path\n\t\trealConfigFilePath = defaultConfigFilePath\n\t}\n\n\t\/\/ Try to see if the file exists in the supplied filesystem\n\tif _, err := fs.Stat(realConfigFilePath); err != nil {\n\t\tif os.IsNotExist(err) && configFilePath == \"\" {\n\t\t\t\/\/ If the file doesn't exist, but it was the default config file (i.e. the user\n\t\t\t\/\/ didn't specify anything), silence the error\n\t\t\terr = nil\n\t\t}\n\t\treturn Config{}, realConfigFilePath, err\n\t}\n\n\tdata, err := afero.ReadFile(fs, realConfigFilePath)\n\tif err != nil {\n\t\treturn Config{}, realConfigFilePath, err\n\t}\n\tvar conf Config\n\terr = json.Unmarshal(data, &conf)\n\treturn conf, realConfigFilePath, err\n}\n\n\/\/ Serializes the configuration to a JSON file and writes it in the supplied\n\/\/ location on the supplied filesystem\nfunc writeDiskConfig(fs afero.Fs, configPath string, conf Config) error {\n\tdata, err := json.MarshalIndent(conf, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := fs.MkdirAll(filepath.Dir(configPath), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn afero.WriteFile(fs, configPath, data, 0644)\n}\n\n\/\/ Reads configuration variables from the environment.\nfunc readEnvConfig() (conf Config, err error) {\n\t\/\/ TODO: replace envconfig and refactor the whole configuration from the groun up :\/\n\tfor _, err := range []error{\n\t\tenvconfig.Process(\"k6\", &conf),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.Cloud),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.InfluxDB),\n\t\tenvconfig.Process(\"k6\", &conf.Collectors.Kafka),\n\t} {\n\t\treturn conf, err\n\t}\n\treturn conf, nil\n}\n\n\/\/ This checks for conflicting options and turns any shortcut options (i.e. duration, iterations,\n\/\/ stages) into the proper scheduler configuration\nfunc buildExecutionConfig(conf Config) (Config, error) {\n\tresult := conf\n\tif conf.Duration.Valid {\n\t\tif conf.Iterations.Valid {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both duration and iterations is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Stages != nil {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both duration and stages is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Execution != nil {\n\t\t\t\/\/TODO: use a custom error type\n\t\t\treturn result, errors.New(\"specifying both duration and execution is not supported\")\n\t\t}\n\n\t\tif conf.Duration.Duration <= 0 {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying infinite duration in this way is deprecated and won't be supported in the future k6 versions\")\n\t\t} else {\n\t\t\tds := scheduler.NewConstantLoopingVUsConfig(lib.DefaultSchedulerName)\n\t\t\tds.VUs = conf.VUs\n\t\t\tds.Duration = conf.Duration\n\t\t\tds.Interruptible = null.NewBool(true, false) \/\/ Preserve backwards compatibility\n\t\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t\t}\n\t} else if conf.Stages != nil {\n\t\tif conf.Iterations.Valid {\n\t\t\t\/\/TODO: make this an error in the next version\n\t\t\tlog.Warnf(\"Specifying both iterations and stages is deprecated and won't be supported in the future k6 versions\")\n\t\t}\n\n\t\tif conf.Execution != nil {\n\t\t\treturn conf, errors.New(\"specifying both stages and execution is not supported\")\n\t\t}\n\n\t\tds := scheduler.NewVariableLoopingVUsConfig(lib.DefaultSchedulerName)\n\t\tds.StartVUs = conf.VUs\n\t\tfor _, s := range conf.Stages {\n\t\t\tif s.Duration.Valid {\n\t\t\t\tds.Stages = append(ds.Stages, scheduler.Stage{Duration: s.Duration, Target: s.Target})\n\t\t\t}\n\t\t}\n\t\tds.Interruptible = null.NewBool(true, false) \/\/ Preserve backwards compatibility\n\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t} else if conf.Iterations.Valid {\n\t\tif conf.Execution != nil {\n\t\t\treturn conf, errors.New(\"specifying both iterations and execution is not supported\")\n\t\t}\n\t\t\/\/ TODO: maybe add a new flag that will be used as a shortcut to per-VU iterations?\n\n\t\tds := scheduler.NewSharedIterationsConfig(lib.DefaultSchedulerName)\n\t\tds.VUs = conf.VUs\n\t\tds.Iterations = conf.Iterations\n\t\tresult.Execution = scheduler.ConfigMap{lib.DefaultSchedulerName: ds}\n\t} else if conf.Execution != nil {\n\t\t\/\/TODO: remove this warning in the next version\n\t\tlog.Warnf(\"The execution settings are not functional in this k6 release, they will be ignored\")\n\t} else {\n\t\t\/\/ No execution parameters whatsoever were specified, so we'll create a per-VU iterations config\n\t\t\/\/ with 1 VU and 1 iteration. We're choosing the per-VU config, since that one could also\n\t\t\/\/ be executed both locally, and in the cloud.\n\t\tresult.Execution = scheduler.ConfigMap{\n\t\t\tlib.DefaultSchedulerName: scheduler.NewPerVUIterationsConfig(lib.DefaultSchedulerName),\n\t\t}\n\t}\n\n\t\/\/TODO: validate the config; questions:\n\t\/\/ - separately validate the duration, iterations and stages for better error messages?\n\t\/\/ - or reuse the execution validation somehow, at the end? or something mixed?\n\t\/\/ - here or in getConsolidatedConfig() or somewhere else?\n\n\treturn result, nil\n}\n\n\/\/ Assemble the final consolidated configuration from all of the different sources:\n\/\/ - start with the CLI-provided options to get shadowed (non-Valid) defaults in there\n\/\/ - add the global file config options\n\/\/ - if supplied, add the Runner-provided options\n\/\/ - add the environment variables\n\/\/ - merge the user-supplied CLI flags back in on top, to give them the greatest priority\n\/\/ - set some defaults if they weren't previously specified\n\/\/ TODO: add better validation, more explicit default values and improve consistency between formats\n\/\/ TODO: accumulate all errors and differentiate between the layers?\nfunc getConsolidatedConfig(fs afero.Fs, cliConf Config, runner lib.Runner) (conf Config, err error) {\n\tcliConf.Collectors.InfluxDB = influxdb.NewConfig().Apply(cliConf.Collectors.InfluxDB)\n\tcliConf.Collectors.Cloud = cloud.NewConfig().Apply(cliConf.Collectors.Cloud)\n\tcliConf.Collectors.Kafka = kafka.NewConfig().Apply(cliConf.Collectors.Kafka)\n\n\tfileConf, _, err := readDiskConfig(fs)\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\tenvConf, err := readEnvConfig()\n\tif err != nil {\n\t\treturn conf, err\n\t}\n\n\tconf = cliConf.Apply(fileConf)\n\tif runner != nil {\n\t\tconf = conf.Apply(Config{Options: runner.GetOptions()})\n\t}\n\tconf = conf.Apply(envConf).Apply(cliConf)\n\n\treturn buildExecutionConfig(conf)\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/asaskevich\/govalidator\"\n\t\"github.com\/mebiusashan\/beaker\/cli\"\n\t\"github.com\/mebiusashan\/beaker\/common\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar (\n\taddWebSiteAlias string\n\taddWebSiteUser string\n\taddWebSitePassword string\n\taddWebSiteIsDefault bool\n\n\tconfigCmd = &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Configure blog information\",\n\t\tLong: `The configuration command can \nset your blog background address`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t},\n\t}\n\n\taddWebSiteCmd = &cobra.Command{\n\t\tUse: \"addw\",\n\t\tShort: \"Add blog site information\",\n\t\tLong: `To add a blog server information, \nyou need to specify the blog address, \nuser name and password, and it will be \nverified after adding`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\turl := args[0]\n\t\t\tif !govalidator.IsURL(url) || !govalidator.IsIP(url) {\n\t\t\t\tcommon.Err(\"Blog address format error\")\n\t\t\t}\n\n\t\t\t\/\/check current config , has duplicate config\n\t\t\twebsite := viper.GetString(addWebSiteAlias)\n\t\t\tif website != \"\" {\n\t\t\t\tcommon.Err(\"Duplicate alias\")\n\t\t\t}\n\t\t\tallsettings := viper.AllSettings()\n\t\t\tfor _, data := range allsettings {\n\t\t\t\tif data == url {\n\t\t\t\t\tcommon.Err(\"Duplicate host\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/need login with current website\n\t\t\t\/\/if success login, set info and server key to config file\n\t\t\t\/\/if it's default website, need reset all website config\n\t\t\tpubKey := cli.Ping(url)\n\t\t\tserverPubKey := cli.Login(url, pubKey, addWebSiteUser, addWebSitePassword)\n\t\t\tif cli.Check(url, serverPubKey) {\n\t\t\t\tviper.Set(addWebSiteAlias, url)\n\t\t\t\tviper.Set(addWebSiteAlias+\"key\", serverPubKey)\n\t\t\t\tif addWebSiteIsDefault {\n\t\t\t\t\tviper.Set(\"defaulutWebsite\", addWebSiteAlias)\n\t\t\t\t}\n\t\t\t\tviper.SafeWriteConfig()\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"login fail\")\n\t\t\t}\n\t\t},\n\t}\n)\n\n\/\/ type websiteConfig struct {\n\/\/ \tIsDefault bool\n\/\/ \tName string\n\/\/ \tHOST string\n\/\/ \tKey string\n\/\/ }\n\nfunc init() {\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSiteAlias, \"alias\", \"a\", \"\", \"blog alias\")\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSiteUser, \"user\", \"u\", \"\", \"blog administrator account name\")\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSitePassword, \"password\", \"p\", \"\", \"blog administrator account password\")\n\taddWebSiteCmd.PersistentFlags().BoolVarP(&addWebSiteIsDefault, \"defalut\", \"d\", false, \"set as default blog\")\n\n\tconfigCmd.AddCommand(addWebSiteCmd)\n}\n\nfunc initConfig() {\n\thome, err := homedir.Dir()\n\tcommon.Assert(err)\n\n\tviper.AddConfigPath(home)\n\tviper.SetConfigType(\"yaml\")\n\tviper.SetConfigName(\".beaker\")\n\tviper.SafeWriteConfig()\n\n\terr = viper.ReadInConfig()\n\tcommon.Assert(err)\n\n\t\/\/ fmt.Println(viper.GetString(\"license\"))\n\t\/\/ viper.SafeWriteConfig()\n\t\/\/ website := viper.GetStringMap(\"website\")\n\t\/\/ if website == nil || len(website) == 0 {\n\t\/\/ \ter(\"No blog information is configured. Please check the help for the config command.\")\n\t\/\/ }\n\n}\nadd config add website command featurepackage cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/asaskevich\/govalidator\"\n\t\"github.com\/mebiusashan\/beaker\/cli\"\n\t\"github.com\/mebiusashan\/beaker\/common\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\ntype websiteConfig struct {\n\tAlias string\n\tHOST string\n\tKey string\n}\n\ntype config struct {\n\tDefaultWebsite string\n\tWebsites []websiteConfig\n}\n\nvar (\n\tlocalConfig config\n\taddWebSiteAlias string\n\taddWebSiteUser string\n\taddWebSitePassword string\n\taddWebSiteIsDefault bool\n\n\tconfigCmd = &cobra.Command{\n\t\tUse: \"config\",\n\t\tShort: \"Configure blog information\",\n\t\tLong: `The configuration command can \nset your blog background address`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Help()\n\t\t},\n\t}\n\n\taddWebSiteCmd = &cobra.Command{\n\t\tUse: \"addw\",\n\t\tShort: \"Add blog site information\",\n\t\tLong: `To add a blog server information, \nyou need to specify the blog address, \nuser name and password, and it will be \nverified after adding`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\turl := args[0]\n\t\t\tif !govalidator.IsURL(url) && !govalidator.IsIP(url) {\n\t\t\t\tcommon.Err(\"Blog address format error\")\n\t\t\t}\n\n\t\t\tif addWebSiteAlias == \"\" {\n\t\t\t\tcommon.Err(\"Alias ​​cannot be empty\")\n\t\t\t}\n\n\t\t\t\/\/check current config , has duplicate config\n\t\t\tfor _, website := range localConfig.Websites {\n\t\t\t\tif website.Alias == addWebSiteAlias {\n\t\t\t\t\tcommon.Err(\"Duplicate alias\")\n\t\t\t\t}\n\t\t\t\tif website.HOST == url {\n\t\t\t\t\tcommon.Err(\"Duplicate host\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/need login with current website\n\t\t\t\/\/if success login, set info and server key to config file\n\t\t\t\/\/if it's default website, need reset all website config\n\t\t\tpubKey := cli.Ping(url)\n\t\t\tserverPubKey := cli.Login(url, pubKey, addWebSiteUser, addWebSitePassword)\n\t\t\tif cli.Check(url, serverPubKey) {\n\t\t\t\tif len(localConfig.Websites) == 0 || localConfig.Websites == nil {\n\t\t\t\t\tlocalConfig.Websites = make([]websiteConfig, 0)\n\t\t\t\t\taddWebSiteIsDefault = true\n\t\t\t\t}\n\t\t\t\tif addWebSiteIsDefault {\n\t\t\t\t\tlocalConfig.DefaultWebsite = addWebSiteAlias\n\t\t\t\t}\n\t\t\t\td := websiteConfig{Alias: addWebSiteAlias, HOST: url, Key: string(serverPubKey)}\n\n\t\t\t\tlocalConfig.Websites = append(localConfig.Websites, d)\n\t\t\t\tviper.Set(\"config\", localConfig)\n\t\t\t\terr := viper.WriteConfig()\n\t\t\t\tcommon.Assert(err)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"login fail\")\n\t\t\t}\n\t\t},\n\t}\n)\n\nfunc init() {\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSiteAlias, \"alias\", \"a\", \"\", \"blog alias\")\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSiteUser, \"user\", \"u\", \"\", \"blog administrator account name\")\n\taddWebSiteCmd.PersistentFlags().StringVarP(&addWebSitePassword, \"password\", \"p\", \"\", \"blog administrator account password\")\n\taddWebSiteCmd.PersistentFlags().BoolVarP(&addWebSiteIsDefault, \"defalut\", \"d\", false, \"set as default blog\")\n\n\tconfigCmd.AddCommand(addWebSiteCmd)\n}\n\nfunc initConfig() {\n\thome, err := homedir.Dir()\n\tcommon.Assert(err)\n\n\tviper.AddConfigPath(home)\n\tviper.SetConfigType(\"yaml\")\n\tviper.SetConfigName(\".beaker\")\n\tviper.SafeWriteConfig()\n\n\terr = viper.ReadInConfig()\n\tcommon.Assert(err)\n\n\terr = viper.UnmarshalKey(\"config\", &localConfig)\n\tcommon.Assert(err)\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/kleister\/kleister-api\/config\"\n\t\"github.com\/kleister\/kleister-api\/router\"\n\t\"github.com\/kleister\/kleister-api\/shared\/s3client\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ Server provides the sub-command to start the API server.\nfunc Server() cli.Command {\n\treturn cli.Command{\n\t\tName: \"server\",\n\t\tUsage: \"Start the Kleister API\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-driver\",\n\t\t\t\tValue: \"mysql\",\n\t\t\t\tUsage: \"Database driver selection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_DRIVER\",\n\t\t\t\tDestination: &config.Database.Driver,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-name\",\n\t\t\t\tValue: \"kleister\",\n\t\t\t\tUsage: \"Name for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_NAME\",\n\t\t\t\tDestination: &config.Database.Name,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-username\",\n\t\t\t\tValue: \"root\",\n\t\t\t\tUsage: \"Username for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_USERNAME\",\n\t\t\t\tDestination: &config.Database.Username,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-password\",\n\t\t\t\tValue: \"root\",\n\t\t\t\tUsage: \"Password for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_PASSWORD\",\n\t\t\t\tDestination: &config.Database.Password,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-host\",\n\t\t\t\tValue: \"localhost:3306\",\n\t\t\t\tUsage: \"Host for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_HOST\",\n\t\t\t\tDestination: &config.Database.Host,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"host\",\n\t\t\t\tValue: \"http:\/\/localhost:8080\",\n\t\t\t\tUsage: \"External access to server\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_HOST\",\n\t\t\t\tDestination: &config.Server.Host,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"addr\",\n\t\t\t\tValue: \":8080\",\n\t\t\t\tUsage: \"Address to bind the server\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_ADDR\",\n\t\t\t\tDestination: &config.Server.Addr,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"cert\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Path to SSL cert\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_CERT\",\n\t\t\t\tDestination: &config.Server.Cert,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Path to SSL key\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_KEY\",\n\t\t\t\tDestination: &config.Server.Key,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"root\",\n\t\t\t\tValue: \"\/\",\n\t\t\t\tUsage: \"Root folder of the app\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_ROOT\",\n\t\t\t\tDestination: &config.Server.Root,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"storage\",\n\t\t\t\tValue: \"storage\/\",\n\t\t\t\tUsage: \"Folder for storing uploads\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_STORAGE\",\n\t\t\t\tDestination: &config.Server.Storage,\n\t\t\t},\n\t\t\tcli.DurationFlag{\n\t\t\t\tName: \"expire\",\n\t\t\t\tValue: time.Hour * 24,\n\t\t\t\tUsage: \"Session expire duration\",\n\t\t\t\tEnvVar: \"KLEISTER_SESSION_EXPIRE\",\n\t\t\t\tDestination: &config.Session.Expire,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"s3-enabled\",\n\t\t\t\tUsage: \"Enable S3 uploads\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ENABLED\",\n\t\t\t\tDestination: &config.S3.Enabled,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-endpoint\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 API endpoint\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ENDPOINT\",\n\t\t\t\tDestination: &config.S3.Endpoint,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-bucket\",\n\t\t\t\tValue: \"kleister\",\n\t\t\t\tUsage: \"S3 bucket name\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_BUCKET\",\n\t\t\t\tDestination: &config.S3.Bucket,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-region\",\n\t\t\t\tValue: \"us-east-1\",\n\t\t\t\tUsage: \"S3 region name\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_REGION\",\n\t\t\t\tDestination: &config.S3.Region,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-access\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 public key\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ACCESS_KEY\",\n\t\t\t\tDestination: &config.S3.Access,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-secret\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 secret key\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_SECRET_KEY\",\n\t\t\t\tDestination: &config.S3.Secret,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"s3-path-style\",\n\t\t\t\tUsage: \"S3 path style\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_PATH_STYLE\",\n\t\t\t\tDestination: &config.S3.PathStyle,\n\t\t\t},\n\t\t},\n\t\tBefore: func(c *cli.Context) error {\n\t\t\tif config.S3.Enabled {\n\t\t\t\t_, err := s3client.New().List()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tif config.Debug {\n\t\t\t\t\t\treturn fmt.Errorf(\"Failed to connect to S3. %s\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"Failed to connect to S3.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\tlogrus.Infof(\"Starting the API on %s\", config.Server.Addr)\n\n\t\t\tif config.Server.Cert != \"\" && config.Server.Key != \"\" {\n\t\t\t\tlogrus.Fatal(\n\t\t\t\t\thttp.ListenAndServeTLS(\n\t\t\t\t\t\tconfig.Server.Addr,\n\t\t\t\t\t\tconfig.Server.Cert,\n\t\t\t\t\t\tconfig.Server.Key,\n\t\t\t\t\t\trouter.Load(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tlogrus.Fatal(\n\t\t\t\t\thttp.ListenAndServe(\n\t\t\t\t\t\tconfig.Server.Addr,\n\t\t\t\t\t\trouter.Load(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t}\n}\nAlways print useful error for s3 connectionpackage cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/kleister\/kleister-api\/config\"\n\t\"github.com\/kleister\/kleister-api\/router\"\n\t\"github.com\/kleister\/kleister-api\/shared\/s3client\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ Server provides the sub-command to start the API server.\nfunc Server() cli.Command {\n\treturn cli.Command{\n\t\tName: \"server\",\n\t\tUsage: \"Start the Kleister API\",\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-driver\",\n\t\t\t\tValue: \"mysql\",\n\t\t\t\tUsage: \"Database driver selection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_DRIVER\",\n\t\t\t\tDestination: &config.Database.Driver,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-name\",\n\t\t\t\tValue: \"kleister\",\n\t\t\t\tUsage: \"Name for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_NAME\",\n\t\t\t\tDestination: &config.Database.Name,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-username\",\n\t\t\t\tValue: \"root\",\n\t\t\t\tUsage: \"Username for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_USERNAME\",\n\t\t\t\tDestination: &config.Database.Username,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-password\",\n\t\t\t\tValue: \"root\",\n\t\t\t\tUsage: \"Password for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_PASSWORD\",\n\t\t\t\tDestination: &config.Database.Password,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"db-host\",\n\t\t\t\tValue: \"localhost:3306\",\n\t\t\t\tUsage: \"Host for database connection\",\n\t\t\t\tEnvVar: \"KLEISTER_DB_HOST\",\n\t\t\t\tDestination: &config.Database.Host,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"host\",\n\t\t\t\tValue: \"http:\/\/localhost:8080\",\n\t\t\t\tUsage: \"External access to server\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_HOST\",\n\t\t\t\tDestination: &config.Server.Host,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"addr\",\n\t\t\t\tValue: \":8080\",\n\t\t\t\tUsage: \"Address to bind the server\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_ADDR\",\n\t\t\t\tDestination: &config.Server.Addr,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"cert\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Path to SSL cert\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_CERT\",\n\t\t\t\tDestination: &config.Server.Cert,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"key\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Path to SSL key\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_KEY\",\n\t\t\t\tDestination: &config.Server.Key,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"root\",\n\t\t\t\tValue: \"\/\",\n\t\t\t\tUsage: \"Root folder of the app\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_ROOT\",\n\t\t\t\tDestination: &config.Server.Root,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"storage\",\n\t\t\t\tValue: \"storage\/\",\n\t\t\t\tUsage: \"Folder for storing uploads\",\n\t\t\t\tEnvVar: \"KLEISTER_SERVER_STORAGE\",\n\t\t\t\tDestination: &config.Server.Storage,\n\t\t\t},\n\t\t\tcli.DurationFlag{\n\t\t\t\tName: \"expire\",\n\t\t\t\tValue: time.Hour * 24,\n\t\t\t\tUsage: \"Session expire duration\",\n\t\t\t\tEnvVar: \"KLEISTER_SESSION_EXPIRE\",\n\t\t\t\tDestination: &config.Session.Expire,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"s3-enabled\",\n\t\t\t\tUsage: \"Enable S3 uploads\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ENABLED\",\n\t\t\t\tDestination: &config.S3.Enabled,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-endpoint\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 API endpoint\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ENDPOINT\",\n\t\t\t\tDestination: &config.S3.Endpoint,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-bucket\",\n\t\t\t\tValue: \"kleister\",\n\t\t\t\tUsage: \"S3 bucket name\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_BUCKET\",\n\t\t\t\tDestination: &config.S3.Bucket,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-region\",\n\t\t\t\tValue: \"us-east-1\",\n\t\t\t\tUsage: \"S3 region name\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_REGION\",\n\t\t\t\tDestination: &config.S3.Region,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-access\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 public key\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_ACCESS_KEY\",\n\t\t\t\tDestination: &config.S3.Access,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"s3-secret\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"S3 secret key\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_SECRET_KEY\",\n\t\t\t\tDestination: &config.S3.Secret,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"s3-path-style\",\n\t\t\t\tUsage: \"S3 path style\",\n\t\t\t\tEnvVar: \"KLEISTER_S3_PATH_STYLE\",\n\t\t\t\tDestination: &config.S3.PathStyle,\n\t\t\t},\n\t\t},\n\t\tBefore: func(c *cli.Context) error {\n\t\t\tif config.S3.Enabled {\n\t\t\t\t_, err := s3client.New().List()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Failed to connect to S3. %s\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\tlogrus.Infof(\"Starting the API on %s\", config.Server.Addr)\n\n\t\t\tif config.Server.Cert != \"\" && config.Server.Key != \"\" {\n\t\t\t\tlogrus.Fatal(\n\t\t\t\t\thttp.ListenAndServeTLS(\n\t\t\t\t\t\tconfig.Server.Addr,\n\t\t\t\t\t\tconfig.Server.Cert,\n\t\t\t\t\t\tconfig.Server.Key,\n\t\t\t\t\t\trouter.Load(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tlogrus.Fatal(\n\t\t\t\t\thttp.ListenAndServe(\n\t\t\t\t\t\tconfig.Server.Addr,\n\t\t\t\t\t\trouter.Load(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\tgolog \"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\/atomic\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/NYTimes\/gziphandler\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/stscreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3iface\"\n\t\"github.com\/go-redis\/redis\/v8\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/namsral\/flag\"\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"golang.org\/x\/net\/http2\"\n\t\"golang.org\/x\/net\/http2\/h2c\"\n\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/buffer\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/cache\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/config\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/handler\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/log\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/metrics\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/storage\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/tile\"\n)\n\nconst (\n\t\/\/ The time to wait after responding \/ready with non-200 before starting to shut down the HTTP server\n\tgracefulShutdownSleep = 20 * time.Second\n\t\/\/ The time to wait for the in-flight HTTP requests to complete before exiting\n\tgracefulShutdownTimeout = 5 * time.Second\n)\n\nfunc main() {\n\tvar listen, healthcheck, readyCheck string\n\tvar poolNumEntries, poolEntrySize int\n\tvar metricsStatsdAddr, metricsStatsdPrefix string\n\tvar redisAddr string\n\n\thc := config.HandlerConfig{}\n\n\tsystemLogger := golog.New(os.Stdout, \"\", golog.LstdFlags|golog.LUTC|golog.Lmicroseconds)\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\t\/\/ NOTE: if there are legitimate cases when this can fail, we\n\t\t\/\/ can leave off the hostname in the logger.\n\t\t\/\/ But for now we prefer to get notified of it.\n\t\tsystemLogger.Fatalf(\"ERROR: Cannot find hostname to use for logger\")\n\t}\n\t\/\/ use this logger everywhere.\n\tlogger := log.NewJsonLogger(systemLogger, hostname)\n\n\tf := flag.NewFlagSetWithEnvPrefix(os.Args[0], \"TAPALCATL\", 0)\n\tf.Var(&hc, \"handler\",\n\t\t`JSON object defining how request patterns will be handled.\n\t Aws { Object present when Aws-wide configuration is needed, eg session config.\n Region string Name of aws region\n }\n Storage { key -> storage definition mapping\n storage name string -> {\n Type string storage type, can be \"s3\" or \"file\n MetatileSize int Number of 256px tiles in each dimension of the metatile.\n MetatileMaxDetailZoom int Maximum level of detail available in the metatiles.\n TileSize int Size of tile in 256px tile units.\n\n (s3 storage)\n Layer string Name of layer to use in this bucket. Only relevant for s3.\n Bucket string Name of S3 bucket to fetch from.\n KeyPattern string Pattern to fill with variables from the main pattern to make the S3 key.\n Healthcheck string Name of S3 key to use when querying health of S3 system.\n\n (file storage)\n BaseDir string Base directory to look for files under.\n Healthcheck string Path to a file (inside BaseDir) when querying health of system.\n }\n }\n Pattern { request pattern -> storage configuration mapping\n request pattern string -> {\n storage string Name of storage defintion to use\n list of optional storage configuration to use:\n defaultPrefix is required for s3, others are optional overrides of relevant definition\n DefaultPrefix string DefaultPrefix to use in this bucket.\n }\n }\n Mime { extension -> content-type used in http response\n }\n`)\n\tf.StringVar(&listen, \"listen\", \":8080\", \"interface and port to listen on\")\n\tf.String(\"config\", \"\", \"Config file to read values from.\")\n\tf.StringVar(&healthcheck, \"healthcheck\", \"\", \"A URL path for healthcheck. Intended for use by load balancer health checks.\")\n\tf.StringVar(&readyCheck, \"readycheck\", \"\", \"A URL path for readiness check. Intended for use by Kubernetes readinessProbe.\")\n\n\tf.IntVar(&poolNumEntries, \"poolnumentries\", 0, \"Number of buffers to pool.\")\n\tf.IntVar(&poolEntrySize, \"poolentrysize\", 0, \"Size of each buffer in pool.\")\n\n\tf.StringVar(&metricsStatsdAddr, \"metrics-statsd-addr\", \"\", \"host:port to use to send data to statsd\")\n\tf.StringVar(&metricsStatsdPrefix, \"metrics-statsd-prefix\", \"\", \"prefix to prepend to metrics\")\n\n\tf.StringVar(&redisAddr, \"redis-addr\", \"\", \"Redis connection address for caching purposes\")\n\n\terr = f.Parse(os.Args[1:])\n\tif err == flag.ErrHelp {\n\t\treturn\n\t} else if err != nil {\n\t\tlogFatalCfgErr(logger, \"Unable to parse input command line, environment or config: %s\", err.Error())\n\t}\n\n\tif len(hc.Pattern) == 0 {\n\t\tlogFatalCfgErr(logger, \"You must provide at least one pattern.\")\n\t}\n\tif len(hc.Storage) == 0 {\n\t\tlogFatalCfgErr(logger, \"You must provide at least one storage.\")\n\t}\n\n\tr := mux.NewRouter()\n\n\t\/\/ buffer manager shared by all handlers\n\tvar bufferManager buffer.BufferManager\n\n\tif poolNumEntries > 0 && poolEntrySize > 0 {\n\t\tbufferManager = bpool.NewSizedBufferPool(poolNumEntries, poolEntrySize)\n\t} else {\n\t\tbufferManager = &buffer.OnDemandBufferManager{}\n\t}\n\n\tvar tileCache cache.Cache\n\tif redisAddr != \"\" {\n\t\tclient := redis.NewClient(&redis.Options{\n\t\t\tAddr: redisAddr,\n\t\t})\n\t\ttileCache = cache.NewRedisCache(client)\n\t\tlogger.Info(\"Configured Redis to connect to %s\", redisAddr)\n\t} else {\n\t\ttileCache = cache.NilCache\n\t}\n\n\t\/\/ metrics writer configuration\n\tvar mw metrics.MetricsWriter\n\tif metricsStatsdAddr != \"\" {\n\t\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", metricsStatsdAddr)\n\t\tif err != nil {\n\t\t\tlogFatalCfgErr(logger, \"Invalid metricsstatsdaddr %s: %s\", metricsStatsdAddr, err)\n\t\t}\n\t\tmw = metrics.NewStatsdMetricsWriter(udpAddr, metricsStatsdPrefix, logger)\n\t} else {\n\t\tmw = &metrics.NilMetricsWriter{}\n\t}\n\n\t\/\/ set if we have s3 storage configured, and shared across all s3 sessions\n\tvar awsSession *session.Session\n\n\tfor sName, sd := range hc.Storage {\n\t\tt := sd.Type\n\t\tswitch t {\n\t\tcase \"s3\":\n\t\tcase \"file\":\n\t\tdefault:\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage type for storage %s: %s\", sName, t)\n\t\t}\n\t}\n\n\t\/\/ keep track of the storages so we can healthcheck them\n\t\/\/ we only need to check unique type\/healthcheck configurations\n\thealthCheckStorages := make(map[config.HealthCheckConfig]storage.Storage)\n\n\t\/\/ create the storage implementations and handler routes for patterns\n\tvar stg storage.Storage\n\tfor reqPattern, rhc := range hc.Pattern {\n\n\t\tstorageDefinitionName := rhc.Storage\n\t\tsd, ok := hc.Storage[storageDefinitionName]\n\t\tif !ok {\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage definition: %s\", storageDefinitionName)\n\t\t}\n\t\tmetatileSize := sd.MetatileSize\n\t\tif rhc.MetatileSize != nil {\n\t\t\tmetatileSize = *rhc.MetatileSize\n\t\t}\n\t\tif !tile.IsPowerOfTwo(metatileSize) {\n\t\t\tlogFatalCfgErr(logger, \"Metatile size must be power of two, but %d is not\", metatileSize)\n\t\t}\n\n\t\ttileSize := 1\n\t\tif sd.TileSize != nil {\n\t\t\ttileSize = *sd.TileSize\n\t\t}\n\t\tif rhc.TileSize != nil {\n\t\t\ttileSize = *rhc.TileSize\n\t\t}\n\t\tif !tile.IsPowerOfTwo(tileSize) {\n\t\t\tlogFatalCfgErr(logger, \"Tile size must be power of two, but %d is not\", tileSize)\n\t\t}\n\n\t\tmetatileMaxDetailZoom := 0\n\t\tif sd.MetatileMaxDetailZoom != nil {\n\t\t\tmetatileMaxDetailZoom = *sd.MetatileMaxDetailZoom\n\t\t}\n\n\t\tlayer := sd.Layer\n\t\tif rhc.Layer != nil {\n\t\t\tlayer = *rhc.Layer\n\t\t}\n\n\t\tvar healthcheck string\n\n\t\tswitch sd.Type {\n\t\tcase \"s3\":\n\t\t\tif rhc.DefaultPrefix == nil {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 configuration requires defaultPrefix\")\n\t\t\t}\n\t\t\tprefix := *rhc.DefaultPrefix\n\n\t\t\tif awsSession == nil {\n\t\t\t\tif hc.Aws != nil && hc.Aws.Region != nil {\n\t\t\t\t\tawsSession, err = session.NewSessionWithOptions(session.Options{\n\t\t\t\t\t\tConfig: aws.Config{Region: hc.Aws.Region},\n\t\t\t\t\t\tSharedConfigState: session.SharedConfigEnable,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tawsSession, err = session.NewSessionWithOptions(session.Options{\n\t\t\t\t\t\tSharedConfigState: session.SharedConfigEnable,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlogFatalCfgErr(logger, \"Unable to set up AWS session: %s\", err.Error())\n\t\t\t}\n\n\t\t\tvar s3Client s3iface.S3API\n\t\t\tif hc.Aws.Role != nil {\n\t\t\t\tcreds := stscreds.NewCredentials(awsSession, *hc.Aws.Role)\n\t\t\t\ts3Client = s3.New(awsSession, &aws.Config{Credentials: creds})\n\t\t\t} else {\n\t\t\t\ts3Client = s3.New(awsSession)\n\t\t\t}\n\n\t\t\tkeyPattern := sd.KeyPattern\n\t\t\tif rhc.KeyPattern != nil {\n\t\t\t\tkeyPattern = *rhc.KeyPattern\n\t\t\t}\n\n\t\t\tif sd.Bucket == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 storage missing bucket configuration\")\n\t\t\t}\n\t\t\tif keyPattern == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 storage missing key pattern\")\n\t\t\t}\n\n\t\t\tif sd.Healthcheck == \"\" {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Missing healthcheck for storage s3\")\n\t\t\t}\n\n\t\t\thealthcheck = sd.Healthcheck\n\t\t\tstg = storage.NewS3Storage(s3Client, tileCache, sd.Bucket, keyPattern, prefix, layer, healthcheck)\n\n\t\tcase \"file\":\n\t\t\tif sd.BaseDir == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"File storage missing base dir\")\n\t\t\t}\n\n\t\t\tif sd.Healthcheck == \"\" {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Missing healthcheck for storage file\")\n\t\t\t}\n\n\t\t\thealthcheck = sd.Healthcheck\n\t\t\tstg = storage.NewFileStorage(sd.BaseDir, tileCache, layer, healthcheck)\n\n\t\tdefault:\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage type: %s\", sd.Type)\n\t\t}\n\n\t\tif healthcheck != \"\" {\n\t\t\tstorageErr := stg.HealthCheck()\n\t\t\tif storageErr != nil {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Healthcheck failed on storage: %s\", storageErr)\n\t\t\t}\n\n\t\t\thcc := config.HealthCheckConfig{\n\t\t\t\tType: sd.Type,\n\t\t\t\tHealthcheck: healthcheck,\n\t\t\t}\n\n\t\t\tif _, ok := healthCheckStorages[hcc]; !ok {\n\t\t\t\thealthCheckStorages[hcc] = stg\n\t\t\t}\n\t\t}\n\n\t\tif rhc.Type == nil || *rhc.Type == \"metatile\" {\n\t\t\tparser := &handler.MetatileMuxParser{\n\t\t\t\tMimeMap: hc.Mime,\n\t\t\t}\n\n\t\t\th := handler.MetatileHandler(parser, metatileSize, tileSize, metatileMaxDetailZoom, stg, bufferManager, mw, logger, tileCache)\n\t\t\tgzipped := gziphandler.GzipHandler(h)\n\n\t\t\tr.Handle(reqPattern, gzipped).Methods(\"GET\")\n\n\t\t} else if rhc.Type != nil && *rhc.Type == \"tilejson\" {\n\t\t\tparser := &handler.TileJsonParser{}\n\t\t\th := handler.TileJsonHandler(parser, stg, mw, logger)\n\t\t\tgzipped := gziphandler.GzipHandler(h)\n\t\t\tr.Handle(reqPattern, gzipped).Methods(\"GET\")\n\t\t} else {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Invalid route handler type: %s\\n\", *rhc.Type)\n\t\t}\n\n\t}\n\n\tif hc.Preview != nil {\n\t\tif hc.Preview.Path == nil || hc.Preview.Template == nil {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Preview must have path and template specified\")\n\t\t}\n\n\t\tvar templateData map[string]interface{}\n\t\tif hc.Preview.Data != nil {\n\t\t\ttemplateData = *hc.Preview.Data\n\t\t}\n\n\t\tfileHandler, err := handler.NewFileHandler(*hc.Preview.Template, templateData)\n\t\tif err != nil {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Couldn't load preview template: %+v\", err)\n\t\t}\n\n\t\tr.Handle(*hc.Preview.Path, fileHandler).Methods(\"GET\")\n\t}\n\n\tif len(healthcheck) > 0 {\n\t\tstoragesToCheck := make([]storage.Storage, len(healthCheckStorages))\n\t\ti := 0\n\t\tfor _, s := range healthCheckStorages {\n\t\t\tstoragesToCheck[i] = s\n\t\t\ti++\n\t\t}\n\t\thc := handler.HealthCheckHandler(storagesToCheck, logger)\n\t\tr.Handle(healthcheck, hc).Methods(\"GET\")\n\t}\n\n\t\/\/ Readiness probe for graceful shutdown support\n\treadinessResponseCode := uint32(http.StatusOK)\n\tif len(readyCheck) > 0 {\n\t\tr.HandleFunc(readyCheck, func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(int(atomic.LoadUint32(&readinessResponseCode)))\n\t\t})\n\t}\n\n\tcorsHandler := handlers.CORS()(r)\n\tloggingHandler := log.LoggingMiddleware(logger)(corsHandler)\n\n\tlogger.Info(\"Server started and listening on %s\", listen)\n\n\t\/\/ Support for upgrading an http\/1.1 connection to http\/2\n\t\/\/ See https:\/\/github.com\/thrawn01\/h2c-golang-example\n\thttp2Server := &http2.Server{}\n\tserver := &http.Server{\n\t\tAddr: listen,\n\t\tHandler: h2c.NewHandler(loggingHandler, http2Server),\n\t}\n\n\t\/\/ Code to handle shutdown gracefully\n\tshutdownChan := make(chan struct{})\n\tgo func() {\n\t\tdefer close(shutdownChan)\n\n\t\t\/\/ Wait for SIGTERM to come in\n\t\tsignals := make(chan os.Signal, 1)\n\t\tsignal.Notify(signals, syscall.SIGTERM)\n\t\t<-signals\n\n\t\tlogger.Info(\"SIGTERM received. Starting graceful shutdown.\")\n\n\t\t\/\/ Start failing readiness probes\n\t\tatomic.StoreUint32(&readinessResponseCode, http.StatusInternalServerError)\n\t\t\/\/ Wait for upstream clients\n\t\ttime.Sleep(gracefulShutdownSleep)\n\t\t\/\/ Begin shutdown of in-flight requests\n\t\tshutdownCtx, shutdownCtxCancel := context.WithTimeout(context.Background(), gracefulShutdownTimeout)\n\t\tif err := server.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogger.Info(\"Error waiting for server shutdown: %+v\", err)\n\t\t}\n\t\tshutdownCtxCancel()\n\t}()\n\n\tlogger.Info(\"Service started\")\n\tif err := server.ListenAndServe(); err != nil {\n\t\tlogger.Info(\"Couldn't start HTTP server: %+v\", err)\n\t}\n\t<-shutdownChan\n}\n\nfunc logFatalCfgErr(logger log.JsonLogger, msg string, xs ...interface{}) {\n\tlogger.Error(log.LogCategory_ConfigError, msg, xs...)\n\tos.Exit(1)\n}\nPing redis at startuppackage main\n\nimport (\n\t\"context\"\n\tgolog \"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\/atomic\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/NYTimes\/gziphandler\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/stscreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3iface\"\n\t\"github.com\/go-redis\/redis\/v8\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/namsral\/flag\"\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"golang.org\/x\/net\/http2\"\n\t\"golang.org\/x\/net\/http2\/h2c\"\n\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/buffer\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/cache\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/config\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/handler\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/log\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/metrics\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/storage\"\n\t\"github.com\/tilezen\/tapalcatl\/pkg\/tile\"\n)\n\nconst (\n\t\/\/ The time to wait after responding \/ready with non-200 before starting to shut down the HTTP server\n\tgracefulShutdownSleep = 20 * time.Second\n\t\/\/ The time to wait for the in-flight HTTP requests to complete before exiting\n\tgracefulShutdownTimeout = 5 * time.Second\n)\n\nfunc main() {\n\tvar listen, healthcheck, readyCheck string\n\tvar poolNumEntries, poolEntrySize int\n\tvar metricsStatsdAddr, metricsStatsdPrefix string\n\tvar redisAddr string\n\n\thc := config.HandlerConfig{}\n\n\tsystemLogger := golog.New(os.Stdout, \"\", golog.LstdFlags|golog.LUTC|golog.Lmicroseconds)\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\t\/\/ NOTE: if there are legitimate cases when this can fail, we\n\t\t\/\/ can leave off the hostname in the logger.\n\t\t\/\/ But for now we prefer to get notified of it.\n\t\tsystemLogger.Fatalf(\"ERROR: Cannot find hostname to use for logger\")\n\t}\n\t\/\/ use this logger everywhere.\n\tlogger := log.NewJsonLogger(systemLogger, hostname)\n\n\tf := flag.NewFlagSetWithEnvPrefix(os.Args[0], \"TAPALCATL\", 0)\n\tf.Var(&hc, \"handler\",\n\t\t`JSON object defining how request patterns will be handled.\n\t Aws { Object present when Aws-wide configuration is needed, eg session config.\n Region string Name of aws region\n }\n Storage { key -> storage definition mapping\n storage name string -> {\n Type string storage type, can be \"s3\" or \"file\n MetatileSize int Number of 256px tiles in each dimension of the metatile.\n MetatileMaxDetailZoom int Maximum level of detail available in the metatiles.\n TileSize int Size of tile in 256px tile units.\n\n (s3 storage)\n Layer string Name of layer to use in this bucket. Only relevant for s3.\n Bucket string Name of S3 bucket to fetch from.\n KeyPattern string Pattern to fill with variables from the main pattern to make the S3 key.\n Healthcheck string Name of S3 key to use when querying health of S3 system.\n\n (file storage)\n BaseDir string Base directory to look for files under.\n Healthcheck string Path to a file (inside BaseDir) when querying health of system.\n }\n }\n Pattern { request pattern -> storage configuration mapping\n request pattern string -> {\n storage string Name of storage defintion to use\n list of optional storage configuration to use:\n defaultPrefix is required for s3, others are optional overrides of relevant definition\n DefaultPrefix string DefaultPrefix to use in this bucket.\n }\n }\n Mime { extension -> content-type used in http response\n }\n`)\n\tf.StringVar(&listen, \"listen\", \":8080\", \"interface and port to listen on\")\n\tf.String(\"config\", \"\", \"Config file to read values from.\")\n\tf.StringVar(&healthcheck, \"healthcheck\", \"\", \"A URL path for healthcheck. Intended for use by load balancer health checks.\")\n\tf.StringVar(&readyCheck, \"readycheck\", \"\", \"A URL path for readiness check. Intended for use by Kubernetes readinessProbe.\")\n\n\tf.IntVar(&poolNumEntries, \"poolnumentries\", 0, \"Number of buffers to pool.\")\n\tf.IntVar(&poolEntrySize, \"poolentrysize\", 0, \"Size of each buffer in pool.\")\n\n\tf.StringVar(&metricsStatsdAddr, \"metrics-statsd-addr\", \"\", \"host:port to use to send data to statsd\")\n\tf.StringVar(&metricsStatsdPrefix, \"metrics-statsd-prefix\", \"\", \"prefix to prepend to metrics\")\n\n\tf.StringVar(&redisAddr, \"redis-addr\", \"\", \"Redis connection address for caching purposes\")\n\n\terr = f.Parse(os.Args[1:])\n\tif err == flag.ErrHelp {\n\t\treturn\n\t} else if err != nil {\n\t\tlogFatalCfgErr(logger, \"Unable to parse input command line, environment or config: %s\", err.Error())\n\t}\n\n\tif len(hc.Pattern) == 0 {\n\t\tlogFatalCfgErr(logger, \"You must provide at least one pattern.\")\n\t}\n\tif len(hc.Storage) == 0 {\n\t\tlogFatalCfgErr(logger, \"You must provide at least one storage.\")\n\t}\n\n\tr := mux.NewRouter()\n\n\t\/\/ buffer manager shared by all handlers\n\tvar bufferManager buffer.BufferManager\n\n\tif poolNumEntries > 0 && poolEntrySize > 0 {\n\t\tbufferManager = bpool.NewSizedBufferPool(poolNumEntries, poolEntrySize)\n\t} else {\n\t\tbufferManager = &buffer.OnDemandBufferManager{}\n\t}\n\n\tvar tileCache cache.Cache\n\tif redisAddr != \"\" {\n\t\tclient := redis.NewClient(&redis.Options{\n\t\t\tAddr: redisAddr,\n\t\t})\n\n\t\t\/\/ Ping Redis to make sure it's available before starting.\n\t\t\/\/ Using a longer timeout to give time for network connections to spin up, etc.\n\t\ttimeoutCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\t\tcancel()\n\t\tif err := client.Ping(timeoutCtx).Err(); err != nil {\n\t\t\tlogFatalCfgErr(logger, \"Couldn't reach Redis service at %s: %s\", redisAddr, err.Error())\n\t\t}\n\n\t\tlogger.Info(\"Redis connected to %s\", redisAddr)\n\t\ttileCache = cache.NewRedisCache(client)\n\t} else {\n\t\ttileCache = cache.NilCache\n\t}\n\n\t\/\/ metrics writer configuration\n\tvar mw metrics.MetricsWriter\n\tif metricsStatsdAddr != \"\" {\n\t\tudpAddr, err := net.ResolveUDPAddr(\"udp4\", metricsStatsdAddr)\n\t\tif err != nil {\n\t\t\tlogFatalCfgErr(logger, \"Invalid metricsstatsdaddr %s: %s\", metricsStatsdAddr, err)\n\t\t}\n\t\tmw = metrics.NewStatsdMetricsWriter(udpAddr, metricsStatsdPrefix, logger)\n\t} else {\n\t\tmw = &metrics.NilMetricsWriter{}\n\t}\n\n\t\/\/ set if we have s3 storage configured, and shared across all s3 sessions\n\tvar awsSession *session.Session\n\n\tfor sName, sd := range hc.Storage {\n\t\tt := sd.Type\n\t\tswitch t {\n\t\tcase \"s3\":\n\t\tcase \"file\":\n\t\tdefault:\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage type for storage %s: %s\", sName, t)\n\t\t}\n\t}\n\n\t\/\/ keep track of the storages so we can healthcheck them\n\t\/\/ we only need to check unique type\/healthcheck configurations\n\thealthCheckStorages := make(map[config.HealthCheckConfig]storage.Storage)\n\n\t\/\/ create the storage implementations and handler routes for patterns\n\tvar stg storage.Storage\n\tfor reqPattern, rhc := range hc.Pattern {\n\n\t\tstorageDefinitionName := rhc.Storage\n\t\tsd, ok := hc.Storage[storageDefinitionName]\n\t\tif !ok {\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage definition: %s\", storageDefinitionName)\n\t\t}\n\t\tmetatileSize := sd.MetatileSize\n\t\tif rhc.MetatileSize != nil {\n\t\t\tmetatileSize = *rhc.MetatileSize\n\t\t}\n\t\tif !tile.IsPowerOfTwo(metatileSize) {\n\t\t\tlogFatalCfgErr(logger, \"Metatile size must be power of two, but %d is not\", metatileSize)\n\t\t}\n\n\t\ttileSize := 1\n\t\tif sd.TileSize != nil {\n\t\t\ttileSize = *sd.TileSize\n\t\t}\n\t\tif rhc.TileSize != nil {\n\t\t\ttileSize = *rhc.TileSize\n\t\t}\n\t\tif !tile.IsPowerOfTwo(tileSize) {\n\t\t\tlogFatalCfgErr(logger, \"Tile size must be power of two, but %d is not\", tileSize)\n\t\t}\n\n\t\tmetatileMaxDetailZoom := 0\n\t\tif sd.MetatileMaxDetailZoom != nil {\n\t\t\tmetatileMaxDetailZoom = *sd.MetatileMaxDetailZoom\n\t\t}\n\n\t\tlayer := sd.Layer\n\t\tif rhc.Layer != nil {\n\t\t\tlayer = *rhc.Layer\n\t\t}\n\n\t\tvar healthcheck string\n\n\t\tswitch sd.Type {\n\t\tcase \"s3\":\n\t\t\tif rhc.DefaultPrefix == nil {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 configuration requires defaultPrefix\")\n\t\t\t}\n\t\t\tprefix := *rhc.DefaultPrefix\n\n\t\t\tif awsSession == nil {\n\t\t\t\tif hc.Aws != nil && hc.Aws.Region != nil {\n\t\t\t\t\tawsSession, err = session.NewSessionWithOptions(session.Options{\n\t\t\t\t\t\tConfig: aws.Config{Region: hc.Aws.Region},\n\t\t\t\t\t\tSharedConfigState: session.SharedConfigEnable,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tawsSession, err = session.NewSessionWithOptions(session.Options{\n\t\t\t\t\t\tSharedConfigState: session.SharedConfigEnable,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlogFatalCfgErr(logger, \"Unable to set up AWS session: %s\", err.Error())\n\t\t\t}\n\n\t\t\tvar s3Client s3iface.S3API\n\t\t\tif hc.Aws.Role != nil {\n\t\t\t\tcreds := stscreds.NewCredentials(awsSession, *hc.Aws.Role)\n\t\t\t\ts3Client = s3.New(awsSession, &aws.Config{Credentials: creds})\n\t\t\t} else {\n\t\t\t\ts3Client = s3.New(awsSession)\n\t\t\t}\n\n\t\t\tkeyPattern := sd.KeyPattern\n\t\t\tif rhc.KeyPattern != nil {\n\t\t\t\tkeyPattern = *rhc.KeyPattern\n\t\t\t}\n\n\t\t\tif sd.Bucket == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 storage missing bucket configuration\")\n\t\t\t}\n\t\t\tif keyPattern == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"S3 storage missing key pattern\")\n\t\t\t}\n\n\t\t\tif sd.Healthcheck == \"\" {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Missing healthcheck for storage s3\")\n\t\t\t}\n\n\t\t\thealthcheck = sd.Healthcheck\n\t\t\tstg = storage.NewS3Storage(s3Client, tileCache, sd.Bucket, keyPattern, prefix, layer, healthcheck)\n\n\t\tcase \"file\":\n\t\t\tif sd.BaseDir == \"\" {\n\t\t\t\tlogFatalCfgErr(logger, \"File storage missing base dir\")\n\t\t\t}\n\n\t\t\tif sd.Healthcheck == \"\" {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Missing healthcheck for storage file\")\n\t\t\t}\n\n\t\t\thealthcheck = sd.Healthcheck\n\t\t\tstg = storage.NewFileStorage(sd.BaseDir, tileCache, layer, healthcheck)\n\n\t\tdefault:\n\t\t\tlogFatalCfgErr(logger, \"Unknown storage type: %s\", sd.Type)\n\t\t}\n\n\t\tif healthcheck != \"\" {\n\t\t\tstorageErr := stg.HealthCheck()\n\t\t\tif storageErr != nil {\n\t\t\t\tlogger.Warning(log.LogCategory_ConfigError, \"Healthcheck failed on storage: %s\", storageErr)\n\t\t\t}\n\n\t\t\thcc := config.HealthCheckConfig{\n\t\t\t\tType: sd.Type,\n\t\t\t\tHealthcheck: healthcheck,\n\t\t\t}\n\n\t\t\tif _, ok := healthCheckStorages[hcc]; !ok {\n\t\t\t\thealthCheckStorages[hcc] = stg\n\t\t\t}\n\t\t}\n\n\t\tif rhc.Type == nil || *rhc.Type == \"metatile\" {\n\t\t\tparser := &handler.MetatileMuxParser{\n\t\t\t\tMimeMap: hc.Mime,\n\t\t\t}\n\n\t\t\th := handler.MetatileHandler(parser, metatileSize, tileSize, metatileMaxDetailZoom, stg, bufferManager, mw, logger, tileCache)\n\t\t\tgzipped := gziphandler.GzipHandler(h)\n\n\t\t\tr.Handle(reqPattern, gzipped).Methods(\"GET\")\n\n\t\t} else if rhc.Type != nil && *rhc.Type == \"tilejson\" {\n\t\t\tparser := &handler.TileJsonParser{}\n\t\t\th := handler.TileJsonHandler(parser, stg, mw, logger)\n\t\t\tgzipped := gziphandler.GzipHandler(h)\n\t\t\tr.Handle(reqPattern, gzipped).Methods(\"GET\")\n\t\t} else {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Invalid route handler type: %s\\n\", *rhc.Type)\n\t\t}\n\n\t}\n\n\tif hc.Preview != nil {\n\t\tif hc.Preview.Path == nil || hc.Preview.Template == nil {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Preview must have path and template specified\")\n\t\t}\n\n\t\tvar templateData map[string]interface{}\n\t\tif hc.Preview.Data != nil {\n\t\t\ttemplateData = *hc.Preview.Data\n\t\t}\n\n\t\tfileHandler, err := handler.NewFileHandler(*hc.Preview.Template, templateData)\n\t\tif err != nil {\n\t\t\tsystemLogger.Fatalf(\"ERROR: Couldn't load preview template: %+v\", err)\n\t\t}\n\n\t\tr.Handle(*hc.Preview.Path, fileHandler).Methods(\"GET\")\n\t}\n\n\tif len(healthcheck) > 0 {\n\t\tstoragesToCheck := make([]storage.Storage, len(healthCheckStorages))\n\t\ti := 0\n\t\tfor _, s := range healthCheckStorages {\n\t\t\tstoragesToCheck[i] = s\n\t\t\ti++\n\t\t}\n\t\thc := handler.HealthCheckHandler(storagesToCheck, logger)\n\t\tr.Handle(healthcheck, hc).Methods(\"GET\")\n\t}\n\n\t\/\/ Readiness probe for graceful shutdown support\n\treadinessResponseCode := uint32(http.StatusOK)\n\tif len(readyCheck) > 0 {\n\t\tr.HandleFunc(readyCheck, func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.WriteHeader(int(atomic.LoadUint32(&readinessResponseCode)))\n\t\t})\n\t}\n\n\tcorsHandler := handlers.CORS()(r)\n\tloggingHandler := log.LoggingMiddleware(logger)(corsHandler)\n\n\tlogger.Info(\"Server started and listening on %s\", listen)\n\n\t\/\/ Support for upgrading an http\/1.1 connection to http\/2\n\t\/\/ See https:\/\/github.com\/thrawn01\/h2c-golang-example\n\thttp2Server := &http2.Server{}\n\tserver := &http.Server{\n\t\tAddr: listen,\n\t\tHandler: h2c.NewHandler(loggingHandler, http2Server),\n\t}\n\n\t\/\/ Code to handle shutdown gracefully\n\tshutdownChan := make(chan struct{})\n\tgo func() {\n\t\tdefer close(shutdownChan)\n\n\t\t\/\/ Wait for SIGTERM to come in\n\t\tsignals := make(chan os.Signal, 1)\n\t\tsignal.Notify(signals, syscall.SIGTERM)\n\t\t<-signals\n\n\t\tlogger.Info(\"SIGTERM received. Starting graceful shutdown.\")\n\n\t\t\/\/ Start failing readiness probes\n\t\tatomic.StoreUint32(&readinessResponseCode, http.StatusInternalServerError)\n\t\t\/\/ Wait for upstream clients\n\t\ttime.Sleep(gracefulShutdownSleep)\n\t\t\/\/ Begin shutdown of in-flight requests\n\t\tshutdownCtx, shutdownCtxCancel := context.WithTimeout(context.Background(), gracefulShutdownTimeout)\n\t\tif err := server.Shutdown(shutdownCtx); err != nil {\n\t\t\tlogger.Info(\"Error waiting for server shutdown: %+v\", err)\n\t\t}\n\t\tshutdownCtxCancel()\n\t}()\n\n\tlogger.Info(\"Service started\")\n\tif err := server.ListenAndServe(); err != nil {\n\t\tlogger.Info(\"Couldn't start HTTP server: %+v\", err)\n\t}\n\t<-shutdownChan\n}\n\nfunc logFatalCfgErr(logger log.JsonLogger, msg string, xs ...interface{}) {\n\tlogger.Error(log.LogCategory_ConfigError, msg, xs...)\n\tos.Exit(1)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"launchpad.net\/gnuflag\"\n)\n\nvar errUndefinedTarget = errors.New(`No target defined. Please use target-add\/target-set to define a target.\n\nFor more details, please run \"tsuru help target\".`)\n\ntype tsuruTarget struct {\n\tlabel, url string\n}\n\nfunc (t *tsuruTarget) String() string {\n\treturn t.label + \" (\" + t.url + \")\"\n}\n\ntype targetSlice struct {\n\ttargets []tsuruTarget\n\tcurrent int\n\tsorted bool\n}\n\nfunc newTargetSlice() *targetSlice {\n\treturn &targetSlice{current: -1}\n}\n\nfunc (t *targetSlice) add(label, url string) {\n\tt.targets = append(t.targets, tsuruTarget{label: label, url: url})\n\tlength := t.Len()\n\tif length > 1 && !t.Less(t.Len()-2, t.Len()-1) {\n\t\tt.sorted = false\n\t}\n}\n\nfunc (t *targetSlice) Len() int {\n\treturn len(t.targets)\n}\n\nfunc (t *targetSlice) Less(i, j int) bool {\n\treturn t.targets[i].label < t.targets[j].label\n}\n\nfunc (t *targetSlice) Swap(i, j int) {\n\tt.targets[i], t.targets[j] = t.targets[j], t.targets[i]\n}\n\nfunc (t *targetSlice) Sort() {\n\tsort.Sort(t)\n\tt.sorted = true\n}\n\nfunc (t *targetSlice) setCurrent(url string) {\n\tif !t.sorted {\n\t\tt.Sort()\n\t}\n\tfor i, target := range t.targets {\n\t\tif target.url == url {\n\t\t\tt.current = i\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (t *targetSlice) String() string {\n\tif !t.sorted {\n\t\tt.Sort()\n\t}\n\tvalues := make([]string, len(t.targets))\n\tfor i, target := range t.targets {\n\t\tprefix := \" \"\n\t\tif t.current == i {\n\t\t\tprefix = \"* \"\n\t\t}\n\t\tvalues[i] = prefix + target.String()\n\t}\n\treturn strings.Join(values, \"\\n\")\n}\n\nfunc ReadTarget() (string, error) {\n\tif target := os.Getenv(\"TSURU_TARGET\"); target != \"\" {\n\t\treturn target, nil\n\t}\n\ttargetPath := JoinWithUserDir(\".tsuru\", \"target\")\n\tif f, err := filesystem().Open(targetPath); err == nil {\n\t\tdefer f.Close()\n\t\tif b, err := ioutil.ReadAll(f); err == nil {\n\t\t\treturn strings.TrimSpace(string(b)), nil\n\t\t}\n\t}\n\treturn \"\", errUndefinedTarget\n}\n\nfunc deleteTargetFile() {\n\tfilesystem().Remove(JoinWithUserDir(\".tsuru\", \"target\"))\n}\n\nfunc GetURL(path string) (string, error) {\n\tvar prefix string\n\ttarget, err := ReadTarget()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif m, _ := regexp.MatchString(\"^https?:\/\/\", target); !m {\n\t\tprefix = \"http:\/\/\"\n\t}\n\treturn prefix + strings.TrimRight(target, \"\/\") + path, nil\n}\n\nfunc writeTarget(t string) error {\n\ttargetPath := JoinWithUserDir(\".tsuru\", \"target\")\n\ttargetFile, err := filesystem().OpenFile(targetPath, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer targetFile.Close()\n\tn, err := targetFile.WriteString(t)\n\tif n != len(t) || err != nil {\n\t\treturn errors.New(\"Failed to write the target file\")\n\t}\n\treturn nil\n}\n\ntype targetAdd struct {\n\tfs *gnuflag.FlagSet\n\tset bool\n}\n\nfunc (t *targetAdd) Info() *Info {\n\treturn &Info{\n\t\tName: \"target-add\",\n\t\tUsage: \"target-add